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
9e663aa191f6c95c0f2feca01071f9e6034caf14
Java
RyanStyron/OptimalPlugin
/src/optimalplugin/utils/MessageUtils.java
UTF-8
1,389
2.34375
2
[]
no_license
package optimalplugin.utils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import optimalplugin.OptimalPlugin; public class MessageUtils { private static FileConfiguration config = OptimalPlugin.getInstance().getConfig(); public static String convertChatColors(String message) { return ChatColor.translateAlternateColorCodes('&', message); } public static void message(CommandSender sender, String message) { sender.sendMessage(convertChatColors(message)); } public static void configMessage(CommandSender sender, String configString, String regex, String replacement) { if (regex == null || replacement == null) message(sender, config.getString(configString)); else message(sender, config.getString(configString).replaceAll(regex, replacement)); } public static void argumentError(CommandSender sender, String usage) { configMessage(sender, "argument-error", "<usage>", usage); } public static void permissionsError(CommandSender sender) { configMessage(sender, "no-permissions-error", null, null); } public static void invalidPlayerError(CommandSender sender) { configMessage(sender, "invalid-player-error", null, null); } public static void consoleError() { configMessage(Bukkit.getConsoleSender(), "console-error", null, null); } }
true
6c635e9cbd411ef1d943105bb54061795a6b56f8
Java
zafrul-ust/tcmISDev
/src/main/java/com/tcmis/client/het/factory/VvHetSubstrateBeanFactory.java
UTF-8
5,954
2.046875
2
[]
no_license
package com.tcmis.client.het.factory; import java.math.BigDecimal; import java.sql.Connection; import java.util.Collection; import java.util.Iterator; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.tcmis.client.het.beans.VvHetSubstrateBean; import com.tcmis.common.db.DbManager; import com.tcmis.common.db.SqlManager; import com.tcmis.common.exceptions.BaseException; import com.tcmis.common.framework.BaseBeanFactory; import com.tcmis.common.util.DataSet; import com.tcmis.common.util.DataSetRow; import com.tcmis.common.util.SearchCriteria; import com.tcmis.common.util.SearchCriterion; import com.tcmis.common.util.SortCriteria; import com.tcmis.common.util.SqlHandler; /****************************************************************************** * CLASSNAME: VvHetSubstrateBeanFactory <br> * @version: 1.0, Aug 11, 2011 <br> *****************************************************************************/ public class VvHetSubstrateBeanFactory extends BaseBeanFactory { Log log = LogFactory.getLog(getClass()); //column names public String ATTRIBUTE_COMPANY_ID = "COMPANY_ID"; public String ATTRIBUTE_SUBSTRATE_CODE = "SUBSTRATE_CODE"; public String ATTRIBUTE_SUBSTRATE = "SUBSTRATE"; public String ATTRIBUTE_SUBSTRATE_ID = "SUBSTRATE_ID"; //table name public String TABLE = "VV_HET_SUBSTRATE"; //constructor public VvHetSubstrateBeanFactory(DbManager dbManager) { super(dbManager); } //get column names @Override public String getColumnName(String attributeName) { if (attributeName.equals("companyId")) { return ATTRIBUTE_COMPANY_ID; } else if (attributeName.equals("substrateCode")) { return ATTRIBUTE_SUBSTRATE_CODE; } else if (attributeName.equals("substrate")) { return ATTRIBUTE_SUBSTRATE; } else if (attributeName.equals("substrateId")) { return ATTRIBUTE_SUBSTRATE_ID; } else { return super.getColumnName(attributeName); } } //get column types @Override public int getType(String attributeName) { return super.getType(attributeName, VvHetSubstrateBean.class); } //delete public int delete(VvHetSubstrateBean vvHetSubstrateBean) throws BaseException { SearchCriteria criteria = new SearchCriteria("substrateId", SearchCriterion.EQUALS, "" + vvHetSubstrateBean.getSubstrateId()); return delete(criteria); } public int delete(SearchCriteria criteria) throws BaseException { Connection connection = null; int result = 0; try { connection = getDbManager().getConnection(); result = delete(criteria, connection); } finally { getDbManager().returnConnection(connection); } return result; } public int delete(SearchCriteria criteria, Connection conn) throws BaseException { String sqlQuery = " delete from " + TABLE + " " + getWhereClause(criteria); return new SqlManager().update(conn, sqlQuery); } //insert public int insert(VvHetSubstrateBean vvHetSubstrateBean) throws BaseException { Connection connection = null; int result = 0; try { connection = getDbManager().getConnection(); result = insert(vvHetSubstrateBean, connection); } finally { getDbManager().returnConnection(connection); } return result; } public int insert(VvHetSubstrateBean vvHetSubstrateBean, Connection conn) throws BaseException { int newId = getDbManager().getOracleSequence("HET_MISC_SEQ"); vvHetSubstrateBean.setSubstrateId(new BigDecimal(newId)); SqlManager sqlManager = new SqlManager(); String query = "insert into " + TABLE + " (" + ATTRIBUTE_COMPANY_ID + "," + ATTRIBUTE_SUBSTRATE_CODE + "," + ATTRIBUTE_SUBSTRATE + "," + ATTRIBUTE_SUBSTRATE_ID + ")" + " values (" + SqlHandler.delimitString(vvHetSubstrateBean.getCompanyId()) + "," + SqlHandler.delimitString(vvHetSubstrateBean.getSubstrateCode()) + "," + SqlHandler.delimitString(vvHetSubstrateBean.getSubstrate()) + "," + vvHetSubstrateBean.getSubstrateId() + ")"; return sqlManager.update(conn, query); } //update public int update(VvHetSubstrateBean vvHetSubstrateBean) throws BaseException { Connection connection = null; int result = 0; try { connection = getDbManager().getConnection(); result = update(vvHetSubstrateBean, connection); } finally { getDbManager().returnConnection(connection); } return result; } public int update(VvHetSubstrateBean vvHetSubstrateBean, Connection conn) throws BaseException { String query = "update " + TABLE + " set " + ATTRIBUTE_SUBSTRATE_CODE + "=" + SqlHandler.delimitString(vvHetSubstrateBean.getSubstrateCode()) + "," + ATTRIBUTE_SUBSTRATE + "=" + SqlHandler.delimitString(vvHetSubstrateBean.getSubstrate()) + " " + "where " + ATTRIBUTE_SUBSTRATE_ID + "=" + vvHetSubstrateBean.getSubstrateId(); return new SqlManager().update(conn, query); } //select public Collection select(SearchCriteria criteria) throws BaseException { return select(criteria, null); } public Collection select(SearchCriteria criteria, SortCriteria sortCriteria) throws BaseException { Connection connection = null; Collection c = null; try { connection = getDbManager().getConnection(); c = select(criteria, sortCriteria, connection); } finally { getDbManager().returnConnection(connection); } return c; } public Collection select(SearchCriteria criteria, SortCriteria sortCriteria, Connection conn) throws BaseException { Collection vvHetSubstrateBeanColl = new Vector(); String query = "select * from " + TABLE + " " + getWhereClause(criteria) + getOrderByClause(sortCriteria); DataSet dataSet = new SqlManager().select(conn, query); Iterator dataIter = dataSet.iterator(); while (dataIter.hasNext()) { DataSetRow dataSetRow = (DataSetRow) dataIter.next(); VvHetSubstrateBean vvHetSubstrateBean = new VvHetSubstrateBean(); load(dataSetRow, vvHetSubstrateBean); vvHetSubstrateBeanColl.add(vvHetSubstrateBean); } return vvHetSubstrateBeanColl; } }
true
d764b5d9fef5164a482465d2ce719433c3fbb395
Java
capohf/server
/com/vencillio/rs2/entity/player/net/out/impl/SendObjectHint.java
UTF-8
815
2.453125
2
[]
no_license
package com.vencillio.rs2.entity.player.net.out.impl; import com.vencillio.core.network.StreamBuffer; import com.vencillio.rs2.entity.Location; import com.vencillio.rs2.entity.player.net.Client; import com.vencillio.rs2.entity.player.net.out.OutgoingPacket; public class SendObjectHint extends OutgoingPacket { private final Location p; private final int pos; public SendObjectHint(Location p, int pos) { super(); this.p = p; this.pos = pos; } @Override public void execute(Client client) { StreamBuffer.OutBuffer out = StreamBuffer.newOutBuffer(7); out.writeHeader(client.getEncryptor(), 254); out.writeByte(pos); out.writeShort(p.getX()); out.writeShort(p.getY()); out.writeByte(p.getZ()); client.send(out.getBuffer()); } @Override public int getOpcode() { return 254; } }
true
1e0918134aa774b1da7cc0d4107781fd0a30f9f3
Java
Then2017/ThenTools
/src/com/Main/MTKUImain.java
GB18030
7,280
2.046875
2
[]
no_license
package com.Main; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import javax.swing.SwingConstants; import com.MTK.MTKADBRoot; import com.MTK.MTKLogger; import com.MTK.MTKhappentimeUI; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.logging.Level; import javax.swing.JCheckBox; public class MTKUImain extends JPanel { MTKhappentimeUI happentimeUI= new MTKhappentimeUI(); MTKADBRoot adbroot=new MTKADBRoot(); MTKLogger mtklogger=new MTKLogger(); JCheckBox chckbxdel; boolean dellog=true; /** * Create the panel. */ public MTKUImain() { setSize(700,650); setBorder(new EmptyBorder(5, 5, 5, 5)); setLayout(null); //Get logs button JButton btnGet = new JButton(getString("btnGet")); btnGet.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { happentimeUI.updatetime(); happentimeUI.setVisible(true); com.Main.ThenToolsRun.logger.log(Level.INFO,"mtk get log button"); } }); btnGet.setBounds(480, 277, 100, 25); add(btnGet); JLabel lblMtk = new JLabel(getString("lblMtk")); lblMtk.setVerticalAlignment(SwingConstants.TOP); lblMtk.setFont(new Font("΢ź", Font.BOLD, 26)); lblMtk.setBounds(10, 145, 126, 40); add(lblMtk); //adb root button JButton btnAdbroot = new JButton(getString("btnAdbroot")); btnAdbroot.setVisible(false); btnAdbroot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { com.Main.ThenToolsRun.logger.log(Level.INFO,"root mtk button"); JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "inputs *#*#13646633#*#*->Log and Debugging->User2Root->Root,run root.", "Messge", JOptionPane.INFORMATION_MESSAGE); return; //adbroot.main(); } }); btnAdbroot.setBounds(20, 186, 100, 25); add(btnAdbroot); //Active log button JButton btnActiveLogs = new JButton(getString("btnActiveLogs")); btnActiveLogs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { //check devices if(com.Main.ThenToolsRun.selectedID==null){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "No devices checked!", "Messge", JOptionPane.ERROR_MESSAGE); return; } //if mtk platform if(com.Main.ThenToolsRun.platform.contains("msm")){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "Only work for MTK platform!", "Messge", JOptionPane.ERROR_MESSAGE); return; } mtklogger.activemtklog(); com.Main.ThenToolsRun.logger.log(Level.INFO,"active mtk log button"); } }); btnActiveLogs.setBounds(480, 232, 100, 25); add(btnActiveLogs); //Stop log button JButton btnStopLogs = new JButton(getString("btnStopLogs")); btnStopLogs.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //check devices if(com.Main.ThenToolsRun.selectedID==null){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "No devices checked!", "Messge", JOptionPane.ERROR_MESSAGE); return; } //if mtk platform if(com.Main.ThenToolsRun.platform.contains("msm")){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "Only work for MTK platform!", "Messge", JOptionPane.ERROR_MESSAGE); return; } if(!dellog){ int confirm=JOptionPane.showConfirmDialog(com.Main.ThenToolsRun.mainFrame, "Do you want to stop log? ","Pls confirm :", JOptionPane.YES_NO_OPTION); if(confirm==0){ mtklogger.stopmtklog(dellog); }else{ return; } }else{ int confirm=JOptionPane.showConfirmDialog(com.Main.ThenToolsRun.mainFrame, "Do you want to stop and del logs? ","Pls confirm :", JOptionPane.YES_NO_OPTION); if(confirm==0){ mtklogger.stopmtklog(dellog); }else{ return; } } com.Main.ThenToolsRun.logger.log(Level.INFO,"stop mtk log button"); } }); btnStopLogs.setBounds(480, 322, 100, 25); add(btnStopLogs); //Show UI JButton btnShowUi = new JButton(getString("btnShowUi")); btnShowUi.setToolTipText(getString("btnShowUitip")); btnShowUi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //check devices if(com.Main.ThenToolsRun.selectedID==null){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "No devices checked!", "Messge", JOptionPane.ERROR_MESSAGE); return; } //if mtk platform if(com.Main.ThenToolsRun.platform.contains("msm")){ JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "Only work for MTK platform!", "Messge", JOptionPane.ERROR_MESSAGE); return; } mtklogger.showui(); com.Main.ThenToolsRun.logger.log(Level.INFO,"show mtk log ui button"); JOptionPane.showMessageDialog(com.Main.ThenToolsRun.mainFrame, "MTKLogger is opened in your UE, pls check.", "Messge", JOptionPane.INFORMATION_MESSAGE); } }); btnShowUi.setBounds(480, 186, 100, 25); add(btnShowUi); //and del logs chckbxdel = new JCheckBox(getString("chckbxdel")); chckbxdel.setSelected(true); chckbxdel.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ if(chckbxdel.isSelected()){ dellog=true; }else{ dellog=false; } } }); chckbxdel.setBounds(599, 323, 95, 23); add(chckbxdel); //lbl Mtklogger JLabel lblMTKLogger = new JLabel(getString("lblMTKLogger")); lblMTKLogger.setBounds(424, 170, 95, 15); add(lblMTKLogger); //lbl picture JLabel lblPicture = new JLabel(""); lblPicture.setIcon(new ImageIcon(getClass().getResource("/Rescource/MTK.jpg"))); lblPicture.setBounds(10, 200, 400, 300); add(lblPicture); } //Language public String getString(String flag){ switch(flag){ case "btnActiveLogs": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "Log"; }else{ return "Active Logs"; } case "btnGet": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "ȡLog"; }else{ return "Get Logs"; } case "btnStopLogs": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "ֹͣLog"; }else{ return "Stop Logs"; } case "chckbxdel": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "ɾ"; }else{ return "and Del"; } case "btnAdbRoot": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "ADB Root"; }else{ return "ADB Root"; } case "lblMtk": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "MTKƽ̨:"; }else{ return "MTK:"; } case "btnShowUi": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "ʾ"; }else{ return "Show UI"; } case "btnShowUitip": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "豸ʾMTKlogger"; }else{ return "Show MTKlogger in device"; } case "lblMTKLogger": if(com.Main.ThenToolsRun.Language.equals("CN")){ return "MTKLogger:"; }else{ return "MTKLogger:"; } default: return ""; } } }
true
77dc93404a9e41ddae24fea3cfd3c683c69c0aa0
Java
Ugoonuke/Java-Assignments
/Semester 2/Lab 1/SmallestLargest.java
UTF-8
666
3.703125
4
[]
no_license
import java.util.Scanner; public class GetSizes{ public static void main(String args []){ Scanner sc = new Scanner(System.in); double a = sc.nextDouble(); double b = sc.nextDouble(); determineSize(a,b); } public static void determineSize(double a, double b){ if(a > b){ System.out.println("Largest = " + a); System.out.println("Smallest = " + b); } else if(b > a){ System.out.println("Largest = " + b); System.out.println("Smallest= " + a); } else if(a == b){ System.out.println("Numbers are the same"); } } }
true
9dd09fcba855920cb746c7bdd3e2f584fe284595
Java
asamahayder/Galgespil_Aflevering
/src/main/java/com/example/galgespil_aflevering/ResultObject.java
UTF-8
674
2.75
3
[]
no_license
package com.example.galgespil_aflevering; public class ResultObject implements Comparable { String word; String time; String score; public ResultObject(String word, String time, String score) { this.word = word; this.time = time; this.score = score; } public String getWord() { return word; } public String getTime() { return time; } public String getScore() { return score; } @Override public int compareTo(Object compareTo) { int a = Integer.parseInt(score); int b = Integer.parseInt(((ResultObject)compareTo).score); return b-a; } }
true
d8a8116712e51f51741b09743403b20d771c76e3
Java
xsren/AndroidReverseNotes
/docs/weixin_7.0.4_source/反编译源码/未反混淆/src/main/java/com/tencent/mm/plugin/sandbox/SubCoreSandBox.java
UTF-8
4,179
1.523438
2
[]
no_license
package com.tencent.mm.plugin.sandbox; import android.content.Context; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import com.tencent.matrix.trace.core.AppMethodBeat; import com.tencent.mm.cd.h.d; import com.tencent.mm.model.at; import com.tencent.mm.plugin.p.a; import com.tencent.mm.plugin.p.b; import com.tencent.mm.plugin.p.c; import com.tencent.mm.sandbox.monitor.ExceptionMonitorBroadcastReceiver; import com.tencent.mm.sandbox.updater.AppUpdaterUI; import com.tencent.mm.sandbox.updater.Updater; import com.tencent.mm.sdk.platformtools.ab; import com.tencent.mm.sdk.platformtools.ah; import java.util.HashMap; public class SubCoreSandBox implements at, c { public static boolean pYG = false; public static boolean pYH = false; public SubCoreSandBox() { AppMethodBeat.i(24382); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox constructor at: " + System.currentTimeMillis()); AppMethodBeat.o(24382); } public final HashMap<Integer, d> Jx() { AppMethodBeat.i(24383); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox getBaseDBFactories at: " + System.currentTimeMillis()); AppMethodBeat.o(24383); return null; } public final void iy(int i) { AppMethodBeat.i(24384); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox clearPluginData at: " + System.currentTimeMillis()); AppMethodBeat.o(24384); } public final void bz(boolean z) { AppMethodBeat.i(24385); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox onAccountPostReset at: " + System.currentTimeMillis()); AppMethodBeat.o(24385); } public final void bA(boolean z) { AppMethodBeat.i(24386); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox onSdcardMount at: " + System.currentTimeMillis()); AppMethodBeat.o(24386); } public final void onAccountRelease() { AppMethodBeat.i(24387); ab.i("MicroMsg.SubCoreSandBox", "SubCoreSandBox onAccountRelease at: " + System.currentTimeMillis()); AppMethodBeat.o(24387); } public final void bQS() { AppMethodBeat.i(24388); Updater.LS(16); AppMethodBeat.o(24388); } public final a c(Context context, OnCancelListener onCancelListener) { AppMethodBeat.i(24389); Updater e = Updater.e(context, onCancelListener); AppMethodBeat.o(24389); return e; } public final a d(Context context, OnCancelListener onCancelListener) { AppMethodBeat.i(24390); Updater f = Updater.f(context, onCancelListener); AppMethodBeat.o(24390); return f; } public final a ey(Context context) { AppMethodBeat.i(24391); Updater gh = Updater.gh(context); AppMethodBeat.o(24391); return gh; } public final void ez(Context context) { AppMethodBeat.i(24392); Updater.ez(context); AppMethodBeat.o(24392); } public final void e(String str, int i, String str2, String str3) { AppMethodBeat.i(24393); Updater.e(str, i, str2, str3); AppMethodBeat.o(24393); } public final b bQT() { AppMethodBeat.i(24394); com.tencent.mm.sandbox.a.a aVar = new com.tencent.mm.sandbox.a.a(2); AppMethodBeat.o(24394); return aVar; } public final String RP(String str) { AppMethodBeat.i(24395); String RP = com.tencent.mm.sandbox.monitor.c.RP(str); AppMethodBeat.o(24395); return RP; } public final void x(Context context, Intent intent) { AppMethodBeat.i(24396); if (context != null) { intent.setClass(context, ExceptionMonitorBroadcastReceiver.class); ah.getContext().sendBroadcast(intent); } AppMethodBeat.o(24396); } public final void y(Context context, Intent intent) { AppMethodBeat.i(24397); intent.setClass(context, AppUpdaterUI.class); context.startActivity(intent); AppMethodBeat.o(24397); } public final void jd(boolean z) { pYG = true; pYH = z; } }
true
08d9b94e0777e6e6a89775c3498d8cc771f69a22
Java
ThomasLarmignat/Chat-Coffe
/Serveur/Chat_ClientServeur.java
UTF-8
1,166
2.734375
3
[]
no_license
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Chat_ClientServeur implements Runnable { private Socket socket = null; private BufferedReader in = null; private static PrintWriter out = null; private String login = null; ; private Thread tReception; private Clients clients; public Chat_ClientServeur(Socket s, String log, Clients clients){ this.clients = clients; socket = s; login = log; } public static PrintWriter getOut(){ return(out); } public void run() { try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream()); clients.addlistLoginColor(login); clients.addClient(out); clients.addCliOut(out,login); System.out.println(clients.getVector()); Sauvegarde sauvegarde = new Sauvegarde(clients); sauvegarde.sendSave(login); Thread tReception = new Thread(new Reception(in,login,socket,out,clients,sauvegarde)); tReception.start(); } catch (IOException e) { System.err.println(login +"s'est déconnecté "); } } }
true
05307b3bf35204b8a2e6aff86495d657cd67e897
Java
zigtang/LotterySSQ
/src/com/zig/lottery/ssq/utils/SharedPreferencesHelper.java
UTF-8
1,877
2.4375
2
[]
no_license
package com.zig.lottery.ssq.utils; import java.util.ArrayList; import java.util.Set; import android.content.Context; import android.content.SharedPreferences; import com.zig.lottery.ssq.R; import com.zig.lottery.ssq.consts.Key; public class SharedPreferencesHelper { private static SharedPreferencesHelper helper; private static SharedPreferences sp; private static SharedPreferences.Editor editor; private SharedPreferencesHelper(Context context) { sp = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE); editor = sp.edit(); } public static synchronized SharedPreferencesHelper getInstance(Context context) { if (helper == null) { helper = new SharedPreferencesHelper(context); } return helper; } public String getNum() { return sp.getString(Key.NUM, ""); } public void setNum(String Num) { editor.putString(Key.NUM, Num); editor.commit(); } // ----------------------Red Num------------------------- public ArrayList<String> getRedNum() { Set<String> redSet = sp.getStringSet(Key.RED_NUM, null); if (redSet == null) return null; ArrayList<String> redList = new ArrayList<String>(); for (String str : redSet) { redList.add(str); } return redList; } public void setRedNum(Set<String> redNumSet) { editor.putStringSet(Key.RED_NUM, redNumSet); editor.commit(); } // ----------------------Blue Num------------------------- public ArrayList<String> getBlueNum() { Set<String> blueSet = sp.getStringSet(Key.BLUE_NUM, null); if (blueSet == null) return null; ArrayList<String> blueList = new ArrayList<String>(); for (String str : blueSet) { blueList.add(str); } return blueList; } public void setBlueNum(Set<String> blueNumSet) { editor.putStringSet(Key.BLUE_NUM, blueNumSet); editor.commit(); } public void clear() { editor.clear().commit(); } }
true
1aea7b7b766973610771ad64da4162836751216e
Java
canuludag/SpaceXDroid
/app/src/main/java/com/uludag/can/spacexdroid/home/upcomings/UpcomingsFragment.java
UTF-8
1,390
1.890625
2
[]
no_license
package com.uludag.can.spacexdroid.home.upcomings; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.uludag.can.spacexdroid.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.Unbinder; public class UpcomingsFragment extends Fragment { @BindView(R.id.recycler_view_upcomings) RecyclerView mRecyclerViewUpcomings; @BindView(R.id.tv_upcomings_error) TextView mTvUpcomingsError; @BindView(R.id.loading_upcomings) View mLoadingUpcomings; private Unbinder mUnbinder; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_upcomings, container, false); mUnbinder = ButterKnife.bind(this, view); return view; } @Override public void onDestroyView() { super.onDestroyView(); if (mUnbinder != null) { mUnbinder.unbind(); mUnbinder = null; } } }
true
835220ed245453ceb9eda1b585707ac0bcd62728
Java
Alextramper/mypaysystem
/src/main/java/ru/krayPro/beans/Client.java
UTF-8
2,690
2.75
3
[]
no_license
package ru.krayPro.beans; public class Client implements Person { public Client( int id, String login, String psswd, String firstname, String secondname, String surname, Account account) { this.id = id; this.login = login; this.psswd = psswd; this.firstname = firstname; this.secondname = secondname; this.surname = surname; this.account = account; } public Client( String login, String psswd, String firstname, String secondname, String surname) { this.login = login; this.psswd = psswd; this.firstname = firstname; this.secondname = secondname; this.surname = surname; } public Client( int id, String login, String psswd, String firstname, String secondname, String surname) { this.id = id; this.login = login; this.psswd = psswd; this.firstname = firstname; this.secondname = secondname; this.surname = surname; } public Client(String login, String psswd, String firstname, String secondname, String surname, Account account) { this.login = login; this.psswd = psswd; this.firstname = firstname; this.secondname = secondname; this.surname = surname; this.account = account; } public Client( int id, String firstname, String secondname, String surname, Account account) { this.id = id; this.firstname = firstname; this.secondname = secondname; this.surname = surname; this.account = account; } public Client() {} private int id; private String login; private String psswd; private String firstname; private String secondname; private String surname; private Account account; public int getId() {return id;} public void setId(int id) {this.id = id;} public String getLogin() {return login;} public void setLogin(String login) {this.login = login;} public String getPsswd() {return psswd;} public void setPsswd(String psswd) {this.psswd = psswd;} public String getFirstname() {return psswd;} public void setFirstname(String firstname) {this.firstname = firstname;} public String getSecondname() {return secondname;} public void setSecondname(String secondname) {this.secondname = secondname;} public String getSurname() {return surname;} public void setSurname(String surname) {this.surname = surname;} public Account getAccount() {return account;} public void setAccount(Account account) {this.account = account;} public String getFullName() { return String.join(" ", surname, firstname, secondname); } }
true
ece9b9b6c23d500c67f36c8c9c28992e5f591f02
Java
1362420246/security-jwt
/src/main/java/com/qbk/entity/SysRole.java
UTF-8
149
1.507813
2
[]
no_license
package com.qbk.entity; import lombok.Data; /** * role实体 */ @Data public class SysRole { private String id; private String name; }
true
7ed49b300e4c388125950d318e7c8d656a3340d8
Java
Philatelist/ProvEng
/src/main/java/com/provectus/proveng/repository/RepositoryInterface.java
UTF-8
239
1.867188
2
[]
no_license
package com.provectus.proveng.repository; import javax.transaction.Transactional; //@Repository @Transactional public interface RepositoryInterface { void create(); Object findById(); void update(); void delete(); }
true
f27547b0c2add24d345d7ae8e6608347a104a53e
Java
liuxianfengsos/meeting
/meeting/src/main/java/com/chinasofti/meeting/controller/ValidateUsernameServlet.java
UTF-8
1,593
2.34375
2
[]
no_license
package com.chinasofti.meeting.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.chinasofti.meeting.dao.EmployeeDao; import com.chinasofti.meeting.vo.Employee; public class ValidateUsernameServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //System.out.println("1111111111111"); boolean flag = true; String message = ""; EmployeeDao dao = new EmployeeDao(); //获取前端参数 String username = request.getParameter("username"); //查询是否已经存在该用户名 Employee e = dao.selectByUserName(username); if(e == null) { message = "用户名可以使用"; }else { flag = false; message = "用户名已经存在,请使用其他用户名"; } response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); response.setHeader("Cache-Control", "no-cache"); out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.println("<response>"); out.println("<passed>"+Boolean.toString(flag)+"</passed>"); out.println("<message>"+message+"</message>"); out.println("</response>"); out.close(); } }
true
e37ea7e1d4d7d425b9816648258ea17344422d59
Java
whdals7337/my-introduce
/back-end/src/test/java/introduce/domain/project/ProjectRepositoryTest.java
UTF-8
2,804
2.421875
2
[]
no_license
package introduce.domain.project; import introduce.domain.FileInfo; import introduce.domain.member.Member; import introduce.domain.member.MemberRepository; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; @RunWith(SpringRunner.class) @SpringBootTest public class ProjectRepositoryTest { @Autowired ProjectRepository projectRepository; @Autowired private MemberRepository memberRepository; @After public void cleanup() { projectRepository.deleteAll(); memberRepository.deleteAll(); } @Test public void findByLevelBetween() { Member member = givenMember(); for(int i = 1; i < 6; i++) { givenProject(member, i); } List<Project> list = projectRepository.findByLevelBetween(2,5); for(Project project : list) { assertThat(project.getLevel()).isGreaterThanOrEqualTo(2); assertThat(project.getLevel()).isLessThanOrEqualTo(5); } } @Test public void findAllByMember() { Member member = givenMember(); for(int i = 1; i < 6; i++) { givenProject(member, i); } Page<Project> list = projectRepository.findAllByMember(member, null); for(Project project : list) { assertThat(project.getMember()).isEqualTo(member); } } public Member givenMember() { return memberRepository.save(Member.builder() .comment("페이지 탑 영역 내용 부분입니다.") .fileInfo(new FileInfo("헤더 이미지 경로","헤더 이미지 원본 이름","파일 주소")) .subIntroduction("자기소개 서브 내용 부분입니다.") .introduction("자기소개 내용 부분입니다.") .phoneNumber("010-1111-1111") .email("uok0201@gmail.com") .selectYN("Y") .build()); } public Project givenProject(Member member , int level) { return Project.builder() .projectTitle("프로젝트 이름") .projectContent("프로젝트는 Spring4 + angularJs를 기반으로 개발된 프로젝트입니다.") .projectPostScript("#Spring #angularJs #현장실습") .fileInfo(new FileInfo("경로","이름","주소")) .projectLink("http://aergaerg") .level(level) .member(member) .build(); } }
true
f9b4d43df515e2d655591f68786651b56994a651
Java
zhanght86/pdsci
/src/com/pinde/sci/dao/base/SchDeptRelMapper.java
UTF-8
2,886
1.90625
2
[]
no_license
package com.pinde.sci.dao.base; import com.pinde.sci.model.mo.SchDeptRel; import com.pinde.sci.model.mo.SchDeptRelExample; import java.util.List; import org.apache.ibatis.annotations.Param; public interface SchDeptRelMapper { /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int countByExample(SchDeptRelExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int deleteByExample(SchDeptRelExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int deleteByPrimaryKey(String recordFlow); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int insert(SchDeptRel record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int insertSelective(SchDeptRel record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ List<SchDeptRel> selectByExample(SchDeptRelExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ SchDeptRel selectByPrimaryKey(String recordFlow); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int updateByExampleSelective(@Param("record") SchDeptRel record, @Param("example") SchDeptRelExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int updateByExample(@Param("record") SchDeptRel record, @Param("example") SchDeptRelExample example); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int updateByPrimaryKeySelective(SchDeptRel record); /** * This method was generated by MyBatis Generator. This method corresponds to the database table PDSCI.SCH_DEPT_REL * @mbggenerated Fri Aug 21 11:00:50 CST 2015 */ int updateByPrimaryKey(SchDeptRel record); }
true
b61b6e0dde41ff119a98e2035215ad5f8e352dd4
Java
alm1ghty1g/mainonlineshop
/src/main/java/com/sazonov/mainonlineshop/dto/OrderDto.java
UTF-8
412
1.757813
2
[]
no_license
package com.sazonov.mainonlineshop.dto; import lombok.*; import java.time.LocalDate; import java.util.List; @AllArgsConstructor @NoArgsConstructor @Data @Builder public class OrderDto { private int id; private String status; private List<LineItemDto> lineItemDtoSet; private double orderPrice; private UserShortResponseDto userShortResponseDto; private LocalDate created; }
true
98c8f01a30a174cc5f5c7e673f2f85e1b0757a44
Java
Muhitun/MyApp
/app/src/main/java/com/sohan/myapp/OnClickInterface/OnClickForRVAdapters.java
UTF-8
128
1.6875
2
[]
no_license
package com.sohan.myapp.OnClickInterface; public interface OnClickForRVAdapters { public void selectIndex(int position); }
true
e6f1bfd137c2c7fef605574d56d889f8ec463640
Java
NutsAndVolts7725/2020InfiniteRecharge
/robot/subsystems/DistanceSensor.java
UTF-8
1,247
2.171875
2
[]
no_license
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import edu.wpi.first.wpilibj.command.Subsystem; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * Add your docs here. */ public class DistanceSensor extends Subsystem { private static final AnalogInput mb1013 = new AnalogInput(0); private static final double VOLTS_TO_DIST = 108.7; public double getVoltage() { return mb1013.getVoltage(); } public double getDistance() { return mb1013.getVoltage() * VOLTS_TO_DIST; } public void updateDashboard() { SmartDashboard.putNumber("Distance (volts)", getVoltage()); SmartDashboard.putNumber("Distance (real)", getDistance()); } @Override protected void initDefaultCommand() { } }
true
f9e0c1a39d303f2d73296aae677d4b900748836e
Java
boubre/BayouBot
/Workspace/src/interpreter/tree/BooleanResult.java
UTF-8
440
2.703125
3
[ "MIT" ]
permissive
package interpreter.tree; import interpreter.ProgramExecutionException; /** * Represents a block node that returns a boolean value. * @author Brandon Oubre */ public interface BooleanResult extends Result { /** * Calculate or fetch the result of this block. * @return The result. * @throws ProgramExecutionException A program error caused by executing this command. */ public boolean getResult() throws ProgramExecutionException; }
true
d215a1484453347231e91438190d9f8d433d3813
Java
Exordian/qse-sepm-ss13-08
/src/main/java/at/ac/tuwien/sepm/ui/metaLva/ModuleDisplayPanel.java
UTF-8
6,119
2.21875
2
[]
no_license
package at.ac.tuwien.sepm.ui.metaLva; import at.ac.tuwien.sepm.entity.MetaLVA; import at.ac.tuwien.sepm.entity.Module; import at.ac.tuwien.sepm.ui.StandardInsidePanel; import at.ac.tuwien.sepm.ui.UI; import at.ac.tuwien.sepm.ui.template.HintTextField; import at.ac.tuwien.sepm.ui.template.PanelTube; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.List; /** * Author: Lena Lenz */ @UI public class ModuleDisplayPanel extends StandardInsidePanel { private Logger logger = LogManager.getLogger(this.getClass().getSimpleName()); private List<Module> allModules; private List<Module> filteredModules; private ModuleTable table; private JTextField searchName = new HintTextField("Name"); private JTextField searchECTS = new HintTextField("ECTS"); private JPanel searchPanel = new JPanel(); private JScrollPane pane = new JScrollPane(); private MetaLVADisplayPanel metaLVAPanel; int tWidth; public ModuleDisplayPanel(List<Module> modules, int width, int height){ this.tWidth =width; this.allModules = modules; loadFonts(); //this.metaLVAPanel = metaPanel; filteredModules = modules; table = new ModuleTable(modules,width); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { refreshMetaLVAs(); } }); table.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger() || (e.getButton() == 3)) { logger.debug("TEST rechtsklick"); JTable source = ModuleDisplayPanel.this.getTable(); int row = source.rowAtPoint( e.getPoint() ); int column = source.columnAtPoint( e.getPoint() ); if (! source.isRowSelected(row)) source.changeSelection(row, column, false, false); JPopupMenu popup = new PopUpMenu(); popup.show(e.getComponent(), e.getX(), e.getY()); } } }); int searchHeight = 20; add(searchPanel); add(pane); searchPanel.setLayout(new FlowLayout(0,0,0));//.setBorder(BorderFactory.createEmptyBorder(0,0,0,0)); BoxLayout bl = new BoxLayout(this,BoxLayout.Y_AXIS); setLayout(bl); searchPanel.add(searchName); searchName.setPreferredSize(new Dimension(table.getColWidth(0), searchHeight)); searchPanel.add(searchECTS); searchECTS.setPreferredSize(new Dimension(table.getColWidth(1), searchHeight)); pane.setViewportView(table); pane.setPreferredSize(new Dimension(table.getPreferredSize().width, height-searchPanel.getHeight())); KeyListener listener = new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { logger.debug("name: " + searchName.getText()+", total ECTS: "+searchECTS.getText()+")"); filteredModules = new ArrayList<Module>(); for (Module m : allModules) { float ectsCount =0; for(MetaLVA mLVA : m.getMetaLvas()){ ectsCount+=mLVA.getECTS(); } if (m.getName().toLowerCase().contains(searchName.getText().toLowerCase()) &&(""+ectsCount).toLowerCase().contains(searchECTS.getText().toLowerCase())) { filteredModules.add(m); } } table.refreshModules(filteredModules); refreshMetaLVAs(); pane.setViewportView(table); revalidate(); repaint(); } }; searchName.addKeyListener(listener); searchECTS.addKeyListener(listener); } public MetaLVADisplayPanel getMetaLVAPanel(){ return metaLVAPanel; } public void setMetaLVAPanel(MetaLVADisplayPanel metaLVAPanel) { this.metaLVAPanel = metaLVAPanel; refreshMetaLVAs(); } private class PopUpMenu extends JPopupMenu { private JMenuItem button2; public PopUpMenu(){ button2 = new JMenuItem("Bearbeiten"); button2.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) { PanelTube.backgroundPanel.viewModule(getSelectedModule()); } @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} }); add(button2); button2.setFont(standardButtonFont); } } public ModuleTable getTable() { return this.table; } public Module getSelectedModule(){ return table.getSelectedModule(); } public void removeSelectedMetaLVA() { table.removeSelectedModule(); } public void refresh(List<Module> modules) { table.refreshModules(modules); this.allModules=modules; refreshMetaLVAs(); //metaLVAPanel.clearSearch(); } private void refreshMetaLVAs(){ //System.out.println("panel==null: "+metaLVAPanel==null); if(metaLVAPanel!=null){ metaLVAPanel.refresh(new ArrayList<MetaLVA>(0)); if(table.getSelectedRowCount()>0){ //System.out.println("rowcount: "+table.getSelectedRowCount()); metaLVAPanel.refresh(getSelectedModule().getMetaLvas()); } } } }
true
90089d663a0d3ee0424abb78b379e2fd205b3563
Java
yanjunnf/Flow
/src/test/java/com/flow/job/JobManagerTest.java
UTF-8
1,403
2.375
2
[]
no_license
package com.flow.job; import static org.junit.Assert.assertEquals; import org.junit.Test; import com.flow.action.Action; import com.flow.action.DelayAction; import com.flow.recipe.CommonFlow; import com.flow.step.ProcessStep; public class JobManagerTest { @Test public void testJobManagerWithCommonThreadPool() throws Exception { CommonFlow flow = new CommonFlow("Flow1", null); Action waitAction = new DelayAction("Action 1", 100); ProcessStep step = new ProcessStep("Step1", waitAction, flow, null); flow.setRoot(step); JobConfig jc = new JobConfig(0, 0); CommonJob job = new CommonJob(flow, jc); JobManager jobManager = new JobManager(); jobManager.start(job); Thread.sleep(1000*10); } @Test public void testJobManagerWithScheduledThreadPool() throws Exception { CommonFlow flow = new CommonFlow("Flow1", null); Action waitAction = new DelayAction("Action 1", 100); ProcessStep step = new ProcessStep("Step1", waitAction, flow, null); flow.setRoot(step); JobConfig jc = new JobConfig(1, 5); CommonJob job = new CommonJob(flow, jc); JobManager jobManager = new JobManager(); jobManager.start(job); Thread.sleep(1000*10); int jobCount = jobManager.getRunningJobsCount(); assertEquals(jobCount, 1); jobManager.killJob(job.id()); Thread.sleep(1000*10); jobCount = jobManager.getRunningJobsCount(); assertEquals(jobCount, 0); } }
true
7b4c23af2b6f3cf99e3da24c985f53e521f14202
Java
WillEhman/409FinalProject
/src/backend/DatabaseHelper.java
UTF-8
41,211
2.953125
3
[]
no_license
package backend; import shared.*; import java.sql.*; import java.util.Vector; /** * * @author William Ehman * @author David Parkin * @author Luke Kushneryk * @since April 5 2018 * @version 1.0 * * DatabaseHelper for communication with the database * */ public class DatabaseHelper { // Database data members private PreparedStatement statement; private Connection connection; public String databaseName = "school_master", usersTable = "users", coursesTable = "courses", assignmentsTable = "assignments"; public String connectionInfo = "jdbc:mysql://localhost:3306/school_master?verifyServerCertificate=false&useSSL=true", login = "student", password = "student"; // Establish connection public DatabaseHelper() { try { // If this throws an error, make sure you have added the mySQL connector JAR to // the project Class.forName("com.mysql.jdbc.Driver"); // If this fails make sure your connectionInfo and login/password are correct connection = DriverManager.getConnection(connectionInfo, login, password); System.out.println("|---Successfully connected to Database: " + databaseName + "----|"); System.out.println("|--------------------------------------------------------|"); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } // TODO FOR ALL fix try catch statements for proper handling and output /** * Selects and searches for a course id * * @param courseID * to be searched for * @return course or null if no course */ public Course preparedsearchCourses(int courseID) { String sql = "SELECT * FROM courses WHERE COURSENUMBER= ?"; ResultSet course; try { statement = connection.prepareStatement(sql); statement.setInt(1, courseID); course = statement.executeQuery(); if (course.next()) { return new Course(course.getInt("COURSENUMBER"), course.getInt("PROFESSORID"), course.getString("COURSENAME"), course.getBoolean("ACTIVE")); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Logs in user * * @param login * @return */ public User Login(LoginInfo login) { String sql = "SELECT * FROM users WHERE USERNAME= ?"; ResultSet user; try { statement = connection.prepareStatement(sql); statement.setString(1, login.getUsername()); user = statement.executeQuery(); if (user.next()) { return new User(user.getInt("ID"), user.getString("FIRSTNAME"), user.getString("LASTNAME"), user.getString("TYPE"), user.getString("EMAIL")); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Returns true if student login is valid * * @param username * @param password * @return */ public boolean isValidStudentLogin(String username, String password) { String sql = "SELECT * FROM users WHERE USERNAME= ?"; ResultSet user; try { statement = connection.prepareStatement(sql); statement.setString(1, username); user = statement.executeQuery(); if (user.next()) { if (password.equals(user.getString("PASSWORD")) && user.getString("TYPE").equalsIgnoreCase("s")) { return true; } } } catch (SQLException e) { e.printStackTrace(); } return false; } /** * Returns true if prof login is valid * * @param username * @param password * @return */ public boolean isValidProfLogin(String username, String password) { String sql = "SELECT * FROM users WHERE USERNAME= ?"; ResultSet user; try { statement = connection.prepareStatement(sql); statement.setString(1, username); user = statement.executeQuery(); if (user.next()) { if (password.equals(user.getString("PASSWORD")) && user.getString("TYPE").equalsIgnoreCase("p")) { return true; } } } catch (SQLException e) { e.printStackTrace(); } return false; } /** * Makes prepared statement for Add * * @param user * @param username * @param password * @return */ public boolean preparedAdd(User user, String username, String password) { String sql = "INSERT INTO users VALUES ( Default, ?, ?, ?, ?, ?, ?)"; try { statement = connection.prepareStatement(sql); // statement.setInt(1, user.getId()); statement.setString(1, username); statement.setString(2, password); statement.setString(3, user.getType()); statement.setString(4, user.getFirstName()); statement.setString(5, user.getLastName()); statement.setString(6, user.getEmailAddress()); statement.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Gets administrator password * * @return */ public String getAdminPW() { String sql = "SELECT * FROM users WHERE ID= ?"; ResultSet user; try { statement = connection.prepareStatement(sql); statement.setInt(1, 0); user = statement.executeQuery(); if (user.next()) { return user.getString("PASSWORD"); } } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates prepared statement for add * * @param course * @return */ public boolean preparedAdd(Course course) { // System.out.println("Adding Course"); String sql = "INSERT INTO courses VALUES ( ?, ?, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.setInt(2, course.getProfId()); statement.setString(3, course.getCourseName()); statement.setBoolean(4, course.isActive()); statement.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Creates prepared statement for toggle * * @param course * @return */ public boolean preparedToggle(Course course) { // System.out.println("Adding Course"); String sql = "UPDATE courses SET ACTIVE =? WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setBoolean(1, course.isActive()); statement.setInt(2, course.getCourseId()); statement.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Creates prepared statement for Add * * @param assignment */ public void preparedAdd(Assignment assignment) { String sql = "INSERT INTO assignments VALUES (Default, ?, ?, ?, ?, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, assignment.getCourseId()); statement.setInt(2, assignment.getAssignId()); statement.setString(3, assignment.getTitle()); statement.setString(4, assignment.getPath()); statement.setString(5, assignment.getDueDate()); statement.setBoolean(6, assignment.isActive()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for add * * @param submission */ public void preparedAdd(Submission submission) { String sql = "INSERT INTO submissions VALUES (Default, ?, ?, ?, ?, ?, ?, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, submission.getCourseId()); statement.setInt(2, submission.getAssignId()); statement.setInt(3, submission.getStudentId()); statement.setString(4, submission.getPath()); statement.setInt(5, submission.getGrade()); statement.setString(6, submission.getComment()); statement.setString(7, submission.getTitle()); statement.setString(8, submission.getTimeStamp()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for setting course as active * * @param id * @param active */ public void preparedSetActive(int id, boolean active) { String sql = "UPDATE courses SET ACTIVE = ? WHERE COURSENUMBER = ?"; try { statement = connection.prepareStatement(sql); statement.setBoolean(1, active); statement.setInt(2, id); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for setting assignments as active * * @param a * @param active */ public void preparedSetActive(Assignment a, boolean active) { String sql = "UPDATE assignments SET ACTIVE = ? WHERE COURSENUMBER = ? AND ASSIGNMENTID = ?"; try { statement = connection.prepareStatement(sql); statement.setBoolean(1, active); statement.setInt(2, a.getCourseId()); statement.setInt(3, a.getAssignId()); statement.executeUpdate(); System.out.println("Activated Assignment: " + active); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for setting assignments as due * * @param a * @param date */ public void preparedSetDue(Assignment a, String date) { String sql = "UPDATE courses SET DUEDATE = ? WHERE COURSENUMBER = ?"; try { statement = connection.prepareStatement(sql); statement.setString(1, date); statement.setInt(2, a.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for removing a user * * @param user */ public void preparedRemove(User user) { String sql = "DELETE FROM users WHERE ID=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, user.getId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for removing a course * * @param course */ public void preparedRemove(Course course) { String sql = "DELETE FROM courses WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } sql = "DELETE FROM chats WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } sql = "DELETE FROM assignments WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } sql = "DELETE FROM enrolment WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } sql = "DELETE FROM submissions WHERE COURSENUMBER=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for removing a submission * * @param submission */ public void preparedRemove(Submission submission) { String sql = "DELETE FROM submissions WHERE SID=?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, submission.getId()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates prepared statement for searching users * * @param id * @return */ public Vector<User> preparedSearchUsers(int id) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND ID = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setInt(2, id); ResultSet uset = statement.executeQuery(); while (uset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates prepared statement for searching for users within a course * * @param id * @param coursenumber * @return */ public Vector<User> preparedSearchUsersinCourse(int id, int coursenumber) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND ID = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setInt(2, id); ResultSet uset = statement.executeQuery(); while (uset.next()) { sql = "SELECT * FROM enrolment WHERE USERID = ? AND COURSENUMBER= ?"; statement = connection.prepareStatement(sql); statement.setInt(1, uset.getInt("ID")); statement.setInt(2, coursenumber); ResultSet eset = statement.executeQuery(); if (eset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for searching for users by last name * * @param lastname * @return */ public Vector<User> preparedSearchUsers(String lastname) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND LASTNAME = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setString(2, lastname); ResultSet rset = statement.executeQuery(); while (rset.next()) { results.add(new User(rset.getInt("ID"), rset.getString("firstname"), rset.getString("lastname"), rset.getString("type"), rset.getString("email"))); } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for searching for students * * @param lastname * @param coursenumber * @return */ public Vector<User> preparedSearchUsersinCourse(String lastname, int coursenumber) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND LASTNAME = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setString(2, lastname); ResultSet uset = statement.executeQuery(); while (uset.next()) { sql = "SELECT * FROM enrolment WHERE USERID = ? AND COURSENUMBER= ?"; statement = connection.prepareStatement(sql); statement.setInt(1, uset.getInt("ID")); statement.setInt(2, coursenumber); ResultSet eset = statement.executeQuery(); if (eset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for searching for users * * @param lastname * @param object * @return */ public Vector<User> preparedSearchUsersinCourse(String lastname, Course object) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND LASTNAME = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setString(2, lastname); ResultSet uset = statement.executeQuery(); while (uset.next()) { sql = "SELECT * FROM enrolment WHERE USERID = ? AND COURSENUMBER= ?"; statement = connection.prepareStatement(sql); statement.setInt(1, uset.getInt("ID")); statement.setInt(2, object.getCourseId()); ResultSet eset = statement.executeQuery(); if (eset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for searching for users * * @param object * @return */ public Vector<User> preparedSearchUsersinCourse(Course object) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); ResultSet uset = statement.executeQuery(); while (uset.next()) { sql = "SELECT * FROM enrolment WHERE USERID = ? AND COURSENUMBER= ?"; statement = connection.prepareStatement(sql); statement.setInt(1, uset.getInt("ID")); statement.setInt(2, object.getCourseId()); ResultSet eset = statement.executeQuery(); // System.out.println(eset); if (eset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for searching for users * * @param id * @param object * @return */ public Vector<User> preparedSearchUsersinCourse(int id, Course object) { Vector<User> results = new Vector<User>(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND ID = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "s"); statement.setInt(2, id); ResultSet uset = statement.executeQuery(); while (uset.next()) { sql = "SELECT * FROM enrolment WHERE USERID = ? AND COURSENUMBER= ?"; statement = connection.prepareStatement(sql); statement.setInt(1, uset.getInt("ID")); statement.setInt(2, object.getCourseId()); ResultSet eset = statement.executeQuery(); if (eset.next()) { results.add(new User(uset.getInt("ID"), uset.getString("firstname"), uset.getString("lastname"), uset.getString("type"), uset.getString("email"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for enrolling students * * @param userid * @param courseid */ public void preparedEnrol(int userid, int courseid) { String sql = "INSERT INTO enrolment VALUES (Default, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, userid); statement.setInt(2, courseid); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates a prepared statement for enrolling students * * @param userid * @param course * @return */ public boolean preparedEnrol(int userid, Course course) { Vector<User> vu1 = preparedSearchUsers(userid); // confirm user exists if (vu1.size() != 1) { return false; } Vector<User> vu2 = preparedSearchUsersinCourse(userid, course); // confirm they aren't already enrolled if (vu2.size() != 0) { return false; } String sql = "INSERT INTO enrolment VALUES (Default, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, userid); statement.setInt(2, course.getCourseId()); statement.executeUpdate(); return true; } catch (SQLException e) { e.printStackTrace(); return false; } } /** * Creates a prepared statement for unenrolling students * * @param userid * @param courseid */ public void preparedUnenrol(int userid, int courseid) { String sql = "DELETE FROM enrolment WHERE COURSENUMBER=? AND USERID = ?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, courseid); statement.setInt(2, userid); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates a prepared statement for unenrolling students * * @param userid * @param course */ public void preparedUnenrol(int userid, Course course) { String sql = "DELETE FROM enrolment WHERE COURSENUMBER=? AND USERID = ?"; try { statement = connection.prepareStatement(sql); statement.setInt(1, course.getCourseId()); statement.setInt(2, userid); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates a prepared statement for listing courses * * @param prof * @return */ Vector<Course> listCourses(Professor prof) { String sql = "SELECT * FROM courses WHERE PROFESSORID = " + prof.getId(); try { Vector<Course> listofCourses = new Vector<Course>(); statement = connection.prepareStatement(sql); // statement.setInt(1, prof.getId()); ResultSet course = statement.executeQuery(sql); while (course.next()) { Course temp = new Course(); temp.setActive(course.getBoolean("ACTIVE")); temp.setCourseId(course.getInt("COURSENUMBER")); temp.setCourseName(course.getString("COURSENAME")); temp.setProfId(course.getInt("PROFESSORID")); listofCourses.add(temp); } course.close(); return listofCourses; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing courses * * @param student * @return */ Vector<Course> listCourses(Student student) { Vector<Course> results = new Vector<Course>(); try { String sql = "SELECT * FROM enrolment WHERE USERID = ?"; statement = connection.prepareStatement(sql); statement.setInt(1, student.getId()); ResultSet eset = statement.executeQuery(); while (eset.next()) { sql = "SELECT * FROM courses WHERE COURSENUMBER= ? AND ACTIVE =? ORDER BY COURSENUMBER"; statement = connection.prepareStatement(sql); statement.setInt(1, eset.getInt("COURSENUMBER")); statement.setBoolean(2, true); ResultSet cset = statement.executeQuery(); if (cset.next()) { results.add(new Course(cset.getInt("COURSENUMBER"), cset.getInt("PROFESSORID"), cset.getString("COURSENAME"), cset.getBoolean("ACTIVE"))); } } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared statement for listing assignments in a course * * @param course * @return */ Vector<Assignment> listAssignmentsProf(Course course) { String sql = "SELECT * FROM assignments WHERE COURSENUMBER = " + course.getCourseId(); try { Vector<Assignment> listofAssignments = new Vector<Assignment>(); statement = connection.prepareStatement(sql); // statement.setInt(1, prof.getId()); ResultSet assigns = statement.executeQuery(sql); while (assigns.next()) { Assignment temp = new Assignment(); temp.setCourseId(assigns.getInt("COURSENUMBER")); temp.setAssignId(assigns.getInt("ASSIGNMENTID")); temp.setTitle(assigns.getString("ASSIGNMENTNAME")); temp.setPath(assigns.getString("FILEPATH")); temp.setDueDate(assigns.getString("DUEDATE")); temp.setActive(assigns.getBoolean("ACTIVE")); listofAssignments.add(temp); } assigns.close(); return listofAssignments; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing assignments from a course * * @param courseId * @return */ Vector<Assignment> listAssignmentsProf(int courseId) { String sql = "SELECT * FROM assignments WHERE COURSENUMBER = " + courseId; try { Vector<Assignment> listofAssignments = new Vector<Assignment>(); statement = connection.prepareStatement(sql); // statement.setInt(1, prof.getId()); ResultSet assigns = statement.executeQuery(sql); while (assigns.next()) { Assignment temp = new Assignment(); temp.setCourseId(assigns.getInt("COURSENUMBER")); temp.setAssignId(assigns.getInt("ASSIGNMENTID")); temp.setTitle(assigns.getString("ASSIGNMENTNAME")); temp.setPath(assigns.getString("FILEPATH")); temp.setDueDate(assigns.getString("DUEDATE")); temp.setActive(assigns.getBoolean("ACTIVE")); listofAssignments.add(temp); } assigns.close(); return listofAssignments; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing assignments for a course * * @param course * @return */ Vector<Assignment> listAssignmentsStudent(Course course) { String sql = "SELECT * FROM assignments WHERE ACTIVE=TRUE AND COURSENUMBER=" + course.getCourseId(); try { Vector<Assignment> listofAssignments = new Vector<Assignment>(); statement = connection.prepareStatement(sql); // statement.setInt(1, prof.getId()); ResultSet assigns = statement.executeQuery(sql); while (assigns.next()) { Assignment temp = new Assignment(); temp.setCourseId(assigns.getInt("COURSENUMBER")); temp.setAssignId(assigns.getInt("ASSIGNMENTID")); temp.setTitle(assigns.getString("ASSIGNMENTNAME")); temp.setPath(assigns.getString("FILEPATH")); temp.setDueDate(assigns.getString("DUEDATE")); temp.setActive(assigns.getBoolean("ACTIVE")); listofAssignments.add(temp); } assigns.close(); return listofAssignments; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing courses * * @param profid * @return */ Vector<Course> listCourses(int profid) { String sql = "SELECT * FROM courses WHERE PROFESSORID = " + profid; try { Vector<Course> listofCourses = new Vector<Course>(); statement = connection.prepareStatement(sql); // statement.setInt(1, prof.getId()); ResultSet course = statement.executeQuery(sql); while (course.next()) { Course temp = new Course(); temp.setActive(course.getBoolean("ACTIVE")); temp.setCourseId(course.getInt("COURSENUMBER")); temp.setCourseName(course.getString("COURSENAME")); temp.setProfId(course.getInt("PROFESSORID")); listofCourses.add(temp); } course.close(); return listofCourses; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing submissions for an assignment * * @param assignment * @return */ Vector<Submission> listSubmissions(Assignment assignment) { // System.out.println(assignment.getCourseId()); // System.out.println(assignment.getAssignId()); try { // String sql1 = "SELECT * FROM submissions WHERE ASSIGNMENTID=1 AND // COURSENUMBER=453"; String sql2 = "SELECT * FROM submissions WHERE ASSIGNMENTID=" + assignment.getAssignId() + " AND COURSENUMBER=" + assignment.getCourseId(); Vector<Submission> listofSubmissions = new Vector<Submission>(); statement = connection.prepareStatement(sql2); // statement.setInt(1, assignment.getCourseId()); // statement.setInt(2, assignment.getAssignId()); // System.out.println(sql1); // System.out.println(sql2); ResultSet subs = statement.executeQuery(sql2); while (subs.next()) { Submission temp = new Submission(subs.getInt("SID"), subs.getInt("COURSENUMBER"), subs.getInt("ASSIGNMENTID"), subs.getInt("STUDENTID"), subs.getString("FILEPATH"), subs.getInt("Grade"), subs.getString("COMMENT"), subs.getString("TITLE"), subs.getString("TIMESTAMP"), null); listofSubmissions.add(temp); } subs.close(); return listofSubmissions; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing submissions for an assignment * * @param assignment * @param studentId * @return */ public Vector<Submission> listSubmissions(Assignment assignment, int studentId) { try { String sql = "SELECT * FROM submissions WHERE STUDENTID=" + studentId + " AND COURSENUMBER=" + assignment.getCourseId() + " AND ASSIGNMENTID=" + assignment.getAssignId(); Vector<Submission> listofSubmissions = new Vector<Submission>(); statement = connection.prepareStatement(sql); ResultSet subs = statement.executeQuery(sql); while (subs.next()) { Submission temp = new Submission(subs.getInt("SID"), subs.getInt("COURSENUMBER"), subs.getInt("ASSIGNMENTID"), subs.getInt("STUDENTID"), subs.getString("FILEPATH"), subs.getInt("Grade"), subs.getString("COMMENT"), subs.getString("TITLE"), subs.getString("TIMESTAMP"), null); listofSubmissions.add(temp); } subs.close(); return listofSubmissions; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing submissions * * @param submission * @return */ Vector<Submission> listSubmissions(Submission submission) { try { // String sql1 = "SELECT * FROM submissions WHERE ASSIGNMENTID=1 AND // COURSENUMBER=453"; String sql2 = "SELECT * FROM submissions WHERE ASSIGNMENTID=" + submission.getAssignId() + " AND COURSENUMBER=" + submission.getCourseId(); Vector<Submission> listofSubmissions = new Vector<Submission>(); statement = connection.prepareStatement(sql2); // statement.setInt(1, assignment.getCourseId()); // statement.setInt(2, assignment.getAssignId()); // System.out.println(sql1); // System.out.println(sql2); ResultSet subs = statement.executeQuery(sql2); while (subs.next()) { Submission temp = new Submission(subs.getInt("SID"), subs.getInt("COURSENUMBER"), subs.getInt("ASSIGNMENTID"), subs.getInt("STUDENTID"), subs.getString("FILEPATH"), subs.getInt("Grade"), subs.getString("COMMENT"), subs.getString("TITLE"), subs.getString("TIMESTAMP"), null); listofSubmissions.add(temp); } subs.close(); return listofSubmissions; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing a single student's submissions * * @param submission * @param studentid * @return */ Vector<Submission> listSubmissions(Submission submission, int studentid) { try { String sql2 = "SELECT * FROM submissions WHERE ASSIGNMENTID=" + submission.getAssignId() + " AND COURSENUMBER=" + submission.getCourseId() + " AND STUDENTID=" + studentid; Vector<Submission> listofSubmissions = new Vector<Submission>(); statement = connection.prepareStatement(sql2); // statement.setInt(1, assignment.getCourseId()); // statement.setInt(2, assignment.getAssignId()); // System.out.println(sql1); // System.out.println(sql2); ResultSet subs = statement.executeQuery(sql2); while (subs.next()) { Submission temp = new Submission(subs.getInt("SID"), subs.getInt("COURSENUMBER"), subs.getInt("ASSIGNMENTID"), subs.getInt("STUDENTID"), subs.getString("FILEPATH"), subs.getInt("Grade"), subs.getString("COMMENT"), subs.getString("TITLE"), subs.getString("TIMESTAMP"), null); listofSubmissions.add(temp); } subs.close(); return listofSubmissions; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Finds professor of a course * * @param c * @return */ public Professor findProf(Course c) { Professor results = new Professor(); try { String sql = "SELECT * FROM users WHERE TYPE = ? AND ID = ?"; statement = connection.prepareStatement(sql); statement.setString(1, "p"); statement.setInt(2, c.getProfId()); ResultSet rset = statement.executeQuery(); while (rset.next()) { results = new Professor(rset.getInt("ID"), rset.getString("firstname"), rset.getString("lastname"), rset.getString("EMAIL")); } } catch (SQLException e) { e.printStackTrace(); } return results; } /** * Creates a prepared add statement for a message for the chat * * @param chat */ public void preparedAdd(Chat chat) { String sql = "INSERT INTO chats VALUES (Default, ?, ?, ?)"; try { statement = connection.prepareStatement(sql); statement.setInt(1, chat.getCoursenum()); statement.setString(2, chat.getSender()); statement.setString(3, chat.getMessage()); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Creates a prepared statement for retrieving chat messages * * @param course * @return */ Vector<Chat> listChat(Course course) { try { String sql = "SELECT * FROM chats WHERE COURSENUMBER=" + course.getCourseId(); Vector<Chat> listofChat = new Vector<Chat>(); statement = connection.prepareStatement(sql); ResultSet chats = statement.executeQuery(sql); while (chats.next()) { Chat temp = new Chat(chats.getInt("COURSENUMBER"), chats.getString("SENDER"), chats.getString("MESSAGE")); listofChat.add(temp); } chats.close(); return listofChat; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * Creates a prepared statement for listing chat messages * * @param chat * @return */ Vector<Chat> listChat(Chat chat) { try { String sql = "SELECT * FROM chats WHERE COURSENUMBER=" + chat.getCoursenum(); Vector<Chat> listofChat = new Vector<Chat>(); statement = connection.prepareStatement(sql); ResultSet chats = statement.executeQuery(sql); while (chats.next()) { Chat temp = new Chat(chats.getInt("COURSENUMBER"), chats.getString("SENDER"), chats.getString("MESSAGE")); listofChat.add(temp); } chats.close(); return listofChat; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * prints all items in database to console */ public void preparedprintCourses() { try { String sql = "SELECT * FROM " + coursesTable; statement = connection.prepareStatement(sql); ResultSet course = statement.executeQuery(sql); System.out.println("Courses:"); while (course.next()) { System.out.println(course.getInt("COURSENUMBER") + " " + course.getInt("PROFESSORID") + " " + course.getString("COURSENAME") + " " + course.getBoolean("ACTIVE")); } course.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * prints all items in database to console */ public void preparedprintUsers() { try { String sql = "SELECT * FROM " + usersTable; statement = connection.prepareStatement(sql); ResultSet course = statement.executeQuery(sql); System.out.println("Users:"); while (course.next()) { System.out.println( course.getString("ID") + " " + course.getString("USERNAME") + " " + course.getString("PASSWORD") + " " + course.getString("TYPE") + " " + course.getString("FIRSTNAME") + " " + course.getString("LASTNAME") + " " + course.getString("EMAIL")); } course.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * prints all items in database to console */ public void preparedprintAssignments() { try { String sql = "SELECT * FROM " + assignmentsTable; statement = connection.prepareStatement(sql); ResultSet course = statement.executeQuery(sql); System.out.println("Assignments:"); while (course.next()) { System.out.println(course.getInt("COURSENUMBER") + " " + course.getInt("ASSIGNMENTID") + " " + course.getString("FILEPATH")); } course.close(); } catch (SQLException e) { e.printStackTrace(); } } /** * prints all items in database to console */ public void preparedprintEnrolments() { try { String sql = "SELECT * FROM enrolment"; statement = connection.prepareStatement(sql); ResultSet rset = statement.executeQuery(sql); System.out.println("Enrolments:"); while (rset.next()) { System.out.println(rset.getInt("ENROLMENTID") + " " + rset.getInt("USERID") + " " + rset.getString("COURSENUMBER")); } rset.close(); } catch (SQLException e) { e.printStackTrace(); } } // ~~~~~~~~~~~~~FOR_TESTING~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ public static void main(String args[]) { DatabaseHelper masterDB = new DatabaseHelper(); Assignment a = new Assignment(1, 453, "Boolean Logic", "A1.txt", true, "Today", null); Vector<Submission> v = masterDB.listSubmissions(a); System.out.println(v); Course c = new Course(453, 1, "", true); Vector<Assignment> av = masterDB.listAssignmentsStudent(c); String s = masterDB.getAdminPW(); try { System.out.println(s); System.out.println(s.equals("adminPW")); } catch (NullPointerException n) { n.printStackTrace(); } /* * System.out.println(); * System.out.println("Reading all courses from the table:"); * masterDB.preparedprintCourses(); * * System.out. * println("\nSearching table for course 409: should return 'SoftwareDesign'"); * int courseID = 409; Course searchResult = * masterDB.preparedsearchCourses(courseID); if (searchResult == null) * System.out.println("Search Failed to find a course matching ID: " + * courseID); else System.out.println("Search Result: " + * searchResult.getCourseName()); * * System.out. * println("Searching table for course 441: should fail to find a course"); * courseID = 441; searchResult = masterDB.preparedsearchCourses(courseID); if * (searchResult == null) * System.out.println("Search Failed to find a course matching ID: " + * courseID); else System.out.println("Search Result: " + * searchResult.getCourseName()); System.out.println(); * * System.out.println(); System.out.println("Trying to add course 200."); Course * design = new Course(200, 3, "EnggDesign", false); * masterDB.preparedAdd(design); masterDB.preparedprintCourses(); * System.out.println(); System.out.println("Trying to remove course 200."); * masterDB.preparedRemove(design); masterDB.preparedprintCourses(); * * System.out.println(); System.out.println("Trying to set 225 active"); * masterDB.preparedSetActive(225, true); masterDB.preparedprintCourses(); * System.out.println(); System.out.println("Trying to set 225 inactive"); * masterDB.preparedSetActive(225, false); masterDB.preparedprintCourses(); * * System.out.println("\nThe program is finished running through the courses"); * System.out.println(); System.out.println(); * * System.out.println("Reading all users from the table:"); * masterDB.preparedprintUsers(); * * System.out.println(); System.out.println("Student Logins"); * System.out.println("Trying to login as Will. Should succeed:"); if * (masterDB.isValidStudentLogin("will", "pw")) { * System.out.println("Successful login"); } else { * System.err.println("Failed login"); } * * System.out.println("Trying to login as David. Should fail:"); if * (masterDB.isValidStudentLogin("dave", "asdf")) { * System.out.println("Successful login"); } else { * System.out.println("Failed login"); } * * System.out.println(); System.out.println("Professor Logins"); * System.out.println("Trying to login as Will. Should fail:"); if * (masterDB.isValidProfLogin("will", "pw")) { * System.out.println("Successful login"); } else { * System.out.println("Failed login"); } * * System.out.println("Trying to login as Norm. Should Succeed:"); if * (masterDB.isValidProfLogin("norm", "42")) { * System.out.println("Successful login"); } else { * System.out.println("Failed login"); } System.out.println(); * System.out.println("Trying to add user David."); User dave = new User(10, * "David", "Parkin", "S", "dparkin@test.com"); masterDB.preparedAdd(dave, * "dparkin", "pass"); masterDB.preparedprintUsers(); System.out.println(); * System.out.println("Trying to remove user David."); * masterDB.preparedRemove(dave); masterDB.preparedprintUsers(); * * System.out.println(); * System.out.println("Searching for Student 2. Should Return Will Ehman"); * Vector<User> result = masterDB.preparedSearchUsers(2); * System.out.println(result.get(0).toString()); System.out.println(); * System.out. * println("Searching for Students with last name Ehman. Should return 2 results" * ); result = masterDB.preparedSearchUsers("Ehman"); for (int i = 0; i < * result.size(); i++) { System.out.println(result.get(i).toString()); } * System.out. * println("Searching for Students with last name Ehman in 409. Should return 2 results" * ); result = masterDB.preparedSearchUsersinCourse("Ehman", 409); for (int i = * 0; i < result.size(); i++) { System.out.println(result.get(i).toString()); } * System.out. * println("Searching for Students with last name Ehman in 453. Should return 1 result" * ); result = masterDB.preparedSearchUsersinCourse("Ehman", 453); for (int i = * 0; i < result.size(); i++) { System.out.println(result.get(i).toString()); } * * System.out.println("\nThe program is finished running through the users"); * * System.out.println(); * * System.out.println("Reading all enrolments from the table:"); * masterDB.preparedprintEnrolments(); * * System.out.println("Enrolling Will in 453"); masterDB.preparedEnrol(2, 453); * masterDB.preparedprintEnrolments(); * * System.out.println("Unenrolling Will in 453"); masterDB.preparedUnenrol(2, * 453); masterDB.preparedprintEnrolments(); * * System.out.println(); * * System.out.println("Reading all assignments from the table:"); * masterDB.preparedprintAssignments(); */ try { masterDB.statement.close(); masterDB.connection.close(); } catch (SQLException e) { e.printStackTrace(); } finally { System.out.println("\nThe program is finished running through the Database"); } } }
true
769a9c0d20825c74388c19dd88cd11ab1bef4414
Java
black82/RabbitMQBaseConfig
/api_service/src/main/java/com/ecabs/model/Booking.java
UTF-8
1,096
2.09375
2
[]
no_license
package com.ecabs.model; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.deser.std.UUIDDeserializer; import com.fasterxml.jackson.databind.ser.std.UUIDSerializer; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.math.BigDecimal; import java.time.Instant; import java.time.OffsetDateTime; import java.util.List; import java.util.UUID; @Data @AllArgsConstructor @NoArgsConstructor public class Booking { @JsonSerialize(using = UUIDSerializer.class) @JsonDeserialize(contentUsing = UUIDDeserializer.class) private UUID bookingId; private String passengerName; private String passengerContactNumber; private OffsetDateTime pickupTime; private Boolean asap; private Integer waitingTime; private Integer noOfPassengers; private BigDecimal price; private Integer rating; private Instant createdOn; private Instant lastModifiedOn; private List<TripWaypoint> tripWayPoints; }
true
a50b7449864958a7db657f626ac075e0760f47fb
Java
Elen13/GraphTests
/Tester2/src/modules/LinearComplexity.java
UTF-8
2,964
2.421875
2
[]
no_license
package modules; import graphs.BaseGroup; import graphs.LinearGraph; import java.io.IOException; import java.util.ArrayList; import javax.swing.JPanel; import javax.xml.stream.XMLStreamException; import report.HTMLReportArchive; import sequence.Sequence; public class LinearComplexity extends AbstractQCModule{ private byte[] b, c, t, s; private int N; private int L; private int m; int[] arrL = new int[0]; public int getMax(int [] arr){ int max = 0; for(int i = 0; i < arr.length; i++){ if(arr[i] > max) max = arr[i]; } return max; } public void BerlekampRegistryTester(ArrayList<Integer> binSq) { b = new byte[binSq.size()]; c = new byte[binSq.size()]; t = new byte[binSq.size()]; s = new byte[binSq.size()]; for(int i = 0; i < s.length;i++){ s[i] = binSq.get(i).byteValue(); b[i] = c[i] = t[i] = 0; } /*for (int i = 0; i < binSq.size(); i++) b[i] = c[i] = t[i] = 0;*/ b[0] = c[0] = 1; N = L = 0; m = -1; } public void processSequence(Sequence sequence) { String bsq = sequence.getSequence(); ArrayList<Integer> binSq = new ArrayList<Integer>();//Series.sqToBin(sq, cap); for(int i = 0; i < bsq.length(); i++){ int i1 = Character.getNumericValue(bsq.charAt(i)); binSq.add(i1); } BerlekampRegistryTester(binSq); arrL = new int[binSq.size()]; int d; while (N < s.length) { d = 0; for (int i = 0; i <= L; i++) d += s[N-i] * c[i]; d = d % 2; if (d != 0) { t = (byte[])c.clone(); for (int i = 0; i <= s.length + m - 1 - N; i++) c[N - m + i] = (byte)(c[N - m + i] ^ b[i]); if (L <= (N / 2)) { L = N + 1 - L; m = N; b = (byte[])t.clone(); } } arrL[N] = L; N++; } } public JPanel getResultsPanel() { return new LinearGraph(arrL, 0d, getMax(arrL) + 1, "Профиль линейной сложности"); } public String name() { return "Профиль линейной сложности"; } public String description() { return "Исследование последовательности на случайность, анализируя зависимость линейной сложности последовательности от ее длины."; } public void reset() { arrL = new int[0]; b = new byte[0]; c = new byte[0]; t = new byte[0]; s = new byte[0]; } public boolean raisesError() { return false; } public boolean raisesWarning() { return false; } public boolean ignoreFilteredSequences() { return true; } public boolean ignoreInReport() { return false; } @Override public void makeReport(HTMLReportArchive report) throws XMLStreamException, IOException { // TODO Auto-generated method stub } }
true
4b7cee865e2a2502404d82aff4704b2db4fc4cbb
Java
vasiliilantratov/Gallery
/app/src/main/java/com/yad/vasilii/gallery/presentation/mvp/global/BasePresenter.java
UTF-8
451
1.890625
2
[]
no_license
package com.yad.vasilii.gallery.presentation.mvp.global; import com.arellomobile.mvp.*; import io.reactivex.disposables.*; public class BasePresenter<View extends MvpView> extends MvpPresenter<View> { protected CompositeDisposable mDisposables; public BasePresenter() { mDisposables = new CompositeDisposable(); } @Override public void onDestroy() { super.onDestroy(); mDisposables.dispose(); } }
true
956427c5efba7add9407ddfed31730da7aef508b
Java
LGCMcLovin/SkillAPI
/SkillAPI/src/com/sucy/skill/mechanic/DamagePercentMechanic.java
UTF-8
2,174
3.03125
3
[]
no_license
package com.sucy.skill.mechanic; import com.sucy.skill.api.DamageModifier; import com.sucy.skill.api.PlayerSkills; import com.sucy.skill.api.dynamic.DynamicSkill; import com.sucy.skill.api.dynamic.IMechanic; import com.sucy.skill.api.dynamic.Target; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import java.util.List; /** * Mechanic for granting percentage bonus damage */ public class DamagePercentMechanic implements IMechanic { private static final String PERCENT = "Percent", DURATION = "Percent Duration"; /** * Grants a temporary damage bonus to the targets * * @param player player using the skill * @param data data of the player using the skill * @param skill skill being used * @param target target type of the skill * @param targets targets for the effects * @return true if was able to use */ @Override public boolean resolve(Player player, PlayerSkills data, DynamicSkill skill, Target target, List<LivingEntity> targets) { // Requires a target if (targets.size() == 0) return false; // Get attributes int level = data.getSkillLevel(skill.getName()); double bonus = skill.getAttribute(PERCENT, target, level); double duration = skill.getAttribute(DURATION, target, level); // Add damage modifiers for (LivingEntity entity : targets) { data.getAPI().getStatusHolder(entity).addDamageModifier(new DamageModifier(1 + bonus / 100, (int)(duration * 1000))); } return true; } /** * Applies default values for the mechanic attributes * * @param skill skill to apply to * @param prefix prefix to add to the attribute */ @Override public void applyDefaults(DynamicSkill skill, String prefix) { skill.checkDefault(prefix + PERCENT, 10, 5); skill.checkDefault(prefix + DURATION, 5, 0); } /** * @return names of the attributes used by the mechanic */ @Override public String[] getAttributeNames() { return new String[] { PERCENT, DURATION }; } }
true
241efc92491565061b5c178cfbbac0e70adc0f89
Java
ferhatarkan/finalProjectHrms
/src/main/java/finalproject/hrms/api/controllers/ImagesController.java
UTF-8
453
2.015625
2
[]
no_license
package finalproject.hrms.api.controllers; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import finalproject.hrms.business.abstracts.ImageService; @RestController @RequestMapping("/api/images") public class ImagesController { private ImageService imageService; public ImagesController(ImageService imageService) { super(); this.imageService = imageService; } }
true
da6e289115034026eaec9548e5283e59f03297ea
Java
forubaby/MyJavaProgrames
/Sbi.java
UTF-8
305
2.59375
3
[]
no_license
package javapgms; public class Sbi extends Rbi { public void minbal() { System.out.println("5000"); } public void rateofint() { System.out.println("20%"); } } class Cust { public static void main(String[] args) { Sbi s=new Sbi(); s.minbal(); s.rateofint(); } }
true
dfeb72e07a7fd99b80daf8ce6d1243f17eb8d704
Java
Najix-1999/Najix
/HelloWorld/src/HelloJavaApp.java
UTF-8
222
2.671875
3
[]
no_license
/** HelloJavaApp.java */ import java.applet.Applet; import java.awt.Graphics; public class HelloJavaApp extends Applet{ public void paint(Graphics g){ g.drawString("Hfdello, Java Applet World !",50,25); } }
true
29170e6fb2e55eed9ae72f4e432c17cb3388eecc
Java
bokimilinkovic/xml-web-services
/api-gateway/src/main/java/team10/apigateway/config/GlobalPreFilter.java
UTF-8
2,891
1.96875
2
[]
no_license
package team10.apigateway.config; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; import team10.apigateway.dto.UserAuthInfo; import java.util.List; @Component public class GlobalPreFilter implements GlobalFilter { @Autowired DiscoveryClient discoveryClient; @Override public Mono<Void> filter( ServerWebExchange exchange, GatewayFilterChain chain) { ServerHttpRequest mutatedRequest; try { String header = exchange.getRequest().getHeaders().get(JwtProperties.HEADER).get(0); if (header.contains("MASTER")) { List<String> services = discoveryClient.getServices(); for (String service : services) { if (exchange.getRequest().getRemoteAddress().getAddress().getHostAddress().equals(discoveryClient.getInstances(service).get(0).getHost())) { return chain.filter(exchange); } } } String username = JWT.require(Algorithm.HMAC512(JwtProperties.SECRET.getBytes())) .build() .verify(header.replace(JwtProperties.TOKEN_PREFIX, "")) .getSubject(); String userServiceIp = discoveryClient.getInstances("user").get(0).getHost(); HttpHeaders headers = new HttpHeaders(); headers.add(JwtProperties.HEADER, "NONE;MASTER"); HttpEntity<String> entity = new HttpEntity<>("body", headers); ResponseEntity<UserAuthInfo> userAuthInfo = new RestTemplate().exchange("http://" + userServiceIp + ":8080/util/auth/" + username, HttpMethod.GET, entity, UserAuthInfo.class, new Object()); mutatedRequest = exchange.getRequest().mutate().header(JwtProperties.HEADER, username + ";" + userAuthInfo.getBody().getAuthorities()).build(); } catch (Exception e) { mutatedRequest = exchange.getRequest().mutate().header(JwtProperties.HEADER, "NONE;NONE").build(); } ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build(); return chain.filter(mutatedExchange); } }
true
791866788d5c455d4531b3ea421fd12e1f9075db
Java
ralischer/VSS-HM
/Prak4_4/src/edu/hm/vss/prak/rmi/rms/RemoteMethodService.java
UTF-8
6,338
3.03125
3
[]
no_license
package edu.hm.vss.prak.rmi.rms; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.Socket; import java.net.UnknownHostException; import edu.hm.vss.prak.rmi.rms.exceptions.ClassUnboundException; public class RemoteMethodService { private String serverAddress; private int serverPort; private static Server server = null; private final static RemoteMethodService instance = new RemoteMethodService(); private RemoteMethodService() { }; /** * Factory Methode um einen Server zu erstellen. * * @param port * Port auf dem der Server laufen soll. * @return die Serverinstanz. * @throws IOException * falls Port bereits belegt oder andere IOExceptions auftreten. */ public static Server getServerInstance(int port) throws IOException { if (server == null) { server = new Server(port); } return server; } /** * Liefert die Instanz des RemoteMethodService. * * @param serverAddress * die Adresse auf dem Server erreichbar ist. * @param serverPort * der Port auf dem Server läuft. * @return die Instanz des RemoteMethodServices. * @throws UnknownHostException * falls Host nicht gefunden wurde. * @throws IOException */ public static RemoteMethodService getInstance(String serverAddress, int serverPort) throws UnknownHostException, IOException { instance.serverAddress = serverAddress; instance.serverPort = serverPort; return instance; } /** * Ist für die Kommunikation mit dem Server zuständig. Jedes Object hat eine * eigene Client-Instanz. * * @author Reinhard Alischer * */ static class Client { private final Socket socket; private ObjectOutputStream objectOutputStream; private ObjectInputStream objectInputStream; public Client(String serverAddress, int serverPort) throws UnknownHostException, IOException { socket = new Socket(serverAddress, serverPort); objectOutputStream = new ObjectOutputStream( socket.getOutputStream()); } /** * Prüft ob bei Server eine Implementierung zu einem bestimmten * Interface gefunden wurde. * * @param clazz * interface das verwendet werden soll. * @return true falls auf dem Server eine implementierung existiert, * false andernfalls. */ public boolean isClassAvailable(Class<?> clazz) { RequestWrapper request = new RequestWrapper(); request.requestType = RequestType.CLASS; request.requestName = clazz.getName(); request.params = new Integer[0]; try { objectOutputStream.writeObject(request); objectOutputStream.flush(); return socket.getInputStream().read() == 1; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Leitet einen Methodenaufruf zum Server weiter und liefert das * Ergebnis zurück. * * @param method * Methode die ausgeführt werden soll. * @param args * die Pramater der Methode. * @return das Ergebnis der Methode - kann Void.Type liefern falls die * Methode keinen Rückgabewert hat. * @throws Throwable */ public Object invokeMethod(Method method, Object[] args) throws Throwable { RequestWrapper request = new RequestWrapper(); request.requestType = RequestType.METHOD; request.requestName = method.getName(); if (args == null) request.params = new Integer[0]; else request.params = args; objectOutputStream.writeObject(request); objectOutputStream.flush(); if (objectInputStream == null) { objectInputStream = new ObjectInputStream( socket.getInputStream()); } Object respone = objectInputStream.readObject(); if(respone instanceof Throwable) { throw (Throwable) respone; } return respone; } /** * Terminiert den Client - auch Serverseitig. */ public void terminate() { System.out.println("going to terminate"); try { socket.close(); } catch (IOException ignored) { } } } /** * Klasse die die Methoden aufrufe der Client-Stubs entgegen nimmt. * * @author reini * */ private class ClientInvocationHandler implements InvocationHandler { private final Client client; public ClientInvocationHandler(Client client) { this.client = client; } /** * Wird für jede Methode die auf dem Client-Stub aufgerufen wird * ausgeführt. */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /** * Die Methode finalize sollte vom Garbage-Collector aufgerufen * werden falls ein Objekt nicht mehr referenziert wird und dann aus * dem Speicher gelöscht wird. */ if (method.getName().equals("finalize")) { client.terminate(); method.invoke(proxy, args); return Void.TYPE; } /** * Alle Methoden werden zum Server weitergeleitet. */ return client.invokeMethod(method, args); } } /** * Erstellt Client-seitig einen Stub des Interfaces das übergeben wird. * * @param clazz * das interface das auf dem Server Verfügbar sein soll. * @return ein Proxy/Stub Objekt welches die Methodenaufrufe des Client zum * Server weiterleitet. * @throws ClassUnboundException * falls zum Interface auf dem Server keine Implementierung * existiert. * @throws UnknownHostException * - falls der angegebene Host der bei der Erstellung des * RemoteMethodService angegeben wurde nicht gefunden wurde. * @throws IOException */ @SuppressWarnings("unchecked") public <T> T getInstace(Class<T> clazz) throws ClassUnboundException, UnknownHostException, IOException { Client client = new Client(serverAddress, serverPort); if (client.isClassAvailable(clazz)) return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, new ClientInvocationHandler(client)); else throw new ClassUnboundException(); } }
true
2cd2fdc9293a9fa68867fbc646edcf45da40eaa8
Java
sunlight701/Fizzle
/libringclient/src/main/java/ch/seme/account/LinkDevicePresenter.java
UTF-8
2,968
1.851563
2
[]
no_license
/* * Copyright (C) 2004-2020 Savoir-faire Linux Inc. * * Author: Alexandre Lision <alexandre.lision@savoirfairelinux.com> * Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.seme.account; import java.net.SocketException; import javax.inject.Inject; import javax.inject.Named; import ch.seme.model.Account; import ch.seme.mvp.RootPresenter; import ch.seme.services.AccountService; import io.reactivex.Scheduler; public class LinkDevicePresenter extends RootPresenter<ch.seme.account.LinkDeviceView> { private static final String TAG = LinkDevicePresenter.class.getSimpleName(); private AccountService mAccountService; private String mAccountID; @Inject @Named("UiScheduler") protected Scheduler mUiScheduler; @Inject public LinkDevicePresenter(AccountService accountService) { mAccountService = accountService; } public void startAccountExport(String password) { if (getView() == null) { return; } getView().showExportingProgress(); mCompositeDisposable.add(mAccountService .exportOnRing(mAccountID, password) .observeOn(mUiScheduler) .subscribe(pin -> getView().showPIN(pin), error -> { getView().dismissExportingProgress(); if (error instanceof IllegalArgumentException) { getView().showPasswordError(); } else if (error instanceof SocketException) { getView().showNetworkError(); } else { getView().showGenericError(); } })); } public void setAccountId(String accountID) { mCompositeDisposable.clear(); mAccountID = accountID; ch.seme.account.LinkDeviceView v = getView(); Account account = mAccountService.getAccount(mAccountID); if (v != null && account != null) v.accountChanged(account); mCompositeDisposable.add(mAccountService.getObservableAccountUpdates(mAccountID) .observeOn(mUiScheduler) .subscribe(a -> { LinkDeviceView view = getView(); if (view != null) view.accountChanged(a); })); } }
true
4a8ead24b14c05d75025bb2f38a9aa60be36de72
Java
AnonymousAmigo32/My-CP
/Archive/2018.08/2018.08.08 - unsorted/TheRank.java
UTF-8
1,230
3.3125
3
[]
no_license
package CodeForces; import FastIO.InputReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Comparator; public class TheRank { public void solve(int testNumber, InputReader in, PrintWriter out) { int size = in.nextInt(); Student[] arr = new Student[size]; Student req = new Student(in.nextInt()+in.nextInt()+in.nextInt()+in.nextInt(),0); arr[0]=req; for (int i=1;i<size;i++) arr[i]=new Student(in.nextInt()+in.nextInt()+in.nextInt()+in.nextInt(),i); Arrays.sort(arr,new Comp()); out.println(Arrays.binarySearch(arr,req)+1); } static class Student implements Comparable<Student>{ int tot; int id; public Student(int tot,int id){ this.id=id; this.tot=tot; } @Override public int compareTo(Student o) { if(o.tot==tot) return id-o.id; return o.tot-tot; } } static class Comp implements Comparator<Student>{ @Override public int compare(Student o1, Student o2){ if(o1.tot==o2.tot) return o1.id-o2.id; return o2.tot-o1.tot; } } }
true
3a104d46c1cc105d0d5265ae000fd2f2af65c328
Java
yanxin5611598/mydesign_android
/app/src/main/java/com/yx/aircheck/utils/DBUtil.java
UTF-8
984
2.109375
2
[]
no_license
package com.yx.aircheck.utils; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * SQLite数据库连接*/ public class DBUtil extends SQLiteOpenHelper{ private static final String insertSQL = "create table IF NOT EXISTS checkResult(id integer primary key autoincrement,"+ "tem text,hum text,choh text,pm25 text,pm10 text,range text,username text,gpsinfo text,deviceID text," + "time timestamp not null default (datetime('now','localtime')))"; private static final String db_name = "db_check_data"; public DBUtil(Context context) { super(context, db_name,null,1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(insertSQL); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
true
1500e25b70a50756aa9812101e3887018c6ea06b
Java
kou1miyazaki/play-system-fusion
/app/forms/cmn/SystemFusionForm.java
UTF-8
2,460
2.84375
3
[ "Apache-2.0" ]
permissive
package forms.cmn; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import consts.cmn.CommonConstraint; import play.data.validation.ValidationError; /** * * SystemFusionフォーム. * * @since 2016/11/21 * @author kou1miyazaki * @version 1.0 * */ public abstract class SystemFusionForm { /** ノート. */ public String note; /** 作成者. */ public String createUser; /** 作成日. */ public String createDate; /** 最終更新者. */ public String updateUser; /** 最終更新日. */ public String updateDate; /** コンストラクタ. */ public SystemFusionForm() { } /** * * 値チェック. * * @return List * */ public abstract List<ValidationError> validate(); /** * * 詳細アイテムを取得する. * * @return List * */ public final List<ItemForm> getItemRecord() { // リスト作成. List<ItemForm> item = new ArrayList<ItemForm>(); IntStream.range(0, CommonConstraint.C_ITEM_DETAIL.size()) .forEach(i -> { try { item.add( new ItemForm(CommonConstraint.C_ITEM_DETAIL.get(i), CommonConstraint.C_ITEM_TYPE.get(i), CommonConstraint.C_ITEM_DISPLAY.get(i), CommonConstraint.C_ITEM_LABEL.get(i) //, //(String) this.getClass().getDeclaredField(CommonConstraint.C_ITEM_DETAIL.get(i)).get(this) ) ); } catch (IllegalArgumentException e) { e.printStackTrace(); // } catch (IllegalAccessException e) { // e.printStackTrace(); // } catch (NoSuchFieldException e) { // e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } } ); item.get(0).value = this.note; item.get(1).value = this.createUser; item.get(2).value = this.createDate; item.get(3).value = this.updateUser; item.get(4).value = this.updateDate; return item; } /** * * 文字列へ変換. * * @return String * */ @Override public final String toString() { StringBuilder sb = new StringBuilder(); sb.append("Class: " + this.getClass().getCanonicalName() + "\n"); sb.append("Settings:\n"); for (Field field : this.getClass().getDeclaredFields()) { try { field.setAccessible(true); sb.append(field.getName() + " = " + field.get(this) + "\n"); } catch (IllegalAccessException e) { sb.append(field.getName() + " = " + "access denied\n"); } } return sb.toString(); } }
true
33c8e15eae9a56ea120f305f7f04079c288e06b1
Java
HelenaAnufrieva/Task8
/src/java15/entity/exceptions/TapeIsEnded.java
UTF-8
164
1.835938
2
[]
no_license
package java15.entity.exceptions; public class TapeIsEnded extends RegisterExceptions { public TapeIsEnded(String message) { super(message); } }
true
26baacb4fb9bcb7f87daf47c6313b9e70a2dc593
Java
HexNationCode/discordghostfindingbot
/src/main/java/org/spoopy/commands/Start.java
UTF-8
247
1.820313
2
[]
no_license
package org.spoopy.commands; import org.javacord.api.event.message.MessageCreateEvent; public class Start { public static void run(MessageCreateEvent event) { event.getChannel().sendMessage("Whoo, the interface works!"); } }
true
79eef258bf6e2babeb75ef2bc62c574ad42a4e66
Java
Tournamanager/api
/src/main/java/com/fontys/api/repositories/TournamentRepository.java
UTF-8
412
2.015625
2
[]
no_license
package com.fontys.api.repositories; import com.fontys.api.entities.Tournament; import com.fontys.api.entities.User; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; import java.util.Optional; public interface TournamentRepository extends JpaRepository<Tournament, Integer> { Optional<Tournament> findByName(String name); List<Tournament> findByOwner(User user); }
true
222138bfdebb8a00e5a76b230d22a0694f2864b9
Java
wololo1993/Oware
/src/oware/game/Main.java
UTF-8
6,062
3.3125
3
[]
no_license
package oware.game; public class Main { //private int[][] board = {{4,4,4,4,4,4},{4,4,4,4,4,4}}; // normales spielBrett private int[][] board = {{1,0,2,5,0,3},{0,0,0,0,0,1}}; // board zum debuggen spezielle züge etc public int[] stonesP = {0, 0}; // die Gewonnen steine im spiel public boolean finished = false; public boolean forcedPlay = false; /** * Debugging lebt wuhu * @param args */ public static void main(String[] args) { Main main = new Main(); System.out.println(main); System.out.println("Next Turn Possible :"+main.saveTurnPossible(main.board,1)); System.out.println(main); } /** * \_(ツ)_/¯ */ public Main() { } /** * gibt das spielfeld schön aus * @return */ @Override public String toString() { String s = ""; for (int i = 0; i < board.length; i++) { if (i == 0) { for (int j = board[i].length - 1; j >= 0; j--) { //moonwalk s = s + "[" + board[i][j] + "]"; } } else { for (int j = 0; j < board[i].length; j++) { s = s + "[" + board[i][j] + "]"; } } s = s + "\n"; } return s; } /** * Das hier macht den Zug :) * @param i int stelle im arry 0 <= i <= 5 * @param player int Spieler 1||0 */ public void makeTurn(int i, int player) { //take stones int playerGhost = player; int iGhost = i; int stones = board[playerGhost][iGhost]; board[playerGhost][iGhost] = 0; while (stones > 0) { iGhost++; //wichtig zuerst hochzählen \_(ツ)_/¯ if (iGhost >= board[playerGhost].length) { //Spiel Seitenwechsel playerGhost = playerGhost ^ 1; iGhost = 0; } if (playerGhost == player && iGhost == i) { //Stelle wo man Steine entnommen hat iGhost++; } else { board[playerGhost][iGhost] += 1 ; stones--; } } System.out.println("Prüfe ob stehlbar"); //Solange auf Gegnerseite && steine = 3 || 2 nimm steine und gehe eins zurück dann nochmal prüfen etc while (iGhost >= 0 && iGhost < 6 && playerGhost != player && (board[playerGhost][iGhost] == 2 || board[playerGhost][iGhost] == 3)) { System.out.println("Stehle STeine"); stonesP[player] += board[playerGhost][iGhost]; board[playerGhost][iGhost] = 0; iGhost--; } finished(); } private boolean finished() { boolean finished = false; System.out.println("Prüfe ob finished"); System.out.println(""); for (int i = 0; i < board.length; i++) { if (countPlayersBoardStones(i) == 0 && !saveTurnPossible(board,i^1)) { finished = true; this.finished = true; System.out.println("Should be Ended"); } } return finished; } /** * nächster zug möglich ? * @return */ private boolean checkNextPossible(int player) { boolean possible = false; return possible; } /** * iteriert das feld des spielers und gibt Steine auf seiner Seite zurück * @param player int * @return int Steine auf player Seite */ private int countPlayersBoardStones(int player) { int count = 0; for (int i : board[player]) { count += i; } return count; } /** * Gibt ein neues "board" int[] zurück damit keine verlinkungen entstehen * @return int[] */ public int[] getField() { int[] ret = new int[12]; int c = 0; for (int i = 0; i < board.length; i++) { if (i == 0) { for (int j = board[i].length - 1; j >= 0; j--) { ret[c] = board[i][j]; c++; } } else { for (int j = 0; j < board[i].length; j++) { ret[c] = board[i][j]; c++; } } } return ret; } /** * setzt das ganze feld auf 4 */ public void resetField(){ for(int i = 0; i < board.length; i++){ for(int j = 0; j < board[i].length; j++){ board[i][j] = 4; } } } /** * setzt alles auf Anfang */ public void resetGame(){ resetField(); stonesP[0] = 0; stonesP[1] = 0; finished = false; } public boolean saveTurnPossible(int[][] board, int player){ boolean ret = false; int [] turns = getSaveTurns(player); for(int i = 0; i < turns.length; i++){ if (turns[i] == 0){ ret = true; forcedPlay = true; } } return ret; } /** * 0 if turn at i is possible * -1 if not possible * @param player * @return */ public int[] getSaveTurns(int player){ int[] ret = {-1,-1,-1,-1,-1,-1}; int zuZiehen; for(int i = 0; i < board[player].length; i++){ zuZiehen = Math.abs(i-6); if(zuZiehen <= board[player][i]){ ret[i] = 0; } } for(int i : ret ){ System.out.println(i); } return ret; } public void collectAll(){ for(int i = 0; i < board.length ; i++){ for(int j = 0; j < board[i].length; j++){ stonesP[i] += board[i][j]; board[i][j] = 0; } } } public void clearBoard(){ for(int i = 0; i < board.length ; i++){ for(int j = 0; j < board[i].length; j++){ board[i][j] = 0; } } } }
true
11f52054542e1b9529874559385145b17643b7b7
Java
kmiloramirez/vacaciones
/src/main/java/dominio/dto/SolicitudVacacionesDTO.java
UTF-8
895
2.1875
2
[]
no_license
package dominio.dto; import java.util.Calendar; import java.util.Date; public class SolicitudVacacionesDTO { public Calendar fechaInicial; public Calendar fechaFinal; public String jefeInmediato; public Date fechaInicio; public Date fechaFin; public Calendar getFechaInicial() { return fechaInicial; } public Calendar getFechaFinal() { return fechaFinal; } public String getJefeInmediato() { return jefeInmediato; } public void setFechaInicial(Calendar fechaInicial) { this.fechaInicial = fechaInicial; } public void setFechaFinal(Calendar fechaFinal) { this.fechaFinal = fechaFinal; } public Date getFechaInicio() { return fechaInicio; } public Date getFechaFin() { return fechaFin; } public void setFechaInicio(Date fechaInicio) { this.fechaInicio = fechaInicio; } public void setFechaFin(Date fechaFin) { this.fechaFin = fechaFin; } }
true
51b190bfdeea5fd9cfb17a04ad7a8fa237db0bcb
Java
aspineon/spring-integration-training
/Lab03/src/main/java/pl/training/integration/lab03/Entry.java
UTF-8
1,917
2.75
3
[]
no_license
package pl.training.integration.lab03; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import java.io.Serializable; @XmlAccessorType(XmlAccessType.FIELD) @XmlType public class Entry implements Serializable { private Long id; @XmlElement(name = "nazwa_waluty") private String currency; @XmlElement(name = "kod_waluty") private String code; @XmlElement(name = "kurs_sredni") private double value; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public String getCurrency() { return currency; } public String getCode() { return code; } public double getValue() { return value; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Entry entry = (Entry) o; if (Double.compare(entry.value, value) != 0) return false; if (currency != null ? !currency.equals(entry.currency) : entry.currency != null) return false; return code != null ? code.equals(entry.code) : entry.code == null; } @Override public int hashCode() { int result; long temp; result = currency != null ? currency.hashCode() : 0; result = 31 * result + (code != null ? code.hashCode() : 0); temp = Double.doubleToLongBits(value); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public String toString() { return "Entry{" + "id=" + id + ", currency='" + currency + '\'' + ", code='" + code + '\'' + ", value=" + value + '}'; } }
true
6d783deb1f675526e35c55fdb1a7886a6c545e69
Java
xiaobu1994/ssh
/src/main/java/com/example/base/service/BaseServiceImpl.java
UTF-8
6,298
2.28125
2
[]
no_license
package com.example.base.service; import com.example.base.entity.vo.PageFinder; import com.example.base.entity.vo.QueryBuilder; import com.example.base.repository.BaseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; /** * @author xiaobu * @version JDK1.8.0_171 * @date on 2018/11/15 11:31 * @description V1.0 */ public abstract class BaseServiceImpl<T extends Serializable, ID extends Serializable> implements BaseService<T, ID> { @Autowired private BaseRepository<T, ID> baseRepository; private String getTName() { /* * this.getClass().getSuperClass()和this.getClass().getGenericSuperclass()的区别 * 都是获得本类的父类,假设this.getClass()是test<T> * 则this.getClass().getSuperClass()的结果是Test * 则this.getClass().getGenericSuperclass()的结果是Test<T> */ Type genType = getClass().getGenericSuperclass(); //getActualTypeArguments()就是获取泛型参数的类型,比如Test<T>,最后就得到T类型 Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); Object entityClass = (Object) params[0]; String name = entityClass.toString(); int position = name.lastIndexOf("."); return name.substring(position + 1); } @Override public T findById(ID id){ Optional<T> optional= baseRepository.findById(id); return optional.get(); } @Override public boolean existsById(ID var1){ return baseRepository.existsById(var1); } @Override public void save(T t){ baseRepository.save(t); } @Override public void update(T t){ baseRepository.saveAndFlush(t); } @Override public void delete(T t) { baseRepository.delete(t); } @Override public void deleteById(ID id) { baseRepository.deleteById(id); } @Override public int count() { return (int) baseRepository.count(); } @Override public List<T> findAll() { return baseRepository.findAll(); } @Override public List<T> findAllByOrderAsc(String param) { return baseRepository.findAll(Sort.by(Sort.Order.asc(param))); } @Override public List<T> findAllByOrderDesc(String param) { return baseRepository.findAll(Sort.by(Sort.Order.desc(param))); } @Override public Page<T> findByPageable(Pageable pageable) { return baseRepository.findAll(pageable); } @Override public T findUnique(String hql) { return baseRepository.findUnique(hql); } @Override public List<T> findEntityListBySql(String sql, Class c) { return baseRepository.findEntityListBySql(sql, c); } @Override public List<T> findEntityListByHql(String hql) { return baseRepository.findEntityListByHql(hql); } @Override public List findByHql(String hql) { return baseRepository.findByHql(hql); } @Override public List<Object[]> findListBySql(String sql) { return baseRepository.findListBySql(sql); } @Override public int countTotalByHql(String hql) { return baseRepository.countTotalByHql(hql); } @Override public int countTotalBySql(String sql) { return baseRepository.countTotalBySql(sql); } @Override public int getCountByCriteriaBuilder(Class c){ return baseRepository.getCountByCriteriaBuilder(c); } @Override public List<T> getEntityListByCriteriaBuilder(Class c){ return baseRepository.getEntityListByCriteriaBuilder(c); } @Override public PageFinder<T> findPageListByHql(QueryBuilder queryBuilder) { String tName = getTName(); PageFinder<T> pageFinder = new PageFinder<T>(); StringBuilder hql = new StringBuilder("from " + tName); hql.append(" o"); //判断是否有map查询条件 HashMap<String, String> map = queryBuilder.getMap(); if (!map.isEmpty()) { Set<String> keys = queryBuilder.getMap().keySet(); for (Map.Entry<String, String> mapEntry : map.entrySet()) { String key = mapEntry.getKey(); String value = mapEntry.getValue(); //判断当前字符串是否包含“where”,如果包含说明不止一个条件,要加关键字“and” if (hql.toString().contains("where o.")) { hql.append(" and o."); } else { hql.append(" where o."); } hql.append(key); //如果是模糊查询需要拼凑模糊查询语句 if (queryBuilder.isLike()) { hql.append(" like '%"); hql.append(value); hql.append("%'"); } else { hql.append(" ='"); hql.append(value); hql.append("'"); } } } //判断是否有list查询条件 if (!queryBuilder.getList().isEmpty()) { for (String list : queryBuilder.getList()) { //判断当前字符串是否包含“where”,如果包含说明不止一个条件,要加关键字“and” if (hql.toString().contains("where o.")) { hql.append(" and o."); } else { hql.append(" where o."); } hql.append(list); } } //判断是否有排序 if (queryBuilder.getOrder() != null) { hql.append(" order by o.").append(queryBuilder.getOrder()); if (queryBuilder.getIsAsc()) { hql.append(" asc"); } else { hql.append(" desc"); } } pageFinder = baseRepository.findPageListByHql(hql.toString(), queryBuilder); return pageFinder; } }
true
f15902c8b371dfa66e9b1d14d6ab6a222c96bd4b
Java
RobbeKeters/SWOP_iteratie_3
/src/Model/Handler/AddMessageHandler.java
UTF-8
9,498
2.828125
3
[]
no_license
package Model.Handler; import java.util.ArrayList; import java.util.LinkedList; import java.util.Stack; import Model.ADJUSTED_TYPE; import Model.Canvas; import Model.InvocationMessage; import Model.Label; import Model.Message; import Model.Party; import Model.PartyRole; import Model.Point; import Model.ResultMessage; import Model.Window; /** * A handler that handles the actions of a message being added to a canvas. */ public class AddMessageHandler extends Handler { /** * Handles a message being added to the canvas * @param window The canvas to edit. * @param x Unused input. * @param y Unused input. */ public static void handle(Window window, int x, int y) { Party sender = null; Party receiver = null; // Determine receiver for(Party r : window.getParties()) { if(approxLifeLine(r, x)) { receiver = r; r.setSelectedYPosition(y); break;} } // Determine sender for(Party p : window.getParties()) { if(p.getRole()==PartyRole.SENDER) {sender = p;} } if(sender==null || receiver==null) {return;} // Check if the sending party is allowed as sender if(!messageAllowed(window, sender,receiver)) { // Reset roles resetRoles(window); return; } else { // Create Invocation Message InvocationMessage invocationMessage = new InvocationMessage(null, null); invocationMessage.setSentBy(sender); invocationMessage.setReicevedBy(receiver); int messageNumber = Window.getAvailableMessageNumber(window); invocationMessage.setMessageNumber(messageNumber); Message foundMessage = findMessage(window, sender, receiver); if( foundMessage == null ) { invocationMessage.setOrder(getMaxOrder(window)+1); } else { updateOrderMessages(window, foundMessage); invocationMessage.setOrder(foundMessage.getOrder()+1); } // First argument invocationMessage invocationMessage.addArgument("firstArg"); window.addMessage(invocationMessage); // Create Result Message ResultMessage resultMessage = new ResultMessage(null); resultMessage.setSentBy(receiver); resultMessage.setReicevedBy(sender); resultMessage.setOrder((invocationMessage.getOrder()+1)); messageNumber = Window.getAvailableMessageNumber(window); resultMessage.setMessageNumber(messageNumber); invocationMessage.setResult(resultMessage); window.addMessage(resultMessage); // Handle Invocation Message Label labelInvocation = new Label(""); labelInvocation.setSelected(true); int invocLabelX = Math.max(invocationMessage.getReicevedBy().getPosSeq().getX(), invocationMessage.getSentBy().getPosSeq().getX()) - Math.abs( (invocationMessage.getReicevedBy().getPosSeq().getX() - invocationMessage.getSentBy().getPosSeq().getX() )/2); int invocLabelY = window.getOrigineY() +window.getHeight()/6 + 42 + (50 * getAmountPredecessors(window, invocationMessage)); labelInvocation.setLabelPositionSeq(new Point(invocLabelX, invocLabelY)); invocationMessage.setLabel(labelInvocation); // Handle ResultMessage Label labelResultMessage = new Label("RESULT"); labelResultMessage.setSelected(false); int RLabelX = Math.max(resultMessage.getReicevedBy().getPosSeq().getX(), resultMessage.getSentBy().getPosSeq().getX()) - Math.abs( (resultMessage.getReicevedBy().getPosSeq().getX() - resultMessage.getSentBy().getPosSeq().getX() )/2); int RLabelY = window.getOrigineY() +window.getHeight()/6 + 42 + (50 * getAmountPredecessors(window, resultMessage)); System.out.println(RLabelX + " ----------=-=-=-=-=-=-=-=-=-=-:("); labelInvocation.setLabelPositionSeq(new Point(RLabelX, RLabelY)); resultMessage.setLabel(labelResultMessage); // First all the orders needs to be updated because of the number of predecessors for (Message m : window.getMessages()) { //if( m.getClass()== InvocationMessage.class) { m.getLabel().setLabelPositionSeq(Math.max(m.getReicevedBy().getPosSeq().getX(), m.getSentBy().getPosSeq().getX()) - Math.abs( (m.getReicevedBy().getPosSeq().getX() - m.getSentBy().getPosSeq().getX() )/2),window.getOrigineY() + window.getHeight()/6 + 42 + (50 * getAmountPredecessors(window, m))); //} } System.out.println(resultMessage.getLabel().getLabelPositionSequence().getX() + " =====<><><><>++++++"); // Notify Interaction window.getInteraction().adjusted(ADJUSTED_TYPE.ADDED_MESSAGE,window); // 2 messages are added window.getInteraction().adjusted(ADJUSTED_TYPE.ADDED_MESSAGE,window); EditLabelHandler.handle(window, labelInvocation, invocationMessage, invocLabelX, invocLabelY); // System.out.println(labelInvocation.getLabelname()); // setArguments(invocationMessage, labelInvocation); } // Reset roles resetRoles(window); return; } private static int getMaxOrder(Window window) { int max = 0; for(Message m : window.getMessages()) { if(m.getOrder()>max) {max=m.getOrder();} } return max; } /** * Returns how many messages precede the given message. * @param window The canvas where the message is located. * @param message The given message. * @return The amount of messages preceding the given message. */ public static int getAmountPredecessors(Window window, Message message) { int amount = 0; for (Message m : window.getMessages()) { if (m.getOrder() < message.getOrder()) amount++; } return amount; } private static boolean messageAllowed(Window window,Party sender, Party receiver) { int firstClick = sender.getSelectedYPosition(); int secondClick = receiver.getSelectedYPosition(); int difference = Math.abs((firstClick-secondClick)); if(sender==receiver) {return false;} Stack<Party> stackParties = new Stack<Party>(); LinkedList<Message> messages = new LinkedList<Message>(); messages.addAll(window.getMessages()); LinkedList<Message> sortedList = Model.Window.messageSort(messages); if(sortedList.isEmpty()) { return true; } // Height for messages used in sequence diagram======= if ( (difference > 50)) { return false; } // =================================================== Message firstMessage = sortedList.getFirst(); stackParties.push(firstMessage.getSentBy()); Message lastMessage = null; Message lastMessagePlusOne = null; for (Message m : sortedList) { int yPostionMessage = window.getOrigineY() + window.getHeight()/6 + 50 + (50 * getAmountPredecessors(window,m)); int YUpper = yPostionMessage + 49; if ( firstClick > yPostionMessage && secondClick > yPostionMessage && firstClick < YUpper && secondClick < YUpper ) { stackParties.push(m.getReicevedBy()); lastMessage = m; } else if ( firstClick > yPostionMessage && secondClick > yPostionMessage) { stackParties.push(m.getReicevedBy()); } else { lastMessagePlusOne = m; break; } } try { Party topStack = stackParties.pop(); Party belowTop = stackParties.pop(); if( topStack == sender ) { if (belowTop == receiver && lastMessage != null && lastMessage.getClass().equals(InvocationMessage.class)) { return false; } else if ( lastMessagePlusOne != null &&lastMessagePlusOne.getReicevedBy() == receiver && lastMessagePlusOne.getClass() == ResultMessage.class) { return false; } else { return true; } } } catch (Exception e) { } return false; } //update order of the messages => all messages who have a higher order than the received message get a order of +2 private static void updateOrderMessages(Window window, Message message) { for (Message m : window.getMessages()) { if( m.getOrder() > message.getOrder()) { m.setOrder(m.getOrder()+2); } } } // find the 2 messages where the Invocation and ResultMessage must be placed in between => Returns the first Message(lowest order) private static Message findMessage(Window window, Party sender, Party receiver) { LinkedList<Message> messages = new LinkedList<Message>(); messages.addAll(window.getMessages()); for ( Message m : messages) { // Height for messages used in sequence diagram======= int y = window.getOrigineY() + window.getHeight()/6 + 50 + (50 * getAmountPredecessors(window,m)); int upperY = y + 49; // =================================================== if( (m.getReicevedBy()== sender) && (receiver.getSelectedYPosition() > y) && (sender.getSelectedYPosition() > y) && (receiver.getSelectedYPosition() < upperY) && (sender.getSelectedYPosition() < upperY)) { return m; } } return null; } /*private static void setArguments(InvocationMessage i, Label messLabel){ String methodCall = messLabel.getLabelname(); boolean methodName = true; int index = 0; boolean stop = false; for(int j=0; j<methodCall.length();j++) { if(stop) break; String var = ""; for(int k=j; k<methodCall.length();k++) { if(methodName) { if(methodCall.charAt(k)=='(') { methodName=false; j=k; index++; System.out.println("new method: " + var); i.setMethodName(var); break; } else { var = var + methodCall.charAt(k); } } else { if(methodCall.charAt(k)==',') { j=k; index++; System.out.println("new arg: " + var); i.addArgument(var); break; } else if (methodCall.charAt(k) == ')'){ stop = true; index++; break; } else { var = var + methodCall.charAt(k); } } } } }*/ }
true
96033cb33010df6e654241284593c4a4488e3c32
Java
dragosbudrica/ThinkingInJava
/src/initialization/exercise22/InitializationEx22.java
UTF-8
1,318
4.28125
4
[]
no_license
package initialization.exercise22; enum Currency { ONE, FIVE, TEN, TWENTY, FIFTY, HUNDRED } public class InitializationEx22 { Currency currency; public InitializationEx22(Currency currency) { this.currency = currency; } public void showCurrency() { System.out.print("The paper currency is the "); switch(currency) { case ONE: System.out.println("ONE dollar one."); break; case FIVE: System.out.println("FIVE dollars one."); break; case TEN: System.out.println("TEN dollars one."); break; case TWENTY: System.out.println("TWENTY dollars one."); break; case FIFTY: System.out.println("FIFTY dollars one."); break; default: System.out.println("one HUNDRED dollars one."); } } public static void main(String[] args) { for (Currency curr : Currency.values()) { System.out.println(curr + ", ordinal " + curr.ordinal()); } System.out.println("----------------------------------------"); InitializationEx22 curr1 = new InitializationEx22(Currency.FIVE); InitializationEx22 curr2 = new InitializationEx22(Currency.FIFTY); InitializationEx22 curr3 = new InitializationEx22(Currency.HUNDRED); curr1.showCurrency(); curr2.showCurrency(); curr3.showCurrency(); } }
true
7ced53986e43b78937ef2b7bc4c6637683726bf4
Java
JetBrains/intellij-community
/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ModuleElementsEditor.java
UTF-8
3,085
1.703125
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2017 JetBrains s.r.o. * * 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.intellij.openapi.roots.ui.configuration; import com.intellij.openapi.CompositeDisposable; import com.intellij.openapi.Disposable; import com.intellij.openapi.module.ModuleConfigurationEditor; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.util.Disposer; import com.intellij.util.EventDispatcher; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.EventListener; /** * @author Eugene Zhuravlev */ public abstract class ModuleElementsEditor implements ModuleConfigurationEditor { @NotNull protected final Project myProject; protected JComponent myComponent; private final CompositeDisposable myDisposables = new CompositeDisposable(); private final EventDispatcher<ModuleElementsEditorListener> myDispatcher = EventDispatcher.create(ModuleElementsEditorListener.class); private final ModuleConfigurationState myState; protected ModuleElementsEditor(@NotNull ModuleConfigurationState state) { myProject = state.getProject(); myState = state; } public void addListener(ModuleElementsEditorListener listener) { myDispatcher.addListener(listener); } protected void fireConfigurationChanged() { myDispatcher.getMulticaster().configurationChanged(); } @Override public boolean isModified() { return getModel() != null && getModel().isChanged(); } protected ModifiableRootModel getModel() { return myState.getModifiableRootModel(); } @NotNull protected ModuleConfigurationState getState() { return myState; } public void canApply() throws ConfigurationException {} @Override public void apply() throws ConfigurationException {} public void moduleCompileOutputChanged(final String baseUrl, final String moduleName) {} @Override public void disposeUIResources() { Disposer.dispose(myDisposables); } // caching @Override public final JComponent createComponent() { if (myComponent == null) { myComponent = createComponentImpl(); } return myComponent; } public JComponent getComponent() { return createComponent(); } protected void registerDisposable(Disposable disposable) { myDisposables.add(disposable); } protected abstract JComponent createComponentImpl(); public interface ModuleElementsEditorListener extends EventListener { void configurationChanged(); } }
true
6d1c127c9b6e63736db7da11a38c92646ccd6bf2
Java
ghosalsukanta/weatherapp
/src/ErrorClass.java
UTF-8
2,363
2.9375
3
[]
no_license
import java.awt.Color; import java.awt.EventQueue; import java.awt.Font; import java.awt.SystemColor; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; public class ErrorClass { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { String errorMessage=args[0].toString(); ErrorClass window = new ErrorClass(errorMessage); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ErrorClass(String errorMessage) { initialize(errorMessage); } /** * Initialize the contents of the frame. */ private void initialize(String errorMessage) { frame = new JFrame(); frame.getContentPane().setBackground(new Color(153, 255, 204)); frame.setBounds(200, 200, 515, 357); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); frame.setTitle("WeatherReport"); frame.setResizable(false); JLabel lblNewLabel = new JLabel("Error !!!!"); lblNewLabel.setForeground(SystemColor.controlHighlight); lblNewLabel.setFont(new Font("Comic Sans MS", Font.BOLD, 30)); lblNewLabel.setBounds(197, 73, 162, 52); frame.getContentPane().add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Powered by: IBM Weather.com"); lblNewLabel_1.setFont(new Font("Comic Sans MS", Font.BOLD, 16)); lblNewLabel_1.setForeground(SystemColor.controlHighlight); lblNewLabel_1.setBounds(247, 281, 262, 36); frame.getContentPane().add(lblNewLabel_1); JLabel lblNewLabel_2 = new JLabel(errorMessage); lblNewLabel_2.setFont(new Font("Comic Sans MS", Font.BOLD, 22)); lblNewLabel_2.setBackground(new Color(240, 240, 240)); lblNewLabel_2.setForeground(SystemColor.controlHighlight); lblNewLabel_2.setBounds(40, 187, 443, 36); frame.getContentPane().add(lblNewLabel_2); JLabel lblNewLabel_7 = new JLabel("New label"); lblNewLabel_7.setIcon(new ImageIcon(WeatherHome.class.getResource("/resources/unnamed.jpg"))); lblNewLabel_7.setBounds(0, 0, 509, 317); frame.getContentPane().add(lblNewLabel_7); } }
true
9c9a4debe957876c0bf1837be1e2f1db6f14183a
Java
chaeri234/cheal
/src/controller/DeptController.java
UTF-8
491
2.140625
2
[]
no_license
package controller; import java.util.List; import model.DeptDAO; import model.DeptDTO; import view.DeptView; public class DeptController { public static void main(String[] args) { DeptDAO dao = new DeptDAO(); //모든부서 정보 조회 List<DeptDTO> deptlist = dao.selectDeptAll(); DeptView.print(deptlist); //특정부서 정보 조회 DeptDTO dept = dao.selectDeptbyId(10); DeptView.print(dept); //문자 DeptView.print("JDBC재밋어~~~"); } }
true
8158ce03f7576c00aae64d4097b707a9b731e5f1
Java
barbietunnie/jboss-5-to-7-migration
/MessageCore/JavaSource/test/JmsReceiver.java
UTF-8
1,284
2.515625
3
[]
no_license
package test; import javax.jms.Message; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.jms.core.JmsTemplate; import com.legacytojava.jbatch.SpringUtil; public class JmsReceiver { public static void main(String[] args){ AbstractApplicationContext factory = SpringUtil.getAppContext(); javax.jms.Queue queue = (javax.jms.Queue) factory.getBean("customerCareInput"); queue = (javax.jms.Queue) factory.getBean("destination"); try { JmsReceiver test = (JmsReceiver)factory.getBean("jmsReceiver"); for (int i=0; i<10; i++) { test.receive(queue); } } catch (Exception e) { e.printStackTrace(); } finally { // } System.exit(0); } private JmsTemplate jmsTemplate; public void setJmsTemplate(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } private void receive(javax.jms.Queue queue) { jmsTemplate.setDefaultDestination(queue); System.out.println("Will wait "+(this.jmsTemplate.getReceiveTimeout()/1000)+" seconds..."); Message msg = this.jmsTemplate.receive(this.jmsTemplate.getDefaultDestination()); System.out.println("Received Message: "+msg); //System.out.println(jmsTemplate.isSessionTransacted()); } }
true
d9e66c50a610329fc46962537149bdeb015a37e7
Java
AdamClayton98/FinalYearProject
/app/src/main/java/com/example/finalyearproject/MainActivity.java
UTF-8
5,406
1.71875
2
[]
no_license
package com.example.finalyearproject; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import android.app.DatePickerDialog; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.example.finalyearproject.Models.AllergyModel; import com.example.finalyearproject.fragments.AddToPantryFragment; import com.example.finalyearproject.fragments.AllergiesFragment; import com.example.finalyearproject.fragments.FavouritesFragment; import com.example.finalyearproject.fragments.HomeFragment; import com.example.finalyearproject.fragments.MyDetailsFragment; import com.example.finalyearproject.fragments.MyRatingFragment; import com.example.finalyearproject.fragments.MyRecipesFragment; import com.example.finalyearproject.fragments.PantryFragment; import com.example.finalyearproject.fragments.PlanningDateSelectionFragment; import com.example.finalyearproject.fragments.PlanningFragment; import com.example.finalyearproject.fragments.ProfileFragment; import com.example.finalyearproject.fragments.SearchFragment; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.google.firebase.auth.FirebaseAuth; import java.util.Calendar; import java.util.List; public class MainActivity extends AppCompatActivity { Fragment selectedFragment = null; Toolbar toolbar; ImageView searchButton; public static String uid = FirebaseAuth.getInstance().getUid(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar=findViewById(R.id.customToolbar); setSupportActionBar(toolbar); toolbar.setTitleTextColor(ContextCompat.getColor(getApplicationContext(),R.color.white)); searchButton = findViewById(R.id.searchActionBarButton); MainActivity.uid = FirebaseAuth.getInstance().getUid(); searchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, new SearchFragment()).addToBackStack(null).commit(); } }); BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation); bottomNavigationView.setOnNavigationItemSelectedListener(navListener); getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper,new HomeFragment()).addToBackStack(null).commit(); } private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.ic_home: selectedFragment = new HomeFragment(); break; case R.id.ic_plan: selectedFragment = new PlanningDateSelectionFragment(); break; case R.id.ic_fave: selectedFragment = new FavouritesFragment(); break; case R.id.ic_pantry: selectedFragment = new PantryFragment(); break; case R.id.ic_profile: selectedFragment = new ProfileFragment(); break; } getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, selectedFragment).addToBackStack(null).commit(); return true; } }; public void signOut(View view){ FirebaseAuth.getInstance().signOut(); startActivity(new Intent(MainActivity.this,LoginActivity.class)); finish(); } public void toAllergies(View view){ getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, new AllergiesFragment()).addToBackStack(null).commit(); } public void toMyDetails(View view){ getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, new MyDetailsFragment()).addToBackStack("myDetailsFragment").commit(); } public void toMyRecipes(View view){ getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper,new MyRecipesFragment()).addToBackStack(null).commit(); } public void toAddToPantry(View view){ getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, new AddToPantryFragment()).addToBackStack(null).commit(); } public void toMyRating(View view){ getSupportFragmentManager().beginTransaction().replace(R.id.fl_wrapper, new MyRatingFragment()).addToBackStack(null).commit(); } }
true
e95fcf48b213a2fcd174beee9d37f1e25f61342b
Java
EliosNieto/ecommerr
/src/main/java/com/ias/ecommerce/application/errors/ProductExistsError.java
UTF-8
1,015
2.484375
2
[]
no_license
package com.ias.ecommerce.application.errors; import com.ias.ecommerce.application.commons.errors.ApplicationError; import com.ias.ecommerce.application.commons.errors.HttpStatusCode; import com.ias.ecommerce.application.domain.IdentificationProduct; import java.util.Map; public class ProductExistsError extends ApplicationError { private final IdentificationProduct identificationProduct; public ProductExistsError(IdentificationProduct identificationProduct) { this.identificationProduct = identificationProduct; } @Override public String getMessage() { return "Code product already exists"; } @Override public String errorCode() { return "PRODUCT_ALREADY_EXISTS_ERROR"; } @Override public HttpStatusCode httpStatusCode() { return HttpStatusCode.BAD_REQUEST; } @Override public Map<String, Object> metadata() { return Map.of( "idProduct", identificationProduct.getValue() ); } }
true
3b419fe7f3ad9972886e0158d45045db73fc5d8b
Java
jinloes/coding_practice
/binary_trees/src/test/java/CheckHeightBalancedTest.java
UTF-8
794
2.671875
3
[]
no_license
import org.junit.jupiter.api.Test; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; class CheckHeightBalancedTest { @Test void check() { BinaryTreeNode<Integer> n1l = new BinaryTreeNode<>(2); BinaryTreeNode<Integer> n1r = new BinaryTreeNode<>(3); BinaryTreeNode<Integer> root = new BinaryTreeNode<>(1); root.left = n1l; root.right = n1r; assertThat(CheckHeightBalanced.check(root)).isTrue(); BinaryTreeNode<Integer> n3l = new BinaryTreeNode<>(4); n1r.left = n3l; assertThat(CheckHeightBalanced.check(root)).isTrue(); BinaryTreeNode<Integer> n4r = new BinaryTreeNode<>(3); n3l.right = n4r; assertThat(CheckHeightBalanced.check(root)).isFalse(); } }
true
40a5ec01e17e993000d853ddf0361f3ee1e3a468
Java
Akshay21212/DDF_Project
/DemoWebShopdesign/src/test/java/com/dws/wa/pages/RegisterPages.java
UTF-8
1,355
2.234375
2
[]
no_license
package com.dws.wa.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class RegisterPages { WebDriver driver; @FindBy(how=How.XPATH, using="//input[@id=\"gender-male\"]") WebElement gem; @FindBy(how=How.XPATH, using="//input[@id=\"gender-female\"]") WebElement gef; @FindBy(how=How.NAME,using="FirstName") WebElement first; @FindBy(how=How.NAME,using="LastName") WebElement last; @FindBy(how=How.NAME,using="Email") WebElement mail; @FindBy(how=How.NAME,using="Password") WebElement pass; @FindBy(how=How.NAME,using="ConfirmPassword") WebElement confirm; @FindBy(how=How.NAME,using="register-button") WebElement regbutton; public RegisterPages(WebDriver driver) { this.driver=driver; } public void regData(String ge1,String fname, String lname, String email, String pword, String cword) { if(ge1.equalsIgnoreCase("male")) { gem.click(); } else { gef.click(); } System.out.println("gender clicked"); first.sendKeys(fname); last.sendKeys(lname); mail.sendKeys(email); pass.sendKeys(pword); confirm.sendKeys(cword); } public void regisbutton() { regbutton.click(); } }
true
f01a831300c4a48da94348f63af7de4b70585ba0
Java
leungjch/universe-maker-app
/app/src/main/java/com/leungjch/universemaker/MainActivity.java
UTF-8
19,802
2.09375
2
[ "Apache-2.0" ]
permissive
package com.leungjch.universemaker; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.Toast; import com.leungjch.universemaker.universe.Universe; import static com.leungjch.universemaker.GameView.RESET_TYPE; import static com.leungjch.universemaker.GameView.ADD_TYPE; import static com.leungjch.universemaker.GameView.PLACEMENT_TYPE; import static com.leungjch.universemaker.GameView.SIZE_TYPE; public class MainActivity extends Activity { public RESET_TYPE loadTypeState; public ADD_TYPE addTypeState; public PLACEMENT_TYPE placementState; public SIZE_TYPE sizeState; public float scaleState; GameView gameView; @Override public void onCreate(Bundle savedInstanceState) { // Log.d("MainActivity","Creating MainActivity"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); gameView = (GameView) findViewById(R.id.gameView); // Handle buttons // Reset button Button resetButton = (Button)findViewById(R.id.resetButton); resetButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gameView.reset(gameView.currentLoadType, scaleState); } }); // Set default preset type loadTypeState = RESET_TYPE.BLANK; // Set default selected addType addTypeState = ADD_TYPE.PLANET; // Set default selected placementType placementState = PLACEMENT_TYPE.SCATTER; // Set default selected size sizeState = SIZE_TYPE.MEDIUM; // Load buttons // Set load preset button Button loadTypeButton = (Button)findViewById(R.id.loadButton); loadTypeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialogLoadType(); } }); // Add type button Button addTypeButton = (Button)findViewById(R.id.addType); addTypeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialogAddType(); } }); // Placement Type button Button placementTypeButton = (Button)findViewById(R.id.placementType); placementTypeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialogPlacementType(); } }); // Size Type button Button sizeTypeButton = (Button)findViewById(R.id.objectSizeType); sizeTypeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialogSizeType(); } }); // Zoom mode toggle final Button zoomButton = (Button)findViewById(R.id.zoomMode); zoomButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!gameView.isZoomMode) { zoomButton.setAlpha(0.45f); Toast.makeText(MainActivity.this, "Use drag move, pinch to zoom", Toast.LENGTH_LONG).show(); } else { zoomButton.setAlpha(1.f); Toast.makeText(MainActivity.this, "Move mode disabled", Toast.LENGTH_LONG).show(); } gameView.toggleZoomMode(); } }); // Zoom mode toggle final Button traceButton = (Button)findViewById(R.id.traceMode); traceButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!gameView.isTraceMode) { traceButton.setAlpha(0.45f); Toast.makeText(MainActivity.this, "Trace paths ON", Toast.LENGTH_LONG).show(); } else { traceButton.setAlpha(1.0f); Toast.makeText(MainActivity.this, "Trace paths OFF", Toast.LENGTH_LONG).show(); } gameView.toggleTraceMode(); } }); // Speed button #0 (pause) final ImageButton pauseButton = (ImageButton)findViewById(R.id.pauseplay); pauseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gameView.setCurrentDeltaT(Universe.CONSTANTS.dT_0); } }); // Speed button #1 (slow) final ImageButton speedButton1 = (ImageButton)findViewById(R.id.speed1); speedButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gameView.setCurrentDeltaT(Universe.CONSTANTS.dT_1); } }); // Speed button #2 (medium) final ImageButton speedButton2 = (ImageButton)findViewById(R.id.speed2); speedButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gameView.setCurrentDeltaT(Universe.CONSTANTS.dT_2); } }); // Speed button #3 (fast) final ImageButton speedButton3 = (ImageButton)findViewById(R.id.speed3); speedButton3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { gameView.setCurrentDeltaT(Universe.CONSTANTS.dT_3); } }); // Options button final ImageButton optionsButton = (ImageButton)findViewById(R.id.options); optionsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAlertDialogOptions(); } }); } @Override protected void onResume() { super.onResume(); // gameView.reset(RESET_TYPE.BLANK, SCALECONSTANTS.DEFAULTSCALE); // gameView.setRunning(true); gameView.resume(); // Log.d("MAINACTIVITY", "RESUMING"); } @Override protected void onPause() { super.onPause(); // gameView.reset(RESET_TYPE.BLANK, SCALECONSTANTS.DEFAULTSCALE); // gameView.setRunning(false); gameView.pause(); // Log.d("MAINACTVITY", "PAUSING"); } // Called when user leaves app (presses home) // Save current state @Override public void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); } // Choose load preset type private void showAlertDialogLoadType() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("Load preset"); String[] list = RESET_TYPE.getString(); final Button loadTypeButton = (Button)findViewById(R.id.loadButton); // scale factor after resetting for view scaleState = GameView.SCALECONSTANTS.DEFAULTSCALE; alertDialog.setSingleChoiceItems(list, loadTypeState.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: Toast.makeText(MainActivity.this, "Clear all", Toast.LENGTH_LONG).show(); dialog.dismiss(); loadTypeState = RESET_TYPE.BLANK; break; case 1: Toast.makeText(MainActivity.this, "Single star system", Toast.LENGTH_LONG).show(); dialog.dismiss(); loadTypeState = RESET_TYPE.SINGLE_STAR_SYSTEM; break; case 2: Toast.makeText(MainActivity.this, "Binary star system", Toast.LENGTH_LONG).show(); loadTypeState = RESET_TYPE.BINARY_STAR_SYSTEM; break; case 3: Toast.makeText(MainActivity.this, "Random Planets", Toast.LENGTH_LONG).show(); loadTypeState = RESET_TYPE.PLANETS_COALESCING; scaleState = GameView.SCALECONSTANTS.MINSCALE; break; case 4: Toast.makeText(MainActivity.this, "Random satellites", Toast.LENGTH_LONG).show(); loadTypeState = RESET_TYPE.CIRCLING_SATELLITES; break; case 5: Toast.makeText(MainActivity.this, "Black hole accretion disk", Toast.LENGTH_LONG).show(); loadTypeState = RESET_TYPE.BLACK_HOLE_ACCCRETION_DISK; break; } dialog.dismiss(); gameView.setCurrentResetType(loadTypeState); gameView.reset(loadTypeState, scaleState); } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(true); alert.show(); } // Choose type private void showAlertDialogAddType() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("Celestial Body"); String[] list = ADD_TYPE.getString(); final Button addTypeButton = (Button)findViewById(R.id.addType); alertDialog.setSingleChoiceItems(list, addTypeState.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case 0: Toast.makeText(MainActivity.this, "Asteroid", Toast.LENGTH_LONG).show(); dialog.dismiss(); addTypeState = ADD_TYPE.ASTEROID; break; case 1: Toast.makeText(MainActivity.this, "Planet", Toast.LENGTH_LONG).show(); dialog.dismiss(); addTypeState = ADD_TYPE.PLANET; break; case 2: Toast.makeText(MainActivity.this, "Star", Toast.LENGTH_LONG).show(); addTypeState = ADD_TYPE.STAR; break; case 3: Toast.makeText(MainActivity.this, "Black Hole", Toast.LENGTH_LONG).show(); addTypeState = ADD_TYPE.BLACK_HOLE; break; case 4: Toast.makeText(MainActivity.this, "White Hole", Toast.LENGTH_LONG).show(); addTypeState = ADD_TYPE.WHITE_HOLE; break; case 5: Toast.makeText(MainActivity.this, "Satellite", Toast.LENGTH_LONG).show(); addTypeState = ADD_TYPE.SATELLITE; break; case 6: Toast.makeText(MainActivity.this, "Player ship: Drag to control", Toast.LENGTH_LONG).show(); addTypeState = ADD_TYPE.PLAYER_SHIP; gameView.isPlayerShipMode = true; // Enable player ship mode break; } dialog.dismiss(); addTypeButton.setText(ADD_TYPE.getString()[addTypeState.ordinal()]); gameView.setCurrentAddType(addTypeState); } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(true); alert.show(); } // Choose creation mode private void showAlertDialogPlacementType() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("Placement Mode"); String[] list = PLACEMENT_TYPE.getString(); alertDialog.setSingleChoiceItems(list, placementState.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Button placementButton = (Button)findViewById(R.id.placementType); switch (which) { case 0: Toast.makeText(MainActivity.this, "Scatter", Toast.LENGTH_LONG).show(); dialog.dismiss(); placementState = PLACEMENT_TYPE.SCATTER; break; case 1: Toast.makeText(MainActivity.this, "Flick", Toast.LENGTH_LONG).show(); placementState = PLACEMENT_TYPE.FLICK; break; case 2: Toast.makeText(MainActivity.this, "Target", Toast.LENGTH_LONG).show(); placementState = PLACEMENT_TYPE.TARGET; break; case 3: Toast.makeText(MainActivity.this, "Idle", Toast.LENGTH_LONG).show(); placementState = PLACEMENT_TYPE.IDLE; break; case 4: Toast.makeText(MainActivity.this, "Fixed", Toast.LENGTH_LONG).show(); placementState = PLACEMENT_TYPE.FIXED; break; case 5: Toast.makeText(MainActivity.this, "Orbit", Toast.LENGTH_LONG).show(); placementState = PLACEMENT_TYPE.ORBIT; break; } dialog.dismiss(); placementButton.setText(placementState.name()); gameView.setCurrentPlacementType(placementState); } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(true); alert.show(); } // Choose creation size private void showAlertDialogSizeType() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this); alertDialog.setTitle("Object Size"); String[] list = SIZE_TYPE.getString(); alertDialog.setSingleChoiceItems(list, sizeState.ordinal(), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Button sizeButton = (Button)findViewById(R.id.objectSizeType); switch (which) { case 0: Toast.makeText(MainActivity.this, "Small", Toast.LENGTH_LONG).show(); dialog.dismiss(); sizeState = SIZE_TYPE.SMALL; break; case 1: Toast.makeText(MainActivity.this, "Medium", Toast.LENGTH_LONG).show(); sizeState = SIZE_TYPE.MEDIUM; break; case 2: Toast.makeText(MainActivity.this, "Large", Toast.LENGTH_LONG).show(); sizeState = SIZE_TYPE.LARGE; break; case 3: Toast.makeText(MainActivity.this, "Random", Toast.LENGTH_LONG).show(); sizeState = SIZE_TYPE.RANDOM; break; } dialog.dismiss(); sizeButton.setText(SIZE_TYPE.getAbbreviation(sizeState)); gameView.setCurrentSizeType(sizeState); } }); AlertDialog alert = alertDialog.create(); alert.setCanceledOnTouchOutside(true); alert.show(); } // Show general options private void showAlertDialogOptions() { // 1. Instantiate an <code><a href="/reference/android/app/AlertDialog.Builder.html">AlertDialog.Builder</a></code> with its constructor AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE); View dialogView = inflater.inflate(R.layout.activity_dialog, null); // Set layout items to wrap content LinearLayout.LayoutParams params= new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.setMargins(10,10,10,10); dialogView.setLayoutParams(params); final SeekBar timeSeeker = (SeekBar)dialogView.findViewById(R.id.timeSeeker); // Avoid using seeker.setmin for API compatibility final double minTime = Universe.CONSTANTS.STEPS_3/3; timeSeeker.setMax((int)(Universe.CONSTANTS.STEPS_1*3 - minTime)); // slowest setting timeSeeker.setProgress(gameView.getCurrentSteps()); final SeekBar gravitySeeker = (SeekBar)dialogView.findViewById(R.id.gravitySeeker); gravitySeeker.setMax(10); // highest setting // gravitySeeker.setMin(); // lowest setting gravitySeeker.setProgress((int)(Math.log10(gameView.getCurrentGravity()/Universe.CONSTANTS.G)+5)); builder.setTitle("Options"); builder.setPositiveButton("Apply", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked OK button // Apply changes // set gravity seekbar value // gameView.setCurrentDeltaT((double)(1/timeSeeker.getProgress())); gameView.setCurrentSteps((int)(timeSeeker.getProgress() - minTime)); gameView.setCurrentGravity(Universe.CONSTANTS.G*Math.pow(10,(gravitySeeker.getProgress()-5))); // set Toast.makeText(MainActivity.this, "Applied changes", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User cancelled the dialog } }); builder.setNeutralButton("Rate app", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Launch google play page startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.leungjch.universemaker"))); } }); builder.setView(dialogView); AlertDialog dialog = builder.create(); // change buttoon colours dialog.setCanceledOnTouchOutside(false); dialog.show(); } }
true
d43024592a8da896e3999dfc2c74d3c838151680
Java
Kedlawv/SDA_WPR_Java
/Wpr_Java_4T/src/Person.java
UTF-8
343
3.421875
3
[]
no_license
public abstract class Person { private void walk() { System.out.println("Person is walking"); } public static void main(String[] args) { Employee p = new Employee(); p.walk(); } } class Employee extends Person { protected void walk() { System.out.println("Employee is walking"); } }
true
f50db0d7754158ce6cb283f16c38a0da6ed0bd2f
Java
bronzebasket/Approximating-Pi-part-2
/test/java/PiTest.java
UTF-8
261
2.234375
2
[]
no_license
import org.junit.Assert; import org.junit.Test; import static org.junit.Assert.*; public class PiTest { @Test public void approx() { double approximatedPi = Pi.approx(10e6); Assert.assertEquals(Math.PI, approximatedPi, 0.001); } }
true
c1f523c05be2685220e9bcb41c64b3eb9468ed06
Java
lel352/JavaIntermediario
/src/training/cursojava/aula75_84/Aula81.java
UTF-8
374
2.78125
3
[]
no_license
package training.cursojava.aula75_84; public class Aula81 { public static void main(String[] args) { String teste = "Teste"; String testeMinusculo = teste.toLowerCase(); String testeMaisculo = teste.toUpperCase(); System.out.println(testeMinusculo); System.out.println(testeMaisculo); //if (teste.toLowerCase().equals(teste.toLowerCase())) } }
true
f5265f7c3f2559bf6bd46b46f52688664a0ce094
Java
Javier9710/SpringBoot
/src/main/java/com/ejemplo/demo/repository/MateriaRepository.java
UTF-8
225
1.585938
2
[]
no_license
package com.ejemplo.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ejemplo.demo.entities.Materia; public interface MateriaRepository extends JpaRepository<Materia, Integer> { }
true
7b78c8f358a0c2596e4e79d99b947d37a679f63e
Java
maoxiaoyuan/sukodu
/sudoku/sudokuBiz/src/main/java/com/sudoku/biz/HouseResourceBiz.java
UTF-8
275
1.929688
2
[]
no_license
package com.sudoku.biz; import com.sudoku.entity.HouseResource; public interface HouseResourceBiz { void add(HouseResource houseResource); void edit(HouseResource houseResource); void editPrice(Integer id); HouseResource getResourceById(Integer id); }
true
7dbf11b9d31cd8e86ae03c32715c8ffb44083f75
Java
interventure-growingtogether/spring-certification
/container/quiz2/orig07/src/test/java/org/interventure/configuration/dynamicproxy/DynamicProxyAppConfigTest.java
UTF-8
885
2.203125
2
[]
no_license
package org.interventure.configuration.dynamicproxy; import static org.hamcrest.MatcherAssert.assertThat; import java.lang.reflect.Proxy; import org.hamcrest.CoreMatchers; import org.interventure.configuration.AppConfig; import org.interventure.configuration.ClientService; import org.interventure.configuration.Config; import org.junit.Test; /** * @author <a href="mailto:slavisa.avramovic@escriba.de">avramovics</a> * @since 2019-11-25 */ public class DynamicProxyAppConfigTest { @Test public void testSingleton() { Config appConfig = (Config) Proxy.newProxyInstance(DynamicProxyAppConfigTest.class.getClassLoader(), new Class[]{Config.class}, new AppConfigDynamicProxy(new AppConfig())); ClientService cs = appConfig.clientService1(); ClientService cs2 = appConfig.clientService2(); assertThat(cs.getClientDao() == cs2.getClientDao(), CoreMatchers.is(Boolean.FALSE)); } }
true
c8a102a97a13dc8fb10ce13d9dd219c2e168993c
Java
30Taps/crud-task
/crud-task-manager/src/main/java/org/ygx/crudtaskmanager/handler/OptimisticLockerHandler.java
UTF-8
603
2.09375
2
[]
no_license
package org.ygx.crudtaskmanager.handler; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; import org.springframework.context.annotation.Bean; /** * 乐观锁配置 * @author ygx */ public class OptimisticLockerHandler { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return interceptor; } }
true
16205f943889a7e386be4e1ee357a32ea9bd1cea
Java
magefree/mage
/Mage.Sets/src/mage/cards/d/DemonsJester.java
UTF-8
1,507
2.59375
3
[ "MIT" ]
permissive
package mage.cards.d; import java.util.UUID; import mage.MageInt; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.condition.common.HellbentCondition; import mage.abilities.decorator.ConditionalContinuousEffect; import mage.abilities.effects.common.continuous.BoostSourceEffect; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.Duration; import mage.constants.Zone; /** * * @author daagar */ public final class DemonsJester extends CardImpl { public DemonsJester(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.CREATURE},"{3}{B}"); this.subtype.add(SubType.IMP); this.power = new MageInt(2); this.toughness = new MageInt(2); // Flying this.addAbility(FlyingAbility.getInstance()); // Hellbent - Demon's Jester gets +2/+1 as long as you have no cards in hand. this.addAbility(new SimpleStaticAbility(Zone.BATTLEFIELD, new ConditionalContinuousEffect( new BoostSourceEffect(2,1,Duration.WhileOnBattlefield), HellbentCondition.instance, "<i>Hellbent</i> &mdash; {this} gets +2/+1 as long as you have no cards in hand"))); } private DemonsJester(final DemonsJester card) { super(card); } @Override public DemonsJester copy() { return new DemonsJester(this); } }
true
ca4be28af29d29b412c882ed8497bdc4d6c04bd5
Java
EducaT01/EducaT01
/EducaT-web/src/main/java/ec/edu/espe/EducaT/web/alumnoBean.java
UTF-8
879
2.015625
2
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author USER */ package ec.edu.espe.EducaT.web; import ec.edu.espe.EducaT.model.Alumno; import ec.edu.espe.EducaT.service.AlumnosService; import java.util.List; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; @ManagedBean @ViewScoped public class alumnoBean { @EJB private AlumnosService alumnosService; private List<Alumno> alumno; @PostConstruct public void inicio(){ this.alumno = this.alumnosService.obtenerAlumnos(); } public List<Alumno> getAlumno() { return alumno; } }
true
ae57c1cde3e36e4f41a56d3d8d6666e1975bf94a
Java
ilaif/ray-tracer
/src/physicalObjects/Sphere.java
UTF-8
1,291
2.90625
3
[]
no_license
package physicalObjects; import core.*; public class Sphere extends Surface { //Fields Vector centerPos; double radius; //Constructor public Sphere(Vector centerPos, double radius, Material material) { super(material); this.centerPos = centerPos; this.radius = radius; this.keyPoint = centerPos; } //Super class methods implementations public RayHit getIntersection(Ray ray) { Vector p = ray.getSource(); Vector u = ray.getDirection(); Vector v = new Vector(this.centerPos, p); double b = 2 * (v.dot(u)); double c = v.dot(v) - this.radius * this.radius; double discriminant = b * b - 4 * c; if (discriminant < 0) { return null; } double tMinus = (-b - Math.sqrt(discriminant)) / 2; double tPlus = (-b + Math.sqrt(discriminant)) / 2; if (tMinus < 0 && tPlus < 0) { return null; } double tValue; if (tMinus < 0 && tPlus > 0) { tValue = tPlus; } else { tValue = tMinus; } return new RayHit(ray, this, tValue); } public Vector getNormalAtPoint(Vector point) { return new Vector(this.centerPos, point).normalize(); } }
true
c4d0429b348bc5319ce184716b2a0c39d7e1a655
Java
D-a-r-e-k/Code-Smells-Detection
/Preparation/processed-dataset/god-class_4_1088/5.java
UTF-8
200
1.703125
2
[]
no_license
//}}} // {{{ setDefaultFocusComponent() /** Only used by VFSFileChooserDialog, since it embeds this in a dialog */ void setDefaultFocusComponent(JComponent c) { defaultFocusComponent = c; }
true
4ffaa75a73cfc10757c06aa13a314c01466e84de
Java
Lightwgh/learnforJavaWeb
/07_book/src/web/UserServlet.java
UTF-8
4,584
2.734375
3
[]
no_license
package web; import com.google.gson.Gson; import pojo.User; import service.UserService; import service.impl.UserServiceImpl; import utils.WebUtils; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashMap; /** * @author 孟享广 * @date 2020-10-18 4:13 下午 * @description */ public class UserServlet extends BaseServlet { private UserService userService = new UserServiceImpl(); /** * 处理登录的功能 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、获取请求的参数 String username = request.getParameter("username"); String password = request.getParameter("password"); // 调用 userService.login()登录处理业务 User loginUser = userService.login(new User(null, username, password, null)); // 如果等于null,说明登录 失败! if (loginUser == null) { // 把错误信息,和回显的表单项信息,保存到Request域中 request.setAttribute("msg", "用户或密码错误!"); request.setAttribute("username", username); // 跳回登录页面 request.getRequestDispatcher("/pages/user/login.jsp").forward(request, response); } else { // 登录 成功 //跳到成功页面login_success.html request.getRequestDispatcher("/pages/user/login_success.jsp").forward(request, response); } } /** * 处理注册的功能 * * @param request * @param response * @throws ServletException * @throws IOException */ protected void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、获取请求的参数 String username = request.getParameter("username"); String password = request.getParameter("password"); String email = request.getParameter("email"); String code = request.getParameter("code"); User user = WebUtils.copyParamToBean(request.getParameterMap(), new User()); // 2、检查 验证码是否正确 === 写死,要求验证码为:abcde if ("abcde".equalsIgnoreCase(code)) { // 3、检查 用户名是否可用 if (userService.existUsername(username)) { System.out.println("用户名[" + username + "]已存在!"); // 把回显信息,保存到Request域中 request.setAttribute("msg", "用户名已存在!!"); request.setAttribute("username", username); request.setAttribute("email", email); // 跳回注册页面 request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response); } else { // 可用 // 调用Sservice保存到数据库 userService.registUser(new User(null, username, password, email)); // // 跳到注册成功页面 regist_success.jsp request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request, response); } } else { // 把回显信息,保存到Request域中 request.setAttribute("msg", "验证码错误!!"); request.setAttribute("username", username); request.setAttribute("email", email); System.out.println("验证码[" + code + "]错误"); request.getRequestDispatcher("/pages/user/regist.jsp").forward(request, response); } } public void ajaxExistUsername(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取请求的参数username String username = request.getParameter("username"); String password = request.getParameter("password"); // 调用userService.existsUsername(); boolean existUsername = userService.existUsername(username); // 把返回的结果封装成为map对象 HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("existUsername", existUsername); Gson gson = new Gson(); String json = gson.toJson(resultMap); response.getWriter().write(json); } }
true
7d94c42904ffeee5b3bd74b35053e61373c8d2dc
Java
budlinville/mobile-app-ws
/src/main/java/com/walmart/app/ws/security/WebSecurity.java
UTF-8
2,481
2.28125
2
[]
no_license
package com.walmart.app.ws.security; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.walmart.app.ws.service.UserService; @EnableWebSecurity public class WebSecurity extends WebSecurityConfigurerAdapter { private final UserService userDetailsService; private final BCryptPasswordEncoder bCryptPasswordEncoder; public WebSecurity(UserService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) { this.userDetailsService = userDetailsService; this.bCryptPasswordEncoder = bCryptPasswordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests() .antMatchers(HttpMethod.POST, SecurityConstants.SIGN_UP_URL) // allow POST requests on /user (all other endpoints require authentication) .permitAll() .antMatchers(HttpMethod.GET, SecurityConstants.VERIFICATION_EMAIL_URL) // allow public access of email verification .permitAll() .antMatchers(HttpMethod.POST, SecurityConstants.PASSWORD_RESET_REQUEST_URL) // allow public access of password reset request .permitAll() .antMatchers(HttpMethod.POST, SecurityConstants.PASSWORD_RESET_URL) // allow public access of password reset .permitAll() .anyRequest().authenticated().and() .addFilter(getAuthenticationFilter()) .addFilter(new AuthorizationFilter(authenticationManager())) .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); // Never cache httpsessions } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder); } // Override authorization url from '/login' to '/users/login' public AuthenticationFilter getAuthenticationFilter() throws Exception { final AuthenticationFilter filter = new AuthenticationFilter(authenticationManager()); filter.setFilterProcessesUrl("/users/login"); return filter; } }
true
dfd862b84f73e114581544be19fddcd3c59cf69d
Java
solehudindt/belajar-java
/Cat.java
UTF-8
345
3.765625
4
[]
no_license
public class Cat extends Animal { String color; public Cat(String name, int age, String color) { super(name,age); this.color = color; } @Override public void hello(){ System.out.println("This cat is" +name); } public void meow() { System.out.println("Meow.... " +this.name); } }
true
ed9c4f6ade1c3bbdf3780b23503eb4761df9eb95
Java
huylllooo/Programming-Enshu-B
/src/enshu6/MousePanelTest.java
UTF-8
461
2.453125
2
[]
no_license
package enshu6; import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; public class MousePanelTest { public MousePanelTest() { JFrame jf = new JFrame("Mouse Panel Test"); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setLayout(new BorderLayout()); jf.add(new MousePanel(), BorderLayout.CENTER); jf.pack(); jf.setVisible(true); } public static void main(String[] args) { new MousePanelTest(); } }
true
ef9e04ca18eb3304bd5813000061f2f4cff9cccb
Java
Bagzot/bagzot
/Week4_Automation/src/test/java/com/automation/pages/Base.java
UTF-8
1,018
2.203125
2
[]
no_license
package com.automation.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import com.automation.library.GlobalSeleniumLibrary; public class Base { public static WebDriver driver; public static GlobalSeleniumLibrary myLibrary; @BeforeClass public void beforeAllTestStart() { myLibrary = new GlobalSeleniumLibrary(driver); myLibrary.setDemo(true); } @AfterClass public void afterAllTestCompleted() { } @BeforeMethod public void beforeEachTestStart() { driver = myLibrary.startChromeBrowser(); } @AfterMethod public void afterEachTestEnd() { try { Thread.sleep(10 * 1000); driver.close(); // close the browser driver.quit(); // kills/deletes the driver object } catch (Exception e) { e.printStackTrace(); } } }
true
ef130e8964ca2eaae53e080e207220f37e32b06f
Java
Hathot/HUSACCT
/src/husacct/analyse/IAnalyseService.java
UTF-8
1,763
1.859375
2
[ "MIT" ]
permissive
package husacct.analyse; import javax.swing.JInternalFrame; import husacct.common.dto.AnalysedModuleDTO; import husacct.common.dto.DependencyDTO; import husacct.common.dto.ExternalSystemDTO; import husacct.common.dto.ProjectDTO; import husacct.common.services.IObservableService; public interface IAnalyseService extends IObservableService { public String[] getAvailableLanguages(); @Deprecated public void analyseApplication(String[] paths, String programmingLanguage); public void analyseApplication(ProjectDTO project); public boolean isAnalysed(); public JInternalFrame getJInternalFrame(); //The following function has been inserted due to performance issues. The function enables //function-users to use cache-mechanisms and special search-algorithms public DependencyDTO[] getAllDependencies(); public DependencyDTO[] getDependencies(String from, String to); public DependencyDTO[] getDependenciesFrom(String from); public DependencyDTO[] getDependenciesTo(String to); public DependencyDTO[] getDependencies(String from, String to, String[] dependencyFilter); public DependencyDTO[] getDependenciesFrom(String from, String[] dependencyFilter); public DependencyDTO[] getDependenciesTo(String to, String[] dependencyFilter); public AnalysedModuleDTO getModuleForUniqueName(String uniquename); public AnalysedModuleDTO[] getRootModules(); public AnalysedModuleDTO[] getChildModulesInModule(String from); public AnalysedModuleDTO[] getChildModulesInModule(String from, int depth); public AnalysedModuleDTO getParentModuleForModule(String child); public void exportDependencies(String fullPath); public ExternalSystemDTO[] getExternalSystems(); }
true
aa0aa86db08a218bf48a831902205bd45bc1da6a
Java
Badmuts/hsleiden-IPSEN4
/app/src/main/java/com/inc/yoghurt/ipsen4/Stucomm/StucommTask.java
UTF-8
949
2.140625
2
[]
no_license
package com.inc.yoghurt.ipsen4.Stucomm; import android.os.AsyncTask; import android.util.Log; import com.inc.yoghurt.ipsen4.Models.Event; import com.inc.yoghurt.ipsen4.Stucomm.StucommApi; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import retrofit2.Call; /** * Created by daan on 05/04/16. */ public class StucommTask extends AsyncTask<Void, Void, List<Event>> { private final StucommApi stucommApi; public StucommTask(StucommApi stucommApi) { this.stucommApi = stucommApi; } @Override protected List<Event> doInBackground(Void... params) { Call<List<Event>> schedule = stucommApi.getSchedule("1453071600", "1453590000"); List<Event> events = new ArrayList<>(); try { events = schedule.execute().body(); } catch (IOException e) { e.printStackTrace(); } return events; } }
true
b5f1c7cbc2f5184013ab5eb1d9a24781f97070e5
Java
esigate/esigate
/esigate-core/src/main/java/org/esigate/test/conn/SequenceResponse.java
UTF-8
1,627
2.609375
3
[ "Apache-2.0" ]
permissive
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.esigate.test.conn; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; /** * A response handler, which returns HTTP reponses one after another. * <p> * Sends IllegalStateException if no reponse has been added, or if execute is called too many times. * * @author Nicolas Richeton * */ public class SequenceResponse implements IResponseHandler { private int count = 0; private List<HttpResponse> responses = new ArrayList<>(); @Override public HttpResponse execute(HttpRequest request) { if (this.responses.size() <= this.count) { throw new IllegalStateException("Unexpected request"); } HttpResponse result = this.responses.get(this.count); this.count++; return result; } /** * Add a Http response. * * @param response * @return this object */ public SequenceResponse response(HttpResponse response) { this.responses.add(response); return this; } }
true
8db780e8ee96a90d323cb138feaa4e2e333e299f
Java
mumacj/personnel-statistics-back-end
/src/main/java/com/mumacj/personnelstatisticsbackend/controller/GetInInfoController.java
UTF-8
6,495
2.28125
2
[]
no_license
package com.mumacj.personnelstatisticsbackend.controller; import com.github.pagehelper.util.StringUtil; import com.mumacj.personnelstatisticsbackend.entity.GetInInfo; import com.mumacj.personnelstatisticsbackend.entity.User; import com.mumacj.personnelstatisticsbackend.serviece.GetInInfoService; import com.mumacj.personnelstatisticsbackend.serviece.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.print.DocFlavor; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @CrossOrigin @RestController @RequestMapping("/getInInfo") public class GetInInfoController { @Autowired private GetInInfoService getInInfoService; @Autowired private UserService userService; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); @RequestMapping("addInfo") private Boolean addInfo(@RequestBody Map<String,Object> data) throws ParseException { String uuid = UUID.randomUUID().toString().replaceAll("-",""); String name = (String) data.get("name"); String idCard = (String) data.get("idCard"); String time1 = ((String) data.get("time")).replace("Z", " UTC"); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");//转换时区格式 Date time = format1 .parse(time1); String address = (String) data.get("address"); Double tempNow = Double.parseDouble((String) data.get("tempNow")); String wheLeave = (String) data.get("wheLeave"); Boolean healthCode = (Boolean) data.get("healthCode"); GetInInfo getInInfo = new GetInInfo(); getInInfo.setId(uuid); if (!StringUtil.isEmpty(name)){ getInInfo.setName(name); } if (!StringUtil.isEmpty(idCard)){ getInInfo.setIdCard(idCard); } if (time != null){ getInInfo.setInTime(time); } if (!StringUtil.isEmpty(address)){ getInInfo.setAddress(address); } if (tempNow != null){ getInInfo.setTemperature(tempNow); } if (!StringUtil.isEmpty(wheLeave)){ if ("是".equals(wheLeave)){ getInInfo.setWheLeave("1"); }else { getInInfo.setWheLeave("0"); } } if (healthCode != null){ getInInfo.setHealthCode(healthCode ? "1" : "0"); } getInInfo.setRegistTime(new Date()); getInInfo.setRegistePeople("aaa"); User infoById = userService.getInfoById(idCard); if (getInInfoService.addInfo(getInInfo)) { infoById.setInTimes(infoById.getInTimes() + 1); if (userService.updateInfo(infoById)){ return true; } } return false; } @RequestMapping("getInfos") private List<HashMap<String, Object>> getInfos(@RequestBody Map<String,Object> data){ HashMap<String,Object> pageData = (HashMap<String, Object>) data; Integer currentPage = Integer.valueOf(pageData.get("currentPage").toString()); Integer size = Integer.valueOf(pageData.get("size").toString()); List<HashMap<String, Object>> getInInfos = new ArrayList<>(); getInInfos = getInInfoService.getAllInfosWithPage(currentPage,size); if (getInInfos != null && getInInfos.size() > 0){ return getInInfos; } return null; } @RequestMapping("getInfosByTimeOrName") private List<HashMap<String,Object>> getInfosByTimeOrName(@RequestBody Map<String,Object> data) throws ParseException { System.out.println(data); String datesString = String.valueOf(data.get("date")); String name = (String) data.get("name"); List<HashMap<String, Object>> resultInfos = new ArrayList<>(); ArrayList<Date> dates = new ArrayList<>(); if (datesString != null && !StringUtil.isEmpty(datesString)){ datesString = datesString.replace("[","").replace("]",""); dates = new ArrayList(Arrays.asList(datesString.split(","))); } if ((dates != null && dates.size() == 2) || !StringUtil.isEmpty(name)){ resultInfos = getInInfoService.getInfosByTimeOrName(dates, name); }else if (dates != null && dates.size() == 0 && StringUtil.isEmpty(name)){ resultInfos = getInInfoService.getAllInfos(); } if ( resultInfos != null && resultInfos.size() > 0) { return resultInfos; } return new ArrayList<>(); } @RequestMapping("updateInfo") private Boolean updateInfoById(@RequestBody Map<String,Object> data) throws ParseException { System.out.println(data); GetInInfo getInInfo = new GetInInfo(); String id = (String) data.get("id"); String name = (String) data.get("name"); String address = (String) data.get("address"); String idCard = (String) data.get("idCard"); Date inTime =sdf.parse(String.valueOf(data.get("dateTime"))); Double tempNow = (Double) data.get("tempNow"); String wheLeave = (String) data.get("wheLeave"); Boolean healthCode = (Boolean) data.get("healthCode"); getInInfo.setId(id); getInInfo.setName(name); getInInfo.setIdCard(idCard); getInInfo.setAddress(address); getInInfo.setInTime(inTime); getInInfo.setTemperature(tempNow); getInInfo.setWheLeave("否".equals(wheLeave)?"0":"1"); getInInfo.setHealthCode(healthCode?"1":"0"); if (getInInfoService.updateInfo(getInInfo)) { return true; } return false; } @RequestMapping("deleteInfo/{id}") private Boolean deleteInfoById(@PathVariable String id) { if (id != null && !StringUtil.isEmpty(id)) { return getInInfoService.deleteInfo(id); } return false; } @RequestMapping("getTemps/{idCard}") private List<HashMap<String,Object>> getTemps(@PathVariable String idCard){ if (!StringUtil.isEmpty(idCard)){ return getInInfoService.getTemps(idCard); } return new ArrayList<>(); } @RequestMapping("getDailyTempInfo") private HashMap<String,Object> getDailyTempInfo(){ HashMap<String, Object> dailyTempInfo = getInInfoService.getDailyTempInfo(); return dailyTempInfo; } }
true
d54ac7e72dda527159edefd542eb4d935050b3cf
Java
tteofili/btl
/core/src/test/java/com/github/tteofili/btl/core/InformationExtractionIT.java
UTF-8
4,145
2.078125
2
[ "Apache-2.0" ]
permissive
package com.github.tteofili.btl.core; import java.io.File; import java.net.URL; import java.nio.file.Paths; import java.util.Collection; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.FSDirectory; import org.apache.uima.UIMAFramework; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Feature; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.resource.ResourceSpecifier; import org.apache.uima.util.XMLInputSource; import org.junit.Test; import com.github.tteofili.btl.crawler.Crawler; import com.github.tteofili.btl.crawler.Page; import com.github.tteofili.btl.crawler.SimpleDescendingCrawler; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * IT for IE tasks */ public class InformationExtractionIT { @Test public void testCrawlingAndIE() throws Exception { Crawler crawler = new SimpleDescendingCrawler(); Page rootPage = crawler.getPage(new URL("http://www.repubblica.it/politica")); assertNotNull(rootPage); Collection<Page> pages = crawler.getLinkedPages(rootPage); assertNotNull(pages); XMLInputSource in = new XMLInputSource(getClass().getResource("/uima/BtlAggregateAEDescriptor.xml")); ResourceSpecifier specifier = UIMAFramework.getXMLParser().parseResourceSpecifier(in); AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(specifier); for (Page p : pages) { CAS cas = ae.newCAS(); cas.setDocumentText(p.getText()); ae.process(cas); for (AnnotationFS a : cas.getAnnotationIndex()) { if (a.getType().getName().startsWith("com.github.tteofili.btl") || a.getType().getName().startsWith("org.apache.uima.alchemy")) { System.out.println("a: " + a.getType() + " -> " + a.getCoveredText()); for (Feature f : a.getType().getFeatures()) { if ("uima.cas.AnnotationBase:sofa".equals(f.getName())) { // ignore it } else if (!f.getRange().isPrimitive()) { FeatureStructure featureValue = a.getFeatureValue(f); if (featureValue instanceof AnnotationFS) { System.out.println("a: " + a.getType() + "/" + f.getName() + "-> " + ((AnnotationFS) featureValue).getCoveredText()); } else { System.out.println("a: " + a.getType() + "/" + f.getName() + "-> " + featureValue); } } else { System.out.println("a: " + a.getType() + "/" + f.getName() + "-> " + a.getFeatureValueAsString(f)); } } } } cas.release(); } FSDirectory directory = FSDirectory.open(Paths.get(getClass().getResource("/").getFile())); IndexReader reader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(reader); try { TopDocs topDocs = indexSearcher.search(new MatchAllDocsQuery(), Integer.MAX_VALUE); assertTrue(topDocs.totalHits > 0); for (ScoreDoc scoreDoc : topDocs.scoreDocs) { Document doc = indexSearcher.doc(scoreDoc.doc); String author = doc.get("author"); assertNotNull(author); String statement = doc.get("statement"); assertNotNull(statement); System.out.println(author + ": \"" + statement + "\""); } } finally { reader.close(); directory.close(); } } }
true
fbcf7f0e563385dc48c680fd306f0c99efc135b9
Java
winvaz/winvaz-boot
/src/test/java/com/icore/winvaz/javase/basic/io/IOArrayTotalTest.java
UTF-8
6,277
3.625
4
[]
no_license
package com.icore.winvaz.javase.basic.io; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Objects; /** * 提供一个文本文件,文件中保存的是姓名和成绩 * 读取文件,对姓名和成绩按照成绩高低排序 * 将排序后的结果,保存到另一个文件中 * 数据中姓名,成绩可能重复 * 对于文件有要求,提供你的文件 * studentscore.txt 排序后另存的文件sortstudentscore.txt. * abc.txt sortabc.txt * <p> * IO,字符,File * 集合List Collections */ /** * 张三 10 * 李四 11 * 王五 12 * 赵六 12 * 田七 15 * 周八 0 * 吴九 20 * 郑十 100 */ public class IOArrayTotalTest { public static void main(String[] args) { BufferedReader bufferedReader = null; BufferedWriter bufferedWriter = null; try { // 把文件封装成File对象 File file = new File("/Users/wdq/Documents/studentscore.txt"); // 字符缓冲流对象读取文件 bufferedReader = new BufferedReader(new FileReader(file)); // 定义一个数组存储读取到的学生信息 List<Student> students = new ArrayList<>(); String line = null; while ((line = bufferedReader.readLine()) != null) { // 对读到的数据用空格切割 String[] split = line.split(" +"); // 数组0下标为学生姓名,数组1小标为学生成绩,存入集合中 students.add(new Student(split[0], Integer.parseInt(split[1]))); } // 使用Collections工具类中的方法 sort,排序的是自定义对象 Collections.sort(students, new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // 先按成绩,成绩之后再按姓名 /* double different = 1e-6d; int flag; if (Math.abs(o1.getScore() - o2.getScore()) < different) { flag = 0; } else if (Math.abs(o1.getScore() - o2.getScore()) > different) { flag = 1; } else { flag = -1; } */ int x = o1.getScore() - o2.getScore(); return x == 0 ? o1.getName().compareTo(o2.getName()) : x; } }); // 将排序后的内存,存储到新的文本文件中,要求文件名前面加sort // 获取源文件的文件名 String fileName = "sort" + file.getName(); // 获取源文件的父路径 String fileParent = file.getParent(); // 父路径和文件名组成File对象,传递给字符输出流写文件 File desFile = new File(fileParent, fileName); // 字符缓冲流输出 bufferedWriter = new BufferedWriter(new FileWriter(desFile)); // 循环文件写入 for (Student student : students) { bufferedWriter.write(student.getName() + " " + student.getScore()); // 换行 bufferedWriter.newLine(); // 刷新 bufferedWriter.flush(); } } catch (FileNotFoundException e) { e.printStackTrace(); System.out.println("文件不存在"); } catch (IOException e) { e.printStackTrace(); System.out.println("IO异常,请检查"); } finally { try { if (bufferedWriter != null) { bufferedWriter.close(); } } catch (Exception e) { e.printStackTrace(); System.out.println("字符缓冲输出流资源关闭失败."); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } } catch (Exception e) { e.printStackTrace(); System.out.println("字符缓冲输入流资源关闭失败."); } } } } } /** * 定义一个学生类 */ class Student { private String name; // private Double score; // 把分数改成Integer private Integer score; // 构造函数 public Student() { } public Student(String name, int score) { this.name = name; this.score = score; } // get/set方法 public void setName(String name) { this.name = name; } public String getName() { return name; } public void setScore(int score) { this.score = score; } public Integer getScore() { return score; } // equals/hashcode @Override public boolean equals(Object o) { // 如果this==o返回true if (this == o) { return true; } // 判断是否等于null和是否是Student类型 if (o != null || getClass() != o.getClass()) { return false; } // 对参数o进行向下转型 Student student = (Student) o; /* // 对于浮点类型数据不能用基本数据类型不能==包装数据类型不能equals比较,让成绩小于某个区间则为相等。 double different = 1e-6d; boolean flag = false; if (Math.abs(score - student.score) < different) { flag = true; } */ return name.equals(student.name) && score.equals(student.score); } @Override public int hashCode() { return Objects.hash(name, score); } // 覆盖toString() @Override public String toString() { return "Student{" + "name=" + name + '\'' + "socre=" + score + "}"; } }
true
7a1124cd5e0d460ac31533312bbc8d8e5c6345c0
Java
XJGamma/BookGamma
/app/src/main/java/cn/edu/xjtu/se/bookgamma/pretend/way/part_or_day/Large_year_or_little_time.java
UTF-8
540
2.8125
3
[]
no_license
package cn.edu.xjtu.se.bookgamma.pretend.way.part_or_day; public class Large_year_or_little_time { private int year_or_big_way; private int other_week_or_eye; public Large_year_or_little_time() { year_or_big_way = 2051; other_week_or_eye = 3816; } public void problem() { ask_woman_above_group(); System.out.println("seem_bad_way" + year_or_big_way); } private void ask_woman_above_group() { System.out.println("small_company_and_world" + other_week_or_eye); } }
true
f3342a16d0d0a6b2265c6e77ed49b5ca4618ab86
Java
dabinDev/BleBracelet
/app/src/main/java/cn/dabin/opensource/ble/base/BaseFragment.java
UTF-8
4,610
2.109375
2
[]
no_license
package cn.dabin.opensource.ble.base; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import androidx.fragment.app.Fragment; import cn.dabin.opensource.ble.util.SharedPreUtil; import github.opensource.dialog.BeToastUtil; import github.opensource.dialog.prompt.PromptDialog; /** * Project : BleBracelet. * Package name: cn.dabin.opensource.ble.base * Created by : dabin. * Created time: 2019/8/27 16:09 * Changed by : dabin. * Changed time: 2019/8/27 16:09 * Class description: */ public abstract class BaseFragment extends Fragment { public View view; private boolean isLazyLoaded; private boolean isPrepared; private PromptDialog loading; @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); lazyLoad(); } /** * 获取状态栏高度 */ public int getStatusBarHeight() { //获取status_bar_height资源的ID int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { //根据资源ID获取响应的尺寸值 return getResources().getDimensionPixelSize(resourceId); } return -1; } //显示信息toast protected void showCenterInfoMsg(String text) { if (!TextUtils.isEmpty(text)) { BeToastUtil.get().showCenterInfoMsg(getActivity(), text); } } //显示成功toast protected void showCenterSuccessMsg(String text) { if (!TextUtils.isEmpty(text)) { BeToastUtil.get().showCenterSuccessMsg(getActivity(), text); } } //显示错误snaker protected void showTopWrongMsg(String text) { if (!TextUtils.isEmpty(text)) { BeToastUtil.get().showTopWrongMsg(getActivity(), text); } } /** * 调用懒加载 */ private void lazyLoad() { if (getUserVisibleHint() && isPrepared && !isLazyLoaded) { onLazyLoad(); isLazyLoaded = true; } } protected abstract int getLayoutId(); @UiThread public abstract void onLazyLoad(); @Override public void onAttach(Context context) { super.onAttach(context); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(getLayoutId(), container, false); loading = new PromptDialog(getActivity()); } else { // 二次加载删除上一个子view ViewGroup viewGroup = (ViewGroup) view.getParent(); if (viewGroup != null) { viewGroup.removeView(view); } } return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); isPrepared = true; //只有Fragment onCreateView好了, //另外这里调用一次lazyLoad() lazyLoad(); } @Override public void onDestroyView() { super.onDestroyView(); } public String readToken() { return SharedPreUtil.getString(getContext(), "token", ""); } public void saveToken(String token) { SharedPreUtil.saveString(getContext(), "token", token); } public void removeToken() { SharedPreUtil.clearByKey(getContext(), "token"); } public String readMobile() { return SharedPreUtil.getString(getContext(), "mobile", ""); } public void saveMobile(String mobile) { SharedPreUtil.saveString(getContext(), "mobile", mobile); } public void removeMobile() { SharedPreUtil.clearByKey(getContext(), "mobile"); } public String readMac() { return SharedPreUtil.getString(getContext(), "mac", ""); } public void saveMac(String mac) { SharedPreUtil.saveString(getContext(), "mac", mac); } public void removeMac(String mac) { SharedPreUtil.clearByKey(getContext(), "mac"); } public void loading(String message) { if (loading == null) { return; } loading.showLoading(message); } public void dissmiss() { if (loading == null) { return; } loading.dismiss(); } }
true
d56dfdbf1717e53d9a90e901510730ab86e2ddc2
Java
Mapuut/2D-MMO
/src/game/entity/projectile/HandProjectile.java
UTF-8
945
3.03125
3
[]
no_license
/* * Decompiled with CFR 0_115. */ package game.entity.projectile; import game.entity.mob.Mob; public class HandProjectile extends Projectile { public HandProjectile(int x, int y, double dir, Mob mob) { super(x, y, dir, mob); this.cooldown = 90; this.range = 25.0; this.speed = 10.0; this.damage = 2.0; this.size = 15; this.xSpeed = this.speed * Math.cos(this.angle); this.ySpeed = this.speed * Math.sin(this.angle); } @Override public void update() { this.checkIfEnemy(); if (this.removed) { return; } this.move(); } @Override public void render() { } protected void move() { this.xx += this.xSpeed; this.yy += this.ySpeed; this.x = (int)this.xx; this.y = (int)this.yy; if (this.distance() >= this.range) { this.remove(); } } }
true
921af9a9fc649929294a4100c87480f333b0ae05
Java
ertugertshkulaku/IOT
/backend/src/main/java/com/moveengineering/backend/repository/AssetRepository.java
UTF-8
304
1.65625
2
[]
no_license
package com.moveengineering.backend.repository; import com.moveengineering.backend.model.Asset; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; @Repository public interface AssetRepository extends MongoRepository<Asset, String> { }
true
7e0941bab5ed5d758daf80537edd155639503956
Java
maoxiaofei2009/2012_Vehicle
/src/com/zjdx/vehicle/activity/main/ui/ContentAreaAirCondition.java
IBM852
16,052
2.03125
2
[]
no_license
package com.zjdx.vehicle.activity.main.ui; import android.content.Context; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.zjdx.vehicle.R; import com.zjdx.vehicle.activity.main.common.CarStatusHelper; import com.zjdx.vehicle.activity.main.control.IControl; import com.zjdx.vehicle.activity.utils.ActivityUtils; public class ContentAreaAirCondition implements OnClickListener{ private static final String TAG = "ContentAreaLeft"; private final Context mContext; private RelativeLayout mParentLayoutArea; private RelativeLayout mAirConditionArea; private IControl mIControl; public ContentAreaAirCondition(Context context, IControl control, RelativeLayout layout){ mContext = context; mIControl = control; mParentLayoutArea = layout; initLayout(); initStatus(); } private void initLayout(){ initAirConditionArea(); initAirModel(); initAirWind(); initControl(); mParentLayoutArea.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { return true; } }); } private void initStatus(){ updateAirModelSelection(); updateAirWindSelection(); updateAirConditionTemperature(); updateAirConditionControl(); } private void initAirConditionArea(){ mAirConditionArea = new RelativeLayout(mContext); mAirConditionArea.setBackgroundResource(R.drawable.main_air_condition_background); LayoutParams params = ActivityUtils.getLayoutParams(696, 456); params.addRule(RelativeLayout.CENTER_IN_PARENT); mParentLayoutArea.addView(mAirConditionArea, params); } private ImageView mAirConditionHot; private ImageView mAirConditionCold; private ImageView mAirConditionAuto; private ImageView mAirConditionWet; private void initAirModel(){ mAirConditionHot = new ImageView(mContext); mAirConditionHot.setImageResource(R.drawable.main_air_condition_hot_select); mAirConditionHot.setId(mAirConditionHot.hashCode()); LayoutParams params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(100); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.ALIGN_PARENT_TOP); mAirConditionArea.addView(mAirConditionHot, params); mAirConditionCold = new ImageView(mContext); mAirConditionCold.setImageResource(R.drawable.main_air_condition_cold_normal); mAirConditionCold.setId(mAirConditionCold.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(2); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.BELOW, mAirConditionHot.getId()); mAirConditionArea.addView(mAirConditionCold, params); mAirConditionAuto = new ImageView(mContext); mAirConditionAuto.setImageResource(R.drawable.main_air_condition_auto_normal); mAirConditionAuto.setId(mAirConditionAuto.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(2); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.BELOW, mAirConditionCold.getId()); mAirConditionArea.addView(mAirConditionAuto, params); mAirConditionWet = new ImageView(mContext); mAirConditionWet.setImageResource(R.drawable.main_air_condition_wet_normal); mAirConditionWet.setId(mAirConditionWet.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(2); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.BELOW, mAirConditionAuto.getId()); mAirConditionArea.addView(mAirConditionWet, params); mAirConditionHot.setBackgroundResource(R.drawable.main_air_mode_background); mAirConditionHot.setOnClickListener(this); mAirConditionCold.setBackgroundResource(R.drawable.main_air_mode_background); mAirConditionCold.setOnClickListener(this); mAirConditionAuto.setBackgroundResource(R.drawable.main_air_mode_background); mAirConditionAuto.setOnClickListener(this); mAirConditionWet.setBackgroundResource(R.drawable.main_air_mode_background); mAirConditionWet.setOnClickListener(this); } private ImageView mAirWindHigh; private ImageView mAirWindLow; private void initAirWind(){ mAirWindHigh = new ImageView(mContext); mAirWindHigh.setImageResource(R.drawable.main_air_condition_low_wind_normal); mAirWindHigh.setId(mAirWindHigh.hashCode()); LayoutParams params = ActivityUtils.getLayoutParams(64, 64); params.rightMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(150); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params.addRule(RelativeLayout.ALIGN_PARENT_TOP); mAirConditionArea.addView(mAirWindHigh, params); mAirWindLow = new ImageView(mContext); mAirWindLow.setImageResource(R.drawable.main_air_condition_high_wind_normal); mAirWindLow.setId(mAirWindLow.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.rightMargin = ActivityUtils.scaleX(75); params.topMargin = ActivityUtils.scaleY(20); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); params.addRule(RelativeLayout.BELOW, mAirWindHigh.getId()); mAirConditionArea.addView(mAirWindLow, params); mAirWindHigh.setBackgroundResource(R.drawable.main_air_mode_background); mAirWindHigh.setOnClickListener(this); mAirWindLow.setBackgroundResource(R.drawable.main_air_mode_background); mAirWindLow.setOnClickListener(this); } private ImageView mAirConditionOnOff; private ImageView mAirConditionAdd; private ImageView mAirConditionReduce; private TextView mAirConditionText; private void initControl(){ mAirConditionOnOff = new ImageView(mContext); mAirConditionOnOff.setImageResource(R.drawable.main_air_condition_btn_off); mAirConditionOnOff.setId(mAirConditionOnOff.hashCode()); LayoutParams params = ActivityUtils.getLayoutParams(64, 64); params.bottomMargin= ActivityUtils.scaleY(55); params.addRule(RelativeLayout.CENTER_HORIZONTAL); params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); mAirConditionArea.addView(mAirConditionOnOff, params); mAirConditionReduce = new ImageView(mContext); mAirConditionReduce.setImageResource(R.drawable.main_air_condition_btn_reduce); mAirConditionReduce.setId(mAirConditionReduce.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(230); params.bottomMargin= ActivityUtils.scaleY(35); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.ABOVE, mAirConditionOnOff.getId()); mAirConditionArea.addView(mAirConditionReduce, params); mAirConditionAdd = new ImageView(mContext); mAirConditionAdd.setImageResource(R.drawable.main_air_condition_btn_add); mAirConditionAdd.setId(mAirConditionAdd.hashCode()); params = ActivityUtils.getLayoutParams(64, 64); params.leftMargin = ActivityUtils.scaleX(390); params.bottomMargin= ActivityUtils.scaleY(35); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.ABOVE, mAirConditionOnOff.getId()); mAirConditionArea.addView(mAirConditionAdd, params); mAirConditionText = new TextView(mContext); mAirConditionText.setId(mAirConditionText.hashCode()); mAirConditionText.setTextSize((mContext.getResources().getDimension(R.dimen.main_text_air_condition))); mAirConditionText.setText("24 ."); mAirConditionText.setGravity(Gravity.CENTER); params = ActivityUtils.getLayoutParams(200, 100); params.leftMargin = ActivityUtils.scaleX(245); params.bottomMargin= ActivityUtils.scaleY(95); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT); params.addRule(RelativeLayout.ABOVE, mAirConditionOnOff.getId()); mAirConditionArea.addView(mAirConditionText, params); mAirConditionOnOff.setBackgroundResource(R.drawable.main_air_on_off_background); mAirConditionOnOff.setOnClickListener(this); mAirConditionReduce.setBackgroundResource(R.drawable.main_air_add_reduce_background); mAirConditionReduce.setOnClickListener(this); mAirConditionAdd.setBackgroundResource(R.drawable.main_air_add_reduce_background); mAirConditionAdd.setOnClickListener(this); } @Override public void onClick(View view) { if (view == mAirConditionHot){ CarStatusHelper.getInstance().setAirConditionModel(CarStatusHelper.AIR_MODEL_HOT); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, CarStatusHelper.AIR_MODEL_HOT); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, null); } if (view == mAirConditionCold){ CarStatusHelper.getInstance().setAirConditionModel(CarStatusHelper.AIR_MODEL_COLD); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, CarStatusHelper.AIR_MODEL_COLD); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, null); } if (view == mAirConditionAuto){ CarStatusHelper.getInstance().setAirConditionModel(CarStatusHelper.AIR_MODEL_AUTO); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, CarStatusHelper.AIR_MODEL_AUTO); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, null); } if (view == mAirConditionWet){ CarStatusHelper.getInstance().setAirConditionModel(CarStatusHelper.AIR_MODEL_WET); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, CarStatusHelper.AIR_MODEL_WET); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_MODEL_CHANGE, null); } if (view == mAirWindLow){ CarStatusHelper.getInstance().setAirConditionWind(CarStatusHelper.AIR_WIND_STYLE_LOW); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_WIND_CHANGE, CarStatusHelper.AIR_WIND_STYLE_LOW); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_WIND_CHANGE, null); } if (view == mAirWindHigh){ CarStatusHelper.getInstance().setAirConditionWind(CarStatusHelper.AIR_WIND_STYLE_HIGH); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_WIND_CHANGE, CarStatusHelper.AIR_WIND_STYLE_HIGH); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_WIND_CHANGE, null); } if (view == mAirConditionOnOff){ CarStatusHelper.getInstance().setAirConditionStatus( !CarStatusHelper.getInstance().getAirConditionStatus()); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_OPEN_CHANGE, CarStatusHelper.getInstance().getAirConditionStatus()? 1:0); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_OPEN_CHANGE, null); } if (view == mAirConditionAdd){ int vaule = CarStatusHelper.getInstance().getAirConditionTemperature(); if (vaule + 1 < 35){ vaule = vaule + 1; CarStatusHelper.getInstance().setAirConditionTemperature(vaule); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_TEMPERATURE_CHANGE, vaule); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_TEMPERATURE_CHANGE, null); } } if (view == mAirConditionReduce){ int vaule = CarStatusHelper.getInstance().getAirConditionTemperature(); if (vaule - 1 > 16){ vaule = vaule - 1; CarStatusHelper.getInstance().setAirConditionTemperature(vaule); mIControl.actionCarAirCondition(IControl.EVENT_AIR_CONDITION_TEMPERATURE_CHANGE, vaule); mIControl.updateCarAirCondition(IControl.EVENT_AIR_CONDITION_TEMPERATURE_CHANGE, null); } } } public void updateAirConditionStatus(int event){ switch (event) { case IControl.EVENT_AIR_CONDITION_OPEN_CHANGE: updateAirConditionControl(); break; case IControl.EVENT_AIR_CONDITION_TEMPERATURE_CHANGE: updateAirConditionTemperature(); break; case IControl.EVENT_AIR_CONDITION_MODEL_CHANGE: updateAirModelSelection(); break; case IControl.EVENT_AIR_CONDITION_WIND_CHANGE: updateAirWindSelection(); break; default: break; } } private void updateAirModelSelection(){ int model = CarStatusHelper.getInstance().getAirConditionModel(); if (model == CarStatusHelper.AIR_MODEL_HOT){ mAirConditionHot.setImageResource(R.drawable.main_air_condition_hot_select); mAirConditionCold.setImageResource(R.drawable.main_air_condition_cold_normal); mAirConditionAuto.setImageResource(R.drawable.main_air_condition_auto_normal); mAirConditionWet.setImageResource(R.drawable.main_air_condition_wet_normal); }else if(model == CarStatusHelper.AIR_MODEL_COLD){ mAirConditionHot.setImageResource(R.drawable.main_air_condition_hot_normal); mAirConditionCold.setImageResource(R.drawable.main_air_condition_cold_select); mAirConditionAuto.setImageResource(R.drawable.main_air_condition_auto_normal); mAirConditionWet.setImageResource(R.drawable.main_air_condition_wet_normal); }else if(model == CarStatusHelper.AIR_MODEL_AUTO){ mAirConditionHot.setImageResource(R.drawable.main_air_condition_hot_normal); mAirConditionCold.setImageResource(R.drawable.main_air_condition_cold_normal); mAirConditionAuto.setImageResource(R.drawable.main_air_condition_auto_select); mAirConditionWet.setImageResource(R.drawable.main_air_condition_wet_normal); }else if(model == CarStatusHelper.AIR_MODEL_WET){ mAirConditionHot.setImageResource(R.drawable.main_air_condition_hot_normal); mAirConditionCold.setImageResource(R.drawable.main_air_condition_cold_normal); mAirConditionAuto.setImageResource(R.drawable.main_air_condition_auto_normal); mAirConditionWet.setImageResource(R.drawable.main_air_condition_wet_select); } } private void updateAirWindSelection(){ int windStyle = CarStatusHelper.getInstance().getAirConditionWind(); if (windStyle == CarStatusHelper.AIR_WIND_STYLE_LOW){ mAirWindLow.setImageResource(R.drawable.main_air_condition_low_wind_select); mAirWindHigh.setImageResource(R.drawable.main_air_condition_high_wind_normal); }else if(windStyle == CarStatusHelper.AIR_WIND_STYLE_HIGH){ mAirWindLow.setImageResource(R.drawable.main_air_condition_low_wind_normal); mAirWindHigh.setImageResource(R.drawable.main_air_condition_high_wind_select); } } private void updateAirConditionControl(){ boolean open = CarStatusHelper.getInstance().getAirConditionStatus(); mAirConditionOnOff.setImageResource(open ? R.drawable.main_air_condition_btn_off : R.drawable.main_air_condition_btn_on); mAirConditionText.setVisibility(open? View.VISIBLE:View.INVISIBLE); mAirWindLow.setEnabled(open); mAirWindHigh.setEnabled(open); mAirConditionHot.setEnabled(open); mAirConditionCold.setEnabled(open); mAirConditionAuto.setEnabled(open); mAirConditionWet.setEnabled(open); mAirConditionAdd.setEnabled(open); mAirConditionReduce.setEnabled(open); } private void updateAirConditionTemperature(){ int temperature = CarStatusHelper.getInstance().getAirConditionTemperature(); mAirConditionText.setText("" + temperature + " ."); } }
true
8fec1ad7740567a45849cf83e8fcbe05079052a4
Java
lewis-king/footypredictor
/src/main/java/io/footypredictor/model/odds/OddsPayload.java
UTF-8
873
2.1875
2
[]
no_license
package io.footypredictor.model.odds; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class OddsPayload { private final boolean success; @JsonProperty("data") private final List<Event> events; public OddsPayload(boolean success, List<Event> events) { this.success = success; this.events = events; } public OddsPayload() { success = false; events = null; } public boolean isSuccess() { return success; } public List<Event> getEvents() { return events; } @Override public String toString() { final StringBuilder sb = new StringBuilder("OddsPayload{"); sb.append("success='").append(success).append('\''); sb.append(", events=").append(events); sb.append('}'); return sb.toString(); } }
true
d0e72fb5ba55cf54ac7d872f31326e8cf258133d
Java
vishaljohri/AlgorithmPool
/TreeOperations/TreeOperations.java
UTF-8
27,120
3.71875
4
[]
no_license
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; class TreeNode { int data; TreeNode left; TreeNode right; public TreeNode(int data) { this.data = data; left = null; right = null; } } public class TreeOperations { TreeNode root; int count = 0; ArrayList<Integer> al; // for storing traversed nodes in pre-order int rank = 0; // for rank of number public TreeOperations() { this.root = null; count = 0; al = new ArrayList<>(); } public TreeNode getRoot() { return root; } public void setRoot(TreeNode root) { this.root = root; } void BSTInsertRecursive(int data, TreeNode cur) { if (cur == null) { count++; root = new TreeNode(data); } else { if (data > cur.data) { if (cur.right != null) BSTInsertRecursive(data, cur.right); else { cur.right = new TreeNode(data); count++; } } else { if (cur.left != null) BSTInsertRecursive(data, cur.left); else { cur.left = new TreeNode(data); count++; } } } } void BTInsert(int data, TreeNode cur) { if (cur == null) { root = new TreeNode(data); count++; return; } // like level order traversal java.util.Queue<TreeNode> queueNodes = new java.util.LinkedList<>(); queueNodes.add(root); while (queueNodes.size() != 0) { TreeNode tn = queueNodes.poll(); if (tn.left != null) queueNodes.add(tn.left); else { tn.left = new TreeNode(data); count++; return; } if (tn.right != null) queueNodes.add(tn.right); else { tn.right = new TreeNode(data); count++; return; } } } void levelTraversal(TreeNode cur) { if (cur == null) return; else { java.util.Queue<TreeNode> queueNodes = new java.util.LinkedList<>(); queueNodes.add(cur); while (queueNodes.size() != 0) { TreeNode temp = queueNodes.poll(); System.out.print(temp.data + " "); if (temp.left != null) queueNodes.add(temp.left); if (temp.right != null) queueNodes.add(temp.right); } } } void inOrderTraversal(TreeNode cur) { if (cur == null) return; inOrderTraversal(cur.left); System.out.print(cur.data + " "); inOrderTraversal(cur.right); } void preOrderTraversal(TreeNode cur) { if (cur == null) return; System.out.print(cur.data + " "); al.add(cur.data); preOrderTraversal(cur.left); preOrderTraversal(cur.right); } void postOrderTraversal(TreeNode cur) { if (cur == null) return; postOrderTraversal(cur.left); postOrderTraversal(cur.right); System.out.print(cur.data + " "); } void inOrderNumberRankProblem(TreeNode cur, int key) { if (cur == null) { return; } inOrderNumberRankProblem(cur.left, key); if (cur.data == key) { System.out.println("rank of element is: " + rank); return; } rank++; inOrderNumberRankProblem(cur.right, key); } int height(TreeNode cur) { if (cur == null) return 0; else return (1 + (Math.max(height(cur.left), height(cur.right)))); } boolean findNode(int element, TreeNode cur) { if (cur == null) return false; else { if (element == cur.data) return true; else if (element > cur.data) return findNode(element, cur.right); else return findNode(element, cur.left); } } TreeNode findMin(TreeNode cur) { if (cur == null) return null; else { while (cur.left != null) { cur = cur.left; } return cur; } } TreeNode findMax(TreeNode cur) { if (cur == null) return null; else { while (cur.right != null) { cur = cur.right; } return cur; } } boolean IsBalanced(TreeNode cur) { if (cur == null) { System.out.println("no element in the tree"); return true; } else { java.util.Queue<TreeNode> queueNodes = new java.util.LinkedList<>(); queueNodes.add(cur); while (queueNodes.size() != 0) { TreeNode temp = queueNodes.poll(); if (Math.abs(height(temp.left) - height(temp.right)) > 1) { System.out.println("tree is unbalanced"); return false; } if (temp.left != null) queueNodes.add(temp.left); if (temp.right != null) queueNodes.add(temp.right); } System.out.println("balanced tree"); return true; } } int IsBalancedOptimizedVersion(TreeNode cur) { if (cur == null) { return 0; } else { int leftSubtree = IsBalancedOptimizedVersion(cur.left); int rightSubtree = IsBalancedOptimizedVersion(cur.right); int diff = leftSubtree - rightSubtree; if (Math.abs(diff) > 1) { System.out.println("unbalanced tree"); return -1; } else { return (Math.max(leftSubtree, rightSubtree) + 1); } } } TreeNode createMinimumHeightBST(int ar[], int first, int last) { if (first > last) return null; int mid = (first + last) / 2; TreeNode n = new TreeNode(ar[mid]); n.left = createMinimumHeightBST(ar, first, mid - 1); n.right = createMinimumHeightBST(ar, mid + 1, last); return n; } TreeNode lastVisited = null; boolean IsBST(TreeNode cur) { if (cur == null) return true; // check and recurse left if (!IsBST(cur.left)) return false; // check current if (lastVisited != null && cur.data <= lastVisited.data) return false; lastVisited = cur; // check and recurse right if (!IsBST(cur.right)) return false; return true; } void depthLists(TreeNode cur) { if (cur == null) return; ArrayList<LinkedList<TreeNode>> result = new ArrayList<>(); LinkedList<TreeNode> l = new LinkedList<>(); l.add(cur); while (l.size() != 0) { result.add(l); LinkedList<TreeNode> parents = l; l = new LinkedList<>(); for (TreeNode parent : parents) { if (parent.left != null) l.add(parent.left); if (parent.right != null) l.add(parent.right); } } System.out.println(result); } boolean covers(TreeNode cur, int data) { if (cur == null) return false; if (cur.data == data) return true; return (covers(cur.left, data) || covers(cur.right, data)); } TreeNode commonAncestorHelper(TreeNode cur, int first, int second) { if (cur == null) return null; if ((cur.data == first) || (cur.data == second)) return cur; boolean isLeftFirst = covers(cur.left, first); boolean isLeftSecond = covers(cur.left, second); // if on diff sides return cur if (isLeftFirst != isLeftSecond) return cur; // else check which side to go as both on same side TreeNode childSide = isLeftFirst ? cur.left : cur.right; return commonAncestorHelper(childSide, first, second); } void commonAncestor(TreeNode cur, int first, int second) { /* * basically four conditions should be kept in mind: 1) Check if both * the given elements are there in tree. 2) See if one of the elements * is cur node, if its true return cur. 3) See if given elements are * present on different side of trees, if true return cur. 4) If given * elements are present on same side, then call function recursively * after checking which side to proceed. */ if (covers(cur, first) && covers(cur, second)) { System.out.println("common ancestor exists: " + commonAncestorHelper(cur, first, second).data); } else { System.out.println("there is no common ancestor"); } } boolean containsTree(TreeNode first, TreeNode second) { if (second == null) return true; return subTree(first, second); } boolean subTree(TreeNode first, TreeNode second) { if (first == null) return false; if (first.data == second.data) { if (matchTree(first, second)) return true; } return ((subTree(first.left, second) || subTree(first.right, second))); } boolean matchTree(TreeNode first, TreeNode second) { if (first == null && second == null) // both empty return true; if (first == null || second == null) // if only one is empty return false; if (first.data != second.data) return false; return ((matchTree(first.left, second.left) && matchTree(first.right, second.right))); } void findSumAllPathsHelper(TreeNode cur, int sum, int path[], int level) { if (cur == null) return; path[level] = cur.data; // look for paths that end at this node int t = 0; for (int i = level; i >= 0; i--) { t = t + path[i]; if (t == sum) { System.out.print("Path is: "); for (int j = i; j <= level; j++) System.out.print(path[j] + " "); System.out.println(); } } // look for nodes beneath this one findSumAllPathsHelper(cur.left, sum, path, level + 1); findSumAllPathsHelper(cur.right, sum, path, level + 1); } void findSumAllPaths(TreeNode cur, int sum) { int ht = height(cur); int[] path = new int[ht]; findSumAllPathsHelper(cur, sum, path, 0); } void mirror(TreeNode cur) { LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(cur); while (queue.size() != 0) { TreeNode first = queue.poll(); TreeNode temp = first.left; first.left = first.right; first.right = temp; if (first.left != null) queue.add(first.left); if (first.right != null) queue.add(first.right); } } void mirrorRecursive(TreeNode cur) { if (cur == null) return; // appply pre-order traversal and swap // swap TreeNode temp = cur.left; cur.left = cur.right; cur.right = temp; mirrorRecursive(cur.left); mirrorRecursive(cur.right); } // detect cycle boolean detectCycle(ArrayList<ArrayList<Integer>> adjacencylist, int start) { int vertices = adjacencylist.size(); boolean visited[] = new boolean[vertices]; boolean stack[] = new boolean[vertices + 1]; hasCycle(adjacencylist, visited, start, stack); int i = 0; while (i < adjacencylist.size()) { if (!visited[i]) { hasCycle(adjacencylist, visited, start, stack); } i++; } return stack[vertices]; } void hasCycle(ArrayList<ArrayList<Integer>> adjacencylist, boolean[] visited, int v, boolean[] stack) { // logic is similar to dfs visited[v] = true; stack[v] = true; System.out.print(v + " "); for (int w : adjacencylist.get(v)) { if (stack[w]) stack[stack.length - 1] = true; if (!visited[w] && !stack[w]) hasCycle(adjacencylist, visited, w, stack); } stack[v] = false; } void dfs(ArrayList<ArrayList<Integer>> adjacencylist, int start) { int vertices = adjacencylist.size(); boolean visited[] = new boolean[vertices]; dfsHelper(adjacencylist, visited, start); // iterating left out vertices int i = 0; while (i < adjacencylist.size()) { if (!visited[i]) dfsHelper(adjacencylist, visited, i); i++; } } void dfsHelper(ArrayList<ArrayList<Integer>> adjacencylist, boolean[] visited, int v) { visited[v] = true; System.out.print(v + " "); for (int w : adjacencylist.get(v)) { if (!visited[w]) dfsHelper(adjacencylist, visited, w); } } void bfs(ArrayList<ArrayList<Integer>> adjacencyList, int v) { int vertices = adjacencyList.size(); boolean[] visited = new boolean[vertices]; LinkedList<Integer> list = new LinkedList<>(); // call bfsHelper bfsHelper(adjacencyList, visited, v, list); } void bfsHelper(ArrayList<ArrayList<Integer>> adjacencyList, boolean[] visited, int v, LinkedList<Integer> list) { list.add(v); while (list.size() != 0) { int element = list.poll(); System.out.print(element + " "); for (int i : adjacencyList.get(element)) { if (!visited[i]) { list.add(i); visited[i] = true; } } } } void IsPath(ArrayList<ArrayList<Integer>> adjacencyList, int start, int end) { int vertices = adjacencyList.size(); boolean[] visited = new boolean[vertices]; LinkedList<Integer> list = new LinkedList<>(); // call bfsHelper bfsHelper(adjacencyList, visited, start, list); // check if end is visited if (visited[end]) System.out.println("\npath exists"); else System.out.println("\nthere is no path"); } void printNeighbor(TreeNode cur) { LinkedList<TreeNode> list = new LinkedList<>(); list.add(cur); list.add(null); while (list.size() > 1) { TreeNode temp = list.poll(); if (temp == null) list.add(null); else { if (temp.left != null) list.add(temp.left); if (temp.right != null) list.add(temp.right); TreeNode next = list.peek(); if (next != null) System.out.println(temp.data + " : " + next.data); else System.out.println(temp.data + " : " + next); } } } void numberLeaves(TreeNode cur) { int count = 0; LinkedList<TreeNode> list = new LinkedList<>(); list.add(cur); while (list.size() != 0) { TreeNode temp = list.poll(); if (temp.left == null && temp.right == null) count++; else { if (temp.left != null) list.add(temp.left); if (temp.right != null) list.add(temp.right); } } System.out.println("number of leaf nodes = " + count); } TreeNode convertToDLL(TreeNode cur) { if (cur == null) return null; cur = convertToDLLHelper(cur); while (cur.left != null) cur = cur.left; return cur; } TreeNode convertToDLLHelper(TreeNode cur) { if (cur == null) return null; if (cur.left != null) { TreeNode leftNode = convertToDLLHelper(cur.left); // find inorder predecessor for (; leftNode.right != null; leftNode = leftNode.right) ; leftNode.right = cur; cur.left = leftNode; } if (cur.right != null) { TreeNode rightNode = convertToDLLHelper(cur.right); // find inorder successor for (; rightNode.left != null; rightNode = rightNode.left) ; rightNode.left = cur; cur.right = rightNode; } return cur; } public ArrayList<String> serialize(TreeNode root) { ArrayList<String> s = new ArrayList<>(); if (root == null) { s.add("n"); return s; } LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(root); while (queue.size() != 0) { TreeNode cur = queue.poll(); if (cur == null) { s.add("n"); continue; } queue.add(cur.left); queue.add(cur.right); s.add(String.valueOf(cur.data)); } return s; } // Decodes your encoded data to tree. public TreeNode deserialize(ArrayList<String> data) { if (data.get(0).equals("n")) return null; TreeNode cur = new TreeNode(Integer.parseInt(data.get(0))); TreeNode rootTree = cur; LinkedList<TreeNode> queue = new LinkedList<>(); for (int i = 0; i < data.size(); i++) { int leftLoc = 2 * i + 1; int rightLoc = 2 * i + 2; if (leftLoc < data.size()) { String left = data.get(leftLoc); if (left != "n") { TreeNode childLeft = new TreeNode(Integer.parseInt(left)); cur.left = childLeft; queue.add(childLeft); } } if (rightLoc < data.size()) { String right = data.get(rightLoc); if (right != "n") { TreeNode childRight = new TreeNode(Integer.parseInt(right)); cur.right = childRight; queue.add(childRight); } } cur = queue.poll(); } return rootTree; } List<List<Integer>> result = new ArrayList<>(); public List<List<Integer>> pathSum(TreeNode root, int sum) { List<Integer> list = new ArrayList<>(); pathSumHelper(root, sum, list); return result; } void pathSumHelper(TreeNode root, int sum, List<Integer> list) { if (root == null) return; list.add(root.data); if (root.left == null && root.right == null && sum - root.data == 0) { result.add(new ArrayList<>(list)); } pathSumHelper(root.left, sum - root.data, list); pathSumHelper(root.right, sum - root.data, list); list.remove(list.size() - 1); } HashMap<Integer, List<TreeNode>> hm = new HashMap<>(); void columnTraversal(TreeNode root) { columnTraversalHelperMethod(root, 0); int min = Collections.min(hm.keySet()); int max = Collections.max(hm.keySet()); System.out.println(min + " " + max); for (int i = min; i <= max; i++) { List<TreeNode> result = hm.get(i); for (TreeNode t : result) { System.out.print(t.data + " "); } } } void columnTraversalHelperMethod(TreeNode root, int horDist) { if (root == null) return; if (!hm.containsKey(horDist)) { List<TreeNode> list = new ArrayList<>(); list.add(root); hm.put(horDist, list); } else { hm.get(horDist).add(root); } columnTraversalHelperMethod(root.left, horDist - 1); columnTraversalHelperMethod(root.right, horDist + 1); } TreeNode deleteNodeInBST(TreeNode root, int value) { if (root == null) return null; if (root.data == value) { TreeNode rightNode = root.right; TreeNode leftNode = root.left; if (rightNode != null && leftNode != null) { TreeNode cur = leftNode; TreeNode prev = root; while (cur.right != null) { prev = cur; cur = cur.right; } root.data = cur.data; if (prev != root) prev.right = cur.left; else prev.left = cur.left; } else if (leftNode != null) { return root.left; } else { return root.right; } } else if (root.data > value) root.left = deleteNodeInBST(root.left, value); else root.right = deleteNodeInBST(root.right, value); return root; } public static void main(String[] args) { TreeOperations to = new TreeOperations(); to.BSTInsertRecursive(5, to.root); to.BSTInsertRecursive(4, to.root); to.BSTInsertRecursive(2, to.root); to.BSTInsertRecursive(7, to.root); to.BSTInsertRecursive(10, to.getRoot()); to.BSTInsertRecursive(9, to.getRoot()); System.out.println("\nprinting in order traversal: "); to.inOrderTraversal(to.getRoot()); System.out.println("\nprinting pre order traversal: "); to.preOrderTraversal(to.getRoot()); System.out.println("\nprinting post order traversal: "); to.postOrderTraversal(to.getRoot()); System.out.println(); System.out.println("height of the tree is: " + to.height(to.getRoot())); System.out.println("seraching for a node: " + to.findNode(9, to.getRoot())); System.out.println("seraching for a node: " + to.findNode(6, to.getRoot())); System.out.println("Minimum element is: " + to.findMin(to.getRoot()).data); System.out.println("Maximum element is: " + to.findMax(to.getRoot()).data); // creating BT TreeOperations binaryTree = new TreeOperations(); binaryTree.BTInsert(5, binaryTree.root); binaryTree.BTInsert(4, binaryTree.root); binaryTree.BTInsert(2, binaryTree.root); binaryTree.BTInsert(7, binaryTree.root); binaryTree.BTInsert(10, binaryTree.getRoot()); binaryTree.BTInsert(9, binaryTree.getRoot()); System.out.println("Inorder traversal of BT"); binaryTree.inOrderTraversal(binaryTree.getRoot()); System.out.println("\nlevel order traversal is: "); binaryTree.levelTraversal(binaryTree.getRoot()); System.out.println("\nchecking for balanced bst:"); System.out.println(to.IsBalanced(to.getRoot())); System.out.println("\nchecking for balanced bst optimized:"); int x = (to.IsBalancedOptimizedVersion(to.getRoot())); if (x == -1) System.out.println("unbalanced"); else System.out.println("balanced"); System.out.println("checking for balanced bt"); System.out.println(binaryTree.IsBalanced(binaryTree.getRoot())); System.out.println("checking for balanced bt optimized"); x = (binaryTree.IsBalancedOptimizedVersion(binaryTree.getRoot())); if (x == -1) System.out.println("unbalanced"); else System.out.println("balanced"); System.out.println("constructing minimum ht BST from sorted array"); int ar[] = { 1, 2, 3, 4, 5, 6, 7 }; TreeOperations createBSTFromArray = new TreeOperations(); createBSTFromArray.root = createBSTFromArray.createMinimumHeightBST(ar, 0, ar.length - 1); System.out.println("height = " + createBSTFromArray.height(createBSTFromArray.getRoot())); createBSTFromArray.levelTraversal(createBSTFromArray.getRoot()); System.out.println("\nchecking BST: " + binaryTree.IsBST(binaryTree.getRoot())); System.out.println("again checking the BST: " + to.IsBST(to.getRoot())); System.out.println("printing each level in link list: "); binaryTree.levelTraversal(binaryTree.getRoot()); binaryTree.depthLists(binaryTree.getRoot()); System.out.println("creating a new BT"); TreeOperations binaryTest = new TreeOperations(); binaryTest.BTInsert(5, binaryTest.getRoot()); binaryTest.BTInsert(4, binaryTest.getRoot()); binaryTest.BTInsert(2, binaryTest.getRoot()); binaryTest.BTInsert(7, binaryTest.getRoot()); binaryTest.BTInsert(10, binaryTest.getRoot()); binaryTest.BTInsert(9, binaryTest.getRoot()); binaryTest.BTInsert(8, binaryTest.getRoot()); binaryTest.BTInsert(6, binaryTest.getRoot()); binaryTest.BTInsert(1, binaryTest.getRoot()); binaryTest.levelTraversal(binaryTest.getRoot()); System.out.println("\nchecking if root covers: " + binaryTest.covers(binaryTest.getRoot(), 6)); System.out.println("checking if root covers: " + binaryTest.covers(binaryTest.getRoot(), 0)); System.out.println("checking for common ancestor"); binaryTest.commonAncestor(binaryTest.getRoot(), 6, 10); binaryTest.commonAncestor(binaryTest.getRoot(), 6, 7); System.out.println("checking for subtree existence"); TreeOperations subTree = new TreeOperations(); subTree.BTInsert(4, subTree.getRoot()); subTree.BTInsert(7, subTree.getRoot()); subTree.BTInsert(10, subTree.getRoot()); subTree.BTInsert(6, subTree.getRoot()); subTree.BTInsert(1, subTree.getRoot()); binaryTest.preOrderTraversal(binaryTest.getRoot()); ArrayList<Integer> parent = binaryTest.al; System.out.println(); System.out.println(parent); subTree.preOrderTraversal(subTree.getRoot()); ArrayList<Integer> sub = subTree.al; System.out.println(); System.out.println(sub); int flag = 1; // check similarly for inorder traversal as well int c = (parent.indexOf(sub.get(0))); if (c == -1) { System.out.println("not subtree"); } else { for (int i = 0; i < sub.size(); i++) { if (sub.get(i) != parent.get(c++)) { flag = 0; break; } } if (flag == 1) { System.out.println("subtree found"); } else { System.out.println("subtree is not found"); } } System.out .println("again checking for subtree with optimized implementation"); System.out.println(binaryTest.containsTree(binaryTest.getRoot(), subTree.getRoot())); System.out .println("checking for the paths with the given sum as input:"); binaryTest.findSumAllPaths(binaryTree.getRoot(), 9); System.out.println("before creating mirror: "); binaryTest.levelTraversal(binaryTest.getRoot()); binaryTest.mirror(binaryTest.getRoot()); System.out.println("\n after creating the mirror"); binaryTest.levelTraversal(binaryTest.getRoot()); System.out.println("\napplying recursive mirror again"); binaryTest.mirrorRecursive(binaryTest.getRoot()); binaryTest.levelTraversal(binaryTest.getRoot()); System.out.println("\nimplementing graphs"); // creating graph by adjacency list using ArrayList<ArrayList> ArrayList<ArrayList<Integer>> graph = new ArrayList<>(); // assuming 8 vertices add empty adjacency list for each for (int i = 0; i < 8; i++) { graph.add(new ArrayList<Integer>()); } // insert neighboring vertices for each vertex graph.get(0).add(1); graph.get(0).add(2); graph.get(0).add(3); graph.get(1).add(5); graph.get(1).add(6); graph.get(2).add(4); graph.get(3).add(2); graph.get(3).add(4); graph.get(4).add(1); graph.get(6).add(5); // call dfs TreeOperations dummy = new TreeOperations(); System.out.println("DFS:"); dummy.dfs(graph, 0); // call bfs System.out.println("\nBFS:"); dummy.bfs(graph, 0); // check path dummy.IsPath(graph, 0, 4); dummy.IsPath(graph, 0, 7); dummy.IsPath(graph, 5, 0); dummy.IsPath(graph, 2, 0); dummy.IsPath(graph, 4, 1); binaryTest.printNeighbor(binaryTest.getRoot()); binaryTest.numberLeaves(binaryTest.getRoot()); TreeOperations numberRank = new TreeOperations(); numberRank.BSTInsertRecursive(20, numberRank.getRoot()); numberRank.BSTInsertRecursive(15, numberRank.getRoot()); numberRank.BSTInsertRecursive(25, numberRank.getRoot()); numberRank.BSTInsertRecursive(10, numberRank.getRoot()); numberRank.BSTInsertRecursive(5, numberRank.getRoot()); numberRank.BSTInsertRecursive(13, numberRank.getRoot()); numberRank.BSTInsertRecursive(23, numberRank.getRoot()); numberRank.BSTInsertRecursive(24, numberRank.getRoot()); numberRank.inOrderNumberRankProblem(numberRank.getRoot(), 25); // check for cycles in the graph System.out.println(); System.out.println("\nchecking for cycle in the graph: " + dummy.detectCycle(graph, 0)); // testing bst for converting to dll TreeOperations treeToDoublyList = new TreeOperations(); treeToDoublyList.BSTInsertRecursive(4, treeToDoublyList.root); treeToDoublyList.BSTInsertRecursive(2, treeToDoublyList.root); treeToDoublyList.BSTInsertRecursive(5, treeToDoublyList.root); treeToDoublyList.BSTInsertRecursive(1, treeToDoublyList.root); treeToDoublyList.BSTInsertRecursive(3, treeToDoublyList.getRoot()); treeToDoublyList.BSTInsertRecursive(0, treeToDoublyList.getRoot()); treeToDoublyList.BSTInsertRecursive(6, treeToDoublyList.root); TreeNode cur = treeToDoublyList.convertToDLL(treeToDoublyList.root); System.out.println("converting bst to linked list"); while (cur != null) { System.out.print(cur.data + " "); cur = cur.right; } // TreeOperations serializationTest = new TreeOperations(); serializationTest.BTInsert(-1, serializationTest.getRoot()); serializationTest.BTInsert(0, serializationTest.getRoot()); serializationTest.BTInsert(-1, serializationTest.getRoot()); ArrayList<String> s = serializationTest.serialize(serializationTest .getRoot()); System.out.println(); System.out.println(s); serializationTest.deserialize(s); TreeOperations binaryTree2 = new TreeOperations(); binaryTree2.BTInsert(2, binaryTree2.root); binaryTree2.BTInsert(5, binaryTree2.root); binaryTree2.BTInsert(5, binaryTree2.root); binaryTree2.pathSum(binaryTree2.root, 7); TreeOperations bTColumnTraversal = new TreeOperations(); bTColumnTraversal.BTInsert(1, bTColumnTraversal.root); bTColumnTraversal.BTInsert(2, bTColumnTraversal.root); bTColumnTraversal.BTInsert(3, bTColumnTraversal.root); bTColumnTraversal.BTInsert(4, bTColumnTraversal.root); bTColumnTraversal.BTInsert(5, bTColumnTraversal.root); bTColumnTraversal.BTInsert(6, bTColumnTraversal.root); bTColumnTraversal.BTInsert(7, bTColumnTraversal.root); bTColumnTraversal.columnTraversal(bTColumnTraversal.root); // testing deletion of node TreeOperations treeBSTDelete = new TreeOperations(); treeBSTDelete.BSTInsertRecursive(5, treeBSTDelete.root); treeBSTDelete.BSTInsertRecursive(2, treeBSTDelete.root); treeBSTDelete.BSTInsertRecursive(7, treeBSTDelete.root); treeBSTDelete.BSTInsertRecursive(1, treeBSTDelete.root); treeBSTDelete.BSTInsertRecursive(4, treeBSTDelete.getRoot()); treeBSTDelete.BSTInsertRecursive(6, treeBSTDelete.getRoot()); treeBSTDelete.BSTInsertRecursive(8, treeBSTDelete.root); treeBSTDelete.deleteNodeInBST(treeBSTDelete.root, 2); System.out.println(); treeBSTDelete.inOrderTraversal(treeBSTDelete.root); } }
true
e848e56ca35617c5aecb8682d47fc773994e6ed9
Java
Joeb3219/GovtSimulator
/GovernmentSimulator/src/com/charredsoftware/governmentsimulator/people/Person.java
UTF-8
1,102
3
3
[]
no_license
package com.charredsoftware.governmentsimulator.people; import com.charredsoftware.governmentsimulator.legal.Party; import com.charredsoftware.governmentsimulator.legal.State; import com.charredsoftware.governmentsimulator.util.Controller; /** * @author Joe Boyle <joe@charredgames.com> * @since Apr 8, 2014 */ public class Person { public String firstName, lastName; public int age; public long money; //Money is stored in cents to avoid rounding errors public Party party; public State state; public Job job; public Person(String first, String last, int age, long money, State state, Party party){ firstName = first; lastName = last; this.age = age; this.money = money; this.party = party; this.state = state; this.job = Job.NON_POLITICAL; } public void pay(){ money += job.sallary / (12 * 4); } public void alterBalance(double val){ money += val * 100.00; } public double getMoney(){ if(money >= 100000000000000000L) money = 10000000000000000L; return money / 100.00; } public String getMoneyString(){ return "$" + Controller.simpleFormat(getMoney(), 0); } }
true
3f000d94fc00662cfa9f6e8ce4012d78b015ea81
Java
Lovegoodstudy/WordCount
/src/Params.java
UTF-8
1,605
2.71875
3
[]
no_license
import java.util.ArrayList; import java.awt.Frame; import java.awt.FileDialog; public class Params { public static boolean charParam = false, wordParam = false, lineParam = false, detailParam = false, exceptWordListParam = false, recursionParam = false; public static String outputFile = "outputFile.txt", exceptWordListFile = ""; public static ArrayList<String> inputFile = new ArrayList<String>();; Params(String[] args) { for (int i = 0; i < args.length; i++) { switch (args[i]) { case "-c": this.charParam = true; break; case "-w": this.wordParam = true; break; case "-l": this.lineParam = true; break; case "-a": this.detailParam = true; break; case "-s": this.recursionParam = true; break; case "-x": this.charParam = true; this.wordParam = true; this.lineParam = true; this.detailParam = true; Frame frame = new Frame(); FileDialog openFile = new FileDialog(frame, "打开文件", FileDialog.LOAD); openFile.setVisible(true); String dirName = openFile.getDirectory(); String fileName = openFile.getFile(); System.out.println(dirName + fileName); this.inputFile.add(dirName + fileName); frame.dispose(); break; case "-o": this.outputFile = args[i + 1]; i = i + 1; break; case "-e": this.exceptWordListParam = true; this.exceptWordListFile = args[i + 1]; i = i + 1; break; default: this.inputFile.add(args[i]); break; } } } }
true
57750f6ac45f8dd2ff56edd3fd180ff52ab577b1
Java
SetAdapter/WisdomMedical
/app/src/main/java/com/hjy/wisdommedical/ui/web/WebViewActivity.java
UTF-8
6,675
1.851563
2
[]
no_license
package com.hjy.wisdommedical.ui.web; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.webkit.SslErrorHandler; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.TextView; import com.example.handsomelibrary.base.BaseActivity; import com.example.handsomelibrary.utils.JumpUtils; import com.hjy.wisdommedical.R; import butterknife.BindView; import butterknife.OnClick; /** * Created by Gab on 2018/1/15 0015. * WebView 相关内容 */ public class WebViewActivity extends BaseActivity { @BindView(R.id.web_view) WebView mWebView; @BindView(R.id.progressBar1) ProgressBar progressBar1; @BindView(R.id.showError) TextView showError; @BindView(R.id.tv_title) TextView tv_title; private static final String WEB_URL = "web_url"; @Override protected int getContentView() { return R.layout.activity_webview; } @Override protected void initData(Bundle savedInstanceState) { initView(); } @OnClick({R.id.showError, R.id.iv_back}) @Override public void onClick(View view) { switch (view.getId()) { case R.id.showError: mWebView.setVisibility(View.VISIBLE); showError.setVisibility(View.GONE); mWebView.reload(); break; case R.id.iv_back: JumpUtils.exitActivity(mContext); break; } } public static void startWebActivity(Context context, String url) { Intent intent = new Intent(context, WebViewActivity.class); intent.putExtra(WEB_URL, url); context.startActivity(intent); } @SuppressLint("SetJavaScriptEnabled") private void initView() { String url = getIntent().getStringExtra(WEB_URL); //加快HTML网页加载完成的速度,等页面finish再加载图片 if (Build.VERSION.SDK_INT >= 19) { mWebView.getSettings().setLoadsImagesAutomatically(true); } else { mWebView.getSettings().setLoadsImagesAutomatically(false); } mWebView.setHorizontalScrollBarEnabled(false);//水平不显示 mWebView.setVerticalScrollBarEnabled(false); //垂直不显示 mWebView.loadUrl(url); // Enable Javascript WebSettings webSettings = mWebView.getSettings(); //设置WebView支持javascript脚本 webSettings.setDomStorageEnabled(true); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(true); //允许缩放 webSettings.setBuiltInZoomControls(true); //原网页基础上缩放 webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // 5.0 以后的WebView加载的链接为Https开头,但是链接里面的内容,比如图片为Http链接,加载图片方法 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //两者都可以 webSettings.setMixedContentMode(webSettings.getMixedContentMode()); //mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } // Force links and redirects to open in the WebView instead of in a browser mWebView.setWebViewClient(new WebViewClient()); mWebView.setWebChromeClient(new WebChromeClient() { //用网页的标题来设置自己的标题栏 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); if (null != title) { tv_title.setText(title); } else { tv_title.setText(getString(R.string.health_information)); } } @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressBar1.setVisibility(View.GONE);//加载完网页进度条消失 } else { progressBar1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条 progressBar1.setProgress(newProgress);//设置进度值 } } }); mWebView.setWebViewClient(new WebViewClient() { @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { mWebView.setVisibility(View.GONE); showError.setVisibility(View.VISIBLE); super.onReceivedError(view, request, error); } //在认证证书不被Android所接受的情况下,我们可以通过设置重写WebViewClient的onReceivedSslError方法在其中设置接受所有网站的证书来解决 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { //super.onReceivedSslError(view, handler, error);注意一定要去除这行代码,否则设置无效。 // handler.cancel();// Android默认的处理方式 handler.proceed();// 接受所有网站的证书 // handleMessage(Message msg);// 进行其他处理 } }); } //销毁WebView @Override public void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.removeAllViews(); //在5.1上如果不加上这句话就会出现内存泄露。这是5.1的bug // mComponentCallbacks导致的内存泄漏 mWebView.setTag(null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } //改写物理按键——返回的逻辑 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack();//返回上一页面 return true; } return super.onKeyDown(keyCode, event);//退出整个应用程序 } }
true
b9445d19811d636f499ef062bd3c6522252e2161
Java
francishero/Introduction-to-java-programming-solutions
/src/chapter_1/exercise10.java
UTF-8
862
4.15625
4
[]
no_license
package chapter_1; /** * Chapter 1 Exercise 10: * * (Average speed in miles) Assume a runner runs 14 kilometers in 45 minutes and 30 seconds. * Write a program that displays the average speed in miles per hour. * (Note that 1 mile is 1.6 kilometers.) * * Created by Francis Miyoba on 05/feb/2018 */ public class exercise10 { public static void main (String[] args) { double kilometers = 14.0 ; double miles = kilometers / 1.6 ; // 1 minute = 60 seconds // convert 45 minutes to seconds and add 30 seconds // convert the whole thing to hours // 1 hour has 60 minutes, 60 minutes has 60 seconds // so 1 hour has 60*60 seconds double rate = (45.0 * 60.0 + 30.0) / (60.0 * 60.0) ; double average_speed = miles / rate ; System.out.println(average_speed); } }
true
99e7cf45b026d9870d429326f1ab4fa7828f758d
Java
muten84/spring-security-oauth2
/others/sdotodocservice-poc/sdoordinari-datalayer/src/main/java/it/eng/areas/ems/ordinari/dao/rule/WebBookingDeepDepthRule.java
UTF-8
461
1.898438
2
[]
no_license
package it.eng.areas.ems.ordinari.dao.rule; import org.hibernate.Criteria; import org.hibernate.FetchMode; import it.eng.area118.sdocommon.dao.impl.FetchRule; public class WebBookingDeepDepthRule implements FetchRule { public static String NAME = "DEEP"; @Override public void applyRule(Criteria criteria) { criteria.setFetchMode("webBookingEquipments", FetchMode.JOIN); } @Override public String getName() { return NAME; } }
true
ba088255ec68eb6da04ccd4acce3be139d4d302c
Java
adzo/GoldenDev
/src/entities/ParticipationConcour.java
UTF-8
1,451
2.34375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entities; /** * * @author ift */ public class ParticipationConcour { private int idParticipationConcour; private int idArbitre; private int idConcour; public ParticipationConcour() { } public ParticipationConcour(int idParticipationConcour, int idArbitre, int idConcour) { this.idParticipationConcour = idParticipationConcour; this.idArbitre = idArbitre; this.idConcour = idConcour; } public int getIdParticipationConcour() { return idParticipationConcour; } public int getIdArbitre() { return idArbitre; } public int getIdConcour() { return idConcour; } public void setIdParticipationConcour(int idParticipationConcour) { this.idParticipationConcour = idParticipationConcour; } public void setIdArbitre(int idArbitre) { this.idArbitre = idArbitre; } public void setIdConcour(int idConcour) { this.idConcour = idConcour; } @Override public String toString() { return "ParticipationConcour{" + "idParticipationConcour=" + idParticipationConcour + ", idArbitre=" + idArbitre + ", idConcour=" + idConcour + '}'; } }
true
a5c5ed518eb3c91e8981f7aab28e677d01779b82
Java
nothene/UVa-Solutions
/11115.java
UTF-8
416
2.984375
3
[]
no_license
import java.io.*; import java.util.*; import java.math.BigInteger; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int N, T, M, K, D; while(true){ N = sc.nextInt(); D = sc.nextInt(); if(N == 0 && D == 0) break; System.out.println(BigInteger.valueOf(N).pow(D)); } sc.close(); } }
true
4350450463a0069f778f930ef115d5c770844280
Java
simonblund/soa-g2-examination-service
/service/src/main/java/com/g2/examinationservice/domain/Submission.java
UTF-8
707
1.90625
2
[]
no_license
package com.g2.examinationservice.domain; import com.g2.examinationservice.api.rest.submission.Grade; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.time.Instant; import java.time.LocalDate; @Data @AllArgsConstructor @NoArgsConstructor @Entity @Builder public class Submission { @Id private String submissionId; @ManyToOne @JoinColumn(name = "examination_id") private Examination examination; private String moduleCode; private String studentId; private String teacherId; private LocalDate createdAt; private Grade grade; private boolean verified; }
true
c339d88a14849a9c07f2069207ef8e43de6dc13e
Java
yan-huan/mos
/myb-framework/src/main/java/com/myb/framework/data/Log/type/FloatTypeHandler.java
UTF-8
994
2.5
2
[]
no_license
package com.myb.framework.data.Log.type; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class FloatTypeHandler extends BaseTypeHandler<Float> { @Override public void setNonNullParameter(PreparedStatement ps, int i, Float parameter, JdbcType jdbcType) throws SQLException { ps.setFloat(i, parameter); } @Override public Float getNullableResult(ResultSet rs, String columnName) throws SQLException { return rs.getFloat(columnName); } @Override public Float getNullableResult(ResultSet rs, int columnIndex) throws SQLException { return rs.getFloat(columnIndex); } @Override public Float getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { return cs.getFloat(columnIndex); } @Override public void appendLog(StringBuilder builder, Float parameter, DatabaseDialect dialect) { if (DatabaseDialect.MYSQL == dialect) { builder.append(parameter); } } }
true
3e53e9354b8892db1156af973262abca5b380c2c
Java
Aquerr/FutrzakBot
/src/main/java/io/github/aquerr/futrzakbot/discord/audio/FutrzakAdditionalAudioTrackData.java
UTF-8
194
1.648438
2
[ "MIT" ]
permissive
package io.github.aquerr.futrzakbot.discord.audio; import lombok.Value; import net.dv8tion.jda.api.entities.Member; @Value public class FutrzakAdditionalAudioTrackData { Member addedBy; }
true
92e3a5dcececb21c429d44ebc83abdd160bababc
Java
juanbecaria/boot2016
/src/main/java/negocio/Localidad.java
UTF-8
1,172
3.0625
3
[]
no_license
package negocio; /** * Created by juanb on 9/26/2016. */ public class Localidad implements Comparable<Localidad>{ private String ciudad; private String region; private String pais; public Localidad(String ciudad, String region, String pais) { this.ciudad = ciudad; this.region = region; this.pais = pais; } public String getCiudad() { return ciudad; } public String getRegion() { return region; } public String getPais() { return pais; } @Override public String toString() { return "Localidad{" + "ciudad='" + ciudad + '\'' + ", region='" + region + '\'' + ", pais='" + pais + '\'' + '}'; } public int compareTo(Localidad o) { int res =0; res= pais.compareTo(o.getPais()); if(res==0){ res= region.compareTo(o.getRegion()); if(res==0){ res= ciudad.compareTo(o.getCiudad()); if(res==0) { return 0; } } } return 1; } }
true
e7b2bdc0349f4e0bf710bea90470cda92021ad66
Java
henryhyn/druid-demo
/src/main/java/com/example/dao/mapper/WebsiteSearchSuggestKeywordMapper.java
UTF-8
346
1.515625
2
[]
no_license
package com.example.dao.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.dao.entity.WebsiteSearchSuggestKeyword; import org.apache.ibatis.annotations.Mapper; /** * Created by henry on 2019/8/2. */ @Mapper public interface WebsiteSearchSuggestKeywordMapper extends BaseMapper<WebsiteSearchSuggestKeyword> { }
true
d2a3bdf2687b1207327f3a99df18e0ec8b66536d
Java
manuelalcalavilchez/ReservasAulas-v4
/src/main/java/org/iesalandalus/programacion/reservasaulas/vista/grafica/VistasReservasAulas.java
UTF-8
5,661
2.09375
2
[]
no_license
/* ?¿donde esta? * 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 org.iesalandalus.programacion.reservasaulas.vista.grafica; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.iesalandalus.programacion.reservasaulas.controlador.IControladorReservasAulas; import org.iesalandalus.programacion.reservasaulas.vista.IVistaReservasAulas; import org.iesalandalus.programacion.reservasaulas.vista.grafica.controladoresVistas.VentanaPrincipalFXMLController; /** * * @author Manuel */ public class VistasReservasAulas extends Application implements IVistaReservasAulas { //declaro controlador de mi modelo private IControladorReservasAulas controladorMVC; private static VistasReservasAulas instancia=null; // constructor de la clase public VistasReservasAulas() { //System.out.println("IUGVEntanas: Constructor llamado"); if (instancia != null) { controladorMVC = instancia.controladorMVC; } else { instancia = this; } } @Override public void start(Stage stage) throws Exception { FXMLLoader loader= new FXMLLoader(getClass().getResource("Vistas/VentanaPrincipal.fxml")); Parent root = loader.load(); //System.out.println("Antes de setControlador"); VentanaPrincipalFXMLController controlador=loader.getController(); controlador.setControladorMVC(controladorMVC); Scene scene = new Scene(root); stage.setScene(scene); stage.show(); } /** * @param args the command line arguments */ /* public static void main(String[] args) { launch(args); } */ public IControladorReservasAulas getControladorMVC() { return controladorMVC; } @Override public void comenzar() { launch(this.getClass()); } @Override public void setControlador(IControladorReservasAulas controlador) { this.controladorMVC = controlador; } @Override public void anularReserva() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void borrarAula() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void borrarProfesor() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void buscarAula() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void buscarProfesor() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void consultarDisponibilidad() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void insertarAula() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void insertarProfesor() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarAulas() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarProfesores() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarReservas() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarReservasAula() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarReservasPermanencia() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void listarReservasProfesor() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void realizarReserva() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void salir() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
true
4567cd39efa284c08ab8f34e0ea4ab970732b303
Java
santiago-blip/simulacroCarrito
/src/main/java/simulacionCarrito/service/impl/CarritoProductoServiceImpl.java
UTF-8
1,294
2.15625
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package simulacionCarrito.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import simulacionCarrito.DAO.CarritoProductoDAO; import simulacionCarrito.entities.Carrito; import simulacionCarrito.entities.CarritoProducto; import simulacionCarrito.entities.Productos; import simulacionCarrito.service.ICarritoProductoService; @Service public class CarritoProductoServiceImpl implements ICarritoProductoService{ @Autowired private CarritoProductoDAO serviceDAO; @Override public void guardarCarritoProducto(CarritoProducto carritoProducto) { serviceDAO.save(carritoProducto); } @Override public void eliminarCarritoProducto(int id) { serviceDAO.deleteById(id); } @Override public CarritoProducto buscarSiExiste(Productos producto,Carrito carrito) { return serviceDAO.findByIdProductoAndIdCarrito(producto,carrito).orElse(null); } @Override public CarritoProducto buscarCarrito(int id) { return serviceDAO.findById(id).orElse(null); } }
true
97b76531acfbf7b1e521c7cca4683c0202c56074
Java
pavel-sipaty/JB29_HT4
/JB29_HT4-2/Task07.java
UTF-8
979
3.828125
4
[]
no_license
package by.jb29.mod1.les06.masMas; //Дан двухмерный массив 5×5. Найти сумму модулей отрицательных нечетных элементов. public class Task07 { public static void main(String[] args) { int sum = 0; int[][] mas = new int[][] { { 1, 5, -7, -6, -1 }, { 0, 1, 8, 4, -9 }, { 5, 8, 9, -4, -1 }, { 2, 6, 3, -5, 4 }, { 0, 0, 3, -5, 4 } }; for (int i = 0; i < mas.length; i++) { for (int j = 0; j < mas[i].length; j++) { System.out.print(mas[i][j] + " "); } System.out.println(); } System.out.println("--------"); for (int i = 0; i < mas.length; i++) { for (int j = 0; j < mas[i].length; j++) { if(mas[i][j] < 0 && mas[i][j] % 2 != 0) { sum = sum + Math.abs(mas[i][j]); } } } System.out.println("Сумма модулей отрицательных нечетных элементов равна " + sum); } }
true
68cf5968dbe3e5c7fe21251ca4d1819d651e4c74
Java
dishabehrani/practise-assignments
/insert.java
UTF-8
999
3.140625
3
[]
no_license
package com.psl.insert; public class Example1 { public static void main(String[] args) { StringBuilder sb1=new StringBuilder("Hello"); StringBuilder sb2=new StringBuilder("Hello"); char []ar=new char[]{'h','o','l','a'}; StringBuilder sb3=new StringBuilder("Disha"); StringBuilder sb4=new StringBuilder("0123456"); sb1.insert(1,'o'); System.out.println(sb1); sb2.insert(0,ar,1,3); System.out.println(sb2); //4 position exculded sb1.delete(2, 4); System.out.println(sb1); //specifiy sb1.deleteCharAt(2); System.out.println(sb1); // sb1.trim();//CE-doest exist for String Builder System.out.println(sb1.reverse()); //4 excluded sb3.replace(2, 4, "ABC"); System.out.println(sb3); //4 excluded returns charSequence System.out.println(sb4.subSequence(2, 3)); //System.out.println(sb4.subSequence(2, 2)); //blank //doesn't modify System.out.println(sb4); } }
true
6cd96c7de07db7acfdf505aefd3ce1102562c928
Java
ragnarokkrr/rgn_messaging
/rgn_jms_richards/rgn_jms_richards_ch09/src/main/java/org/rgn/jms/richards/ch09/spring/AMQ.java
UTF-8
466
2.21875
2
[]
no_license
package org.rgn.jms.richards.ch09.spring; import java.net.URI; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.broker.TransportConnector; public class AMQ { public static void main(String[] args) throws Exception { BrokerService broker = new BrokerService(); TransportConnector connector = new TransportConnector(); connector.setUri(new URI("tcp://localhost:61616")); broker.addConnector(connector); broker.start(); } }
true