file_id
stringlengths 4
9
| content
stringlengths 41
35k
| repo
stringlengths 7
113
| path
stringlengths 5
90
| token_length
int64 15
4.07k
| original_comment
stringlengths 3
9.88k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | excluded
bool 2
classes |
---|---|---|---|---|---|---|---|---|
189571_13 | package com.getepay.smartcitycheckin;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by aber on 17/05/15.
*/
public class Globals {
public static String logged_user = "trt";
public static String url = "http://tickera.com/tstt/";
public static String licenseURL_OLD = "http://update.tickera.com/license/";
public static String licenseURL = "http://update.tickera.com/license_check/";
public static String licenseApiRoute_OLD = "/can_access_chrome_app";
public static String licenseApiRoute = "/fr";
public static String key = "";
public static String eventName = "";
public static String eventDate = "";
public static String eventLocation = "";
public static int checked = 0;
public static int sold = 0;
public static boolean show_attendee_screen = false;
public static boolean show_at_once = false;
public static JSONObject translateJson;
public static boolean autosave = true;
private static ProgressDialog _progressDialog=null;
public static void showProgress(Context context){
if (_progressDialog != null) return;
ProgressDialog pd = ProgressDialog.show(context,"","");
_progressDialog = pd;
pd.setCancelable(false);
}
public static void cancelProgressDialog(){
if (_progressDialog!=null){
_progressDialog.hide();
_progressDialog.dismiss();
_progressDialog = null;
}
}
public static void showSuccess(Context context, boolean autoClose){
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.success_dialog);
TextView title = (TextView)dialog.findViewById(R.id.title);
TextView msg = (TextView)dialog.findViewById(R.id.msg);
final Handler handler = new Handler();
title.setText(Globals.getTranslation("SUCCESS"));
// msg.setText(Globals.getTranslation("SUCCESS_MESSAGE"));
// msg.setText(Globals.getTranslation("Check In Successful"));
TextView tv = (TextView)dialog.findViewById(R.id.dialogText);
tv.setText(Globals.getTranslation("OK"));
LinearLayout dialogButton = (LinearLayout) dialog.findViewById(R.id.okbtn);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("SUCCESS OK", "OK");
if (handler != null)
handler.removeCallbacksAndMessages(null);
dialog.hide();
dialog.dismiss();
//dialog = null;
}
});
dialog.show();
if (autoClose) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (dialog != null) {
dialog.hide();
dialog.dismiss();
}
}
}, 2000);
}
}
public static void showFailCheck(Context context){
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.success_dialog);
ImageView iv = (ImageView)dialog.findViewById(R.id.image);
iv.setImageDrawable(context.getResources().getDrawable(R.drawable.fail));
LinearLayout dialogButton = (LinearLayout) dialog.findViewById(R.id.okbtn);
TextView tv = (TextView)dialog.findViewById(R.id.dialogText);
tv.setText(Globals.getTranslation("OK"));
TextView title = (TextView)dialog.findViewById(R.id.title);
TextView msg = (TextView)dialog.findViewById(R.id.msg);
title.setText(Globals.getTranslation("FAIL"));
msg.setText(Globals.getTranslation("ERROR_MESSAGE"));
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("FAIL OK", "OK");
dialog.hide();
dialog.dismiss();
//dialog = null;
}
});
dialog.show();
}
public static void getPreferences(Context context){
getPreferences(context, false);
}
public static void getPreferences(Context context, boolean firstTime){
SharedPreferences sp = context.getSharedPreferences("tickera", Context.MODE_PRIVATE);
key = sp.getString("key", "");
url = sp.getString("url", "");
autosave = sp.getBoolean("autosave", true);
try {
String trs = sp.getString("translate", defaultTranslate);
// uncomment for reset language after logout
// if (firstTime) {
// translateJson = new JSONObject(((autosave) ? trs : defaultTranslate));
// setPreferences(context, "translate", ((autosave)? trs : defaultTranslate));
// }
// else
translateJson = new JSONObject(trs);
// check for newly added translates
if (!translateJson.has("ERROR_LICENSE_KEY")){
translateJson.put("ERROR_LICENSE_KEY", "License key is not valid. Please contact your administrator.");
}
}catch (JSONException jex){
jex.printStackTrace();
}
}
public static void setPreferences(Context context, String key, String value){
SharedPreferences sp = context.getSharedPreferences("tickera", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
if (key.equals("translate")) {
JSONObject oldt = translateJson;
try {
translateJson = new JSONObject(value);
}catch (JSONException jex){
translateJson = oldt;
jex.printStackTrace();
return;
}
}
ed.putString(key, value);
if (key.equals("key")) Globals.key = value;
ed.commit();
}
public static void showClassicDialog(Context context, String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setTitle(title);
builder.setMessage(message);
AlertDialog dialog = builder.create();
dialog.show();
}
public static void setAutosave(boolean b, Context context){
SharedPreferences sp = context.getSharedPreferences("tickera", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = sp.edit();
ed.putBoolean("autosave", b);
Globals.autosave = b;
ed.commit();
}
public static String getTranslation(String key){
try {
String ret = translateJson.getString(key);
return ret;
}catch (JSONException jex){}
return "";
}
public static void resetTranslate(Context c){
// uncomment for reset language after logout
//setPreferences(c, "translate", defaultTranslate);
getPreferences(c);
}
private static final String defaultTranslate = "{\n" +
"\"WORDPRESS_INSTALLATION_URL\": \"URL\",\n" +
"\"API_KEY\": \"API KEY\",\n" +
"\"AUTO_LOGIN\": \"AUTO LOGIN\",\n" +
"\"SIGN_IN\": \"SIGN IN\",\n" +
"\"SOLD_TICKETS\": \"SOLD TICKETS\",\n" +
"\"CHECKED_IN_TICKETS\": \"CHECKED IN TICKETS\",\n" +
"\"HOME_STATS\": \"HOME-STATUS\",\n" +
"\"LIST\": \"LIST\",\n" +
"\"SIGN_OUT\": \"SIGN OUT\",\n" +
"\"CANCEL\": \"CANCEL\",\n" +
"\"SEARCH\": \"Search\",\n" +
"\"ID\": \"ID\",\n" +
"\"PURCHASED\": \"Purchased\",\n" +
"\"CHECKINS\": \"CHECKINS\",\n" +
"\"CHECK_IN\": \"CHECK IN\",\n" +
"\"SUCCESS\": \"SUCCESS\",\n" +
"\"SUCCESS_MESSAGE\": \"Check In Successful\",\n" +
// "\"SUCCESS_MESSAGE\": \"TICKET WITH THIS CODE HAS BEEN CHECKED\",\n" +
"\"OK\": \"OK\",\n" +
"\"ERROR\": \"ERROR\",\n" +
"\"ERROR_MESSAGE\": \"THERE IS NO TICKET WITH THIS CODE\",\n" +
"\"PASS\": \"Pass\",\n" +
"\"FAIL\": \"Fail\",\n" +
"\"ERROR_LOADING_DATA\": \"Error loading data.\",\n" +
"\"API_KEY_LOGIN_ERROR\": \"An error occurred. Please check your internet connection, URL and the API Key entered.\",\n" +
// "\"APP_TITLE\": \"Wild Waadi\",\n" +
"\"APP_TITLE\": \"National Science Centre\",\n" +
"\"ERROR_LICENSE_KEY\": \"License key is not valid. Please contact your administrator.\"\n" +
"}";
}
| Deepanshi13/Ticket-Booking-App | Globals.java | 2,140 | // setPreferences(context, "translate", ((autosave)? trs : defaultTranslate));
| line_comment | en | true |
189813_2 | package louvain;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
public class Louvain implements Cloneable{
int n;
int m;
int num_communities = 0; // this gets returned to main by louvain which checks if equal to 10
int cluster[];
Edge edge[];
int head[];
int top;
double resolution;
double[] node_weight;
double totalEdgeWeight;
double[] cluster_weight;
double eps = 1e-14;
int global_n;
int global_cluster[];
Edge[] new_edge;
int[] new_head;
int new_top = 0;
final int iteration_time = 3;
Edge[] global_edge;
int[] global_head;
int global_top=0;
void addEdge(int u, int v, double weight) {
if(edge[top]==null)
edge[top]=new Edge();
edge[top].v = v;
edge[top].weight = weight;
edge[top].next = head[u];
head[u] = top++;
}
void addNewEdge(int u, int v, double weight) {
if(new_edge[new_top]==null)
new_edge[new_top]=new Edge();
new_edge[new_top].v = v;
new_edge[new_top].weight = weight;
new_edge[new_top].next = new_head[u];
new_head[u] = new_top++;
}
void addGlobalEdge(int u, int v, double weight) {
if(global_edge[global_top]==null)
global_edge[global_top]=new Edge();
global_edge[global_top].v = v;
global_edge[global_top].weight = weight;
global_edge[global_top].next = global_head[u];
global_head[u] = global_top++;
}
void init(String filePath, double control_communities) {
try {
String encoding = "UTF-8";
File file = new File(filePath);
if (file.isFile() && file.exists()) {
int numOfNodes = 0;
int numOfEdges = 0;
{
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader br = new BufferedReader(read);
for(String line = br.readLine(); line !=null; line = br.readLine()) {
String linedata[] = line.split(";");
int node1 = Integer.parseInt(linedata[0]);
int node2 = Integer.parseInt(linedata[1]);
numOfNodes = Math.max(Math.max(numOfNodes, node1),node2);
numOfEdges += 1;
}
br.close();
numOfNodes += 1; // Node id starts at 0
}
InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
lineTxt = bufferedReader.readLine();
global_n = n = numOfNodes;
m = numOfEdges * 2;
edge = new Edge[m];
head = new int[n];
for (int i = 0; i < n; i++)
head[i] = -1;
top = 0;
global_edge=new Edge[m];
global_head = new int[n];
for(int i=0;i<n;i++)
global_head[i]=-1;
global_top=0;
global_cluster = new int[n];
for (int i = 0; i < global_n; i++)
global_cluster[i] = i;
node_weight = new double[n];
totalEdgeWeight = 0.0;
while ((lineTxt = bufferedReader.readLine()) != null) {
String cur[] = lineTxt.split(";");
int u = Integer.parseInt(cur[0]);
int v = Integer.parseInt(cur[1]);
double curw;
if (cur.length > 2) {
curw = Double.parseDouble(cur[2]);
} else {
curw = 1.0;
}
addEdge(u, v, curw);
addEdge(v, u, curw);
addGlobalEdge(u,v,curw);
addGlobalEdge(v,u,curw);
totalEdgeWeight += 2 * curw;
node_weight[u] += curw;
if (u != v) {
node_weight[v] += curw;
}
}
resolution = (1 / totalEdgeWeight); // * 0.001;
resolution = resolution * control_communities; // this is the factor to get the right number of clusters, initialized as 1.0
// then steps up/down by 0.01 until 10 communities are obtained
System.out.println("resolution:"+resolution);
read.close();
} else {
System.out.println("ja1");
}
} catch (Exception e) {
System.out.println("ja2");
e.printStackTrace();
}
}
void init_cluster() {
cluster = new int[n];
for (int i = 0; i < n; i++) {
cluster[i] = i;
}
num_communities = n;
System.out.format("\n n:%d\n",n);
}
boolean try_move_i(int i) {
double[] edgeWeightPerCluster = new double[n];
for (int j = head[i]; j != -1; j = edge[j].next) {
int l = cluster[edge[j].v];
edgeWeightPerCluster[l] += edge[j].weight;
}
int bestCluster = -1;
double maxx_deltaQ = 0.0;
boolean[] vis = new boolean[n];
cluster_weight[cluster[i]] -= node_weight[i];
for (int j = head[i]; j != -1; j = edge[j].next) {
int l = cluster[edge[j].v];
if (vis[l])
continue;
vis[l] = true;
double cur_deltaQ = edgeWeightPerCluster[l];
cur_deltaQ -= node_weight[i] * cluster_weight[l] * resolution;
if (cur_deltaQ > maxx_deltaQ) {
bestCluster = l;
maxx_deltaQ = cur_deltaQ;
}
edgeWeightPerCluster[l] = 0;
}
if (maxx_deltaQ < eps) {
bestCluster = cluster[i];
}
//System.out.println(maxx_deltaQ);
cluster_weight[bestCluster] += node_weight[i];
if (bestCluster != cluster[i]) {
cluster[i] = bestCluster;
return true;
}
return false;
}
void rebuildGraph() {
int[] change = new int[n];
int change_size=0;
boolean vis[] = new boolean[n];
for (int i = 0; i < n; i++) {
if (vis[cluster[i]])
continue;
vis[cluster[i]] = true;
change[change_size++]=cluster[i];
}
int[] index = new int[n];
for (int i = 0; i < change_size; i++)
index[change[i]] = i;
int new_n = change_size;
new_edge = new Edge[m];
new_head = new int[new_n];
new_top = 0;
double new_node_weight[] = new double[new_n];
for(int i=0;i<new_n;i++)
new_head[i]=-1;
ArrayList<Integer>[] nodeInCluster = new ArrayList[new_n];
for (int i = 0; i < new_n; i++)
nodeInCluster[i] = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
nodeInCluster[index[cluster[i]]].add(i);
}
for (int u = 0; u < new_n; u++) {
boolean visindex[] = new boolean[new_n];
double delta_w[] = new double[new_n];
for (int i = 0; i < nodeInCluster[u].size(); i++) {
int t = nodeInCluster[u].get(i);
for (int k = head[t]; k != -1; k = edge[k].next) {
int j = edge[k].v;
int v = index[cluster[j]];
if (u != v) {
if (!visindex[v]) {
addNewEdge(u, v, 0);
visindex[v] = true;
}
delta_w[v] += edge[k].weight;
}
}
new_node_weight[u] += node_weight[t];
}
for (int k = new_head[u]; k != -1; k = new_edge[k].next) {
int v = new_edge[k].v;
new_edge[k].weight = delta_w[v];
}
}
int[] new_global_cluster = new int[global_n];
for (int i = 0; i < global_n; i++) {
new_global_cluster[i] = index[cluster[global_cluster[i]]];
}
for (int i = 0; i < global_n; i++) {
global_cluster[i] = new_global_cluster[i];
}
top = new_top;
for (int i = 0; i < m; i++) {
edge[i] = new_edge[i];
}
for (int i = 0; i < new_n; i++) {
node_weight[i] = new_node_weight[i];
head[i] = new_head[i];
}
n = new_n;
init_cluster();
}
void print() {
for (int i = 0; i < global_n; i++) {
System.out.println(i + ": " + global_cluster[i]);
}
System.out.println("-------");
}
int louvain() {
init_cluster();
int count = 0;
boolean update_flag;
do {
// print();
count++;
cluster_weight = new double[n];
for (int j = 0; j < n; j++) {
cluster_weight[cluster[j]] += node_weight[j];
}
int[] order = new int[n];
for (int i = 0; i < n; i++)
order[i] = i;
Random random = new Random();
for (int i = 0; i < n; i++) {
int j = random.nextInt(n);
int temp = order[i];
order[i] = order[j];
order[j] = temp;
}
int enum_time = 0;
int point = 0;
update_flag = false;
do {
int i = order[point];
point = (point + 1) % n;
if (try_move_i(i)) {
enum_time = 0;
update_flag = true;
} else {
enum_time++;
}
} while (enum_time < n);
if (count > iteration_time || !update_flag)
break;
rebuildGraph();
} while (true);
return num_communities;
}
} | dnettlet/MEDICI | src/louvain/Louvain.java | 2,809 | // * 0.001; | line_comment | en | true |
190087_0 | /*------------------------------------------------------------------------
* rbe.EBWInitTrans.java
* Timothy Heil
* 10/13/99
*
* ECE902 Fall '99
*
* TPC-W initial transition. Decides whether new or returning user,
* and sets eb.cid accordingly. Sends HTTP request for home page.
*------------------------------------------------------------------------
*
* This is part of the the Java TPC-W distribution,
* written by Harold Cain, Tim Heil, Milo Martin, Eric Weglarz, and Todd
* Bezenek. University of Wisconsin - Madison, Computer Sciences
* Dept. and Dept. of Electrical and Computer Engineering, as a part of
* Prof. Mikko Lipasti's Fall 1999 ECE 902 course.
*
* Copyright (C) 1999, 2000 by Harold Cain, Timothy Heil, Milo Martin,
* Eric Weglarz, Todd Bezenek.
*
* This source code is distributed "as is" in the hope that it will be
* useful. It comes with no warranty, and no author or distributor
* accepts any responsibility for the consequences of its use.
*
* Everyone is granted permission to copy, modify and redistribute
* this code under the following conditions:
*
* This code is distributed for non-commercial use only.
* Please contact the maintainer for restrictions applying to
* commercial use of these tools.
*
* Permission is granted to anyone to make or distribute copies
* of this code, either as received or modified, in any
* medium, provided that all copyright notices, permission and
* nonwarranty notices are preserved, and that the distributor
* grants the recipient permission for further redistribution as
* permitted by this document.
*
* Permission is granted to distribute this code in compiled
* or executable form under the same conditions that apply for
* source code, provided that either:
*
* A. it is accompanied by the corresponding machine-readable
* source code,
* B. it is accompanied by a written offer, with no time limit,
* to give anyone a machine-readable copy of the corresponding
* source code in return for reimbursement of the cost of
* distribution. This written offer must permit verbatim
* duplication by anyone, or
* C. it is distributed by someone who received only the
* executable form, and is accompanied by a copy of the
* written offer of source code that they received concurrently.
*
* In other words, you are welcome to use, share and improve this codes.
* You are forbidden to forbid anyone else to use, share and improve what
* you give them.
*
************************************************************************/
package rbe;
public class EBWInitTrans extends EBTransition {
public String request(EB eb, String html) {
RBE rbe = eb.rbe;
if (eb.nextInt(10)<8) {
eb.cid = rbe.NURand(eb.rand, rbe.cidA, 1,rbe.numCustomer);
eb.sessionID = null;
return(rbe.homeURL + "?" + rbe.field_cid + "=" + eb.cid);
}
else {
eb.cid = eb.ID_UNKNOWN;
eb.sessionID = null;
return(rbe.homeURL);
}
}
public void postProcess(EB eb, String html)
{
// System.out.println("INIT: SESSIONID = " + eb.sessionID);
if (eb.sessionID == null) {
eb.sessionID = eb.findSessionID(html, RBE.yourSessionID, RBE.endSessionID);
if (eb.sessionID==null) {
eb.rbe.stats.error("Trey: Unable to find shopping (session) id" +
" tag in shopping cart page." + "sessionid = " + RBE.yourSessionID + " endsessionID = " +RBE.endSessionID+ "\nHtml\n"+ html + "<???>", "<???>");
}
}
// System.out.println("INIT: Found SESSIONID = " + eb.sessionID);
};
}
| jopereira/java-tpcw | tpcw/rbe/EBWInitTrans.java | 1,011 | /*------------------------------------------------------------------------
* rbe.EBWInitTrans.java
* Timothy Heil
* 10/13/99
*
* ECE902 Fall '99
*
* TPC-W initial transition. Decides whether new or returning user,
* and sets eb.cid accordingly. Sends HTTP request for home page.
*------------------------------------------------------------------------
*
* This is part of the the Java TPC-W distribution,
* written by Harold Cain, Tim Heil, Milo Martin, Eric Weglarz, and Todd
* Bezenek. University of Wisconsin - Madison, Computer Sciences
* Dept. and Dept. of Electrical and Computer Engineering, as a part of
* Prof. Mikko Lipasti's Fall 1999 ECE 902 course.
*
* Copyright (C) 1999, 2000 by Harold Cain, Timothy Heil, Milo Martin,
* Eric Weglarz, Todd Bezenek.
*
* This source code is distributed "as is" in the hope that it will be
* useful. It comes with no warranty, and no author or distributor
* accepts any responsibility for the consequences of its use.
*
* Everyone is granted permission to copy, modify and redistribute
* this code under the following conditions:
*
* This code is distributed for non-commercial use only.
* Please contact the maintainer for restrictions applying to
* commercial use of these tools.
*
* Permission is granted to anyone to make or distribute copies
* of this code, either as received or modified, in any
* medium, provided that all copyright notices, permission and
* nonwarranty notices are preserved, and that the distributor
* grants the recipient permission for further redistribution as
* permitted by this document.
*
* Permission is granted to distribute this code in compiled
* or executable form under the same conditions that apply for
* source code, provided that either:
*
* A. it is accompanied by the corresponding machine-readable
* source code,
* B. it is accompanied by a written offer, with no time limit,
* to give anyone a machine-readable copy of the corresponding
* source code in return for reimbursement of the cost of
* distribution. This written offer must permit verbatim
* duplication by anyone, or
* C. it is distributed by someone who received only the
* executable form, and is accompanied by a copy of the
* written offer of source code that they received concurrently.
*
* In other words, you are welcome to use, share and improve this codes.
* You are forbidden to forbid anyone else to use, share and improve what
* you give them.
*
************************************************************************/ | block_comment | en | true |
190097_0 | /*------------------------------------------------------------------------
* rbe.EBWProdDetTrans.java
* Timothy Heil
* 11/10/99
*
* ECE902 Fall '99
*
* TPC-W transistion to product detail. From new products page, best
* sellers page and search results page. Also used for the "curl"
* transition from the product detail page back to itself. Pick a
* uniform random item ID from the HTML, and make a request to the
* product detail page.
*------------------------------------------------------------------------
*
* This is part of the the Java TPC-W distribution,
* written by Harold Cain, Tim Heil, Milo Martin, Eric Weglarz, and Todd
* Bezenek. University of Wisconsin - Madison, Computer Sciences
* Dept. and Dept. of Electrical and Computer Engineering, as a part of
* Prof. Mikko Lipasti's Fall 1999 ECE 902 course.
*
* Copyright (C) 1999, 2000 by Harold Cain, Timothy Heil, Milo Martin,
* Eric Weglarz, Todd Bezenek.
*
* This source code is distributed "as is" in the hope that it will be
* useful. It comes with no warranty, and no author or distributor
* accepts any responsibility for the consequences of its use.
*
* Everyone is granted permission to copy, modify and redistribute
* this code under the following conditions:
*
* This code is distributed for non-commercial use only.
* Please contact the maintainer for restrictions applying to
* commercial use of these tools.
*
* Permission is granted to anyone to make or distribute copies
* of this code, either as received or modified, in any
* medium, provided that all copyright notices, permission and
* nonwarranty notices are preserved, and that the distributor
* grants the recipient permission for further redistribution as
* permitted by this document.
*
* Permission is granted to distribute this code in compiled
* or executable form under the same conditions that apply for
* source code, provided that either:
*
* A. it is accompanied by the corresponding machine-readable
* source code,
* B. it is accompanied by a written offer, with no time limit,
* to give anyone a machine-readable copy of the corresponding
* source code in return for reimbursement of the cost of
* distribution. This written offer must permit verbatim
* duplication by anyone, or
* C. it is distributed by someone who received only the
* executable form, and is accompanied by a copy of the
* written offer of source code that they received concurrently.
*
* In other words, you are welcome to use, share and improve this codes.
* You are forbidden to forbid anyone else to use, share and improve what
* you give them.
*
************************************************************************/
package rbe;
import java.util.Vector;
import rbe.util.StrStrPattern;
import rbe.util.CharRangeStrPattern;
import rbe.util.CharSetStrPattern;
public class EBWProdDetTrans extends EBTransition {
public static final StrStrPattern itemPat =
new StrStrPattern("I_ID=");
public String request(EB eb, String html) {
Vector iid = new Vector(0);
RBE rbe = eb.rbe;
int i;
// Save HTML for the <CURL> transistion.
// See TPC-W Spec. Clause 2.14.5.4 and chart in Clause 1.1
eb.prevHTML = html;
// Scan html for items.
for (i = itemPat.find(html);i!=-1;i=itemPat.find(html, i)) {
i=i+itemPat.length();
int s = CharSetStrPattern.digit.find(html,i);
int e = CharSetStrPattern.notDigit.find(html,s+1);
iid.addElement(new Integer(Integer.parseInt(html.substring(s,e))));
}
if (iid.size()==0) {
rbe.stats.error("Unable to find any items for product detail.", "???");
return("");
}
i = eb.nextInt(iid.size());
i = ((Integer) iid.elementAt(i)).intValue();
String url=rbe.prodDetURL + "?" + rbe.field_iid + "=" + i;
return(eb.addIDs(url));
}
}
| jopereira/java-tpcw | tpcw/rbe/EBWProdDetTrans.java | 1,075 | /*------------------------------------------------------------------------
* rbe.EBWProdDetTrans.java
* Timothy Heil
* 11/10/99
*
* ECE902 Fall '99
*
* TPC-W transistion to product detail. From new products page, best
* sellers page and search results page. Also used for the "curl"
* transition from the product detail page back to itself. Pick a
* uniform random item ID from the HTML, and make a request to the
* product detail page.
*------------------------------------------------------------------------
*
* This is part of the the Java TPC-W distribution,
* written by Harold Cain, Tim Heil, Milo Martin, Eric Weglarz, and Todd
* Bezenek. University of Wisconsin - Madison, Computer Sciences
* Dept. and Dept. of Electrical and Computer Engineering, as a part of
* Prof. Mikko Lipasti's Fall 1999 ECE 902 course.
*
* Copyright (C) 1999, 2000 by Harold Cain, Timothy Heil, Milo Martin,
* Eric Weglarz, Todd Bezenek.
*
* This source code is distributed "as is" in the hope that it will be
* useful. It comes with no warranty, and no author or distributor
* accepts any responsibility for the consequences of its use.
*
* Everyone is granted permission to copy, modify and redistribute
* this code under the following conditions:
*
* This code is distributed for non-commercial use only.
* Please contact the maintainer for restrictions applying to
* commercial use of these tools.
*
* Permission is granted to anyone to make or distribute copies
* of this code, either as received or modified, in any
* medium, provided that all copyright notices, permission and
* nonwarranty notices are preserved, and that the distributor
* grants the recipient permission for further redistribution as
* permitted by this document.
*
* Permission is granted to distribute this code in compiled
* or executable form under the same conditions that apply for
* source code, provided that either:
*
* A. it is accompanied by the corresponding machine-readable
* source code,
* B. it is accompanied by a written offer, with no time limit,
* to give anyone a machine-readable copy of the corresponding
* source code in return for reimbursement of the cost of
* distribution. This written offer must permit verbatim
* duplication by anyone, or
* C. it is distributed by someone who received only the
* executable form, and is accompanied by a copy of the
* written offer of source code that they received concurrently.
*
* In other words, you are welcome to use, share and improve this codes.
* You are forbidden to forbid anyone else to use, share and improve what
* you give them.
*
************************************************************************/ | block_comment | en | true |
190171_0 | /*
Copyright 2018 Gianfranco Giulioni
This file is part of the Commodity Market Simulator (CMS):
CMS 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.
CMS 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 CMS. If not, see <http://www.gnu.org/licenses/>.
*/
package cms.agents;
import repast.simphony.essentials.RepastEssentials;
import repast.simphony.random.RandomHelper;
import cms.Cms_builder;
import cms.utils.ElementOfSupplyOrDemandCurve;
import cms.agents.MarketSession;
import java.util.ArrayList;
/**
* The Producer class hold all the relevant variable for a producer; It has methods for performing the producer's actions. The realization of production and the decision on the quantity offered in each market session are of particular importance.
* @author Gianfranco Giulioni
*
*/
public class Producer {
public String name,markets,varieties;
public double latitude,longitude,productionShare,sizeInGuiDisplay;
public boolean exportAllowed=true;
public ArrayList<Double> supplyPrices=new ArrayList<Double>();
public ArrayList<Double> marketSessionsPricesRecord=new ArrayList<Double>();
public ArrayList<ElementOfSupplyOrDemandCurve> supplyCurve=new ArrayList<ElementOfSupplyOrDemandCurve>();
public ArrayList<MarketSession> marketSessionsList=new ArrayList<MarketSession>();
public double priceEarnedInLatestMarketSession,quantitySoldInLatestMarketSession;
public String varietySoldInLatestMarketSession;
int timeOfFirstProduction=1;
int initialProduction,targetProduction,stock,numberOfMarkets,totalMarketSessions,remainingMarketSessions,offerInThisSession,production;
double sumOfSellingPrices,averageSellingPrice;
/**
* The Cms_builder calls the constructor giving as parameters the values found in a line of the producers.csv file located in the data folder.
*<br>
*The format of each line is the following:
*<br>
*name,ISO3code,latitude,longitude,productionShare,listOfMarkets,listOfProducedVarietyes,listOfPossiblePrices,timeOfProduction
*<br>
*the production share is the ratio between the producer production and the total production of the commodity.
*<br>
*When the producer sells in more than one market, the market names are separated by the | character in the listOfMarkets
*<br>
*When the producer makes more than one variety, the varieties names are separated by the | character in the listOfProducedVarieties. However, the present version of the model does not handle multiple products and the user should modify the code to achieve this result.
*<br>
*Note that the last element of the line is not used in this constructor. It is used by the setup method.
*<br>
*example:
*<br>
*China,39.9390731,120.1172706,0.05,market1|market 2,variety 1|variety 2,2
*<br>
*This line gives the geographic coordinates of China and says that this country sells in two markets, makes two variety of the product and obtain the production in the second period (if periods corresponds to month, it realizes the production in February)
* @param producerName name of the producer
* @param producerLatitude the latitude
* @param producerLongitude the longitude
* @param producerProductionShare share of the total production produced by this producer
* @param producerMarkets the list of markets in which the producer sells
* @param producerVarieties the list of varieties produced by the producer
* @param possiblePrices prices to compute the supply curve
*/
public Producer(String producerName,double producerLatitude,double producerLongitude,double producerProductionShare,String producerMarkets,String producerVarieties,ArrayList<Double> possiblePrices){
name=producerName;
latitude=producerLatitude;
longitude=producerLongitude;
productionShare=producerProductionShare;
sizeInGuiDisplay=productionShare*100;
markets=producerMarkets;
String[] partsTmpMarkets=markets.split("\\|");
numberOfMarkets=partsTmpMarkets.length;
varieties=producerVarieties;
if(Cms_builder.verboseFlag){System.out.println("Created producer: "+name+", latitude: "+latitude+", longitude: "+longitude);}
if(Cms_builder.verboseFlag){System.out.println(" sells in "+numberOfMarkets+" market(s): "+markets);}
if(Cms_builder.verboseFlag){System.out.println(" produces: "+varieties);}
supplyPrices=possiblePrices;
}
public void stepExportAllowedFlag(){
if(RandomHelper.nextDouble()<Cms_builder.probabilityToAllowExport){
exportAllowed=true;
}
else{
exportAllowed=false;
}
if(Cms_builder.verboseFlag){System.out.println(" producer: "+name+" exportAllowed "+exportAllowed);}
}
public ArrayList<ElementOfSupplyOrDemandCurve> getSupplyCurve(String theVariety){
offerInThisSession=(int)stock/remainingMarketSessions;
supplyCurve=new ArrayList<ElementOfSupplyOrDemandCurve>();
for(Double aPrice : supplyPrices){
supplyCurve.add(new ElementOfSupplyOrDemandCurve(aPrice,(double)offerInThisSession));
}
if(Cms_builder.verboseFlag){System.out.println(" "+name+" stock "+stock+" remaining market sessions "+remainingMarketSessions);}
if(Cms_builder.verboseFlag){System.out.println(" supply curve sent to market by "+name+" for product "+theVariety+" (some points)");}
return supplyCurve;
}
public void setQuantitySoldInLatestMarketSession(String theVariety, double marketPrice, double soldQuantity){
varietySoldInLatestMarketSession=theVariety;
priceEarnedInLatestMarketSession=marketPrice;
quantitySoldInLatestMarketSession=soldQuantity;
marketSessionsPricesRecord.add(new Double(priceEarnedInLatestMarketSession));
if(marketSessionsPricesRecord.size()>Cms_builder.producersPricesMemoryLength){
marketSessionsPricesRecord.remove(0);
}
if(Cms_builder.verboseFlag){System.out.println(" "+name+" state before session stock: "+stock+" remaining sessions: "+remainingMarketSessions);}
if(Cms_builder.verboseFlag){System.out.println(" "+name+" price "+priceEarnedInLatestMarketSession+" quantity sold in this session "+quantitySoldInLatestMarketSession+" of "+varietySoldInLatestMarketSession);}
stock+=-quantitySoldInLatestMarketSession;
remainingMarketSessions--;
if(Cms_builder.verboseFlag){System.out.println(" "+name+" state after session stock: "+stock+" remaining sessions: "+remainingMarketSessions);}
}
public void makeProduction(){
if(Cms_builder.verboseFlag){System.out.println(name+" state before production stock: "+stock+" remaining sessions: "+remainingMarketSessions);}
production=(new Double(targetProduction*(1+(RandomHelper.nextDouble()*2-1.0)*Cms_builder.productionRateOfChangeControl))).intValue();
/*
if(RepastEssentials.GetTickCount()>119 && RepastEssentials.GetTickCount()<123){
production=(new Double(targetProduction*(1-Cms_builder.productionRateOfChangeControl))).intValue();
}
if(RepastEssentials.GetTickCount()>131 && RepastEssentials.GetTickCount()<135){
production=targetProduction;
}
*/
stock+=production;
remainingMarketSessions=totalMarketSessions;
if(Cms_builder.verboseFlag){System.out.println(name+" production realized: "+production);}
if(Cms_builder.verboseFlag){System.out.println(name+" state after production stock: "+stock+" remaining sessions: "+remainingMarketSessions);}
//plan production for the next period
if(marketSessionsPricesRecord.size()==Cms_builder.producersPricesMemoryLength){
if(Cms_builder.verboseFlag){System.out.println(name+" set target production for next production cycle");}
//compute average price
sumOfSellingPrices=0;
for(Double tmpDouble : marketSessionsPricesRecord){
sumOfSellingPrices+=tmpDouble;
}
averageSellingPrice=sumOfSellingPrices/marketSessionsPricesRecord.size();
//increase production if average selling price higher than threshold
if(averageSellingPrice>Cms_builder.priceThresholdToIncreaseTargetProduction){
targetProduction=(int)(targetProduction*(1+Cms_builder.percentageChangeInTargetProduction));
if(Cms_builder.verboseFlag){System.out.println(name+" target production increased to "+targetProduction);}
}
//increase production if average selling price higher than threshold
if(averageSellingPrice<Cms_builder.priceThresholdToDecreaseTargetProduction){
targetProduction=(int)(targetProduction*(1+Cms_builder.percentageChangeInTargetProduction));
if(Cms_builder.verboseFlag){System.out.println(name+" target production decreased to "+targetProduction);}
}
}
else{
averageSellingPrice=0;
if(Cms_builder.verboseFlag){System.out.println(name+" there are not enough data to set target production for next production cycle");}
}
}
public void setup(int producerTimeOfFirstProduction){
timeOfFirstProduction=producerTimeOfFirstProduction;
initialProduction=(int)(productionShare*Cms_builder.globalProduction);
targetProduction=initialProduction;
production=targetProduction;
stock=(int)(productionShare*Cms_builder.globalProduction*((double)timeOfFirstProduction/Cms_builder.productionCycleLength));
totalMarketSessions=numberOfMarkets*Cms_builder.productionCycleLength;
remainingMarketSessions=numberOfMarkets*timeOfFirstProduction;
if(Cms_builder.verboseFlag){System.out.println(" time of First production "+timeOfFirstProduction+" production "+(int)(productionShare*Cms_builder.globalProduction)+" stock "+stock+" total market sessions "+totalMarketSessions+" remaining market sessions "+remainingMarketSessions);}
}
public void addMarketSession(MarketSession aNewMarketSession){
marketSessionsList.add(aNewMarketSession);
if(Cms_builder.verboseFlag){System.out.println(" producer "+name+" market Session added");}
}
public ArrayList<MarketSession> getMarkeSessions(){
return marketSessionsList;
}
public String getName(){
return name;
}
public String getMarkets(){
return markets;
}
public String getVarieties(){
return varieties;
}
public double getLatitude(){
return latitude;
}
public double getLongitude(){
return longitude;
}
public double getProductionShare(){
return productionShare;
}
public double getSizeInGuiDisplay(){
return sizeInGuiDisplay;
}
public boolean getExportAllowerFlag(){
return exportAllowed;
}
public int getTimeOfFirstProduction(){
return timeOfFirstProduction;
}
public int getStock(){
return stock;
}
public int getProduction(){
return production;
}
public int getTargetProduction(){
return targetProduction;
}
public double getAverageSellingPrice(){
return averageSellingPrice;
}
}
| gfgprojects/cms | src/cms/agents/Producer.java | 2,839 | /*
Copyright 2018 Gianfranco Giulioni
This file is part of the Commodity Market Simulator (CMS):
CMS 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.
CMS 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 CMS. If not, see <http://www.gnu.org/licenses/>.
*/ | block_comment | en | true |
190228_1 |
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.TreeMap;
/**
* Created by dgotbaum on 1/7/14.
*/
public class Market {
public static final String[] HEADER = {"Submarket & Class", "Number of Buildings","Inventory","Direct Available Space"
,"Direct Availability","Sublet Available Space","Sublet Availability","Total Available Space","Total Availability",
"Direct Vacant Space","Direct Vacancy","Sublet Vacant Space","Sublet Vacancy","Total Vacant Space","Total Vacancy","Occupied Space","Net Absorption",
"Weighted Direct Average Rent","Weighted Sublease Average Rent","Weighted Overall Average Rent","Under Construction","Under Construction (SF)"};
public int marketIndex;
public int subMarketIndex;
public int classIndex;
public Workbook wb;
public Sheet s;
public TreeMap<String, TreeMap<String,TreeMap<String,ArrayList<Row>>>> MARKETS;
public Market(Workbook wb) {
this.MARKETS = new TreeMap<String, TreeMap<String, TreeMap<String, ArrayList<Row>>>>();
this.wb = wb;
this.s = wb.getSheetAt(0);
Row headerRow = s.getRow(0);
for (Cell c : headerRow) {
if (c.getRichStringCellValue().getString().contains("Market (my data)"))
this.marketIndex = c.getColumnIndex();
else if (c.getRichStringCellValue().getString().contains("submarket"))
this.subMarketIndex = c.getColumnIndex();
else if (c.getRichStringCellValue().getString().contains("Class"))
this.classIndex = c.getColumnIndex();
}
//Iterates through the rows and populates the hashmap of the buildings by district
for (Row r: this.s) {
if (!(r.getRowNum() == 0) && r.getCell(0) != null) {
String marketName = r.getCell(marketIndex).getStringCellValue();
String subMarketName = r.getCell(subMarketIndex).getStringCellValue();
String Grade = r.getCell(classIndex).getStringCellValue();
if (!MARKETS.containsKey(marketName)) {
TreeMap<String, TreeMap<String,ArrayList<Row>>> sub = new TreeMap<String, TreeMap<String,ArrayList<Row>>>();
TreeMap<String, ArrayList<Row>> classes = new TreeMap<String, ArrayList<Row>>();
classes.put("A", new ArrayList<Row>());
classes.put("B", new ArrayList<Row>());
classes.put("C", new ArrayList<Row>());
classes.get(Grade).add(r);
sub.put(subMarketName, classes);
MARKETS.put(marketName,sub);
}
else {
if (MARKETS.get(marketName).containsKey(subMarketName))
MARKETS.get(marketName).get(subMarketName).get(Grade).add(r);
else {
TreeMap<String, ArrayList<Row>> classes = new TreeMap<String, ArrayList<Row>>();
classes.put("A", new ArrayList<Row>());
classes.put("B", new ArrayList<Row>());
classes.put("C", new ArrayList<Row>());
classes.get(Grade).add(r);
MARKETS.get(marketName).put(subMarketName, classes);
}
}
}
}
}
}
| dgotbaum/MarketReport | src/Market.java | 835 | //Iterates through the rows and populates the hashmap of the buildings by district | line_comment | en | false |
190294_0 | package Trees;
public class LCABst extends BinarySearchTree{
public Node lowestCommonAncestor(Node root, Node p, Node q){
if (root == null) return null;
int cur = root.value;
if(cur < p.value && cur < q.value){
return lowestCommonAncestor(root.right, p, q);
}
if(cur > p.value && cur > q.value){
return lowestCommonAncestor(root.left, p, q);
}
return root;
}
public static void main(String[] args) {
LCABst bst = new LCABst();
bst.insert(6);
bst.insert(4);
bst.insert(3);
bst.insert(5);
bst.insert(7);
bst.insert(8);
bst.insert(1);
// System.out.println(bst.lowestCommonAncestor(bst.root));
}
}
| prachisaid/Trees | LCABst.java | 223 | // System.out.println(bst.lowestCommonAncestor(bst.root)); | line_comment | en | true |
190357_3 | package scene2d;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapLayers;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TiledMapTileSets;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.utils.Array;
/** The Map Class
* <p>
* The Map is a Group which automatically loads all the tiles and arranges them accordingly it is
* highly recommended that you override the loadLayer method and customize the map
* </p>
* @author pyros2097 */
public class Map extends Group{
protected int tileSize;
/* List of MapLayers */
protected MapLayers mlayers;
protected MapObjects mobjects;
public static int NoOfColumns;
public static int NoOfRows;
protected float mapWidth;
protected float mapHeight;
public static TiledMapTileSets tileSets;
private Array<MapActor[][]> tiles = new Array<MapActor[][]>();
public Map(){
}
public Map(int levelNo, int tileSize){
setPosition(0, 0);
setOrigin(0, 0);
TiledMap map = Asset.map(levelNo);
this.tileSize = tileSize;
mlayers = map.getLayers();
tileSets = map.getTileSets();
}
public void loadLayer(int layerNo){
Scene.log("Tiles Layer no: "+layerNo);
TiledMapTileLayer layer = (TiledMapTileLayer)mlayers.get(layerNo);
NoOfColumns = layer.getWidth();
Scene.log("MapColumns: "+NoOfColumns);
NoOfRows = layer.getHeight();
Scene.log("MapRows: "+NoOfRows);
tiles .add(new MapActor[NoOfRows][NoOfColumns]);
for(int i=0; i<NoOfRows; i++)
for(int j=0; j<NoOfColumns; j++){
Cell c = layer.getCell(j, i);
if(c != null){
tiles.get(layerNo)[i][j] = new MapActor(c.getTile().getTextureRegion(),
i, j, c.getTile().getId(), tileSize);
addActor(tiles.get(layerNo)[i][j]);
}
else{
tiles.get(layerNo)[i][j] = new MapActor((TextureRegion)null,i, j, 0, tileSize);
addActor(tiles.get(layerNo)[i][j]);
}
}
mapWidth = tileSize * NoOfColumns;
mapHeight = tileSize * NoOfRows;
//Stage.mapOffsetX = mapWidth - Stage.camOffsetX;
//Stage.mapOffsetY = mapHeight - Stage.camOffsetYTop;
}
public void loadObjects(int no){
Scene.log("Objects Layer no: "+no);
MapLayer layer1 = mlayers.get(no);
mobjects = layer1.getObjects();
}
public float getWidth(){
return mapWidth;
}
public float getHeight(){
return mapHeight;
}
public int getNoOfColumns(){
return NoOfColumns;
}
public int getNoOfRows(){
return NoOfRows;
}
public MapObjects getMapObjects(){
return mobjects;
}
public MapLayers getMapLayers(){
return mlayers;
}
}
class MapLayerg extends Group {
public MapLayerg(int index){
this.setZIndex(index);
}
}
class RPGMap {
private static RPGMap instance;
MapLayerg mapLayer1;
MapLayerg mapLayer2;
MapLayerg mapLayer3;
MapLayerg mapLayer4;
MapLayerg mapLayer5;
MapLayerg mapLayer6;
MapLayerg mapLayer7;
private RPGMap(){
mapLayer1 = new MapLayerg(1);
mapLayer2 = new MapLayerg(2);
mapLayer3 = new MapLayerg(3);
mapLayer4 = new MapLayerg(4);
mapLayer5 = new MapLayerg(5);
mapLayer6 = new MapLayerg(6);
mapLayer7 = new MapLayerg(7);
}
public static RPGMap getInstance(){
if(instance == null)
instance = new RPGMap();
return instance;
}
} | pyrossh/gdx-studio | src/scene2d/Map.java | 1,197 | //Stage.mapOffsetY = mapHeight - Stage.camOffsetYTop;
| line_comment | en | true |
190427_0 | package abs.api;
import java.util.concurrent.Future;
/**
* An envelope opener should allow a recipient object process an
* incoming message from another object and finalize the result of the
* message. The message should be opened in a {@link abs.api.Context}
* where the object may possibly need to access other information such
* as the sender of the message.
*
* @see Context
* @see Inbox
* @see Actor#sender()
* @author Behrooz Nobakht
* @since 1.0
*/
@FunctionalInterface
public interface Opener {
/**
* Opens the envelope, runs a process inside the context of the
* target object to prepare the result of the envelope that is
* captured at the time the messages was sent. It is highly
* recommended that the implementation does not throw an exception
* and instead capture an fault into the future result of the
* envelope.
*
* @param envelope
* the envelope to be opened
* @param target
* the recipient object that binds to the reference by
* {@link abs.api.Envelope#to()}
* @return the eventual result of the message which is already
* captured by another actor reference and should complete
* or fail the future of the {@link abs.api.Envelope}.
* Note that the returned here may not actually be used as
* it is already used by using
* {@link java.util.concurrent.Future#get()}.
* @param <V>
* a V object.
*/
<V> Future<V> open(Envelope envelope, Object target);
}
| CrispOSS/abs-frontend | src/api/Opener.java | 375 | /**
* An envelope opener should allow a recipient object process an
* incoming message from another object and finalize the result of the
* message. The message should be opened in a {@link abs.api.Context}
* where the object may possibly need to access other information such
* as the sender of the message.
*
* @see Context
* @see Inbox
* @see Actor#sender()
* @author Behrooz Nobakht
* @since 1.0
*/ | block_comment | en | true |
190487_0 | package com.Week8;
/*CD's parameter contains its artist (String), title (String), and publishing year (int). All CDs weigh 0.1 kg.*/
public class CD implements ToBeStored{
private String artist;
private String title;
private int publishingYear;
public CD(String artist, String title, int publishingYear){
this.artist = artist;
this.title = title;
this.publishingYear = publishingYear;
}
@Override
public double weight() {
return 0.1;
}
}
| Ajla115/OOP_LABS_2022 | Week 8/CD.java | 127 | /*CD's parameter contains its artist (String), title (String), and publishing year (int). All CDs weigh 0.1 kg.*/ | block_comment | en | false |
190779_1 | /** This file is part of MakamBox.
MakamBox 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.
MakamBox 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 MakamBox. If not, see <http://www.gnu.org/licenses/>.
*
* MakamBox is an implementation of MakamToolBox Turkish Makam music analysis tool which is developed by Baris Bozkurt
* This is the project of music tuition system that is a tool that helps users to improve their skills to perform music.
* This thesis aims at developing a computer based interactive tuition system specifically for Turkish music.
*
* Designed and implemented by @author Bilge Mirac Atici
* Supervised by @supervisor Baris Bozkurt
* Bahcesehir University, 2014-2015
*/
package datas;
import java.io.Serializable;
/**
* This class is used for serializing note data to a *.ser file which is used for match ahenk and makam data
*/
public class Note implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4924904970560198346L;
public String name;
public Float ratio;
public Note(String n, Float r){
name = n;
ratio = r;
}
public String getName(){
return name;
}
public float getRatio(){
return ratio;
}
}
| miracatici/MakamBox | src/datas/Note.java | 447 | /**
* This class is used for serializing note data to a *.ser file which is used for match ahenk and makam data
*/ | block_comment | en | true |
191472_0 | /******************************************************************************\
* Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/
import java.io.IOException;
import java.lang.Math;
import com.leapmotion.leap.*;
class SampleListener extends Listener {
public void onInit(Controller controller) {
System.out.println("Initialized");
}
public void onConnect(Controller controller) {
System.out.println("Connected");
}
public void onDisconnect(Controller controller) {
//Note: not dispatched when running in a debugger.
System.out.println("Disconnected");
}
public void onExit(Controller controller) {
System.out.println("Exited");
}
public void onFrame(Controller controller) {
// Get the most recent frame and report some basic information
Frame frame = controller.frame();
System.out.println("Frame id: " + frame.id()
+ ", timestamp: " + frame.timestamp()
+ ", hands: " + frame.hands().count()
+ ", fingers: " + frame.fingers().count());
//Get hands
for(Hand hand : frame.hands()) {
String handType = hand.isLeft() ? "Left hand" : "Right hand";
System.out.println(" " + handType + ", id: " + hand.id()
+ ", palm position: " + hand.palmPosition());
// Get the hand's normal vector and direction
Vector normal = hand.palmNormal();
Vector direction = hand.direction();
// Calculate the hand's pitch, roll, and yaw angles
System.out.println(" pitch: " + Math.toDegrees(direction.pitch()) + " degrees, "
+ "roll: " + Math.toDegrees(normal.roll()) + " degrees, "
+ "yaw: " + Math.toDegrees(direction.yaw()) + " degrees");
// Get arm bone
Arm arm = hand.arm();
System.out.println(" Arm direction: " + arm.direction()
+ ", wrist position: " + arm.wristPosition()
+ ", elbow position: " + arm.elbowPosition());
// Get fingers
for (Finger finger : hand.fingers()) {
System.out.println(" " + finger.type() + ", id: " + finger.id()
+ ", length: " + finger.length()
+ "mm, width: " + finger.width() + "mm");
//Get Bones
for(Bone.Type boneType : Bone.Type.values()) {
Bone bone = finger.bone(boneType);
System.out.println(" " + bone.type()
+ " bone, start: " + bone.prevJoint()
+ ", end: " + bone.nextJoint()
+ ", direction: " + bone.direction());
}
}
}
if (!frame.hands().isEmpty()) {
System.out.println();
}
}
}
class Sample {
public static void main(String[] args) {
// Create a sample listener and controller
SampleListener listener = new SampleListener();
Controller controller = new Controller();
// Have the sample listener receive events from the controller
controller.addListener(listener);
// Keep this process running until Enter is pressed
System.out.println("Press Enter to quit...");
try {
System.in.read();
} catch (IOException e) {
e.printStackTrace();
}
// Remove the sample listener when done
controller.removeListener(listener);
}
}
| leapmotion/LeapCxx | samples/Sample.java | 876 | /******************************************************************************\
* Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. *
* Leap Motion proprietary and confidential. Not for distribution. *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
\******************************************************************************/ | block_comment | en | true |
191520_5 | /**
* An interface describing the functionality of all ClassPeriods
* @author Angie Palm + Ethan Shernan
* @version 42
*/
public interface ClassPeriod {
/**
* Gets the subject of a ClassPeriod
* @return the subject
*/
String getSubject();
/**
* Gets the hours of a ClassPeriod
* @return the hours
*/
int getHours();
/**
* Gets the Student's grade for a ClassPeriod
* @return the grade
*/
double getGrade();
/**
* Gets the Professor for a ClassPeriod
* @return the professor's name
*/
String getProfessor();
/**
* Sets the professor for a ClassPeriod
* @param professor the professor's name
*/
void setProfessor(String professor);
} | alexsaadfalcon/java_intro | hw05/ClassPeriod.java | 182 | /**
* Sets the professor for a ClassPeriod
* @param professor the professor's name
*/ | block_comment | en | false |
191916_0 | package sun.nio.cs;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class IBM437 extends Charset implements HistoricallyNamedCharset {
private static final String b2cTable = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \000\001\002\003\004\005\006\007\b\t\n\013\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
private static final char[] b2c = "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ \000\001\002\003\004\005\006\007\b\t\n\013\f\r\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037 !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".toCharArray();
private static final char[] c2b = new char[1792];
private static final char[] c2bIndex = new char[256];
public IBM437() { super("IBM437", StandardCharsets.aliases_IBM437); }
public String historicalName() { return "Cp437"; }
public boolean contains(Charset paramCharset) { return paramCharset instanceof IBM437; }
public CharsetDecoder newDecoder() { return new SingleByte.Decoder(this, b2c); }
public CharsetEncoder newEncoder() { return new SingleByte.Encoder(this, c2b, c2bIndex); }
static {
char[] arrayOfChar1 = b2c;
char[] arrayOfChar2 = null;
SingleByte.initC2B(arrayOfChar1, arrayOfChar2, c2b, c2bIndex);
}
}
/* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\sun\nio\cs\IBM437.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.0.7
*/ | daiqingliang/rt-source | sun/nio/cs/IBM437.java | 1,098 | /* Location: D:\software\jd-gui\jd-gui-windows-1.6.3\rt.jar!\sun\nio\cs\IBM437.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.0.7
*/ | block_comment | en | true |
191954_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* The bottom border, which can not be mined or crossed
*
* @author Sandro Lenz, Daniel Fankhauser
* @version v1.2
*/
public class Stone extends Actor {}
| sandrolenz/M226a-DwarvenGold | Stone.java | 75 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | true |
192363_0 | /** Proxy Servlet.
*
* Author: Victor Volle [email protected]
* Version: 1.00
*/
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* A most simple proxy, or perhaps better a "redirector". It gets an
* URL as parameter, reads the data from this URL and writes them
* into the response. This servlet can be used to load a file
* from an applet, that is not allowed to open a connection
* to another location.
*/
public class Proxy extends HttpServlet {
// private static final String CONTENT_TYPE = "text/html";
static final int BUFFER_SIZE = 4096;
/** */
public void init(ServletConfig config) throws ServletException
{
super.init(config);
}
/**
* Write the content of the URL (given in the parameter "URL") to the
* response
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// get the URL from the request
String load_url = "";
try {
load_url = request.getParameter("URL");
}
catch(Exception e) {
e.printStackTrace();
}
// open a connection using the given URL
URL url = new URL(load_url);
URLConnection connection = url.openConnection();
connection.connect();
// important: set the correct conetent type in the request
response.setContentType(connection.getContentType());
InputStream in = connection.getInputStream();
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int read;
// standard copying scheme
READ:
while ( true )
{
read = in.read( buffer ) ;
if ( read > 0 )
{
out.write( buffer, 0, read );
}
else
{
break READ;
}
}
}
/**
* Does the same as doGet
*/
protected void doPost(HttpServletRequest req, HttpServletResponse
resp)
throws javax.servlet.ServletException, java.io.IOException
{
doGet( req, resp);
}
/**Ressourcen bereinigen*/
public void destroy() {
}
}
| s3db/s3db | map/src/Proxy.java | 551 | /** Proxy Servlet.
*
* Author: Victor Volle [email protected]
* Version: 1.00
*/ | block_comment | en | true |
192378_0 | package uk.ac.bristol.star.cdf.record;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks field members of {@link Record} subclasses which correspond directly
* to fields in typed CDF records in a CDF file.
*
* <p>These fields are all public and final, and have names matching
* (apart perhaps from minor case tweaking)
* the fields documented in the relevant subsections of Section 2 of the
* CDF Internal Format Description document.
*
* <p>See that document for a description of the meaning of these fields.
*
* @author Mark Taylor
* @since 25 Jun 2013
* @see
* <a href="http://cdaweb.gsfc.nasa.gov/pub/software/cdf/doc/cdf34/cdf34ifd.pdf"
* >CDF Internal Format Description document</a>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CdfField {
}
| mbtaylor/jcdf | CdfField.java | 287 | /**
* Marks field members of {@link Record} subclasses which correspond directly
* to fields in typed CDF records in a CDF file.
*
* <p>These fields are all public and final, and have names matching
* (apart perhaps from minor case tweaking)
* the fields documented in the relevant subsections of Section 2 of the
* CDF Internal Format Description document.
*
* <p>See that document for a description of the meaning of these fields.
*
* @author Mark Taylor
* @since 25 Jun 2013
* @see
* <a href="http://cdaweb.gsfc.nasa.gov/pub/software/cdf/doc/cdf34/cdf34ifd.pdf"
* >CDF Internal Format Description document</a>
*/ | block_comment | en | true |
192791_0 | // Satellite class contains the data members and member functions that are used to manipulate the satellite.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Satellite {
private String orientation;
private String solarPanels;
private int dataCollected;
// Logger object
private static final Logger LOGGER = Logger.getLogger(Satellite.class.getName());
// Constructor to initialize the data members - initial state of the satellite
public Satellite() {
this.orientation = "North";
this.solarPanels = "Inactive";
this.dataCollected = 0;
}
// Function to Rotate the satellite to a given direction
public boolean rotate(String direction) {
Set<String> validDirections = new HashSet<>(Arrays.asList("North", "South", "East", "West"));
// Checks if the satellite is already facing the given direction
if (direction.equals(this.getOrientation())){
LOGGER.warning("Satellite is already facing " + direction);
return true;
}
if (validDirections.contains(direction)) {
this.orientation = direction;
LOGGER.info("Satellite rotated to " + direction);
return true;
}
else{
LOGGER.log(Level.SEVERE, "Invalid direction provided.");
return false;
}
}
public void activatePanels() {
if ("Inactive".equals(this.solarPanels)) {
this.solarPanels = "Active";
LOGGER.info("Solar panels activated");
} else {
LOGGER.warning("Solar panels are already active");
}
}
public void deactivatePanels() {
if ("Active".equals(this.solarPanels)) {
this.solarPanels = "Inactive";
LOGGER.info("Solar panels deactivated");
} else {
LOGGER.warning("Solar panels are already inactive");
}
}
public boolean collectData() {
if ("Active".equals(this.solarPanels)) {
this.dataCollected += 10;
LOGGER.info("Data collected successfully");
return true;
} else {
LOGGER.severe("Cannot collect data. Solar panels are inactive");
return false;
}
}
public String getOrientation() {
return this.orientation;
}
public String getSolarPanels() {
return this.solarPanels;
}
public int getDataCollected() {
return this.dataCollected;
}
}
| VSrihariMoorthy/Satellite-Command-System | Satellite.java | 555 | // Satellite class contains the data members and member functions that are used to manipulate the satellite. | line_comment | en | false |
193056_0 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class LostMap {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[][] adj_list = new int[n][n];
village[] map = new village[n];
// Try taking away the +1 and just add one to the answers
for (int i = 0; i < n; i++) {
map[i] = new village(i);
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 0; j < n; j++) {
adj_list[i][j] = Integer.parseInt(st.nextToken());
}
}
br.close();
// System.out.println("----------------------------------");
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < n; j++) {
// System.out.print(adj_list[i][j] + " ");
// }
// System.out.println();
// }
PriorityQueue<path> pq = new PriorityQueue<path>();
// Add paths from village to village to ArrayList
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
map[i].Paths.add(new path(i, j, adj_list[i][j]));
pq.add(new path(i, j, adj_list[i][j]));
}
}
Kruskal(map, pq, n);
}
public static void Kruskal(village[] map, PriorityQueue<path> pq, int n) {
List<Pair> MST = new ArrayList<>();
UnionFind.UF uf = new UnionFind.UF(n);
while (MST.size() != (n - 1)) {
path current_path = pq.poll();
if (!uf.isSameSet(current_path.v_village, current_path.u_village)) {
MST.add(new Pair(current_path.u_village, current_path.v_village));
uf.unionSet(current_path.u_village, current_path.v_village);
}
}
Collections.sort(MST);
for (Pair pair : MST) {
System.out.println((pair.x + 1) + " " + (pair.y + 1));
}
}
}
class village {
int set;
int village;
ArrayList<path> Paths;
boolean inMap;
village(int uv) {
this.set = uv;
this.village = uv;
this.Paths = new ArrayList<>();
this.inMap = false;
}
village(int uv, int vv, int d) {
this.set = uv;
this.village = uv;
this.Paths.add(new path(uv, vv, d));
this.inMap = false;
}
}
class path implements Comparable<path> {
int u_village;
int v_village;
int distance;
path(int u, int v, int d) {
this.u_village = u;
this.v_village = v;
this.distance = d;
}
@Override
public int compareTo(path that) {
return this.distance - that.distance;
}
}
class Pair implements Comparable<Pair> {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair other) {
// Compare by x first
int compareResult = Integer.compare(this.x, other.x);
// If x values are equal, compare by y
if (compareResult == 0) {
compareResult = Integer.compare(this.y, other.y);
}
return compareResult;
}
}
// union-find disjoint set
class UnionFind {
static class UF {
private Vector<Integer> p, rank, setSize;
private int numSets;
public UF(int N) {
p = new Vector<Integer>(N);
rank = new Vector<Integer>(N);
setSize = new Vector<Integer>(N);
numSets = N;
for (int i = 0; i < N; i++) {
p.add(i);
rank.add(0);
setSize.add(1);
}
}
public int findSet(int i) {
if (p.get(i) == i)
return i;
else {
int ret = findSet(p.get(i));
p.set(i, ret);
return ret;
}
}
// return true if element i and j are in the same set, return false otherwise
public Boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
// union two sets that contain element i and j
public void unionSet(int i, int j) {
if (!isSameSet(i, j)) {
numSets--;
int x = findSet(i), y = findSet(j);
// rank is used to keep the tree short
if (rank.get(x) > rank.get(y)) {
p.set(y, x);
setSize.set(x, setSize.get(x) + setSize.get(y));
} else {
p.set(x, y);
setSize.set(y, setSize.get(y) + setSize.get(x));
if (rank.get(x) == rank.get(y))
rank.set(y, rank.get(y) + 1);
}
}
}
// return number of disjoint sets
public int numDisjointSets() {
return numSets;
}
// return the size of the set that contain element i
public int sizeOfSet(int i) {
return setSize.get(findSet(i));
}
}
}
| BaumanAaron/CSCI3106F23 | LostMap.java | 1,463 | // Try taking away the +1 and just add one to the answers
| line_comment | en | true |
193297_15 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//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 jd.plugins.hoster;
import java.io.IOException;
import jd.PluginWrapper;
import jd.http.Browser;
import jd.http.URLConnectionAdapter;
import jd.plugins.DownloadLink;
import jd.plugins.DownloadLink.AvailableStatus;
import jd.plugins.HostPlugin;
import jd.plugins.LinkStatus;
import jd.plugins.PluginException;
import jd.plugins.PluginForHost;
@HostPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "amateurboobtube.com" }, urls = { "http://(www\\.)?amateurboobtube\\.com/videos/\\d+/.*?\\.html" }, flags = { 0 })
public class AmateurBoobTubeCom extends PluginForHost {
public AmateurBoobTubeCom(PluginWrapper wrapper) {
super(wrapper);
}
private String DLLINK = null;
@Override
public String getAGBLink() {
return "http://www.amateurboobtube.com/terms.php";
}
@Override
public AvailableStatus requestFileInformation(DownloadLink downloadLink) throws IOException, PluginException {
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(downloadLink.getDownloadURL());
if (br.containsHTML("404: File Not Found")) throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
String filename = br.getRegex("id=\"header1\" style=\"font-variant:normal; text-transform:none;\"><h2>\\ (.*?)\\.\\.\\.</h2>").getMatch(0);
DLLINK = br.getRegex("s1\\.addParam\\(\"flashvars\",\"file=(http://.*?\\.(flv|mp4))\\&").getMatch(0);
if (DLLINK == null) DLLINK = br.getRegex("(http://media\\.amateurboobtube\\.com/videos/.*?\\.(flv|mp4))\\&").getMatch(0);
if (filename == null || DLLINK == null) throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
filename = filename.trim();
if (DLLINK.endsWith(".flv"))
downloadLink.setFinalFileName(filename + ".flv");
else
downloadLink.setFinalFileName(filename + ".mp4");
Browser br2 = br.cloneBrowser();
URLConnectionAdapter con = null;
try {
con = br2.openGetConnection(DLLINK);
if (!con.getContentType().contains("html"))
downloadLink.setDownloadSize(con.getLongContentLength());
else
throw new PluginException(LinkStatus.ERROR_FILE_NOT_FOUND);
return AvailableStatus.TRUE;
} finally {
try {
con.disconnect();
} catch (Throwable e) {
}
}
}
@Override
public void handleFree(DownloadLink downloadLink) throws Exception {
requestFileInformation(downloadLink);
dl = jd.plugins.BrowserAdapter.openDownload(br, downloadLink, DLLINK, true, 0);
if (dl.getConnection().getContentType().contains("html")) {
br.followConnection();
throw new PluginException(LinkStatus.ERROR_PLUGIN_DEFECT);
}
dl.startDownload();
}
@Override
public int getMaxSimultanFreeDownloadNum() {
return -1;
}
@Override
public void reset() {
}
@Override
public void resetPluginGlobals() {
}
@Override
public void resetDownloadlink(DownloadLink link) {
}
}
| VSaliy/JDownloader-1 | src/jd/plugins/hoster/AmateurBoobTubeCom.java | 1,020 | //(www\\.)?amateurboobtube\\.com/videos/\\d+/.*?\\.html" }, flags = { 0 })
| line_comment | en | true |
194175_0 | /**
* Framee Class
* @author Christopher Scheruebl, Timon Weiss, Julius Rommel (07.05.2021 n.Chr);
* @version 0.2
*/
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Framee extends JFrame implements ActionListener, Returner {
private final JButton single, ende, settings, multi;
private static Karte kartetest;
private double spielerspeed, speedr;
private final Controller con;
public Framee(String title, Karte k, Controller c) {
super(title);
kartetest = k;
con = c;
single = new JButton("Single Player TEST");
single.setBounds(280, 590, 750, 50);
single.addActionListener(this);
add(single);
multi = new JButton("Multiplayer");
multi.setBounds(280, 650, 750, 50);
multi.addActionListener(this);
add(multi);
settings = new JButton("Settings");
settings.setBounds(280, 710, 750, 50);
settings.addActionListener(this);
add(settings);
ende = new JButton("Beenden");
ende.setBounds(280, 770, 750, 50);
ende.addActionListener(this);
add(ende);
Bild build = new Bild();
build.setBounds(0, 0, 1290, 1100);
add(build);
spielerspeed = 0.1;
speedr = 4;
}
public void actionPerformed(ActionEvent e) {
{
if (e.getSource() == single) {
this.setVisible(false);
singel();
} else if (e.getSource() == multi) {
this.setVisible(false);
mluti();
} else if (e.getSource() == ende) {
System.exit(0);
} else if (e.getSource() == settings) {
this.setVisible(false);
setting();
}
}
}
private void singel() {
Spieler sppileri = new Spieler("Spieler", spielerspeed, speedr, kartetest, con);
con.setSpieler(sppileri);
Singleplayergame gamee = new Singleplayergame(con, sppileri);
con.setGame(gamee);
MulticastSingle cast = new MulticastSingle(con, gamee);
Thread t = new Thread(cast);
cast.updategame();
t.start();
}
private void mluti() {
@SuppressWarnings("unused")
Multiplayer multiplayer = new Multiplayer("Multiplayer", kartetest, spielerspeed, speedr, con);
}
private void setting() {
new Settings(this, spielerspeed, speedr, con);
}
public void returne() {
this.setVisible(true);
}
public double getSpeed() {
return spielerspeed;
}
public void setSpeed(double spielers) {
this.spielerspeed = spielers;
}
public JFrame getFrame(){
return this;
}
public void setSpeedr(double speedrr) {
this.speedr = speedrr;
}
public void dealDamage() {
}
}
| AFG-Q11-2021/Projekt-B | Framee.java | 788 | /**
* Framee Class
* @author Christopher Scheruebl, Timon Weiss, Julius Rommel (07.05.2021 n.Chr);
* @version 0.2
*/ | block_comment | en | true |
194727_0 | /* Pattern Syntax Checker
Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax.
In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid.
Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method.
Input Format
The first line of input contains an integer , denoting the number of test cases. The next lines contain a string of any printable characters representing the pattern of a regex.
Output Format
For each test case, print Valid if the syntax of the given pattern is correct. Otherwise, print Invalid. Do not print the quotes.
Sample Input
3
([A-Z])(.+)
[AZ[a-z](a-z)
batcatpat(nat
Sample Output
Valid
Invalid
Invalid */
import java.util.Scanner;
import java.util.regex.*;
public class task20
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while(testCases>0){
String pattern = in.nextLine();
testCases--;
try {
Pattern.compile(pattern);
System.out.println("Valid");
}
catch (PatternSyntaxException e) {
System.out.println("Invalid");
}
}
}
} | vilasha/Hackerrank---Java-training-solutions | task20.java | 354 | /* Pattern Syntax Checker
Using Regex, we can easily match or search for patterns in a text. Before searching for a pattern, we have to specify one using some well-defined syntax.
In this problem, you are given a pattern. You have to check whether the syntax of the given pattern is valid.
Note: In this problem, a regex is only valid if you can compile it using the Pattern.compile method.
Input Format
The first line of input contains an integer , denoting the number of test cases. The next lines contain a string of any printable characters representing the pattern of a regex.
Output Format
For each test case, print Valid if the syntax of the given pattern is correct. Otherwise, print Invalid. Do not print the quotes.
Sample Input
3
([A-Z])(.+)
[AZ[a-z](a-z)
batcatpat(nat
Sample Output
Valid
Invalid
Invalid */ | block_comment | en | true |
194731_1 | //On my honor:
//I have not discussed the Java language code in my program with anyone other than my instructor or the teaching assistants assigned to this course.
//I have not used Java language code obtained from another student, or any other unauthorized source, either modified or unmodified.
//If any Java language code or documentation used in my program was obtained from another source, such as a text book or course notes, that has been clearly noted with a proper citation in the comments of my program.
//I have not designed this program in such a way as to defeat or interfere with the normal operation of the Curator System.
//Clayton Kuchta
/**
* Creator: Clayton Kuchta
* Project: GIS System
* Last Modified: April. 15th, 2015
*
*
* This is the main class for the GIS Project. This project takes in three
* arguments:
*
* <database file name> <command script file name> <log file name>
*
* Where the database file is where you store imported data. The command script
* bides by the commands specified in the project description
* and the log file is the output of this project.
*
*
* Overall Design:
* The overall design is that the main checks and opens all the inputed files. Then
* it constructs a GISSystemConductor object and then it runs.
*
* nameIndex:
* The nameIndex is the layer between the condutorin the hash table.
*
* CoordinateIndex:
* The CoordinateIndex is the layer between the conductor and the pr quad tree.
*
* BufferPool:
* There is also i buffer pool data object that is the layer between the database file
* and the conductor.
*
* DataStructure Element Wrappers:
* All wrapper classes that are stored in the hash table and the quad tree can be found in the package
* DataStructures.Client.
*
* Point:
* This is what is stored in a quad tree.
*
* HashNameIndex:
* This is what is stored in the hash table.
*
* GISRecord:
* When a GIS record is read in it is converted into a GIS Record to easily get all the information
* from the record without having to split the string every time you want data.
*
* Package gisTools:
* This package contains the Command class which holds the information about a command. It makes any information about
* a command easily accessible for the conductor.
*
*/
import java.io.File;
import java.io.RandomAccessFile;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import error.ErrorMessage;
public class GIS {
private static final int RandomAccessFile = 0;
public static void main(String[] args) throws IOException{
// Check the correct amount of arguments
if (args.length < 3){
ErrorMessage.errorMessage("Not enough arguments");
return;
}
// Make database file
File databaseFile = new File(args[0]);
RandomAccessFile databaseRAF;
if(!databaseFile.createNewFile()){
databaseRAF = new RandomAccessFile(databaseFile, "rw");
databaseRAF.setLength(0);
}else{
databaseRAF = new RandomAccessFile(databaseFile, "rw");
}
// Check for command file
File commandFile = new File(args[1]);
if(!commandFile.exists()){
ErrorMessage.errorMessage("Command file not found " + commandFile.getName());
return;
}
FileReader commandFR = new FileReader(commandFile);
// Check and create a logFile
File logFile = new File(args[2]);
FileWriter logRAF;
if(!databaseFile.createNewFile()){
logRAF = new FileWriter(logFile);
logRAF.write("");
}else{
logRAF = new FileWriter(logFile);
}
// Construct the conductor
GISSystemConductor conductor = new GISSystemConductor(databaseRAF, commandFR, logRAF);
// Execute the program.
try{
conductor.run();
}catch(IOException e){
System.out.println("ERROR:\t" + e.getMessage());
}
logRAF.close();
}
}
| clayton8/GIS_Data_Structures | src/GIS.java | 1,054 | //I have not discussed the Java language code in my program with anyone other than my instructor or the teaching assistants assigned to this course. | line_comment | en | false |
195316_2 | import java.util.*;
//-----------------------------------------------------
// Title: RWT class
// Author: Sarp ARSLAN - 11458145526 - Section03
// Burak SAĞLAM – 13760307838 - Section02
// Description: RWT class for using RWT
//-----------------------------------------------------
public class RWT {
private static final int R = 256;
private Node root = new Node();
private static class Node {
private Object value;
private Node[] next = new Node[R];
}
/**
* Inserts a key-value pair into the RWT.
*
* @param key The key to insert.
* @param val The value to associate with the key.
*/
public void put(String key, Object val) {
root = put(root, new StringBuilder(key).reverse().toString(), val, 0);
}
private Node put(Node x, String key, Object val, int d) {
if (x == null) {
x = new Node();
}
if (d == key.length()) {
x.value = val;
return x;
}
char c = key.charAt(d);
x.next[c] = put(x.next[c], key, val, d + 1);
return x;
}
/**
* Returns a list of all keys in the RWT that have the given prefix.
*
* @param prefix The prefix to search for.
* @return A list of keys with the given prefix.
*/
public List<String> keysWithPrefix(String prefix) {
List<String> results = new ArrayList<>();
Node x = get(root, new StringBuilder(prefix).reverse().toString(), 0);
collect(x, new StringBuilder(prefix).reverse().toString(), results);
Collections.sort(results, Comparator.reverseOrder());
return results;
}
private Node get(Node x, String key, int d) {
if (x == null) return null;
if (d == key.length()) return x;
char c = key.charAt(d);
return get(x.next[c], key, d + 1);
}
private void collect(Node x, String prefix, List<String> results) {
if (x == null) return;
if (x.value != null) results.add(new StringBuilder(prefix).reverse().toString());
for (char c = 0; c < R; c++) {
collect(x.next[c], prefix + c, results);
}
}
}
| sarparslan/Trie-Implementation | RWT.java | 587 | // Author: Sarp ARSLAN - 11458145526 - Section03 | line_comment | en | true |
195619_3 | package au.edu.unimelb.ai.squatter;
// TODO: Auto-generated Javadoc
/**
* The Piece class has two constant values to represent the color. Each piece
* has an "isEnclosed" value that represents the piece's current state.
*
* @author <Andre Peric Tavares> <aperic>
* @author <Felipe Matheus Costa Silva> <fcosta1>
*
*/
public class Piece {
enum Colour {
WHITE, BLACK
};
Colour colour;
boolean isEnclosed;
/**
* Instantiates a new piece.
*
* @param colour
* @param isEnclosed
*/
public Piece(Colour colour, boolean isEnclosed) {
this.colour = colour;
this.isEnclosed = isEnclosed;
}
/**
* Gets the colour.
*
* @return the colour
*/
public Colour getColour() {
return colour;
}
/**
* Sets the colour.
*
* @param colour
* the new colour
*/
public void setColour(Colour colour) {
this.colour = colour;
}
/**
* Checks if is enclosed.
*
* @return true, if is enclosed
*/
public boolean isEnclosed() {
return isEnclosed;
}
/**
* Sets the enclosed.
*
* @param isEnclosed
*/
public void setEnclosed(boolean isEnclosed) {
this.isEnclosed = isEnclosed;
}
}
| flpmat/aiproj.squatter | Piece.java | 380 | /**
* Gets the colour.
*
* @return the colour
*/ | block_comment | en | false |
196249_4 | /**
Graduate 继承了Student类,Student类称为父类,超类
Gradudate称为子类
代码的复用
*/
public class Graduate extends Student {
String research; //扩充了父类的成员
public Graduate(String no,String name,String grade,String research){
//通过super()调用父类的构造方法。
// 1.super()必须放在构造方法体的第一行
// 2.super()显式的指定调用父类哪个构造方法,如果没有指定,默认调用父类的无参构造方法
//super(no,name,grade);
this.research = research;
System.out.println("执行带参数的子类构造方法");
}
public Graduate(){
System.out.println("执行无参的子类构造方法");
}
public void doResearch(){
System.out.println("research field:" + this.research);
}
}
| liangsbin/JavaProgramming | chapter4/Graduate.java | 212 | // 2.super()显式的指定调用父类哪个构造方法,如果没有指定,默认调用父类的无参构造方法 | line_comment | en | true |
196441_0 | import java.util.*;
/**
* Base file for the ChatterBot exercise.
* The bot's replyTo method receives a statement.
* If it starts with the constant REQUEST_PREFIX, the bot returns
* whatever is after this prefix. Otherwise, it returns one of
* a few possible replies as supplied to it via its constructor.
* In this case, it may also include the statement after
* the selected reply (coin toss).
* @author Dan Nirel
*/
class ChatterBot {
// constants
// constant which resemble the phrase to replace in the legal responses templates
public static final String PLACEHOLDER_FOR_REQUESTED_PHRASE = "<phrase>";
// constant which resemble the phrase to replace in the illegal responses templates
public static final String PLACEHOLDER_FOR_ILLEGAL_REQUEST = "<request>";
static final String REQUEST_PREFIX = "say ";
// class's attributes
String name;
String[] repliesToLegalRequest; // array of possible replies for legal requests
String[] repliesToIllegalRequest; // array of possible replies for illegal requests
Random rand = new Random();
/**
* c'tor
* @param name
* @param repliesToLegalRequest
* @param repliesToIllegalRequest
*/
ChatterBot(String name,String[] repliesToLegalRequest, String[] repliesToIllegalRequest) {
this.name = name;
this.repliesToLegalRequest = new String[repliesToLegalRequest.length];
for(int i = 0 ; i < repliesToLegalRequest.length ; i = i+1) {
this.repliesToLegalRequest[i] = repliesToLegalRequest[i];
}
// build the array of the replies
this.repliesToIllegalRequest = new String[repliesToIllegalRequest.length];
for(int i = 0 ; i < repliesToIllegalRequest.length ; i = i+1) {
this.repliesToIllegalRequest[i] = repliesToIllegalRequest[i];
}
}
/**
*
* @return the bot's name
*/
public String getName(){
return this.name;
}
/**
* a method that creates the bot's reply to given statement
* @param statement
* @return
*/
public String replyTo(String statement) {
return statement.startsWith(ChatterBot.REQUEST_PREFIX) ? replyToLegalRequest(statement) :
replyToIllegalRequest(statement) ;
}
/**
* a method that recieves an array of possible responses templates, phrase and requested statemtnt and
* build the random response
* @param s
* @param phrase
* @param statement
* @return
*/
public String replacePlaceholderInARandomPattern(String[] s, String phrase, String statement){
int randomIndex = rand.nextInt(s.length);
String reply = s[randomIndex];
return reply.replaceAll(phrase, statement);
}
/**
* a method that build a reply to legal statement
* @param phrase
* @return
*/
public String replyToLegalRequest(String phrase) {
phrase = phrase.replaceFirst(ChatterBot.REQUEST_PREFIX, "");
return replacePlaceholderInARandomPattern(this.repliesToLegalRequest,
ChatterBot.PLACEHOLDER_FOR_REQUESTED_PHRASE,phrase);
}
String replyToIllegalRequest(String statement) {
return replacePlaceholderInARandomPattern( this.repliesToIllegalRequest,
ChatterBot.PLACEHOLDER_FOR_ILLEGAL_REQUEST , statement);
}
}
| toharys/JAVA | ChatBot/ChatterBot.java | 834 | /**
* Base file for the ChatterBot exercise.
* The bot's replyTo method receives a statement.
* If it starts with the constant REQUEST_PREFIX, the bot returns
* whatever is after this prefix. Otherwise, it returns one of
* a few possible replies as supplied to it via its constructor.
* In this case, it may also include the statement after
* the selected reply (coin toss).
* @author Dan Nirel
*/ | block_comment | en | true |
196488_3 | import java.awt.*;
public class Shot implements Runnable {
private int vitezaLoviturii = 10;
private int LATIMEA_LOVITURII = 12;
private int INALTIMEA_LOVITURII = 23;
private int x = 0;
private int shotHeight = 0;
boolean stareLovitura = true;
private Image imagineLovitura = new javax.swing.ImageIcon("supermanshot.gif").getImage();
Armata armata = null;
Boss boss = null;
SpaceInvaders spaceInvaders = null;
public Shot(int xVal, int yVal, Armata aa, SpaceInvaders si, Boss seful) {
x = xVal;
shotHeight = yVal;
armata = aa;
boss = seful;
spaceInvaders = si;
Thread thread = new Thread(this);
thread.start();
}
private boolean mutaLovitura() {
if(armata.verificaLovitura(x, shotHeight)) {
// Am lovit ceva din armata
System.out.println("Am impuscat un extraterestru!");
stareLovitura = false;
return true;
}
if(boss.bossLovit(x, shotHeight)) {
stareLovitura = false;
return true;
}
shotHeight -= 2;
// Verificam daca am iesit in afara ecranului
if(shotHeight < 0) {
stareLovitura = false;
return true;
}
return false;
}
/**
* Desenarea loviturii propriu zise
*/
public void drawShot(Graphics g) {
if(stareLovitura) {
g.drawImage(imagineLovitura, x, shotHeight, spaceInvaders);
g.setColor(Color.green);
} else {
g.setColor(Color.red);
}
}
public boolean getStareLovitura() {
return stareLovitura;
}
/**
* Thread-ul care misca shot-ul
*/
public void run() {
while(true) {
try {
Thread.sleep(vitezaLoviturii);
} catch(InterruptedException ie) {
// nu facem din nou ceva
}
// Daca folosim moveshot() facand abstractie de shotState vom putea folosi aceeasi
// lovitura pentru a omora toti extraterestrii din drumul ei
//mutaLovitura();
if(mutaLovitura()) {
break;
}
}
}
} | marianstefi20/spaceInvaders | Shot.java | 699 | /**
* Thread-ul care misca shot-ul
*/ | block_comment | en | true |
197048_4 | package p12;
//: c12:Echo.java
// How to read from standard input.
// {RunByHand}
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
import java.io.*;
public class Echo {
public static void main(String[] args)
throws IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String s;
while((s = in.readLine()) != null && s.length() != 0)
System.out.println(s);
// An empty line or Ctrl-Z terminates the program
}
} ///:~
| MatfOOP-I/primeri-knjiga-eckel-tij | src/p12/Echo.java | 175 | // www.BruceEckel.com. See copyright notice in CopyRight.txt. | line_comment | en | true |
197077_0 | /*
* @copyright 1997 Ira R. Forman and Scott H. Danforth
*/
package putting.om;
import java.util.*;
public class List extends Vector implements Value {
public List( ) { }
public List( Object value ) { this.addElement( value ); }
public List( Object value1, Object value2 ) { this.addElement( value1 );
this.addElement( value2 ); }
public List( Object value1, Object value2, Object value3 )
{ this.addElement( value1 );
this.addElement( value2 );
this.addElement( value3 ); }
public List merge( List r ) {
List result = (List) clone();
for ( Enumeration e = r.elements(); e.hasMoreElements(); ) {
Value elt = (Value)e.nextElement();
if ( !result.contains(elt) ) {
result.addElement( elt );
}
}
return result;
}
public List reverse( ){
List result = new List();
for ( Enumeration e = elements(); e.hasMoreElements(); ) {
result.insertElementAt( (Value)e.nextElement(), 0 );
}
return result;
}
public List sublist( int i , int j ) {
if ( i < 0 || i > j || j > size() )
throw new OMRuntimeException();
List newList = new List();
for (; i<j; i++)
newList.addElement( elementAt( i ) );
return newList;
}
}
| OS2World/DEV-SAMPLES-JAVA-Putting_Metaclasses | om/List.java | 355 | /*
* @copyright 1997 Ira R. Forman and Scott H. Danforth
*/ | block_comment | en | true |
197132_2 | // ParamTag.java, created Wed Mar 19 12:42:42 2003 by cananian
// Copyright (C) 2003 C. Scott Ananian ([email protected])
// Licensed under the terms of the GNU GPL; see COPYING for details.
package net.cscott.sinjdoc;
import java.util.List;
/**
* The <code>ParamTag</code> class represents a @param documentation tag.
*
* @author C. Scott Ananian ([email protected])
* @version $Id$
* @see com.sun.javadoc.ParamTag
*/
public interface ParamTag extends Tag {
/** Return the parameter comment associated with this
* <code>ParamTag</code>. */
public List<Tag> parameterComment();
/** Return the name of the parameter associated with this
* <code>ParamTag</code>. */
public String parameterName();
}
| cscott/sinjdoc | src/ParamTag.java | 228 | // Licensed under the terms of the GNU GPL; see COPYING for details. | line_comment | en | true |
197672_13 | import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The type User.
*/
public class User {
private String username;
private int xp;
private int level;
private int title;
private String league;
private ArrayList<Card> cards;
private Card[] currentCards;
private SecureRandom random;
{
cards = new ArrayList<>();
currentCards = new Card[8];
random = new SecureRandom();
username = "";
cards.add(Card.BARBARIANS);
cards.add(Card.ARCHERS);
cards.add(Card.BABYDRAGON);
cards.add(Card.WIZARD);
cards.add(Card.MINIPEKKA);
cards.add(Card.GIANT);
cards.add(Card.VALKYRIE);
cards.add(Card.RAGE);
cards.add(Card.FIREBALL);
cards.add(Card.ARROWS);
cards.add(Card.CANNON);
cards.add(Card.INFERNOTOWER);
}
/**
* Instantiates a new User.
*/
public User() {
xp = 0;
level = 1;
title = 0;
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param level the level
*/
public User(int level) {
xp = 0;
title = 1;
this.level = level;
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param username the username
* @param xp the xp
*/
public User(String username, int xp) {
this.username = username;
this.xp = xp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
league = getLeague(title);
}
/**
* Instantiates a new User.
*
* @param username the username
* @param xp the xp
* @param currentCards the current cards
* @param title the title
*/
public User(String username, int xp, String[] currentCards, int title) {
this(username, xp);
int i = 0;
for (String cardName : currentCards) {
for (Card card : cards) {
if (card.toString().equalsIgnoreCase(cardName)) {
this.currentCards[i] = card;
}
}
i++;
}
this.title = title;
league = getLeague(title);
}
/**
* Get current cards card [ ].
*
* @return the card [ ]
*/
public Card[] getCurrentCards() {
return currentCards;
}
/**
* Gets level.
*
* @return the level
*/
public int getLevel() {
return level;
}
/**
* Gets xp.
*
* @return the xp
*/
public int getXp() {
return xp;
}
/**
* Sets xp.
*
* @param xp the xp
*/
public void setXp(int xp) {
this.xp = xp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
}
/**
* Gets title.
*
* @return the title
*/
public int getTitle() {
return title;
}
/**
* Gets random card.
*
* @return the random card
*/
public Card getRandomCard() {
//return cards.get(random.nextInt(12)); // 8
return currentCards[random.nextInt(8)];
}
/**
* Gets cards.
*
* @return the cards
*/
public ArrayList<Card> getCards() {
return cards;
}
/**
* Gets username.
*
* @return the username
*/
public String getUsername() {
return username;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", currentCards=" + Arrays.toString(currentCards) +
'}';
}
/**
* Increase xp.
*
* @param addedXp the added xp
*/
public void increaseXp(int addedXp) {
xp += addedXp;
if (xp < 300) {
level = 1;
} else if (xp < 500) {
level = 2;
} else if (xp < 900) {
level = 3;
} else if (xp < 1700) {
level = 4;
} else {
level = 5;
}
}
/**
* Increase title.
*
* @param addedTitle the added title
*/
public void increaseTitle(int addedTitle) {
title += addedTitle;
league = getLeague(title);
}
private String getLeague(int title) {
String league = "";
if (title <= 10) {
league = "Goblins";
}
if (11 <= title && title <= 30) {
league = "Archers";
}
if (31 <= title && title <= 100) {
league = "Barbars";
}
if (101 <= title && title <= 300) {
league = "Wizards";
}
if (301 <= title && title <= 1000) {
league = "Princes";
}
if (1001 <= title) {
league = "Legends";
}
league += " League";
return league;
}
/**
* Gets league.
*
* @return the league
*/
public String getLeague() {
return league;
}
} | AshkanShakiba/Clash-Royale | src/User.java | 1,464 | /**
* Gets username.
*
* @return the username
*/ | block_comment | en | false |
197739_1 | import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
/**
* This class represents a league of teams.
*/
public class TeamsLeague {
/**
* This class represents a Team in the league.
* It implements Comparable interface to compare teams based on their points.
*/
private class Team
implements Comparable<Team> {
private String teamName;
private int wins;
private int losses;
private int ties;
private int points;
private int goalsScored;
private int goalsAllowed;
private int teamNumber;
/**
* Constructor for the Team class.
* Initializes the team with the given name and zero wins, losses, ties, and
* points.
*
* @param teamName The name of the team.
*/
public Team(String teamName) {
this.teamName = teamName;
this.wins = 0;
this.losses = 0;
this.ties = 0;
this.points = 0;
}
/**
* Compares this team to another team based on their points.
* Returns a positive integer if this team has more points, 0 if equal, and a
* negative integer if less.
*
* @param o The other team to compare to.
* @return A positive integer if this team has more points, 0 if equal, and a
* negative integer if less.
*/
@Override
public int compareTo(TeamsLeague.Team o) {
if (this.points > o.points) {
return 1;
} else if (this.goalsScored > o.goalsScored) {
return 1;
} else if (this.goalsAllowed < o.goalsAllowed) {
return 1;
} else if (this.teamNumber < o.teamNumber) {
return 1;
} else {
return -1;
}
}
/*
* Compares this team to another object for equality.
* Returns true if the other object is a team with the same name, false
* otherwise.
*
* @param obj The other object to compare to.
*
* @return True if the other object is a team with the same name, false
* otherwise.
*/
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
/*
* Returns a hash code for this team.
*
* @return A hash code for this team.
*/
@Override
public int hashCode() {
return super.hashCode();
}
/*
* Returns a string representation of this team.
*
* @return A string representation of this team.
*/
public String toString() {
return String.format("%-20s %3d %3d %3d", this.teamName, this.points, this.goalsScored, this.goalsAllowed);
}
}
private HashMap<Integer, Team> teams = new HashMap<>();
private int numberOfTeams;
private int teamsProcessed;
private ArrayList<Integer> teamList = new ArrayList<>(numberOfTeams);
/**
* Constructor for the TeamsLeague class.
* Initializes the league by reading team data from a file.
*
* @param teamFile the name of the file containing team data.
* @param gameFile the name of the file containing game data.
*/
public TeamsLeague(String teamFile, String gameFile) {
File teamsFile = new File(teamFile);
Scanner teamInput = null;
try {
teamInput = new Scanner(teamsFile);
} catch (Exception e) {
System.out.println("File not found");
}
String details = teamInput.nextLine();
Scanner detailsScanner = new Scanner(details);
numberOfTeams = Integer.parseInt(detailsScanner.next());
teamsProcessed = Integer.parseInt(detailsScanner.next());
while (teamInput.hasNextLine()) {
String lineString = teamInput.nextLine();
Scanner lineScanner = new Scanner(lineString);
String temp = lineScanner.next();
int teamNumber = Integer.parseInt(temp.trim().substring(0, temp.length() - 1));
String teamName = lineScanner.nextLine().trim();
Team team = new Team(teamName);
teams.put(teamNumber, team);
teams.get(teamNumber).teamNumber = teamNumber;
teamList.add(teamNumber);
}
teamInput.close();
File gamesFile = new File(gameFile);
Scanner gamesInput = null;
try {
gamesInput = new Scanner(gamesFile);
} catch (Exception e) {
System.out.println("File not found");
}
while (gamesInput.hasNextLine()) {
String lineString = gamesInput.nextLine();
Scanner lineScanner = new Scanner(lineString);
int team1 = lineScanner.nextInt();
int team2 = lineScanner.nextInt();
int score1 = lineScanner.nextInt();
int score2 = lineScanner.nextInt();
processTeams(score1, score2, team1, team2);
lineScanner.close();
}
gamesInput.close();
}
/**
* Processes the teams based on the scores of the games.
*
* @param score1 the score of the first team.
* @param score2 the score of the second team.
* @param team1 the number of the first team.
* @param team2 the number of the second team.
*/
private void processTeams(int score1, int score2, int team1, int team2) {
if (score1 > score2) {
teams.get(team1).wins++;
teams.get(team1).points += 3;
teams.get(team2).losses++;
} else if (score1 < score2) {
teams.get(team2).wins++;
teams.get(team2).points += 3;
teams.get(team1).losses++;
} else {
teams.get(team1).ties++;
teams.get(team2).ties++;
teams.get(team1).points++;
teams.get(team2).points++;
}
teams.get(team1).goalsScored += score1;
teams.get(team1).goalsAllowed += score2;
teams.get(team2).goalsScored += score2;
teams.get(team2).goalsAllowed += score1;
}
/**
* Sorts an array of teams using the quick sort algorithm.
*
* @param low the lowest index of the array to sort.
* @param high the highest index of the array to sort.
*/
public void quickSort(int low, int high) {
int pivot = 0;
if ((teamList.get(high).compareTo(teamList.get(low)) < 0)) {
pivot = partition(low, high);
quickSort(low, pivot - 1);
quickSort(pivot + 1, high);
}
}
/**
* Partitions the array of teams for quick sort.
*
* @param low the lowest index of the array to sort.
* @param high the highest index of the array to sort.
* @return the index of the pivot item.
*/
private int partition(int low, int high) {
Team pivotItem = teams.get(teamList.get(low));
int j = low;
for (int i = low + 1; i <= high; i++) {
if (teams.get(teamList.get(i)).compareTo(pivotItem) < 0) {
j++;
int temp = teamList.get(i);
teamList.set(i, teamList.get(j));
teamList.set(j, temp);
}
}
int temp = teamList.get(j);
teamList.set(j, teamList.get(low));
teamList.set(low, temp);
return j;
}
/**
* Returns numbers of teams in the league.
*
* @return the number of teams in the league.
*/
public int getNumberOfTeams() {
return numberOfTeams;
}
/**
* Returns the list of teams in the league.
*
* @return the list of teams in the league.
*/
public ArrayList<Integer> getTeamList() {
return teamList;
}
/**
* Returns the name of the team.
*
* @param teamNumber the number of the team.
* @return the name of the team.
*/
public String getTeamName(int teamNumber) {
return teams.get(teamNumber).teamName;
}
/**
* Returns the number of points of the team.
*
* @param teamNumber the number of the team.
* @return the number of points of the team.
*/
public int getPoints(int teamNumber) {
return teams.get(teamNumber).wins * 3 + teams.get(teamNumber).ties;
}
/**
* Returns the number of goals scored by the team.
*
* @param teamNumber the number of the team.
* @return the number of goals scored by the team.
*/
public int getGoalsScored(int teamNumber) {
return teams.get(teamNumber).goalsScored;
}
/**
* Returns the team number of the team.
*
* @param teamNumber the number of the team.
* @return the number of goals allowed by the team.
*/
public int getTeamNumber(int teamNumber) {
return teams.get(teamNumber).teamNumber;
}
/**
* Returns the number of goals allowed by the team.
*
* @param teamNumber the number of the team.
* @return the number of goals allowed by the team.
*/
public int getGoalsAllowed(int teamNumber) {
return teams.get(teamNumber).goalsAllowed;
}
/**
* Returns the number of teams processed.
*
* @return the number of teams processed.
*/
public int getTeamsProcessed() {
return teamsProcessed;
}
/**
* Returns the team at the given index.
*
* @param i the index of the team.
* @return the team at the given index.
*/
public Team getTeam(int i) {
return teams.get(i);
}
} | BiswashNK/soccerTeamManagementSystem | TeamsLeague.java | 2,335 | /**
* This class represents a Team in the league.
* It implements Comparable interface to compare teams based on their points.
*/ | block_comment | en | true |
198811_1 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Chair here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Chair extends Actor
{
/**
* Act - do whatever the Chair wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| rainbowmess12/End-Of-The-Year-Project | Chair.java | 127 | /**
* Write a description of class Chair here.
*
* @author (your name)
* @version (a version number or a date)
*/ | block_comment | en | true |
199003_1 | // BUGBUG: yuck :(
import java.util.Map.Entry;
/**
* A simple module to encapsulate using HTML tags.
*
* Note, makes use of CSS styling in an effort ease changing the style later.
*
* @author Robert C. Duvall
*/
public class HTMLPage {
/**
* @return tags to be included at top of HTML page
*/
public static String startPage (int numSizes, int startSize, int increment) {
StringBuilder style = new StringBuilder();
for (int k = 0; k < numSizes; k++) {
style.append(" .size-" + k + " { font-size: " + (startSize + increment * (k - 1)) + "px; }");
}
return "<html><head><style>" + style + "</style></head><body><p>\n";
}
/**
* @return tags to be included at bottom of HTML page
*/
public static String endPage () {
return "</p></body></html>";
}
/**
* @return tags to display a single styled word
*/
public static String formatWord (String word, int cssSize) {
return " <span class=\"size-" + cssSize + "\">" + word + "</span>\n";
}
/**
* @return tags to display a single styled word
*/
public static String formatWord (Entry<String, Integer> wordCount) {
return formatWord(wordCount.getKey(), wordCount.getValue());
}
}
| duke-compsci308-spring2015/example_wordcloud | src/HTMLPage.java | 341 | /**
* A simple module to encapsulate using HTML tags.
*
* Note, makes use of CSS styling in an effort ease changing the style later.
*
* @author Robert C. Duvall
*/ | block_comment | en | false |
199074_15 | import java.util.*;
import java.util.regex.*;
import java.io.*;
/**
* CMPUT 291 Wi17
* Mini Project 2
* Phase 1 Code
* March 19th, 2017
* Keith Mills 1442515
**/
public class Phase1 {
// A writer for each file. And the ID of the user.
private BufferedWriter termsWriter;
private BufferedWriter datesWriter;
private BufferedWriter tweetWriter;
private String currentID;
public static void main(String args[]) {
// Don't do anything for nothing.
if (args.length == 0) {
System.out.println("Wrong size of arguments. Exiting.");
}
Phase1 ph = new Phase1();
// It works on multiple files!
for (String file: args) {
ph.parseFile(file);
}
}
public Phase1() {}
public void parseFile(String fileName) {
// Reader for the file.
try(BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
// Setup writers.
termsWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("terms.txt")));
datesWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("dates.txt")));
tweetWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("tweets.txt")));
// Loop for each line, reading entire file.
String rawData = reader.readLine();
while (rawData != null) {
// For valid lines.
if (rawData.startsWith("<status>")) {
// Get ID. Send off tweet information. Send off term information. Send off date information.
currentID = getID(rawData);
parseTweet(rawData);
parseTerms(rawData);
parseDate(rawData);
}
rawData = reader.readLine();
}
}
catch (Exception e) {
System.err.println(e.getMessage());
}
finally {
try {
termsWriter.close();
datesWriter.close();
tweetWriter.close();
}
catch (Exception e) {}
}
}
// Simple enough.
public void parseTweet(String line) throws Exception {
tweetWriter.write(currentID + ":" + line + "\n");
}
// Most complicated of them all.
public void parseTerms(String line) throws Exception {
// Get the proper fields. Yes, my code is kinda hacky here.
String texts = line.substring(line.indexOf("<text>") + 6, line.indexOf("</text>"));
String names = line.substring(line.indexOf("<name>") + 6, line.indexOf("</name>"));
String locations = line.substring(line.indexOf("<location>") + 10, line.indexOf("</location>"));
// For texts, then names, then locations.
matchAndSave(texts, "t");
matchAndSave(names, "n");
matchAndSave(locations, "l");
}
// Get the date. Then write.
public void parseDate(String line) throws Exception {
String theDate = line.substring(line.indexOf("<created_at>") + 12, line.indexOf("</created_at>"));
datesWriter.write(theDate + ":" + currentID + "\n");
}
// Gets ID.
public String getID(String line) {
return line.substring(line.indexOf("<id>") + 4, line.indexOf("</id>"));
}
public void matchAndSave(String data, String format) throws Exception {
// Get rid of all special characters in case they are between two valid terms that should be smooshed together.
data = data.replaceAll("&#[0-9]+;", "");
// Use regex to find the valid terms.
String pattern = "[0-9a-zA-Z_]+";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(data);
// Parse the string. Find valid spots. See if they are the proper length, then print in the desired format.
while (m.find()) {
if (m.end() - m.start() > 2) {
termsWriter.write(format + "-" + data.substring(m.start(), m.end()).toLowerCase() + ":" + currentID + "\n");
}
}
}
} | CMPUT291W17T05/MiniProject_2 | Phase1.java | 1,072 | // Get rid of all special characters in case they are between two valid terms that should be smooshed together. | line_comment | en | true |
199307_1 | /*
* 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 bagImplementations;
import java.util.Iterator;
/**
*
* @author amnwaqar
* @param <E>
*/
public interface Bag<E>
{
public boolean add(E item);
public E grab();
public boolean remove(E item);
public int size();
public int capacityRemaining();
public boolean isFull();
public boolean isEmpty();
public void clear();
public Iterator<E> iterator();
public E[] toArray();
}
| amnw12/bag_implementation | Bag.java | 155 | /**
*
* @author amnwaqar
* @param <E>
*/ | block_comment | en | true |
199314_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Bag here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Bag extends Buttons {
public void act() {
super.act();
if (onMe == 0) {
setImage("Battle/Buttons/Menu/Bag1.png");
} else {
setImage("Battle/Buttons/Menu/Bag0.png");
}
}
} | tanishnalli/Pookiemon | Bag.java | 126 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | true |
199564_14 | // Name: Nicholas Guerrero
// USC NetID: ng55585
// CS 455 PA4
// Fall 2021
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* A Rack of Scrabble tiles
*/
public class Rack {
/**
* Representation invariant:
*
* subsets Rack object and multiplcityMap Rack object should always have unique
* key entries.
*
* The keys of the HashMap multiplicityMap should be the characters from the
* letters, this relationship should always be maintained
*
* Simarly the relationship between the multiplicityMap and subsets should be
* the same, that is the generated subsets are from the keys, values of the
* multiplicityMap.
*/
private String letters;
private HashMap<Character, Integer> multiplicityMap;
private ArrayList<String> subsets;
/**
* Creates a new Rack instance using the given letters. Finds the unique letters
* and the multiplicity of each letter.
*
* @param letters input String
*/
public Rack(String letters) {
this.letters = letters;
this.multiplicityMap = createMultiplicityMap(letters);
this.subsets = createSubsets();
}
/**
* @return Returns the input letters into the Rack.
*/
public String getLetters() {
return this.letters;
}
/**
* @return Returns the MultiplicityMap of the Rack.
*/
public HashMap<Character, Integer> getMultiplicityMap() {
return this.multiplicityMap;
}
/**
* @return Returns the subsets of the Rack.
*/
public ArrayList<String> getSubsets() {
return this.subsets;
}
/**
* Finds all subsets of the multiset starting at position k in unique and mult.
* unique and mult describe a multiset such that mult[i] is the multiplicity of
* the char unique.charAt(i). PRE: mult.length must be at least as big as
* unique.length() 0 <= k <= unique.length()
*
* @param unique a string of unique letters
* @param mult the multiplicity of each letter from unique.
* @param k the smallest index of unique and mult to consider.
* @return all subsets of the indicated multiset. Unlike the multiset in the
* parameters, each subset is represented as a String that can have
* repeated characters in it.
* @author Claire Bono
*/
private static ArrayList<String> allSubsets(String unique, int[] mult, int k) {
ArrayList<String> allCombos = new ArrayList<>();
if (k == unique.length()) { // multiset is empty
allCombos.add("");
return allCombos;
}
// get all subsets of the multiset without the first unique char
ArrayList<String> restCombos = allSubsets(unique, mult, k + 1);
// prepend all possible numbers of the first char (i.e., the one at position k)
// to the front of each string in restCombos. Suppose that char is 'a'...
String firstPart = ""; // in outer loop firstPart takes on the values: "", "a", "aa", ...
for (int n = 0; n <= mult[k]; n++) {
for (int i = 0; i < restCombos.size(); i++) { // for each of the subsets
// we found in the recursive call
// create and add a new string with n 'a's in front of that subset
allCombos.add(firstPart + restCombos.get(i));
}
firstPart += unique.charAt(k); // append another instance of 'a' to the first part
}
return allCombos;
}
/**
* Returns a HashMap with characters as keys and the character's multiplicity in
* the input string as values. The keys by definition will be unique.
*
* @param word a String from which unique characters and multiplicity will be
* calculated
* @return a map of unique characters as values and corresponding multiplicity
* as values
*/
private HashMap<Character, Integer> createMultiplicityMap(String letters) {
HashMap<Character, Integer> multiplicityMap = new HashMap<>();
for (int i = 0; i < letters.length(); i++) {
char character = letters.charAt(i);
if (multiplicityMap.containsKey(character)) {
multiplicityMap.put(character, multiplicityMap.get(character) + 1);
} else {
multiplicityMap.put(character, 1);
}
}
return multiplicityMap;
}
/**
* @return Returns a ArrayList with every entry being a subset of the letters
* passed into the Rack
*/
private ArrayList<String> createSubsets() {
String unique = "";
int[] mult = new int[this.multiplicityMap.size()];
int index = 0;
for (Map.Entry<Character, Integer> entry : this.multiplicityMap.entrySet()) {
unique += entry.getKey();
mult[index] = entry.getValue();
index++;
}
ArrayList<String> subsets = allSubsets(unique, mult, 0);
return subsets;
}
}
| NicholasGuerrero/Scrabble | Rack.java | 1,202 | // to the front of each string in restCombos. Suppose that char is 'a'... | line_comment | en | true |
200209_4 | import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class BuyTShirt
*/
@WebServlet("/BuyTShirt")
public class BuyTShirt extends HttpServlet {
private static final long serialVersionUID = 1L;
String driver = "com.mysql.jdbc.Driver";
String host = "jdbc:mysql://localhost:3306/javaexternal";
String user = "root";
String pass = "mohit";
Connection con;
public BuyTShirt() {
super();
try{
Class.forName(driver);
con = DriverManager.getConnection(host, user, pass);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String tag = request.getParameter("tag");
String colour = request.getParameter("colour");
String[] accessories = request.getParameterValues("acc");
int pocket = Integer.parseInt(request.getParameter("pocket"));
String acc = "";
for (String x : accessories )
acc = acc + x + " ";
try {
PreparedStatement stmt;
stmt = con.prepareStatement("insert into tshirt values(?,?,?,?,?)");
stmt.setInt(1,0);
stmt.setString(2,acc);
stmt.setString(3,tag);
stmt.setInt(4,pocket);
stmt.setString(5,colour);
stmt.executeUpdate();
// stmt.executeUpdate("insert into thirt values("+0+"," + acc + ",'" + tag + "','" + pocket +"','" + colour +"');");
}
catch (Exception e) {
e.printStackTrace();
}
response.sendRedirect("display.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
} | mohitkumartoshniwal/JavaLab | p7/BuyTShirt.java | 566 | /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/ | block_comment | en | true |
201013_0 | package game.frame;
import game.operator.GameManager;
import java.awt.Graphics2D;
/**
*
* @author hp
*/
public abstract class Window {
/**
* @param manager Controller any of Window extended class
*/
public static final int MENU = 0;
public static final int NEW_USER = 1;
public static final int DASHBOARD = 2;
public static final int TRAININHG = 3;
public static final int LUNG = 4;
public static final int BLOOD = 5;
public static final int BREAST = 6;
public static final int PAUSE = 7;
public static final int OPENING = 8;
public static final int HOW_TO_PLAY = 9;
protected GameManager manager;
/**
* Interface for extended classes
*/
public abstract void update();
public abstract void draw(Graphics2D graph);
public abstract void resume();
public abstract void keyPressed(int key);
public abstract void mouseClickd(int x, int y);
}
| rafiulgits/SFC-The-Game | src/game/frame/Window.java | 242 | /**
*
* @author hp
*/ | block_comment | en | true |
201117_7 | /*
* Argus Open Source
* Software to apply Statistical Disclosure Control techniques
*
* Copyright 2014 Statistics Netherlands
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the European Union Public Licence
* (EUPL) version 1.1, as published by the European Commission.
*
* You can find the text of the EUPL v1.1 on
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
*
* This software is distributed on an "AS IS" basis without
* warranties or conditions of any kind, either express or implied.
*/
package muargus;
import argus.model.ArgusException;
import argus.utils.SystemUtils;
import com.ibm.statistics.util.Utility;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.SplashScreen;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.UnsupportedLookAndFeelException;
import muargus.extern.dataengine.CMuArgCtrl;
import muargus.model.ClassPathHack;
import muargus.view.MainFrameView;
import org.apache.commons.io.FilenameUtils;
/**
* Main class of Mu-Argus.
*
* @author Statistics Netherlands
*/
public class MuARGUS {
// Version info
public static final int MAJOR = 5;
public static final int MINOR = 1;
public static final String REVISION = "7";
public static final int BUILD = 4;
public static final int MAXDIMS = 10;
private static final String MESSAGETITLE = "Mu Argus";
private static final int NHISTOGRAMCLASSES = 10;
private static final int NCUMULATIVEHISTOGRAMCLASSES = 100;
private static final String DEFAULTSEPARATOR = ",";
private static final String LOOKANDFEEL = "Windows";
private static final File MANUAL = new File("resources/MUmanual5.1.3.pdf");
private static final int SLEEPTIME = 2000;
private static Process helpViewerProcess;
static {
System.loadLibrary("numericaldll");
System.loadLibrary("muargusdll");
}
private static final CalculationService calcService = new CalculationService(new CMuArgCtrl());
private static SpssUtils spssUtils;
private static String tempDir;
static {
setTempDir(System.getProperty("java.io.tmpdir"));
}
/**
* Gets the calculations service.
*
* @return CalculationService.
*/
public static CalculationService getCalculationService() {
return MuARGUS.calcService;
}
private static String getSpssVersion()
{
Utility FindSpss = new Utility();
return FindSpss.getStatisticsLocationLatest();
}
static{
try{
ClassPathHack.addFile(getSpssVersion() + "\\spssjavaplugin.jar");
}catch (IOException ex){System.out.print(ex.toString());}
}
/**
* Gets the instance of SpssUtils.
*
* @return SpssUtils, or null if the Spss plugin cannot be loaded
*/
public static SpssUtils getSpssUtils() {
try {
if (MuARGUS.spssUtils == null) {
MuARGUS.spssUtils = new SpssUtils();
}
return MuARGUS.spssUtils;
} catch (NoClassDefFoundError err) {
return null;
}
}
/**
* Gets the full version.
*
* @return String containing the full version.
*/
public static String getFullVersion() {
return "" + MuARGUS.MAJOR + "." + MuARGUS.MINOR + "." + MuARGUS.REVISION;
}
/**
* Gets the message title.
*
* @return String containing the message title.
*/
public static String getMessageTitle() {
return MuARGUS.MESSAGETITLE;
}
/**
* Gets the number of histogram classes.
*
* @param cumulative Boolean indicating whether the number of cumulative or
* normal histogram classes are requested.
* @return Integer containing the number of histogram classes.
*/
public static int getNHistogramClasses(boolean cumulative) {
return cumulative ? MuARGUS.NCUMULATIVEHISTOGRAMCLASSES : MuARGUS.NHISTOGRAMCLASSES;
}
/**
* Gets the Locale.
*
* @return Locale containing the English locale.
*/
public static Locale getLocale() {
return Locale.ENGLISH;
}
/**
* Gets the default separator.
*
* @return String containing the default separator.
*/
public static String getDefaultSeparator() {
return MuARGUS.DEFAULTSEPARATOR;
}
/**
* Gets the temp directory.
*
* @return String containing the temp directory.
*/
public static String getTempDir() {
return MuARGUS.tempDir;
}
/**
* Sets the temp directory.
*
* @param tempDir String containing the temp directory.
*/
public static void setTempDir(String tempDir) {
MuARGUS.tempDir = FilenameUtils.normalizeNoEndSeparator(tempDir);
}
/**
* Gets a temp file.
*
* @param fileName String containing the temp file name.
* @return String containing the path to the filename.
*/
public static String getTempFile(String fileName) {
return FilenameUtils.concat(MuARGUS.tempDir, fileName);
}
/**
* Shows the build info on the splash screen.
*/
public static void showBuildInfoInSplashScreen() {
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
} else {
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
} else {
g.setPaintMode();
g.setColor(new Color(255, 0, 0));
Font font = g.getFont().deriveFont(Font.BOLD, 14.0f);
g.setFont(font);
String version = "Version " + getFullVersion() + " (Build " + MuARGUS.BUILD + ")";
g.drawString(version, (splash.getSize().width / 2) - (version.length()*3), (3*splash.getSize().height/4));
splash.update();
sleepThread(MuARGUS.SLEEPTIME);
}
}
}
/**
* Shows the content sensitive help.
*
* @param namedDest String containing the named destination.
* @throws ArgusException Throws an ArgusException when an error occurs
* while trying to display the help file.
*/
public static void showHelp(String namedDest) throws ArgusException {
ArrayList<String> args = new ArrayList<>();
args.add("-loadfile");
args.add(MuARGUS.MANUAL.getAbsolutePath());
if (namedDest != null) {
args.add("-nameddest");
args.add(namedDest);
}
try {
execClass(
"org.icepdf.ri.viewer.Main",
"lib/ICEpdf.jar",
args);
} catch (IOException | InterruptedException ex) {
throw new ArgusException("Error trying to display help file");
}
}
/**
* Creates a new process starting with the class with the given name and
* path
*
* @param className Fully qualified name of the class
* @param classPath Path to the directory or jar file containing the class
* @param arguments List of commandline arguments given to the new instance
* @throws IOException Occurs when de class cannot be loaded
* @throws InterruptedException Occurs when the new process is interrupted
*/
public static void execClass(String className, String classPath, List<String> arguments) throws IOException,
InterruptedException {
if (MuARGUS.helpViewerProcess != null) {
MuARGUS.helpViewerProcess.destroy();
MuARGUS.helpViewerProcess = null;
}
String javaHome = System.getProperty("java.home");
String javaBin = javaHome
+ File.separator + "bin"
+ File.separator + "java";
arguments.add(0, javaBin);
arguments.add(1, "-cp");
arguments.add(2, classPath);
arguments.add(3, className);
ProcessBuilder builder = new ProcessBuilder(arguments);
MuARGUS.helpViewerProcess = builder.start();
}
/**
* Starts a sleep thread for a given amount of time.
*
* @param milliSecs Integer containing the number of milli seconds that the
* program will sleep.
*/
private static void sleepThread(int milliSecs) {
try {
Thread.sleep(milliSecs);
} catch (InterruptedException ex) {
// Do something, if there is a exception
System.out.println(ex.toString());
}
}
/**
* Main method for running Mu-Argus.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
/* Set the look and feel */
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (MuARGUS.LOOKANDFEEL.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainFrameView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
SystemUtils.setRegistryRoot("muargus");
SystemUtils.setLogbook(SystemUtils.getRegString("general", "logbook", getTempFile("MuLogbook.txt")));
SystemUtils.writeLogbook(" ");
SystemUtils.writeLogbook("Start of MuArgus run");
SystemUtils.writeLogbook("Version " + MuARGUS.getFullVersion() + " build " + MuARGUS.BUILD);
SystemUtils.writeLogbook("--------------------------");
showBuildInfoInSplashScreen();
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrameView().setVisible(true);
}
});
}
}
| sdcTools/muargus | src/muargus/MuARGUS.java | 2,453 | /**
* Gets the number of histogram classes.
*
* @param cumulative Boolean indicating whether the number of cumulative or
* normal histogram classes are requested.
* @return Integer containing the number of histogram classes.
*/ | block_comment | en | false |
201401_2 | /**
* Copyright (c) 2017 JEP AUTHORS.
*
* This file is licensed under the the zlib/libpng License.
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any
* damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any
* purpose, including commercial applications, and to alter it and
* redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you
* must not claim that you wrote the original software. If you use
* this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and
* must not be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
package jep;
/**
* Utility functions
*
* @author Mike Johnson
*/
public final class Util {
// these must be the same as util.h
public static final int JBOOLEAN_ID = 0;
public static final int JINT_ID = 1;
public static final int JLONG_ID = 2;
public static final int JOBJECT_ID = 3;
public static final int JSTRING_ID = 4;
public static final int JVOID_ID = 5;
public static final int JDOUBLE_ID = 6;
public static final int JSHORT_ID = 7;
public static final int JFLOAT_ID = 8;
public static final int JARRAY_ID = 9;
public static final int JCHAR_ID = 10;
public static final int JBYTE_ID = 11;
public static final int JCLASS_ID = 12;
private Util() {
}
/**
* <pre>
*
* <b>Internal use only</b>
*
* Does the same thing as util.c::get_jtype, but it's easier more
* stable to do this in java when able.
*
* </pre>
*
* @param obj
* an <code>Object</code> value
* @return an <code>int</code> one of the type _ID constants
*/
public static final int getTypeId(Object obj) {
if (obj == null) {
return -1;
}
if (obj instanceof Integer) {
return JINT_ID;
}
if (obj instanceof Short) {
return JSHORT_ID;
}
if (obj instanceof Double) {
return JDOUBLE_ID;
}
if (obj instanceof Float) {
return JFLOAT_ID;
}
if (obj instanceof Boolean) {
return JBOOLEAN_ID;
}
if (obj instanceof Long) {
return JLONG_ID;
}
if (obj instanceof String) {
return JSTRING_ID;
}
if (obj instanceof Void) {
return JVOID_ID;
}
if (obj instanceof Character) {
return JCHAR_ID;
}
if (obj instanceof Byte) {
return JBYTE_ID;
}
if (obj instanceof Class) {
return JCLASS_ID;
}
Class<?> clazz = obj.getClass();
if (clazz.isArray()) {
return JARRAY_ID;
}
return JOBJECT_ID;
}
/**
* <pre>
*
* <b>Internal use only</b>
*
* Same as <code>getTypeId(Object)</code> but for Class. This is
* useful for determining the _ID for things like
* method.getReturnType.
*
* </pre>
*
* @param clazz
* an <code>Object</code> value
* @return an <code>int</code> one of the type _ID constants
*/
public static final int getTypeId(Class<?> clazz) {
if (clazz == null) {
return -1;
}
if (clazz.isAssignableFrom(Integer.class)) {
return JINT_ID;
}
if (clazz.isAssignableFrom(Short.class)) {
return JSHORT_ID;
}
if (clazz.isAssignableFrom(Double.class)) {
return JDOUBLE_ID;
}
if (clazz.isAssignableFrom(Float.class)) {
return JFLOAT_ID;
}
if (clazz.isAssignableFrom(Boolean.class)) {
return JBOOLEAN_ID;
}
if (clazz.isAssignableFrom(Long.class)) {
return JLONG_ID;
}
if (clazz.isAssignableFrom(String.class)) {
return JSTRING_ID;
}
if (clazz.isAssignableFrom(Void.class)) {
return JVOID_ID;
}
if (clazz.isAssignableFrom(Character.class)) {
return JCHAR_ID;
}
if (clazz.isAssignableFrom(Byte.class)) {
return JBYTE_ID;
}
if (clazz.isAssignableFrom(Class.class)) {
return JCLASS_ID;
}
if (clazz.isArray()) {
return JARRAY_ID;
}
return JOBJECT_ID;
}
}
| Techcable/jep | src/jep/Util.java | 1,208 | // these must be the same as util.h | line_comment | en | true |
201409_17 | import java.util.ArrayList;
import java.util.HashMap;
/**
* This class is used to model a hand of Full House in Big Two Game.
* It is a subclass of the class Hand. It stores the information of
* the player who plays his / her hand. It provides concrete implementations of
* two abstract methods in the superclass and overrides several methods for its use.
* This class also provides a static method for checking whether a given hand is
* a Full House.
* <br>
* <p>
* A Full House is five Big Two Cards with three of the same rank and another
* two of the same rank.
*
* <br>
* <p> <b>Copyright Information</b>
* <br> <br> <i> COMP 2396 OOP & Java Assignment #3 </i>
* <br> <i> ZHANG, Jiayao Johnson / 3035233412 </i>
* <br> Department of Computer Science, The University of Hong Kong
* <br> <a href = "[email protected]"> Contact me via email </a>
* <br> <a href = "http://i.cs.hku.hk/~jyzhang/"> Visit my webpage </a>
*
* @author ZHANG, Jiayao Johnson
* @version 0.1
* @since 2016-10-09
*/
public class FullHouse extends Hand
{
// Private variable storing the type of this hand in String
private String type;
/**
* This constructor construct a FullHouse object with specified player and list
* of cards.
* <br>
* @param player The player who plays his / her hand
* @param cards the list cards that the player plays
*/
public FullHouse(CardGamePlayer player, CardList cards)
{
// Call super constructor first
super(player,cards);
this.type = "FullHouse";
// Storing the type(s) of hand FullHouse can beat
// A Full House can beat, apart from a Pass,
// any Straight and any Flush.
this.beatList.add("Straight");
this.beatList.add("Flush");
}
/**
* This method is used to check if this is a valid FullHouse.
* <br>
* @return a boolean value specifying whether this hand is a valid FullHouse
*/
public boolean isValid()
{
return FullHouse.isValid(this);
}
/**
* This method is used to check whether a given hand is a valid FullHouse hand.
* This method is a static method.
* <br>
* @param hand a given hand to be checked validity
* @return the boolean value to specify whether the given hand is a valid
* FullHouse in Big Two Game.
*/
public static boolean isValid(CardList hand)
{
int numOfCards = hand.size();
// First check the number of cards
if(numOfCards == 5)
{
// Using a HashMap to associate the number of occurrence of a
// particular suit to this particular suit
HashMap<Integer,Integer> cardsRank = new HashMap<Integer,Integer>();
for(int i = 0; i < numOfCards; ++i)
{
Card card = hand.getCard(i);
int suit = card.getSuit();
int rank = card.getRank();
if(!(-1 < suit && suit < 4 && -1 < rank && rank < 13))
{
return false;
}
// Add or update the occurrence of the rank
if(!cardsRank.containsKey(rank))
{
cardsRank.put(rank,1);
} else {
cardsRank.replace(rank,cardsRank.get(rank) + 1);
}
}
// A Full House has two different ranks and the occurrence of the ranks
// is either (2,3) or (3,2). Thus conditioning whether the product of
// the number of occurrence is six to determine whether this is a
// valid Full House given the total number of cards is five.
if((cardsRank.size() == 2)
&& (((int) cardsRank.values().toArray()[0] * (int) cardsRank.values().toArray()[1]) == 6))
{
return true;
}
}
return false;
}
/**
* This method is used to retrieve the top card of this Full House.
* <b> Important Note: This method assumes this hand is a valid Full House. </b>
* <br>
* @return the top card of this hand
*/
public Card getTopCard()
{
// Create two lists to hold cards according to rank
CardList firstList = new CardList();
CardList secondList = new CardList();
// Get one rank for comparison
int firstRank = this.getCard(0).getRank();
// Divide the cards into two lists according to the rank obtained
for(int i = 0; i < this.getNumOfCards(); ++i)
{
Card card = this.getCard(i);
int rank = card.getRank();
if(rank == firstRank)
{
firstList.addCard(card);
} else {
secondList.addCard(card);
}
}
// Get the triplet in Full House
CardList finalList = firstList.size() > secondList.size() ? firstList : secondList;
// Get the top card in the triplet, which is the top card in this Full House
finalList.sort();
return finalList.getCard(0);
}
/**
* This method is used to return the type of this hand in
* String representation.
* @return the String specification of the type of this hand
*/
public String getType()
{
return this.type;
}
}
| zjiayao/BigTwoGame | src/FullHouse.java | 1,433 | /**
* This method is used to retrieve the top card of this Full House.
* <b> Important Note: This method assumes this hand is a valid Full House. </b>
* <br>
* @return the top card of this hand
*/ | block_comment | en | false |
201595_11 | /*
THOUGHT PROCESS :
URL = https://leetcode.com/problems/minimum-size-subarray-sum/
209. Minimum Size Subarray Sum
Whenever contiguous subarrays are mentioned, of varying lengths, bring up the following techniques
1. Prefix sums
2. Sliding windows via priority queues
Ideal [T,S] = [O(N), O(1)] one-pass linear scan, "in-place" performance
Edge cases :
(1) Singleton arrays : len = 1 such as [11]. Quickly check if equal to target or not
(2) [0,0,0,.....,0] Arrays with repeating values
(3) (n-1:1) partition such as [0,0,0,......,0,1] : and say, target = {0,1} . Make sure to return valid if either a single element, but not if target is outside the set of elements encompassed1
(4) Case where target is not found in array : return 0
(5) [1,2,3] : target = 6 : all elements to sum up case
(6) Case such as [2,3,1,2,3,4], and target = 5 : we have two contiguous subarrays whose sum >= target
Luckily, input lacks any negatives or zero : strictly natural numbers within reasonable range [1,10^5]
Max summation possible = [10^5 TIMES 10^5] = 10^10 ( target = 10^9 ).
10000000000 should not overflow the itneger datatype
// int test = 10000000000;
// if(test<minLen) System.out.println("test value < max value of a INT ");
// Needs further exploration here
Can one binary search for minimal subarray length? Versus testing out all subarray lengths?
Total number of contiguous subranges, of an array, naturall equals sum of natural numbers from 1 to n, where n := length of array/number of elements . It entails a BFS solution of O(N^2) then, as summation formula = (N^2 + N ) / 2
Current time-space complexity : [T,S] = [O(NlogN), O(1)]
O(N) + O(NlogN) = time : preprocessing + ( testing each subarray, during binary search )
*/
class Solution
{
public int minSubArrayLen(int target, int[] nums)
{
int minLen = Integer.MAX_VALUE;
// Quickly handle base case
if(nums.length == 1 )
{
if(nums[0] >= target) return 1;
return 0;
}
// Build prefix array sum
// int[] prefix_arr = new int[nums.length];
// for(int i = 0; i < nums.length; ++i)
// prefix_arr[i] = nums[i];
// for(int i = 1; i < nums.length; ++i)
// prefix_arr[i] = prefix_arr[i] + prefix_arr[i-1];
for(int i = 1; i < nums.length; ++i)
nums[i] += nums[i-1];
// Then execute binary search algorithm
// Offsets into lengths can equal 0 too!
int low = 1;
int high = nums.length;
while(low <= high)
{
int mid = (low + high) / 2; // In production, account for Integer overflow, OFC
// boolean greaterThanTarget = checkPrefixSumArrays(prefix_arr, mid, target);
boolean greaterThanTarget = checkPrefixSumArrays(nums, mid, target);
if(greaterThanTarget)
{
minLen = mid;
high = mid - 1;
}
else
low = mid + 1;
}
if(minLen == Integer.MAX_VALUE)
return 0;
return minLen;
}
// Make sure to correct for ( offset - 1 ), in array indexing
// Is a linear time algorithm : low bounded by [0,n] here
public boolean checkPrefixSumArrays(int[] prefix_arr, int offset, int target)
{
int sum = 0;
for(int low = 0; low < prefix_arr.length; ++low)
{
int high = low + ( offset - 1 );
if(high <= (prefix_arr.length - 1))
{
if(low == 0)
sum = prefix_arr[high];
else
sum = prefix_arr[high] - prefix_arr[low - 1];
if(sum >= target)
return true;
}
}
return false;
}
}
| 2018hsridhar/Leetcode_Solutions | leetcode_209.java | 1,118 | // boolean greaterThanTarget = checkPrefixSumArrays(prefix_arr, mid, target); | line_comment | en | true |
201771_10 | import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
//Agustin Quintanar A01636142
//Jonathan Chavez A01636160
public class Index {
private Website[] websites;
private int count;
private HashMap<String, Integer> dns;
private final String websitesPath = "../WEBSITES";
public Index() {
this.count = 0;
this.dns = new HashMap<>(1000000);
this.websites = new Website[1000000];
this.loadMetadata();
}
public void addWebsitesFromWindow() {
AddNewWebsiteWindow addNewWebsiteWindow = new AddNewWebsiteWindow(this);
}
public void addWebsite(String publicUrl, String privateUrl, String rawHtml) {
Website newWebsite = new Website(publicUrl, privateUrl, rawHtml);
this.websites[this.count] = newWebsite; //Adds the website previously created to websites[]
this.dns.put(newWebsite.getPublicUrl(), this.count); //Inserts to the DNS the new website and increases the count
File websiteFolder = this.createEmptyWebsiteFiles();
this.createWebsiteMetadataFile(websiteFolder);
this.createMetaDescriptionFile(websiteFolder);
this.count++;
}
public File createEmptyWebsiteFiles() {
String newWebsiteFolderPath = websitesPath+"/"+Integer.toString(this.count);
File newWebsiteFolder = new File(newWebsiteFolderPath);
newWebsiteFolder.mkdirs(); //Creates empty website folder
return newWebsiteFolder;
}
public void loadMetadata() {
File[] websitesDirectory = new File(this.websitesPath).listFiles(File::isDirectory); //Array of websites directories
for (File websiteFolder : websitesDirectory) {
//System.out.println("folder: " + websiteFolder);
try {
Website newWebsite = this.buildWebsite(websiteFolder);
this.websites[Integer.parseInt(websiteFolder.getName())] = newWebsite; //Adds the website previously created to websites[]
this.dns.put(newWebsite.getPublicUrl(), Integer.parseInt(websiteFolder.getName())); //Inserts to the DNS the new website and increases the count
this.count++;
}
catch (NullPointerException npe) {
System.out.println("Null value found while loading metadata.");
}
catch(IndexOutOfBoundsException iobe) {
}
}
}
public void writeMetadata() {
File[] websitesDirectory = new File(this.websitesPath).listFiles(File::isDirectory);
for (File websiteFolder : websitesDirectory) {
//System.out.println("folderPro: " + websiteFolder);
try {
this.createWebsiteMetadataFile(websiteFolder);
this.createMetaDescriptionFile(websiteFolder);
} catch(NullPointerException npe) {
}
}
}
private boolean createMetaDescriptionFile(File websiteFolder) {
String metaDescriptionPath = websiteFolder.getPath()+"/metaDescription.txt";
try {
FileWriter fw = new FileWriter(metaDescriptionPath);
PrintWriter pw = new PrintWriter(fw);
//System.out.println("index Website: "+Integer.parseInt(websiteFolder.getName()));
Website website = this.websites[Integer.parseInt(websiteFolder.getName())];
pw.println(website.getMetaDescription());
pw.close();
return true;
}
catch(IOException ex) {
System.out.println(metaDescriptionPath+" can not be accessed.");
}
return false;
}
private boolean createWebsiteMetadataFile(File websiteFolder) {
String metadataPath = websiteFolder.getPath()+"/website.metadata";
try {
FileWriter fw = new FileWriter(metadataPath);
PrintWriter pw = new PrintWriter(fw);
pw.println("publicUrl!---!privateUrl!---!TITLE!---!KEYWORDS!---!LINKS_TO!---!CREATED!---!VISITORS!---!RANKS");
Website website = this.websites[Integer.parseInt(websiteFolder.getName())];
String keywordString = "",
linksToString = "";
for (String keyword : website.getKeywords()) keywordString += keyword+",";
for (String link : website.getLinksTo()) linksToString += link+",";
pw.println(
website.getPublicUrl() + "!---!" +
website.getPrivateUrl() + "!---!" +
website.getTitle() + "!---!" +
keywordString + "!---!" +
linksToString + "!---!" +
website.getCreated().toString() + "!---!" +
Integer.toString(website.getVisitors()) + "!---!" +
Double.toString(website.getRank())
);
pw.close();
return true;
}
catch(IOException ex) {
System.out.println(metadataPath+" can not be accessed.");
}
return false;
}
private Website buildWebsite(File websiteFolder) {
String metadataPath = websiteFolder.getPath()+"/website.metadata";
String[] websiteMetadata = this.readWebsiteMetaData(metadataPath);
String publicUrl = websiteMetadata[0],
privateUrl = websiteMetadata[1],
title = websiteMetadata[2],
metaDescription = getFileContent(websiteFolder.getPath()+"/metaDescription.txt");
String[] keywords = websiteMetadata[3].split(",");
try {
HashSet<String> linksTo = new HashSet<>();
for (String link : websiteMetadata[4].split(",")) linksTo.add(link);
Date created = new Date();
try {
created = new SimpleDateFormat("dd/MM/yyyy").parse(websiteMetadata[5]);
} catch(ParseException pe) {
//System.out.println("Error while parsing date.");
}
int visitors = Integer.parseInt(websiteMetadata[6]);
double rank = Double.parseDouble(websiteMetadata[7]);
return new Website(publicUrl, privateUrl, title, metaDescription, keywords, linksTo, visitors, created, rank);
}
catch(IndexOutOfBoundsException iobe) {
return new Website(publicUrl, privateUrl, "");
}
catch(NullPointerException npe) {
return new Website(publicUrl, privateUrl, "");
}
}
private String[] readWebsiteMetaData(String pathFile) {
String[] websiteMetadata = new String[8];
try {
BufferedReader br = new BufferedReader(new FileReader(pathFile));
br.readLine(); //Discards header file
String line = br.readLine();
if (line != null && line.length()>0) {
websiteMetadata = line.toLowerCase().split("!---!");
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(pathFile + " not found!. "+ex);
}
catch (IOException ex){
System.out.println("There was an I/O error.");
}
return websiteMetadata;
}
private String getFileContent(String pathFile) {
String fileContent = "";
try {
BufferedReader br = new BufferedReader(new FileReader(pathFile));
String line;
while((line = br.readLine()) != null){
if (line.length() > 0) {
fileContent += line += "\n";
}
}
br.close();
}
catch (FileNotFoundException ex){
System.out.println(pathFile + " not found!. "+ex);
}
catch (IOException ex){
System.out.println("There was an I/O error.");
}
return fileContent;
}
public int getCount() {
return this.count;
}
public Website[] getWebsites() {
return this.websites;
}
public HashMap<String, Integer> getDns() {
return this.dns;
}
public void setCount(int count) {
this.count = count;
}
public void setWebsites(Website[] websites) {
this.websites = websites;
}
public static void main(String[] args) {
}
} | azartheen/Aether | BACKEND/Index.java | 1,879 | //System.out.println("index Website: "+Integer.parseInt(websiteFolder.getName())); | line_comment | en | true |
202045_3 | package rsa;
/**
*
* Copyright (c) 2023 Archerxy
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @author archer
*
*/
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
/***
* n = p1 * p2 ; (p1,p2 are prime numbers)
*
* φ(n) = (p1 - 1) * (p2 - 1) ; Euler's formula
*
* e * d - k * φ(n) = 1 ; e = random(1~φ(n)), d is calculated
*
* message ^ e = cipher (mod n) ;
*
* cipher ^ d = message (mod n) ;
*
* */
public class RSA {
private static final int BITS = 512;
/***
* generate (e, d, n) pk = (n, e), sk = (n, d)
* @return BigInteger[3] [e, d, n]
* */
public static BigInteger[] genEDN() {
SecureRandom sr = new SecureRandom();
BigInteger p1 = BigInteger.probablePrime(BITS >> 1, sr);
BigInteger p2 = BigInteger.probablePrime(BITS >> 1, sr);
BigInteger n = p1.multiply(p2);
BigInteger fiN = p1.subtract(BigInteger.ONE).multiply(p2.subtract(BigInteger.ONE));
BigInteger e = BigInteger.probablePrime(fiN.bitLength() - 1, sr);
while(e.compareTo(fiN) >= 0) {
e = BigInteger.probablePrime(fiN.bitLength() - 1, sr);
}
/**
* Actually, d can be calculated with {@code BigInteger d = e.modInverse(fiN);}.
* Euclid's algorithm to calculate d.
* */
List<BigInteger[]> rs = new LinkedList<>();
BigInteger r1 = e, r2 = fiN;
boolean b = false;
while(!r1.equals(BigInteger.ONE) && !r2.equals(BigInteger.ONE)) {
rs.add(new BigInteger[] {r1, r2});
if(b) {
r1 = r1.mod(r2);
b = false;
} else {
r2 = r2.mod(r1);
b = true;
}
}
rs.add(new BigInteger[] {r1, r2});
Collections.reverse(rs);
BigInteger d = BigInteger.valueOf(1), k = BigInteger.valueOf(0);
b = r1.equals(BigInteger.ONE);
for(BigInteger[] r : rs) {
if(b) {
d = k.multiply(r[1]).add(BigInteger.ONE).divide(r[0]);
b = false;
} else {
k = d.multiply(r[0]).subtract(BigInteger.ONE).divide(r[1]);
b = true;
}
}
return new BigInteger[] {e, d, n};
}
/**
* rsa encryption,
* @param e
* @param n
* @param message
*
* **/
public static BigInteger encrypt(BigInteger e, BigInteger n, BigInteger message) {
return message.modPow(e, n);
}
/**
* rsa decryption,
* @param d
* @param n
* @param cipher
*
* **/
public static BigInteger decrypt(BigInteger d, BigInteger n, BigInteger cipher) {
return cipher.modPow(d, n);
}
/**
* test
* */
public static void main(String[] args) {
String msg = "hello";
BigInteger[] edn = genEDN();
BigInteger e = edn[0], d = edn[1], n = edn[2];
//encrypt
BigInteger cipher = encrypt(e, n, new BigInteger(1, msg.getBytes()));
System.out.println(cipher.toString(16));
//decrypt
BigInteger message = decrypt(d, n, cipher);
System.out.println(new String(message.toByteArray()));
}
}
| Archerxy/RSA_java | rsa/RSA.java | 1,228 | /**
* Actually, d can be calculated with {@code BigInteger d = e.modInverse(fiN);}.
* Euclid's algorithm to calculate d.
* */ | block_comment | en | false |
202177_0 | import java.util.*;
import java.security.*;
public class Solution {
public static void main(String[] args) {
DoNotTerminate.forbidExit();
try {
Scanner in = new Scanner(System.in);
int n = in .nextInt();
in.close();
//String s=???; Complete this line below
String s = String.valueOf(n);
if (n == Integer.parseInt(s)) {
System.out.println("Good job");
} else {
System.out.println("Wrong answer.");
}
} catch (DoNotTerminate.ExitTrappedException e) {
System.out.println("Unsuccessful Termination!!");
}
}
}
//The following class will prevent you from terminating the code using exit(0)!
class DoNotTerminate {
public static class ExitTrappedException extends SecurityException {
private static final long serialVersionUID = 1;
}
public static void forbidExit() {
final SecurityManager securityManager = new SecurityManager() {
@Override
public void checkPermission(Permission permission) {
if (permission.getName().contains("exitVM")) {
throw new ExitTrappedException();
}
}
};
System.setSecurityManager(securityManager);
}
}
| AnujPawaadia/HackerRank | day21.java | 280 | //String s=???; Complete this line below | line_comment | en | true |
202685_5 | import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
import com.itextpdf.text.DocumentException;
public class ParseFile {
public static String openFile(String filePath) throws IOException{
FileInputStream inputStream = new FileInputStream(filePath);
String file;
try {
file = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
return file;
}
public static ArrayList<Measure> sortMeasure(String body) {
String line = "";
int indexOfNewLine = 0;
int indexOfVerticalLine = 0;
String checkString = "";
Pattern pattern = Pattern.compile("\\|?(\\||([0-9]))(-|\\*)");
Pattern pattern2 = Pattern.compile("\\|?(\\|)(-|\\*)");
ArrayList<String> blockOfMeasures = new ArrayList<String>();
ArrayList<Measure> measures = new ArrayList<Measure>();
// forgot why body length > 0 is used, check again later
while (indexOfNewLine != -1 && body.length() > 0) {
for (int i = 0; i < 6; i ++) {
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
indexOfVerticalLine = matcher.start();
indexOfNewLine = body.indexOf('\n', indexOfVerticalLine + 1);
int check2 = body.indexOf('\n', indexOfNewLine + 1);
checkString = body.substring(indexOfNewLine, check2).trim();
Matcher check = pattern2.matcher(checkString);
if (!check.find() && i != 5) {
blockOfMeasures.clear();
break;
}
line = body.substring(indexOfVerticalLine, indexOfNewLine).trim();
if (line.lastIndexOf("| ") > 0)
line = line.substring(0, line.lastIndexOf("| ") + 2).trim();
body = body.substring(indexOfNewLine + 1);
blockOfMeasures.add(line);
}
}
if (unevenBlockLengthCheck(blockOfMeasures)) {
String message = "";
for (String s : blockOfMeasures) {
message = message + s + '\n';
}
throw new InvalidMeasureException("This measure is formatted incorrectly.\n" + message);
}
if (blockOfMeasures.size() > 0)
measures.addAll(convertToMeasures(blockOfMeasures));
blockOfMeasures.clear();
body = body.substring(body.indexOf('\n') + 1);
if (body.indexOf('\n') <= 1) { // something idk check again later
while (body.indexOf('\n') >= 0 && body.indexOf('\n') <= 1)
body = body.substring(body.indexOf('\n') + 1);
}
}
return measures;
}
public static ArrayList<String> parse(String string) {
ArrayList<String> token = new ArrayList<String>();
String hyphen = "";
Pattern isDigit = Pattern.compile("^[0-9]");
for (int i = 0; i < string.length(); i++) {
Matcher matcher = isDigit.matcher(string);
if (string.charAt(i) == '|') {
if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') {
token.add("|||");
i = i + 2;
}
else if ((i + 1 < string.length()) && string.charAt(i+1) == '|') {
token.add("||");
i++;
}
else if ((i + 1 < string.length()) && (i + 2 < string.length()) && string.charAt(i+1) == '|' && string.charAt(i+2) == '|') {
token.add("|||");
i = i + 2;
}
else if ((i + 1 < string.length()) && (string.charAt(i+1) >= '0' && (string.charAt(i+1) <= '9'))) {
token.add("|" + string.charAt(i+1));
i++;
}
else
token.add("|");
}
else if (string.charAt(i) == '-') {
while (string.charAt(i) == '-') {
hyphen = hyphen + "-"; // use stringbuilder or something for this later
i++;
if (i == string.length())
break;
}
token.add(hyphen);
hyphen = "";
i--;
}
else if (string.charAt(i) == ' ') {
i++;
while (string.charAt(i) == ' ') {
hyphen = hyphen + "-";
i++;
if (i == string.length())
break;
}
token.add(hyphen);
hyphen = "";
i--;
}
else if ((string.charAt(i) >= '0' && (string.charAt(i) <= '9')) && i > 0) {
//check the second digit only if index + 1 is not equal to the length of the string
if (i + 1 < string.length())
// if the second digit is a number, we will treat it as a two-digit number.
if (string.charAt(i + 1) >= '0' && (string.charAt(i + 1) <= '9')) {
if (string.charAt(i-1) == '<') {
token.add(string.substring(i-1, i+3));
i = i + 2;
}
else {
token.add(string.substring(i, i+2));
i = i + 1;
}
}
// if the character ahead is not a digit, we check if the previous character is a angle bracket
else if (string.charAt(i-1) == '<') {
token.add(string.substring(i-1,i+2));
i = i + 1;
}
// if not we just add the number itself.
else {
token.add("" + string.charAt(i));
}
}
else if (string.charAt(i) == 's')
token.add("s");
else if (string.charAt(i) == '*')
token.add("*");
else if (string.charAt(i) == 'h')
token.add("h");
else if (string.charAt(i) == 'p')
token.add("p");
else if (matcher.find()) {
token.add("" + string.charAt(i));
}
else {
if (string.charAt(i) != '>' && string.charAt(i) != '<')
token.add("-");
}
}
return token;
}
public static ArrayList<Measure> convertToMeasures(ArrayList<String> block) {
Pattern separator = Pattern.compile("(\\||^[0-9])([0-9]|\\|)?\\|?");
Matcher matcher = separator.matcher(block.get(2));
ArrayList<String> measure = new ArrayList<String>();
ArrayList<Measure> newMeasures = new ArrayList<Measure>();
int indexOfBeginningStaff = 0;
matcher.find();
while (matcher.find()) {
for (String s : block) {
measure.add(s.substring(indexOfBeginningStaff, matcher.end()));
}
newMeasures.add(new Measure(measure));
measure.clear();
indexOfBeginningStaff = matcher.start();
}
return newMeasures;
}
public static boolean unevenBlockLengthCheck(ArrayList<String> blockOfMeasures) {
HashSet<Integer> lengths = new HashSet<Integer>();
for (String s : blockOfMeasures) {
lengths.add(s.length());
}
if (lengths.size() > 1)
return true;
return false;
}
}
| Hayawi/TAB2PDF | src/ParseFile.java | 2,022 | // if the character ahead is not a digit, we check if the previous character is a angle bracket
| line_comment | en | false |
203053_7 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* 정올_1828_냉장고
* 1s, 32MB
*
* author djunnni
*/
public class Main {
public static class Rifrigator {
int low;
int high;
public Rifrigator(int low, int high) {
this.low = low;
this.high = high;
}
}
public static class Chemical implements Comparable<Chemical> {
int low;
int high;
public Chemical(int low, int high) {
this.low = low;
this.high = high;
}
@Override
public int compareTo(Chemical c) {
if(this.low == c.low) {
return Integer.compare(this.high, c.high);
}
return Integer.compare(this.low, c.low);
}
@Override
public String toString() {
return "[" + low + ", " + high + "]";
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 화학물질 N개
int N = Integer.parseInt(br.readLine());
StringTokenizer st = null;
// 인덱스 i는 C[i] 화학물질이다.
// x[i] : 최저 보관온도, y[i] : 최고 보관온도
// - 270 ~ 10000 온도범위
Chemical c[] = new Chemical[N];
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine(), " ");
c[i] = new Chemical(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
}
Arrays.sort(c);
// 최소한 1대는 기록하자.
Rifrigator rifrigator = null;
int answer = 0;
for(int i = 0; i < N; i++) {
// 냉장고가 현재 설정이 0이면 새롭게 만들어준다.
if(rifrigator == null) {
rifrigator = new Rifrigator(c[i].low, c[i].high);
answer++;
} else {
// 냉장고의 최고온도 보다 화학물질의 최저온도가 낮다면! 냉장고를 새롭게 바꿔야해.
if(rifrigator.high < c[i].low) {
rifrigator.low = c[i].low;
rifrigator.high = c[i].high;
answer++;
} else {
// 그렇지 않다면 냉장고의 최고온도는 항상 다음 화학물징의 높이에 따라 최솟값으로 넣어줘야 한다.
rifrigator.high = Math.min(rifrigator.high, c[i].high);
}
}
}
System.out.println(answer);
}
}
| Djunnni/Algorithm | jungol/1828/Main.java | 769 | // 냉장고의 최고온도 보다 화학물질의 최저온도가 낮다면! 냉장고를 새롭게 바꿔야해. | line_comment | en | true |
204007_0 | package javabasics.Javabasic_esercizi._3;
public class Main {
public static void main(String[] args) {
exercise1();
exercise2();
exercise3();
}
/**
* 1: print out your initials using System.out.print and then a char literal,
* i.e. 'a', 'b', 'c'. You will need multiple print statements
*/
private static void exercise1() {
System.out.println("Exercise 1:");
// Write your code here
System.out.print('M');
System.out.println('D');
}
/**
* 2: Print out your age as an int literal, i.e. 28, then print whether or not you've
* had lunch today as a boolean literal i.e. true, false, then print the price of
* your lunch as a double, i.e. 4.99
*/
private static void exercise2() {
System.out.println("\nExercise 2:");
// Write your code here
System.out.println(31);
System.out.println(true);
System.out.println(15.99);
}
/**
* 3: Complete exercise 2, but store the values in a variable.
* And then print out the variable.
*
* i.e.
* char favouriteLetter = 'g';
* System.out.print("My favourite letter=");
* System.out.println(favouriteLetter)
*/
private static void exercise3() {
System.out.println("\nExercise 3:");
// Write your code here
int myAge = 31;
boolean myLunch = true;
double myLunchprice = 15.99;
System.out.println(myAge);
System.out.println(myLunch);
System.out.println(myLunchprice);
}
}
| MassimilianoDemma/Javabasic_esercizi | _3/Main.java | 444 | /**
* 1: print out your initials using System.out.print and then a char literal,
* i.e. 'a', 'b', 'c'. You will need multiple print statements
*/ | block_comment | en | true |
204664_0 | package irvine.oeis.a069;
import irvine.math.IntegerUtils;
import irvine.math.partition.IntegerPartition;
import irvine.math.predicate.Predicates;
import irvine.math.z.Z;
import irvine.oeis.Sequence1;
import irvine.util.Permutation;
import irvine.util.bumper.Bumper;
import irvine.util.bumper.BumperFactory;
/**
* A069672 Largest n-digit triangular number with minimum digit sum.
* @author Sean A. Irvine
*/
public class A069672 extends Sequence1 {
// After Robert Israel
private static final int[] S = {1, 3, 6, 9};
private int mD = 0;
@Override
public Z next() {
++mD;
final Bumper bumper = BumperFactory.increasing(mD);
for (final int s : S) {
final IntegerPartition part = new IntegerPartition(s);
int[] q;
Z best = Z.ZERO;
while ((q = part.next()) != null) {
final Permutation perm = new Permutation(q);
int[] p;
while ((p = perm.next()) != null) {
final int[] pos = IntegerUtils.identity(new int[p.length]);
do {
if (pos[pos.length - 1] == mD - 1) {
Z x = Z.ZERO;
for (int k = 0; k < pos.length; ++k) {
x = x.add(Z.TEN.pow(pos[k]).multiply(p[k]));
}
if (x.compareTo(best) > 0 && Predicates.TRIANGULAR.is(x)) {
best = x;
}
}
} while (bumper.bump(pos));
}
}
if (!best.isZero()) {
return best;
}
}
throw new UnsupportedOperationException();
}
}
| archmageirvine/joeis | src/irvine/oeis/a069/A069672.java | 481 | /**
* A069672 Largest n-digit triangular number with minimum digit sum.
* @author Sean A. Irvine
*/ | block_comment | en | false |
204913_9 | // Stefan Miklosovic
// [email protected]
import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.LinkedList;
// this class represents a process in a system
public class Process implements MsgHandler {
// process id for process identification
protected int pid;
// number of processes in a system in Ricart-Agrawala's algorithm
protected int numOfProcesses;
// state of critical section from processes view
protected State state;
// port of process it is listening for incomming messages at
protected int port;
// ports of other processes for udp communication
LinkedList<Pair> ports;
// length of a input buffer for message recieving
protected final static int bufferLength = 100;
Process(int id, int n, int p, LinkedList<Pair> ports) {
// state is firstly set to the RELEASED, look at State's constructor
state = new State();
pid = id;
numOfProcesses = n;
port = p;
this.ports = ports;
}
// waiting method for a process thread, typically it waits for a message
public synchronized void processWait() {
try {
wait();
} catch (Exception e) {
System.err.println(e);
}
}
// multicasting of messages to the other processes
public void multicastMessage(Msg message) {
for (int i = 1; i <= numOfProcesses; i++) {
if (i != this.pid) {
sendMessage(ports.get(i-1).getPort(), message);
}
}
}
// sending of a message to another process
public void sendMessage(int port, Msg m) {
DatagramSocket aSocket = null;
try {
aSocket = new DatagramSocket();
InetAddress aHost = InetAddress.getByAddress(
new byte[] {(byte)127, (byte)0, (byte)0 ,(byte) 1});
DatagramPacket message =
new DatagramPacket(m.toBytes(), m.toBytes().length, aHost, port);
// actual sending of a message
aSocket.send(message);
}
catch (IOException ex) { }
finally { if(aSocket != null) aSocket.close(); }
}
// receiving of a message form a network
@Override
public Msg recieveMessage(DatagramSocket aSocket) {
DatagramPacket message = null;
byte[] buffer = null;
try {
buffer = new byte[bufferLength];
message = new DatagramPacket(buffer, buffer.length);
aSocket.receive(message);
}
catch (IOException ex) {
}
return new Msg(message);
}
@Override
public void handleMessage(Msg message) {
// this method is empty since it is overriden in MutexProcess class
}
}
| smiklosovic/ramutex | Process.java | 689 | // state is firstly set to the RELEASED, look at State's constructor | line_comment | en | false |
205488_5 | /*
Copyright 2018-19 Mark P Jones, Portland State University
This file is part of mil-tools.
mil-tools 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.
mil-tools 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 mil-tools. If not, see <https://www.gnu.org/licenses/>.
*/
package mil;
import compiler.*;
import core.*;
import java.io.PrintWriter;
public class Sel extends Tail {
private Cfun cf;
private int n;
private Atom a;
/** Default constructor. */
public Sel(Cfun cf, int n, Atom a) {
this.cf = cf;
this.n = n;
this.a = a;
}
/** Test to determine whether a given tail expression has no externally visible side effect. */
boolean hasNoEffect() {
return true;
}
/** Test if this Tail expression includes a free occurrence of a particular variable. */
boolean contains(Temp w) {
return a == w;
}
/**
* Test if this Tail expression includes an occurrence of any of the variables listed in the given
* array.
*/
boolean contains(Temp[] ws) {
return a.occursIn(ws);
}
/** Add the variables mentioned in this tail to the given list of variables. */
Temps add(Temps vs) {
return a.add(vs);
}
/** Test if two Tail expressions are the same. */
boolean sameTail(Tail that) {
return that.sameSel(this);
}
boolean sameSel(Sel that) {
return this.cf == that.cf && this.n == that.n && this.a.sameAtom(that.a);
}
/** Find the dependencies of this AST fragment. */
Defns dependencies(Defns ds) {
return a.dependencies(ds);
}
/** Display a printable representation of this MIL construct on the specified PrintWriter. */
void dump(PrintWriter out, Temps ts) {
out.print(cf + " " + n + " " + a.toString(ts));
}
/**
* Apply a TempSubst to this Tail, forcing construction of a new Tail, even if the substitution is
* empty.
*/
Tail apply(TempSubst s) {
return new Sel(cf, n, a.apply(s));
}
private AllocType type;
/** The type tuple that describes the outputs of this Tail. */
private Type outputs;
/** Calculate the list of unbound type variables that are referenced in this MIL code fragment. */
TVars tvars(TVars tvs) {
return type.tvars(outputs.tvars(tvs));
}
/** Return the type tuple describing the result that is produced by executing this Tail. */
Type resultType() {
return outputs;
}
Type inferType(Position pos) throws Failure {
type = cf.checkSelIndex(pos, n).instantiate();
type.resultUnifiesWith(pos, a.instantiate());
return outputs = Type.tuple(type.storedType(n));
}
/**
* Generate code for a Tail that appears as a regular call (i.e., in the initial part of a code
* sequence). The parameter o specifies the offset for the next unused location in the current
* frame; this will also be the first location where we can store arguments and results.
*/
void generateCallCode(MachineBuilder builder, int o) {
a.load(builder);
builder.sel(n, o);
}
/**
* Generate code for a Tail that appears in tail position (i.e., at the end of a code sequence).
* The parameter o specifies the offset of the next unused location in the current frame. For
* BlockCall and Enter, in particular, we can jump to the next function instead of doing a call
* followed by a return.
*/
void generateTailCode(MachineBuilder builder, int o) {
a.load(builder);
builder.sel(n, 0);
builder.retn();
}
/**
* Skip goto blocks in a Tail (for a ClosureDefn or TopLevel). TODO: can this be simplified now
* that ClosureDefns hold Tails rather than Calls?
*/
public Tail inlineTail() {
return thisUnless(rewriteSel(null));
}
/**
* Find the variables that are used in this Tail expression, adding them to the list that is
* passed in as a parameter. Variables that are mentioned in BlockCalls or ClosAllocs are only
* included if the corresponding flag in usedArgs is set; all of the arguments in other types of
* Call (i.e., PrimCalls and DataAllocs) are considered to be "used".
*/
Temps usedVars(Temps vs) {
return a.add(vs);
}
/**
* Test to determine whether a given tail expression may be repeatable (i.e., whether the results
* of a previous use of the same tail can be reused instead of repeating the tail). TODO: is there
* a better name for this?
*/
public boolean isRepeatable() {
return true;
}
/**
* Test to determine whether a given tail expression is pure (no externally visible side effects
* and no dependence on other effects).
*/
public boolean isPure() {
return true;
}
public Code rewrite(Defn d, Facts facts) {
Tail t = rewriteSel(facts);
return (t == null) ? null : new Done(t);
}
/** Liveness analysis. TODO: finish this comment. */
Temps liveness(Temps vs) {
a = a.shortTopLevel();
return a.add(vs);
}
/**
* Attempt to rewrite this selector if the argument is known to have been constructed using a
* specific DataAlloc. TODO: find a better name?
*/
Tail rewriteSel(Facts facts) {
DataAlloc data = a.lookForDataAlloc(facts); // is a a known data allocator?
if (data != null) {
Atom a1 = data.select(cf, n); // find matching component
if (a1 != null) {
MILProgram.report("rewriting " + cf + " " + n + " " + a + " -> " + a1);
return new Return(a1);
}
}
return null;
}
/**
* Compute an integer summary for a fragment of MIL code with the key property that alpha
* equivalent program fragments have the same summary value.
*/
int summary() {
return 4 + cf.summary() + n;
}
/** Test to see if two Tail expressions are alpha equivalent. */
boolean alphaTail(Temps thisvars, Tail that, Temps thatvars) {
return that.alphaSel(thatvars, this, thisvars);
}
/** Test two items for alpha equivalence. */
boolean alphaSel(Temps thisvars, Sel that, Temps thatvars) {
return this.cf == that.cf && this.n == that.n && this.a.alphaAtom(thisvars, that.a, thatvars);
}
/** Collect the set of types in this AST fragment and replace them with canonical versions. */
void collect(TypeSet set) {
a.collect(set);
if (outputs != null) {
outputs = outputs.canonType(set);
}
if (type != null) {
type = type.canonAllocType(set);
}
cf = cf.canonCfun(set);
}
/**
* Eliminate a call to a newtype constructor or selector in this Tail by replacing it with a tail
* that simply returns the original argument of the constructor or selector.
*/
Tail removeNewtypeCfun() {
if (cf.isNewtype()) { // Look for use of a newtype constructor
if (n != 0) {
debug.Internal.error("newtype selector for arg!=0");
}
return new Return(a);
}
// No point looking for a selector of a singleton type because they do not have any fields.
return this;
}
/** Generate a specialized version of this Tail. */
Tail specializeTail(MILSpec spec, TVarSubst s, SpecEnv env) {
return new Sel(cf.specializeCfun(spec, type, s), n, a.specializeAtom(spec, s, env));
}
Tail bitdataRewrite(BitdataMap m) {
BitdataRep r = cf.findRep(m); // Look for a possible change of representation
if (r == null) { // No new representation for this type
return this;
} else if (cf.getArity()
== 0) { // Representation change, but nullary so there is no layout constructor
return new Sel(cf.bitdataRewrite(r), n, a);
} else { // Representation change, requires layout constructor
return new BlockCall(cf.bitdataSelBlock(r, n)).withArgs(a);
}
}
Tail mergeRewrite(MergeMap mmap) {
return new Sel(cf.lookup(mmap), n, a);
}
Tail repTransform(RepTypeSet set, RepEnv env) {
return cf.repTransformSel(set, env, n, a);
}
/**
* Apply a representation transformation to this Tail value in a context where the result of the
* tail should be bound to the variables vs before continuing to execute the code in c. For the
* most part, this just requires the construction of a new Bind object. Special treatment,
* however, is required for Selectors that access data fields whose representation has been spread
* over multiple locations. This requires some intricate matching to check for selectors using
* bitdata names or layouts, neither of which require this special treatment.
*/
Code repTransform(RepTypeSet set, RepEnv env, Temp[] vs, Code c) {
return cf.repTransformSel(set, env, vs, n, a, c);
}
/**
* Generate LLVM code to execute this Tail with NO result from the right hand side of a Bind. Set
* isTail to true if the code sequence c is an immediate ret void instruction.
*/
llvm.Code toLLVMBindVoid(LLVMMap lm, VarMap vm, TempSubst s, boolean isTail, llvm.Code c) {
debug.Internal.error("Sel does not return void");
return c;
}
/**
* Generate LLVM code to execute this Tail and return a result from the right hand side of a Bind.
* Set isTail to true if the code sequence c will immediately return the value in the specified
* lhs.
*/
llvm.Code toLLVMBindCont(
LLVMMap lm, VarMap vm, TempSubst s, boolean isTail, llvm.Local lhs, llvm.Code c) { // cf n a
llvm.Type objt = lm.cfunLayoutType(this.cf).ptr();
llvm.Local base = vm.reg(objt); // register to hold a pointer to a structure for cfun this.cf
llvm.Type at = lhs.getType().ptr();
llvm.Local addr = vm.reg(at); // register to hold pointer to the nth component of this.c
return new llvm.Op(
base,
new llvm.Bitcast(a.toLLVMAtom(lm, vm, s), objt),
new llvm.Op(
addr,
new llvm.Getelementptr(at, base, llvm.Word.ZERO, new llvm.Index(n + 1)),
new llvm.Op(lhs, new llvm.Load(addr), c)));
}
}
| habit-lang/mil-tools | src/mil/Sel.java | 2,687 | /** Add the variables mentioned in this tail to the given list of variables. */ | block_comment | en | false |
205516_3 | /*
Copyright 2018 Mark P Jones, Portland State University
This file is part of minitour.
minitour 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.
minitour 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 minitour. If not, see <https://www.gnu.org/licenses/>.
*/
package ast;
import compiler.Position;
/** Abstract syntax for greater than or equal expressions.
*/
public class Gte extends BinCompExpr {
/** Default constructor.
*/
public Gte(Position pos, Expr left, Expr right) {
super(pos, left, right);
}
/** Return a string that provides a simple description of this
* particular type of operator node.
*/
String label() { return "Gte"; }
/** Generate a pretty-printed description of this expression
* using the concrete syntax of the mini programming language.
*/
public void print(TextOutput out) { binary(out, ">="); }
/** Constant folding for binary operators with two known integer
* arguments.
*/
Expr fold(int n, int m) { return new BoolLit(pos, n>=m); }
}
| zipwith/minitour | 19/ast/Gte.java | 359 | /** Return a string that provides a simple description of this
* particular type of operator node.
*/ | block_comment | en | false |
205647_0 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class FenderGuitar here.
*
* @author Jan Kroon
* @version 1
*/
abstract public class FenderGuitar extends ElectricGuitar
{
final String manufacturerName = "Fender Musical Instruments";
final String manufacturerAddress = "17600 North Perimeter Drive, Scottsdale, Arizona, USA";
/**
* Act - do whatever the FenderGuitar wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
// Add your action code here.
}
}
| jankroon/Guitars | FenderGuitar.java | 180 | // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) | line_comment | en | true |
206027_0 | package mdt.smarty;
import net.sf.json.JSONObject;
/**
* This class provides key definitions and cover methods for accessing
* LiveAddress results JSON.
*
* @author Eric Robinson
*/
public class JLiveAddressResult {
public static final String INPUT_INDEX = "input_index";
public static final String CANDIDATE_INDEX = "candidate_index";
public static final String ADDRESSEE = "addressee";
public static final String DELIVERY_LINE_1 = "delivery_line_1";
public static final String DELIVERY_LINE_2 = "delivery_line_2";
public static final String LAST_LINE = "last_line";
public static final String DELIVERY_POINT_BARCODE = "delivery_point_barcode";
public static final String COMPONENTS = "components";
public static final String METADATA = "metadata";
public static final String ANALYSIS = "analysis";
public static final String URBANIZATION = "urbanization";
public static final String PRIMARY_NUMBER = "primary_number";
public static final String STREET_NAME = "street_name";
public static final String STREET_PREDIRECTION = "street_predirection";
public static final String STREET_POSTDIRECTION = "street_postdirection";
public static final String STREET_SUFFIX = "street_suffix";
public static final String SECONDARY_NUMBER = "secondary_number";
public static final String SECONDARY_DESIGNATOR = "secondary_designator";
public static final String PMB_DESIGNATOR = "pmb_designator";
public static final String PMB_NUMBER = "pmb_number";
public static final String CITY_NAME = "city_name";
public static final String STATE_ABBREVIATION = "state_abbreviation";
public static final String ZIPCODE = "zipcode";
public static final String PLUS4_CODE = "plus4_code";
public static final String DELIVERY_POINT = "delivery_point";
public static final String DELIVERY_POINT_CHECK_DIGIT = "delivery_point_check_digit";
public static final String RECORD_TYPE = "record_type";
public static final String COUNTRY_FIPS = "country_fips";
public static final String COUNTRY_NAME = "country_name";
public static final String CARRIER_ROUTE = "carrier_route";
public static final String CONGRESSIONAL_DISTRICT = "congressional_district";
public static final String BUILDING_DEFAULT_INDICATOR = "building_default_indicator";
public static final String RDI = "rdi";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String PRECISION = "precision";
public static final String DPV_MATCH_CODE = "dpv_match_code";
public static final String DPV_FOOTNOTES = "dpv_footnotes";
public static final String DPV_CMRA = "dpv_cmra";
public static final String DPV_VACANT = "dpv_vacant";
public static final String ACTIVE = "active";
public static final String EWS_MATCH = "ews_match";
public static final String FOOTNOTES = "footnotes";
public static final String LACSLINK_CODE = "lacslink_code";
public static final String LACSLINK_INDICATOR = "lacslink_indicator";
JSONObject _addressJSON;
/**
* Create a JLiveAddressResult from the provided json
*
* @param addressJSON
*/
public JLiveAddressResult(JSONObject addressJSON) {
_addressJSON = addressJSON;
}
/**
* get a value from the address JSON
*
* @param key
* @return
*/
public String get(String key) {
return _addressJSON.optString(key);
}
/**
* utility method to get a value from the results "components" map
*
* @param key
* @return
*/
public String getComponent(String key) {
return _addressJSON.optJSONObject(COMPONENTS).optString(key);
}
/**
* utility method to get a value from the results "metadata" map
*
* @param key
* @return
*/
public Object getMetadata(String key) {
return _addressJSON.optJSONObject(METADATA).opt(key);
}
/**
* utility method to get a value from the results "analysis" map
*
* @param key
* @return
*/
public String getAnalysis(String key) {
return _addressJSON.optJSONObject(ANALYSIS).optString(key);
}
/**
* get the raw json
*
* @return
*/
public JSONObject getAddressJSON() {
return _addressJSON;
}
/**
* set the raw json
*
* @param addressJSON
*/
public void setAddressJSON(JSONObject addressJSON) {
_addressJSON = addressJSON;
}
}
| eric-robinson/JLiveAddress | src/mdt/smarty/JLiveAddressResult.java | 1,208 | /**
* This class provides key definitions and cover methods for accessing
* LiveAddress results JSON.
*
* @author Eric Robinson
*/ | block_comment | en | false |
206045_1 | package com.example.electionkhabar;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ListView;
import android.widget.Toast;
public class Party extends ListActivity {
int count=0;
static final String[] Parties = new String[] { "Political Parties",
"Congress", "Bhartiya Janta Party", "Samajwadi Party",
"Bahujan Samaj Party", "CPI(Marxist)", "Trinamool Congress", "DMK",
"AIADMK", "Janata Dal(United)", "Shiv Sena" };
static final String[] Logos = new String[] { "parties", "congress", "bjp",
"sp", "bsp", "cpi", "tmc", "dmk", "aiadmk", "jdu", "shivsena" };
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//String act = getIntent().getExtras().getString("activity");
//if (act.equalsIgnoreCase("home")) {
overridePendingTransition(R.anim.slideleft, R.anim.slideleft2);
//}
//final ListView l = getListView();
setListAdapter(new MobileArrayAdapter(this, Parties, Logos));
// l.setBackgroundResource(R.drawable.partyhome);
// String bgicon="drawable/partyhome";
// int ID =getResources().getIdentifier(bgicon,null,getPackageName());
// Drawable bgimage = getResources().getDrawable(ID);
// l.setBackgroundDrawable(bgimage);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// get selected items
if (position != 0) {
String selectedValue = Logos[position];
String name = Parties[position];
Bundle basket = new Bundle();
basket.putString("party", selectedValue);
basket.putString("title", name);
basket.putString("index", Integer.toString(position));
Intent a = new Intent(Party.this, PartyNews.class);
a.putExtras(basket);
// Toast.makeText(this, selectedValue, Toast.LENGTH_SHORT).show();
startActivity(a);
}
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
this.finish();
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
if(count!=0)
overridePendingTransition(R.anim.slideright, R.anim.slideright2);
count++;
super.onResume();
}
} | yashasvigirdhar/Android-Practice-for-Beginners | Home/src/com/example/electionkhabar/Party.java | 714 | //if (act.equalsIgnoreCase("home")) { | line_comment | en | true |
206709_0 | /*
* Copyright 2015-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.
*
* This is auto-generated file. Do not edit.
*/
package org.schema;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* The publication format of the book.
*/
public enum BookFormatType {
Hardcover("http://schema.org/Hardcover"), EBook("http://schema.org/EBook"), Paperback("http://schema.org/Paperback"), AudiobookFormat("http://schema.org/AudiobookFormat");
BookFormatType(String value) {
myValue = value;
}
@JsonValue
public String getValue() { return myValue; }
private String myValue;
}
| kropp/jsonld-metadata | src/main/java/org/schema/BookFormatType.java | 301 | /*
* Copyright 2015-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.
*
* This is auto-generated file. Do not edit.
*/ | block_comment | en | true |
206755_0 | /**
* This file is part of General Entity Annotator Benchmark.
*
* General Entity Annotator Benchmark is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* General Entity Annotator Benchmark is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with General Entity Annotator Benchmark. If not, see <http://www.gnu.org/licenses/>.
*/
package org.aksw.gerbil.datatypes.marking;
import org.aksw.gerbil.transfer.nif.Span;
public interface ClassifiedSpanMeaning extends Span, ClassifiedMeaning {
}
| dice-group/gerbil | src/main/java/org/aksw/gerbil/datatypes/marking/ClassifiedSpanMeaning.java | 236 | /**
* This file is part of General Entity Annotator Benchmark.
*
* General Entity Annotator Benchmark is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* General Entity Annotator Benchmark is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with General Entity Annotator Benchmark. If not, see <http://www.gnu.org/licenses/>.
*/ | block_comment | en | true |
206772_0 | package com.classifieds;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "Classifieds";
}
}
| eliemugenzi/classifieds-app | android/app/src/main/java/com/classifieds/MainActivity.java | 81 | /**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/ | block_comment | en | true |
206778_1 | /*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.modules;
import com.concursive.commons.text.StringUtils;
import com.concursive.connect.Constants;
import com.concursive.connect.web.modules.blog.dao.BlogPost;
import com.concursive.connect.web.modules.blog.dao.BlogPostComment;
import com.concursive.connect.web.modules.calendar.dao.Meeting;
import com.concursive.connect.web.modules.classifieds.dao.Classified;
import com.concursive.connect.web.modules.common.social.comments.dao.Comment;
import com.concursive.connect.web.modules.discussion.dao.Reply;
import com.concursive.connect.web.modules.discussion.dao.Topic;
import com.concursive.connect.web.modules.documents.dao.FileItem;
import com.concursive.connect.web.modules.promotions.dao.Ad;
import com.concursive.connect.web.modules.reviews.dao.ProjectRating;
import com.concursive.connect.web.modules.wiki.dao.Wiki;
import com.concursive.connect.web.modules.wiki.dao.WikiComment;
import com.concursive.connect.web.modules.webcast.dao.Webcast;
import com.concursive.connect.web.modules.profile.dao.Project;
/**
* Utilties for working with modules
*
* @author matt rajkowski
* @created February 27, 2009
*/
public class ModuleUtils {
// Module Names
public static final String MODULENAME_PROFILE = "profile";
public static final String MODULENAME_PROFILE_IMAGE = "profileimage";
public static final String MODULENAME_REVIEWS = "reviews";
public static final String MODULENAME_BLOG = "blog";
public static final String MODULENAME_NEWS = "news"; //another alias for blogs
public static final String MODULENAME_BLOG_POST = "post";
public static final String MODULENAME_BLOG_COMMENT = "blogcomment";
public static final String MODULENAME_CALENDAR = "calendar";
public static final String MODULENAME_CALENDAR_EVENT = "calendarevent";
public static final String MODULENAME_WIKI = "wiki";
public static final String MODULENAME_WIKI_COMMENT = "wikicomment";
public static final String MODULENAME_DISCUSSION_TOPIC = "topic";
public static final String MODULENAME_DISCUSSION_REPLY = "reply";
public static final String MODULENAME_PROMOTIONS = "promotions";
public static final String MODULENAME_ADS = "ads"; //another alias for promotions
public static final String MODULENAME_CLASSIFIEDS = "classifieds";
public static final String MODULENAME_LISTS = "lists";
public static final String MODULENAME_TICKETS = "tickets";
public static final String MODULENAME_BADGES = "badges";
public static final String MODULENAME_MEMBERS = "members";
public static final String MODULENAME_INBOX = "inbox";
public static final String MODULENAME_DOCUMENTS = "documents";
public static final String MODULENAME_WEBCAST = "webcast";
public static String getTableFromModuleName(String moduleName) {
if (!StringUtils.hasText(moduleName)) {
return null;
} else if (MODULENAME_REVIEWS.equals(moduleName)) {
return ProjectRating.TABLE;
} else if (MODULENAME_ADS.equals(moduleName) || MODULENAME_PROMOTIONS.equals(moduleName)) {
return Ad.TABLE;
} else if (MODULENAME_CLASSIFIEDS.equals(moduleName)) {
return Classified.TABLE;
} else if (MODULENAME_WIKI.equals(moduleName)) {
return Wiki.TABLE;
} else if (MODULENAME_DISCUSSION_TOPIC.equals(moduleName)) {
return Topic.TABLE;
} else if (MODULENAME_NEWS.equals(moduleName) || MODULENAME_BLOG.equals(moduleName) || MODULENAME_BLOG_POST.equals(moduleName)) {
return BlogPost.TABLE;
} else if (MODULENAME_WIKI_COMMENT.equals(moduleName)) {
return WikiComment.TABLE;
} else if (MODULENAME_BLOG_COMMENT.equals(moduleName)) {
return BlogPostComment.TABLE;
} else if (MODULENAME_DOCUMENTS.equals(moduleName)) {
return FileItem.TABLE;
} else if (MODULENAME_CALENDAR_EVENT.equals(moduleName) || MODULENAME_CALENDAR.equals(moduleName)) {
return Meeting.TABLE;
} else if (MODULENAME_PROFILE_IMAGE.equals(moduleName)) {
return FileItem.TABLE;
} else if (MODULENAME_DISCUSSION_REPLY.equals(moduleName)) {
return Reply.TABLE;
} else if (MODULENAME_WEBCAST.equals(moduleName)) {
return Webcast.TABLE;
} else if (MODULENAME_PROFILE.equals(moduleName)) {
return Project.TABLE;
}
return null;
}
public static String getPrimaryKeyFromModuleName(String moduleName) {
if (!StringUtils.hasText(moduleName)) {
return null;
} else if (MODULENAME_REVIEWS.equals(moduleName)) {
return ProjectRating.PRIMARY_KEY;
} else if (MODULENAME_ADS.equals(moduleName) || MODULENAME_PROMOTIONS.equals(moduleName)) {
return Ad.PRIMARY_KEY;
} else if (MODULENAME_CLASSIFIEDS.equals(moduleName)) {
return Classified.PRIMARY_KEY;
} else if (MODULENAME_WIKI.equals(moduleName)) {
return Wiki.PRIMARY_KEY;
} else if (MODULENAME_DISCUSSION_TOPIC.equals(moduleName)) {
return Topic.PRIMARY_KEY;
} else if (MODULENAME_NEWS.equals(moduleName) || MODULENAME_BLOG.equals(moduleName) || MODULENAME_BLOG_POST.equals(moduleName)) {
return BlogPost.PRIMARY_KEY;
} else if (MODULENAME_WIKI_COMMENT.equals(moduleName)) {
return Comment.PRIMARY_KEY;
} else if (MODULENAME_BLOG_COMMENT.equals(moduleName)) {
return Comment.PRIMARY_KEY;
} else if (MODULENAME_DOCUMENTS.equals(moduleName)) {
return FileItem.PRIMARY_KEY;
} else if (MODULENAME_CALENDAR_EVENT.equals(moduleName) || MODULENAME_CALENDAR.equals(moduleName)) {
return Meeting.PRIMARY_KEY;
} else if (MODULENAME_PROFILE_IMAGE.equals(moduleName)) {
return FileItem.PRIMARY_KEY;
} else if (MODULENAME_DISCUSSION_REPLY.equals(moduleName)) {
return Reply.PRIMARY_KEY;
} else if (MODULENAME_WEBCAST.equals(moduleName)) {
return Webcast.PRIMARY_KEY;
} else if (MODULENAME_PROFILE.equals(moduleName)) {
return Project.PRIMARY_KEY;
}
return null;
}
public static int getLinkModuleIdFromModuleName(String moduleName) {
int linkModuleId = -1;
if (MODULENAME_CLASSIFIEDS.equals(moduleName)) {
linkModuleId = Constants.PROJECT_CLASSIFIEDS_FILES;
} else if (MODULENAME_BLOG.equals(moduleName) || MODULENAME_NEWS.equals(moduleName) || MODULENAME_BLOG_POST.equals(moduleName)) {
linkModuleId = Constants.PROJECT_BLOG_FILES;
} else if (MODULENAME_PROMOTIONS.equals(moduleName)) {
linkModuleId = Constants.PROJECT_AD_FILES;
} else if (MODULENAME_PROFILE.equals(moduleName)) {
linkModuleId = Constants.PROFILE_LINK;
} else if (MODULENAME_INBOX.equals(moduleName)) {
linkModuleId = Constants.PROJECT_MESSAGES_FILES;
} else if (MODULENAME_WIKI.equals(moduleName)) {
linkModuleId = Constants.PROJECT_WIKI_FILES;
} else if (MODULENAME_BADGES.equals(moduleName)) {
linkModuleId = Constants.BADGE_FILES;
} else if (MODULENAME_TICKETS.equals(moduleName)) {
linkModuleId = Constants.PROJECT_TICKET_FILES;
} else if (MODULENAME_REVIEWS.equals(moduleName)) {
linkModuleId = Constants.PROJECT_REVIEW_FILES;
} else if (MODULENAME_DISCUSSION_TOPIC.equals(moduleName)) {
linkModuleId = Constants.DISCUSSION_FILES_TOPIC;
} else if (MODULENAME_WIKI_COMMENT.equals(moduleName)) {
linkModuleId = Constants.PROJECT_WIKI_COMMENT_FILES;
} else if (MODULENAME_BLOG_COMMENT.equals(moduleName)) {
linkModuleId = Constants.BLOG_POST_COMMENT_FILES;
} else if (MODULENAME_DOCUMENTS.equals(moduleName)) {
linkModuleId = Constants.PROJECTS_FILES;
} else if (MODULENAME_CALENDAR_EVENT.equals(moduleName) || MODULENAME_CALENDAR.equals(moduleName)) {
linkModuleId = Constants.PROJECTS_CALENDAR_EVENT_FILES;
} else if (MODULENAME_PROFILE_IMAGE.equals(moduleName)) {
linkModuleId = Constants.PROJECT_IMAGE_FILES;
} else if (MODULENAME_DISCUSSION_REPLY.equals(moduleName)) {
linkModuleId = Constants.DISCUSSION_FILES_REPLY;
} else if (MODULENAME_WEBCAST.equals(moduleName)) {
linkModuleId = Constants.PROJECT_WEBCAST_FILES;
}
return linkModuleId;
}
/**
* Return the label for the module (an promotion, classified or blog)
* TODO: may be there is a better way to do this as this information is already in project-portal-config.xml. Also this is configurable in the settings
*
* @param linkModuleId
* @return
*/
public static String getItemLabel(int linkModuleId) {
String itemLabel = null;
if (linkModuleId != -1) {
if (linkModuleId == Constants.PROJECT_CLASSIFIEDS_FILES) {
itemLabel = "Classified Ad";
} else if (linkModuleId == Constants.PROJECT_BLOG_FILES) {
itemLabel = "Blog Post";
} else if (linkModuleId == Constants.PROJECT_AD_FILES) {
itemLabel = "Promotion";
} else if (linkModuleId == Constants.PROJECT_REVIEW_FILES) {
itemLabel = "Review";
} else if (linkModuleId == Constants.PROJECT_WIKI_FILES) {
itemLabel = "Wiki";
} else if (linkModuleId == Constants.DISCUSSION_FILES_TOPIC) {
itemLabel = "Topic";
} else if (linkModuleId == Constants.PROJECT_WIKI_COMMENT_FILES) {
itemLabel = "Wiki Comment";
} else if (linkModuleId == Constants.BLOG_POST_COMMENT_FILES) {
itemLabel = "Blog Comment";
} else if (linkModuleId == Constants.PROJECTS_FILES) {
itemLabel = "Document";
} else if (linkModuleId == Constants.PROJECTS_CALENDAR_EVENT_FILES) {
itemLabel = "Event";
} else if (linkModuleId == Constants.PROJECT_IMAGE_FILES) {
itemLabel = "Profile Images";
} else if (linkModuleId == Constants.PROJECT_MESSAGES_FILES) {
itemLabel = "Message";
} else if (linkModuleId == Constants.PROJECT_WEBCAST_FILES) {
itemLabel = "Webcast";
} else if (linkModuleId == Constants.PROFILE_LINK) {
itemLabel = "Profile";
}
}
return itemLabel;
}
}
| yukoff/concourse-connect | src/main/java/com/concursive/connect/web/modules/ModuleUtils.java | 3,256 | /**
* Utilties for working with modules
*
* @author matt rajkowski
* @created February 27, 2009
*/ | block_comment | en | true |
207231_3 | import javax.swing.JLabel;
/**
* A simple bank account. NSFCA (not safe for concurrent access).
*
* @author original unknown
* Updated for Java Swing, Jim Teresco, The College of Saint Rose, Fall
* 2013
* @version Spring 2022
*/
public class Account {
private int balance;
private JLabel display; // label on screen for balance
/**
* Construct a new account with the given starting balance, which
* will be displayed on the given label.
*
* @param start initial account balance
* @param aDisplay the label where the balance will be displayed
*/
public Account(int start, JLabel aDisplay) {
balance = start;
display = aDisplay;
display.setText("" + balance);
}
/**
* Get the current balance.
*
* @return the current balance
*/
public int getBalance() {
return balance;
}
/**
* Set the balance to a new value and update the label.
*
* @param newBalance the new balance
*/
public void setBalance(int newBalance) {
balance = newBalance;
display.setText("" + newBalance);
}
}
| SienaCSISAdvancedProgramming/ATMConcurrency | Danger1/Account.java | 277 | /**
* Get the current balance.
*
* @return the current balance
*/ | block_comment | en | false |
207351_0 | package Leetcode;
/**
* Created by rbhatnagar2 on 3/5/17.
*/
public class Q514_Freedom_Trail {
}
| chubbysingh/coding | src/Leetcode/Q514_Freedom_Trail.java | 45 | /**
* Created by rbhatnagar2 on 3/5/17.
*/ | block_comment | en | true |
207863_0 | package common;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* This class represents a subject's post.
* It has the following attributes :
*/
public class Post extends DocUnit{
String title, text;
String date;
Date postDate;
String info;
String chunk;
String author;
ArrayList<String> drugs;
ArrayList<String> meds;
ArrayList<String> diseases;
public Post(String id) {
super(id);
this.text = "";
this.title = "";
this.date = "";
this.info = "";
this.chunk = "";
this.author = "";
}
public String getAuthor(){ return author; }
public void setAuthor(String author) { this.author = author; }
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void setText(String text){
this.text = text;
}
public String getText(){
return text;
}
@Override
public String getContent() {
return title + " " + text;
}
public String getChunk() {
return chunk;
}
public void setChunk(String chunk) {
this.chunk = chunk;
}
public Date getPostDate() {
return postDate;
}
public void setPostDate(String date){
SimpleDateFormat sdf;
try {
if(date.contains("T")) {
sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
this.postDate = sdf.parse(date);
}
else
sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
this.postDate = sdf.parse(date);
}catch (ParseException e) {
e.printStackTrace();
}
setDate(postDate.toString());
}
public ArrayList<String> getDrugs() {
return drugs;
}
public void setDrugs(ArrayList<String> drugs) {
this.drugs = drugs;
}
public ArrayList<String> getMeds() {
return meds;
}
public void setMeds(ArrayList<String> meds) {
this.meds = meds;
}
public ArrayList<String> getDiseases() {
return diseases;
}
public void setDiseases(ArrayList<String> diseases) {
this.diseases = diseases;
}
@Override
public String toString(){
return "Post id: " + getId() + "\n" +
"Label: " + getLabel().value() + "\n" +
"Author: " + getAuthor() + "\n" +
"Title: " + getTitle() + "\n" +
"Date: " + getDate()+ "\n\n";
}
} | BigMiners/eRisk2017 | src/main/java/common/Post.java | 753 | /**
* This class represents a subject's post.
* It has the following attributes :
*/ | block_comment | en | true |
208896_7 | package simciv;
/**
* Well... originally, this was for debug :D
* This is a set of flags that make things happen quicker.
* @author Marc
*
*/
public class Cheats
{
/** The cheat codes below will be active only if enabled is true. **/
private static boolean enabled = false;
/** Increases house construction speed **/
private static boolean fastCitizenProduction = false;
/** Increases farmland crops growing speed **/
private static boolean fastFarmlandGrow = true;
/** Money will not drop by being used **/
private static boolean infiniteMoney = false;
/** Allows erasing un-eraseable builds (like fires) **/
private static boolean superEraser = true;
/** The erase tool will also set builds on fire **/
private static boolean burnOnErase = false;
/**
* Method called when cheats are requested from the ingame command prompt
* (Not implemented yet).
* @param cmd : cheat command
*/
public static void onCommand(String cmd)
{
if(enabled)
{
if(cmd == "idontcheat" || cmd == "icheat")
enabled = false;
else if(cmd == "ogm")
fastFarmlandGrow = !fastFarmlandGrow;
else if(cmd == "reproduce")
fastCitizenProduction = !fastCitizenProduction;
else if(cmd == "eldorado")
infiniteMoney = !infiniteMoney;
else if(cmd == "bulldozer")
superEraser = !superEraser;
else if(cmd == "charmander")
burnOnErase = !burnOnErase;
}
else if(cmd == "icheat")
{
enabled = true;
}
}
public static boolean isEnabled() {
return enabled;
}
public static boolean isFastCitizenProduction() {
return enabled && fastCitizenProduction;
}
public static boolean isFastFarmlandGrow() {
return enabled && fastFarmlandGrow;
}
public static boolean isInfiniteMoney() {
return enabled && infiniteMoney;
}
public static boolean isSuperEraser() {
return enabled && superEraser;
}
public static boolean isBurnOnErase() {
return enabled && burnOnErase;
}
}
| Zylann/Simciv | src/simciv/Cheats.java | 578 | /**
* Method called when cheats are requested from the ingame command prompt
* (Not implemented yet).
* @param cmd : cheat command
*/ | block_comment | en | true |
209533_1 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package my.lawyerapp;
public final class R {
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f040000;
public static final int activity_vertical_margin=0x7f040001;
}
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int ClientList=0x7f080009;
public static final int LawyernameText=0x7f080029;
public static final int Mobilenumbertext=0x7f080028;
public static final int RelativeLayout1=0x7f080026;
public static final int accountsettingbutton=0x7f080003;
public static final int action_settings=0x7f08002e;
public static final int addnewClient=0x7f08000b;
public static final int addnewhearings=0x7f08000f;
public static final int cancel=0x7f08000a;
public static final int cancelbutton=0x7f080008;
public static final int cancelbutton2=0x7f080024;
public static final int casedetails=0x7f08001d;
public static final int casedetailtext=0x7f080016;
public static final int caseno=0x7f08001e;
public static final int casenotext=0x7f080017;
public static final int clientidtext=0x7f08001b;
public static final int clientname=0x7f080004;
public static final int clientnametext=0x7f080020;
public static final int datetext=0x7f080015;
public static final int deletehearing=0x7f080023;
public static final int email=0x7f080005;
public static final int firstbutton=0x7f080012;
public static final int gobacktomainmenu=0x7f080010;
public static final int hearingdate=0x7f08001c;
public static final int hearingidtext=0x7f08001a;
public static final int itemclientname=0x7f080000;
public static final int lastbutton=0x7f080013;
public static final int manageclientbutton=0x7f080001;
public static final int managehearingbutton=0x7f080002;
public static final int mylist1=0x7f08001f;
public static final int mylist2=0x7f080018;
public static final int nextbutton=0x7f080014;
public static final int noradio=0x7f08002b;
public static final int phone=0x7f080006;
public static final int previousbutton=0x7f080011;
public static final int saveSMS=0x7f08002c;
public static final int savebutton=0x7f080007;
public static final int textView1=0x7f080027;
public static final int textView2=0x7f08002a;
public static final int updatecasedate=0x7f080021;
public static final int updatecasedetails=0x7f080022;
public static final int updatecaseno=0x7f080025;
public static final int updateemail=0x7f08000d;
public static final int updatehearing=0x7f080019;
public static final int updatename=0x7f08000c;
public static final int updatephone=0x7f08000e;
public static final int yesradio=0x7f08002d;
}
public static final class layout {
public static final int activity_client_item=0x7f030000;
public static final int activity_screen1=0x7f030001;
public static final int activity_screen2=0x7f030002;
public static final int activity_screen2_1=0x7f030003;
public static final int activity_screen2_2=0x7f030004;
public static final int activity_screen3=0x7f030005;
public static final int activity_screen4=0x7f030006;
public static final int activity_screen4_1=0x7f030007;
public static final int activity_screen5=0x7f030008;
}
public static final class menu {
public static final int client_item=0x7f070000;
public static final int screen1=0x7f070001;
public static final int screen2=0x7f070002;
public static final int screen2_1=0x7f070003;
public static final int screen2_2=0x7f070004;
public static final int screen3=0x7f070005;
public static final int screen4=0x7f070006;
public static final int screen4_1=0x7f070007;
public static final int screen5=0x7f070008;
}
public static final class string {
public static final int accountsettings=0x7f050005;
public static final int action_settings=0x7f050001;
public static final int add=0x7f050007;
public static final int app_name=0x7f050000;
public static final int cancel=0x7f050008;
public static final int casedetails=0x7f050015;
public static final int caseno=0x7f050014;
public static final int clientname=0x7f05000c;
public static final int delete=0x7f050012;
public static final int edit=0x7f05001b;
public static final int email=0x7f05000d;
public static final int first=0x7f050018;
public static final int hello_world=0x7f050002;
public static final int last=0x7f050017;
public static final int lawyername=0x7f05001f;
public static final int lawyerpersonaldetails=0x7f05001d;
public static final int manageclients=0x7f050003;
public static final int managehearings=0x7f050004;
public static final int mobilenumber=0x7f050020;
public static final int next=0x7f050019;
public static final int nexthearingdate=0x7f050016;
public static final int no=0x7f050022;
public static final int phone=0x7f05000e;
public static final int previous=0x7f05001a;
public static final int save=0x7f05000f;
public static final int smsalert=0x7f05001e;
public static final int title_activity_client_item=0x7f050010;
public static final int title_activity_screen2=0x7f050009;
public static final int title_activity_screen2_1=0x7f050006;
public static final int title_activity_screen2_2=0x7f050011;
public static final int title_activity_screen3=0x7f05000a;
public static final int title_activity_screen4=0x7f050013;
public static final int title_activity_screen4_1=0x7f05001c;
public static final int title_activity_screen5=0x7f05000b;
public static final int yes=0x7f050021;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f060000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f060001;
}
}
| abhi0901/LawyerAndroidApp | source/gen/my/lawyerapp/R.java | 2,521 | /** Default screen margins, per the Android Design guidelines.
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/ | block_comment | en | true |
209732_1 | import java.util.Scanner;
public class AuctionSystemLauncher {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Auction System");
System.out.print("Admin Username: ");
String username = scanner.nextLine();
System.out.print("Password: ");
String password = scanner.nextLine();
// Simple check for admin login (In real-world scenarios, validate against secure data source)
if ("admin".equals(username) && "adminpass".equals(password)) {
System.out.println("Admin login successful. Starting server...");
AdminServer.startServer(); // AdminServer is a modified version of the server class which includes a static method to start the server.
} else {
System.out.println("Invalid admin credentials.");
}
scanner.close();
}
}
| rambo-san/Auction_System | AuctionSystemLauncher.java | 198 | // AdminServer is a modified version of the server class which includes a static method to start the server. | line_comment | en | true |
209921_0 | import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import com.opencsv.exceptions.CsvException;
public class Cell {
Bucket firstBucket;
Object minFirstColumn;
Object minSecondColumn;
public Cell(int x, int y, String path){
firstBucket = new Bucket(path + "/" + x + "_" + y + ".csv");
}
public ArrayList<BucketEntry> getEntries(String clusteringKeyType){
ArrayList<BucketEntry> entries = new ArrayList<>();
if (!new File(firstBucket.path).exists()) return entries;
CSVReader reader = null;
try{
reader = new CSVReader(new FileReader(firstBucket.path));
List<String[]> lines = reader.readAll();
if (clusteringKeyType.equals("java.lang.Integer"))
for (String[] strings : lines)
entries.add(new BucketEntry(Integer.parseInt(strings[0]), Integer.parseInt(strings[1])));
else if(clusteringKeyType.equals("java.lang.String"))
for (String[] strings : lines)
entries.add(new BucketEntry(strings[0], Integer.parseInt(strings[1])));
else if(clusteringKeyType.equals("java.lang.Double"))
for (String[] strings : lines)
entries.add(new BucketEntry(Double.parseDouble(strings[0]), Integer.parseInt(strings[1])));
else if(clusteringKeyType.equals("java.util.Date")){
for (String[] strings : lines){
SimpleDateFormat formatter = new SimpleDateFormat("DD.MM.YYYY");
Date date = null;
try {
date = formatter.parse(strings[0]);
} catch (ParseException e) {
e.printStackTrace();
}
entries.add(new BucketEntry(date, Integer.parseInt(strings[1])));
}
}
} catch(IOException | CsvException e){
e.printStackTrace();
}
return entries;
}
public void insertRow(Object key, int page) {
CSVReader reader = null;
try{
if (!new File(firstBucket.path).exists())
new File(firstBucket.path).createNewFile();
reader = new CSVReader(new FileReader(firstBucket.path));
List<String[]> lines = reader.readAll();
// for (int i = 0; i < lines.size(); i++) {
// if (lines.get(i)[1].equals("" + page)){
// lines.add(i, new String[]{key.toString(), "" + page});
// CSVWriter writer = new CSVWriter(new FileWriter(firstBucket.path));
// writer.writeAll(lines);
// break;
// }
// }
lines.add(new String[]{key.toString(), "" + page});
CSVWriter writer = new CSVWriter(new FileWriter(firstBucket.path));
writer.writeAll(lines);
writer.close();
} catch(IOException | CsvException e){
e.printStackTrace();
}
}
public void deleteRow(Object key) {
CSVReader reader = null;
CSVWriter writer = null;
try{
reader = new CSVReader(new FileReader(firstBucket.path));
writer = new CSVWriter(new FileWriter(firstBucket.path));
List<String[]> lines = reader.readAll();
for (String[] strings : lines) {
if (strings[0].equals("" + key.toString())){
lines.remove(strings);
break;
}
}
writer.writeAll(lines);
reader.close();
writer.close();
if (lines.size() == 0)
new File(firstBucket.path).delete();
} catch(IOException | CsvException e){
e.printStackTrace();
}
}
public void updateRow(Object key, int page){
deleteRow(key);
insertRow(key, page);
}
}
| omarafekry/DatabaseEngine | Cell.java | 942 | // for (int i = 0; i < lines.size(); i++) { | line_comment | en | true |
209979_8 | import java.io.FileNotFoundException;
import java.lang.NullPointerException;
import java.lang.IllegalArgumentException;
import javax.swing.JOptionPane;
import java.util.*;
/**
* This class controls the aspects of the game by requesting info from a User,
* updating the game, and then passing the updated game back to the User
*
* Variables will be declared as protected after testing is complete
*
* @author (Jesse Nelson)
* @version (October 4, 2012 Windows 7(x64) : Java 1.7)
*/
public class Game {
/**
* Minimum number of guesses user is allowed to have
*/
static final int MIN_NUMBER_GUESSES = 1;
/**
* Maximum number of guesses user is allowed to have
*/
static final int MAX_NUMBER_GUESSES = 26;
Dictionary d;
int numGuesses;
String secretWord;
List<String> candidates;
SortedSet<Character> guesses;
char [] clue;
protected Random rand;
/**
* Initialize instance variables and get first guess from user
*
* Instance variables will be made private once testing is complete
*
* @throws FileNotFoundException if the Dictionary file is not located
*/
public Game(HangMan interfaceType) {
try {
this.d = interfaceType.dictionarySetUp();
this.secretWord = this.d.randWord(interfaceType.wordLength());
this.numGuesses = interfaceType.numberOfGuesses();
this.guesses = new TreeSet<Character>();
this.clue = new char [this.secretWord.length()];
for(int i = 0; i < clue.length; i++) {
this.clue[i] = '_';
}
updateGame(interfaceType.showGame("Welcome to HangMan!", this), interfaceType);
} catch(FileNotFoundException e){
System.out.println("There was an error loading the default and/or selected Dictionary");
}
/* Should never happen!*/
catch(NullPointerException e ){
JOptionPane.showMessageDialog(null, "There is critical information missing from the game.\n"
+ "The game is restarting.", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
public Game(){
}
/**
* Constructer to used for testing
*/
public Game(int guessesAllowed, int wordLength, String word) {
try {
this.d = new Dictionary();
if(word == null) {
this.secretWord = d.randWord(wordLength);
} else secretWord = word;
this.numGuesses = guessesAllowed;
this.guesses = new TreeSet<Character>();
this.clue = new char [this.secretWord.length()];
for(int i = 0; i < clue.length; i++) {
clue[i] = '_';
}
} catch(FileNotFoundException e) {
System.out.println("There was an error loading the default and/or selected Dictionary");
}
}
public Game(Dictionary dictionary, HangMan interfaceType) { // Used by EvilHangMan
try {
this.rand = new Random();
this.d = dictionary;
this.candidates = d.allWordsOfLength(interfaceType.wordLength());
this.numGuesses = interfaceType.numberOfGuesses();
this.secretWord = candidates.get(rand.nextInt(candidates.size()));
this.guesses = new TreeSet<Character>();
this.clue = new char [secretWord.length()];
for(int i = 0; i < clue.length; i++) {
this.clue[i] = '_';
}
/* Should never happen!*/
} catch(NullPointerException e ){
JOptionPane.showMessageDialog(null, "There is critical information missing from the game.\n"
+ "The game is restarting.", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Checks if current guess is part of the secretWord and updates the game accordingly
*
* @param Current guess
*/
public void updateGame(char c, HangMan interfaceType) {
if(checkGuess(c)) {
this.rightGuess(c, interfaceType);
}
else {
this.wrongGuess(c, interfaceType);
}
}
/**
* Checks to see if the User's guess is part of the secret word
*
* @param Current guess
*
* @return Returns true if guess is correct, else false
*/
public boolean checkGuess(char c) {
for(int i = 0; i < this.secretWord.length(); i++) {
if(this.secretWord.charAt(i) == c) return true;
}
return false;
}
/**
* Checks to see if the game is over
*
* @returns true if the secrect word has been guessed
* or the max number of guesses has been reached
* else returns false
*/
public boolean gameOver() {
return this.numGuesses == 0 || Arrays.equals(this.secretWord.toCharArray(), this.clue);
}
/**
* Update the string of wrongLetters, calls decreaseNumberOfGuesses, and checks
* to see if the Game is over.
*
* If the game is lost, GameLost() is called
*
* Shows the game to the user
*
* @param Current guess
*/
public void wrongGuess(char c, HangMan interfaceType) throws IllegalArgumentException {
this.decreaseGuessesLeft(c);
this.guesses.add(c);
if(gameOver()) {
interfaceType.gameLost(secretWord, this);
}
else {
this.updateGame(interfaceType.showGame(c + " Is incorrect", this), interfaceType);
}
}
/**
* Update the clue with the correct guess and check to see if game is over
*
* Shows the game to the user
*
* @param Current guess
*/
public void rightGuess(char c, HangMan interfaceType) {
this.guesses.add(c);
this.updateClue(c);
if(gameOver()) {
interfaceType.gameWon(this);
}
else {
this.updateGame(interfaceType.showGame("You are getting closer! " + c + " Is correct!", this), interfaceType);
}
}
/**
* Decreases the number of guesses unless the guess is a duplicate
*
* @args The current guess
*/
public void decreaseGuessesLeft(char c) {
if (this.guesses.contains(c) || c == '`') {
this.numGuesses = this.numGuesses;
} else {
this.numGuesses--;
}
}
/**
* Updates clue with newly guessed letters when they are correct
*
* @args Current guess
*/
public void updateClue(char c) {
for(int i = 0; i < this.secretWord.length(); i++) {
if(this.secretWord.charAt(i) == c) {
this.clue[i] = c;
}
}
}
/**
* Displays the number of guesses left, the guessed letters, and the clue
*/
public String toString() {
return "Guesses Left: " + this.numGuesses +
"\nGuessed Letters: " + this.guesses +
"\nClue: " + this.formatClue();
}
/**
* Formats the clue to be easily read by the user
*/
private String formatClue() {
String formattedClue = "";
for(int i = 0; i < clue.length; i++) {
formattedClue += clue[i] + " " ;
}
return formattedClue;
}
}
| jnels124/HangMan | Game.java | 1,830 | /**
* Checks if current guess is part of the secretWord and updates the game accordingly
*
* @param Current guess
*/ | block_comment | en | true |
210695_10 | /*
* Copyright (C) 2012 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.internal.telephony;
import static com.android.internal.telephony.RILConstants.*;
import android.content.Context;
import android.os.Parcel;
import android.os.AsyncResult;
import android.util.Log;
import com.android.internal.telephony.RILConstants;
/**
* Custom RIL to handle unique behavior of Samsung's MSM7X30 devices radio
*
* {@hide}
*/
public class SamsungMSMRIL extends RIL implements CommandsInterface {
public SamsungMSMRIL(Context context, int networkMode, int cdmaSubscription) {
super(context, networkMode, cdmaSubscription);
}
@Override
protected void
processUnsolicited (Parcel p) {
Object ret;
int dataPosition = p.dataPosition(); // save off position within the Parcel
int response = p.readInt();
switch(response) {
case RIL_UNSOL_NITZ_TIME_RECEIVED:
handleNitzTimeReceived(p);
return;
default:
// Rewind the Parcel
p.setDataPosition(dataPosition);
// Forward responses that we are not overriding to the super class
super.processUnsolicited(p);
return;
}
}
protected void
handleNitzTimeReceived(Parcel p) {
String nitz = (String)responseString(p);
if (RILJ_LOGD) unsljLogRet(RIL_UNSOL_NITZ_TIME_RECEIVED, nitz);
// has bonus long containing milliseconds since boot that the NITZ
// time was received
long nitzReceiveTime = p.readLong();
Object[] result = new Object[2];
String fixedNitz = nitz;
String[] nitzParts = nitz.split(",");
if (nitzParts.length == 4) {
// 0=date, 1=time+zone, 2=dst, 3=garbage that confuses GsmServiceStateTracker (so remove it)
fixedNitz = nitzParts[0]+","+nitzParts[1]+","+nitzParts[2]+",";
}
result[0] = fixedNitz;
result[1] = Long.valueOf(nitzReceiveTime);
if (mNITZTimeRegistrant != null) {
mNITZTimeRegistrant
.notifyRegistrant(new AsyncResult (null, result, null));
} else {
// in case NITZ time registrant isnt registered yet
mLastNITZTimeInfo = result;
}
}
@Override
protected Object
responseSignalStrength(Parcel p) {
int numInts = 12;
int response[];
/* TODO: Add SignalStrength class to match RIL_SignalStrength */
response = new int[numInts];
for (int i = 0 ; i < 7 ; i++) {
response[i] = p.readInt();
}
// SamsungRIL is a v3 RIL, fill the rest with -1
for (int i = 7; i < numInts; i++) {
response[i] = -1;
}
response[0] = response[0] & 0xFF; // gsmDbm
return response;
}
}
| k2wl/framework_base_telephony | SamsungMSMRIL.java | 901 | // SamsungRIL is a v3 RIL, fill the rest with -1 | line_comment | en | true |
210708_0 | import java.util.*;
import java.lang.*;
import java.io.*;
import custom_utils.*;
class samsungtest {
public static Set<String> outputAttr;
public static String convertToGrammer(String st) {
Preprocess pre = new Preprocess();
DateTimePlaceholder ma = new DateTimePlaceholder();
PlaceholderMatch pm = new PlaceholderMatch();
Concept_parser concept_parser = new Concept_parser();
GrammarAnalyser grammarAnalyser = new GrammarAnalyser();
st = pre.rExtraChars(st);
st = pre.rExtraSpaces(st);
String st_orig = st;
ArrayList<String> stList = new ArrayList<>();
HashMap <String, HashMap<String, ArrayList<String>>> mmm= new HashMap <> ();
stList = concept_parser.generate_concept(st);
ArrayList<String> processed_string_list = new ArrayList<>();
ArrayList<String> processed_string_list_1= new ArrayList<>();
HashMap<String, ArrayList<String>> tagmap = new HashMap<>();
outputAttr = new HashSet<>();
for (String pt : stList) {
st = ma.find_dateTime(pt);
HashMap<String, Set<String>> datetimeMap = ma.map;
for (String each: datetimeMap.keySet()) {
for (String item : datetimeMap.get(each)) {
outputAttr.add(each+" : "+item);
}
}
st = pm.find_placeholder(st);
for(String each : pm.all_replacements.keySet()){
for(String item: pm.all_replacements.get(each)){
outputAttr.add(each+" : "+item);
}
}
OpenPhrase op = new OpenPhrase(st);
tagmap = op.tagmap;
mmm.put(pt, tagmap);
for (String each:tagmap.keySet() ) {
for (String item: tagmap.get(each)) {
outputAttr.add(each+" : "+item);
}
}
st = pre.rExtraSpaces(op.st);
processed_string_list.add(st);
processed_string_list_1.add(pt);
}
st = grammarAnalyser.findGrammer(processed_string_list, processed_string_list_1);
String s = grammarAnalyser.orig;
System.out.println(mmm.get(s));
System.out.println(s);
return st;
}
public static void main(String[] args) {
FileRead fileread = new FileRead();
try {
PrintWriter writer = new PrintWriter("./resources/Testing/output.txt", "UTF-8");
ArrayList<String> sentences = fileread.readFileAsLine(new File("./resources/Testing/input.txt"));
for (String line : sentences) {
if (line.subSequence(0, 4).toString().toLowerCase().equals("case")) {
System.out.println("w: "+line);
writer.println(line);
continue;
}
String result = convertToGrammer(line);
writer.println(result);
System.out.println("w: "+result);
// for (String each: outputAttr) {
// writer.println(each);
// System.out.println("w: "+each);
// }
System.out.println();
}
writer.close();
} catch (Exception e) {
System.out.println("Error reported" + e);
}
}
}
| ketankr9/hackathon-technex | samsungtest.java | 859 | // for (String each: outputAttr) { | line_comment | en | true |
211080_2 | import java.util.*;
/**
* Main World Class
*
* @author Ezekiel Elin
* @author Unknown Author
* @version 11/02/2016
*/
public class World {
private List<List<Cell>> board;
private int lightEnergy;
private int steps;
public World(int width, int height, int light) {
lightEnergy = light;
steps = 0;
board = new ArrayList<List<Cell>>();
for(int i = 0; i < width; i++) {
board.add(new ArrayList<Cell>());
for(int j = 0; j < height; j++) {
board.get(i).add(new Cell(this));
board.get(i).get(j).setLocation(new Point(i, j));
}
}
}
public int getLightEnergy() {
return lightEnergy;
}
public Cell get(int x, int y) {
return this.board.get(x).get(y);
}
public int getWidth() {
return this.board.size();
}
public int getHeight() {
return this.board.get(0).size();
}
public int getSteps() {
return this.steps;
}
/**
* Goes through each cell and runs the activities for each species
* Also adds a new element to the birth and death lists so they can be tracker for the turn
*/
public void turn() {
int curSteps = this.getSteps();
if(Species.getDeaths().size() == curSteps) {
Species.getDeaths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getDeaths().get(curSteps).add(0);
}
}
if(Species.getBirths().size() == curSteps) {
Species.getBirths().add(new ArrayList<Integer>());
for(int i = 0; i < Species.getSpecies().size(); i++) {
Species.getBirths().get(curSteps).add(0);
}
}
for(int i = 0; i < board.size(); i++) {
List<Cell> column = board.get(i);
for(int j = 0; j < column.size(); j++) {
Cell cell = column.get(j);
if(cell.getAnimal() != null) {
cell.getAnimal().activity();
}
if(cell.getPlant() != null) {
cell.getPlant().activity();
}
}
}
steps++;
}
/**
* Prints the board in an easy to view way
*/
public void print() {
for(int y = 0; y < this.getHeight(); y++) {
System.out.print("|");
for(int x = 0; x < this.getWidth(); x++) {
Cell cell = this.get(x, y);
String message = "";
if (cell.isMountain()) {
message += "MNT";
}
if (cell.flag) {
message += "!!!";
}
if(cell.getAnimal() != null) {
message += cell.getAnimal().getRepresentation();
}
if(message.length() > 0 && cell.getPlant() != null) {
message += "/";
}
if(cell.getPlant() != null) {
message += cell.getPlant().getRepresentation();
}
System.out.print(message + "\t|");
}
System.out.println();
System.out.println("-----------------------------------------------------------------------------------------------------");
}
}
/**
* Takes a species and generates random coordinates until it finds an empty cell for it
* @param Species s - the species that should be randomly added to the world
*/
public void randomAddToWorld(Species s) {
Random generator = new Random(Simulation.SEED);
boolean found = false;
int count = 0; //Prevents infinite loop in case more species are trying to be added than there are spaces for them
while(!found && count < 10000) {
count++;
int x = generator.nextInt(this.board.size());
int y = generator.nextInt(this.board.get(0).size());
Cell cell = this.board.get(x).get(y);
/* cannot use mountain spaces */
if (cell.isMountain()) {
continue;
}
if(s instanceof Animal) {
if(cell.getAnimal() == null) {
cell.setAnimal((Animal)s);
s.setCell(cell);
found = true;
}
} else if(s instanceof Plant) {
if(cell.getPlant() == null) {
cell.setPlant((Plant)s);
s.setCell(cell);
found = true;
}
}
}
}
}
| ezfe/Animal-Park-2 | World.java | 1,120 | /**
* Prints the board in an easy to view way
*/ | block_comment | en | false |
212062_0 | package com.creek.scrumpoker;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.widget.TableRow;
import android.widget.TextView;
/**
*
* @author Andrey Pereverzin
*
*/
public class Util {
static public TableRow createRow(Activity activity) {
TableRow row = new TableRow(activity);
row.setClickable(true);
return row;
}
static public TextView createCell(final Activity activity, final String text) {
TextView textView = new TextView(activity);
textView.setText(text);
textView.setBackgroundColor(Color.WHITE);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.CENTER);
textView.setClickable(true);
return textView;
}
static public TextView createRotatedCell(Activity activity, String text) {
RotatedTextView textView = new RotatedTextView(activity);
textView.setText(text);
textView.setBackgroundColor(Color.WHITE);
textView.setTextColor(Color.BLACK);
textView.setGravity(Gravity.CENTER);
textView.setTypeface(null, Typeface.BOLD);
return textView;
}
static class RotatedTextView extends TextView {
public RotatedTextView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(90);
super.onDraw(canvas);
canvas.restore();
}
}
}
| apereverzin/ScrumPoker | src/com/creek/scrumpoker/Util.java | 381 | /**
*
* @author Andrey Pereverzin
*
*/ | block_comment | en | true |
212450_22 | package assembler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import javax.swing.JOptionPane;
/**
* <pre>
* Class Name: Urban
* Description: main controller for the application.
*
* Version information:
* $RCSfile: Urban.java,v $
* $Revision: 1.3 $
* $Date: 2012/05/09 18:17:17 $
* </pre>
*
* @author Andrew
*
*/
public class Urban {
/**
* <pre>
* Procedure Name: getInput
* Description: gets urban assembly input.
*
* Specification reference code(s): N/A
* Calling Sequence: Both
*
* Error Conditions Tested: invalid IO references
* Error messages generated: java runtime exceptions
*
* Modification Log (who when and why):
* Michael Apr 17, 2012 adjusted to work with redesign, added documentation
*
* Coding standards met: Signed by Michael
* Testing standards met: Signed by Michael
* </pre>
*
* @since Apr 12, 2012
* @author Andrew
* @param gui
* is the swing GUI used for interaction
* @return returns the input file
*/
private static String getInput(MainView gui) {
// [input String local text of input source code]
// [fileIn FileReader local reader for input source file]
// [sb StringBuilder local string builder for input source file]
// [c int local integer local value of character used when reading
// source file]
// [ex IOException local exception thrown when there is an error opening
// input file]
String input;
try {
FileReader fileIn = new FileReader(gui.getInputFile());
StringBuilder sb = new StringBuilder();
int c;
while ((c = fileIn.read()) != -1) {
sb.append((char) c);
}
input = sb.toString();
fileIn.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(gui, "Error opening input file");
return "<<ERROR>>";
}
return input;
}
/**
* <pre>
* Procedure Name: outputIfPossible
* Description: Write the given byte array to a file, if the file is writable
*
* Specification reference code(s): N/A
* Calling Sequence: Pass 2
*
* Error Conditions Tested: None
* Error messages generated: N/A
*
* Modification Log (who when and why):
* Michael Apr 17, 2012 adjusted to work with redesign, added documentation
*
* Coding standards met: Signed by Michael
* Testing standards met: Signed by Michael
* </pre>
*
* @since May 9, 2012
* @author Andrew
* @param dir
* Directory to output to
* @param name
* Name of file, including extension, excluding directory
* @param bytes
* A series of bytes to write
*/
private static void outputIfPossible(File dir, String name,
ByteArrayOutputStream bytes) {
// [FileOutputStream fos Holds an array of bytes output by the
// assembler]
FileOutputStream fos = null;
// [File file reference to a file on disk]
File file;
if (dir != null) {
file = new File(dir, name);
if (file != null
&& (file.canWrite() || (!file.exists() && file
.getParentFile().canWrite()))) {
try {
fos = new FileOutputStream(file);
fos.write(bytes.toByteArray());
} catch (Exception e) {
try {
if (fos != null) {
fos.close();
}
} catch (Exception e2) {
}
}
}
}
}
/**
* <pre>
* Procedure Name: assemble
* Description: Runs the first pass of the assembly.
*
* Specification reference code(s): N/A
* Calling Sequence: Pass 1
*
* Error Conditions Tested: null reference, bad streams
* Error messages generated: N/A
*
* Modification Log (who when and why):
* Michael Apr 17, 2012 adjusted to work with redesign, added documentation
*
* Coding standards met: Signed by Michael
* Testing standards met: Signed by Michael
* </pre>
*
* @since Apr 12, 2012
* @author Andrew
* @param gui
* is the swing GUI for interactions
*/
private static void assemble(MainView gui) {
// [prog Program local abstract program created during the assembly
// process]
// [in Reader local string reader for input source code]
// [listingOut ByteArrayOutputStream output stream for listing table]
// [symTableOut ByteArrayOutputStream output stream for symbol table]
String input = getInput(gui);
String name = gui.getInputFile().getName();
if (name.lastIndexOf(".") >= 0) {
name = name.substring(0, name.lastIndexOf("."));
}
File output = gui.getOutputPath() != null
&& gui.getOutputPath().length() > 0 ? new File(
gui.getOutputPath()) : null;
gui.setInputTabText(input);
Reader in = new StringReader(input);
Program prog;
prog = Parser.runFirstPass(in);
if (!prog.runSecondPass()) {
// TODO: Fatal errors
}
// Print the output of the first pass - the intermediate listing file
// and the symbol table
ByteArrayOutputStream listingOut = new ByteArrayOutputStream();
ByteArrayOutputStream symTableOut = new ByteArrayOutputStream();
ByteArrayOutputStream objectOut = new ByteArrayOutputStream();
ByteArrayOutputStream reportOut = new ByteArrayOutputStream();
prog.printListing(listingOut);
prog.printSymbols(symTableOut);
prog.generateObjectFile(objectOut);
prog.printAssemblyReport(reportOut);
gui.setOutputTabText(new String(listingOut.toByteArray()));
outputIfPossible(output, name + ".tmp", listingOut);
gui.setSymbolTableTabText(new String(symTableOut.toByteArray()));
outputIfPossible(output, name + ".sym", symTableOut);
gui.setObjectFileTabText(new String(objectOut.toByteArray()));
outputIfPossible(output, name + ".obj", objectOut);
gui.setUsrReportTabText(new String(reportOut.toByteArray()));
outputIfPossible(output, name + ".report", reportOut);
}
/**
* <pre>
* Procedure Name: main
* Description: assembles, links, and loads input program.
*
* Specification reference code(s): N/A
* Calling Sequence: Both
*
* Error Conditions Tested: N/A
* Error messages generated: N/A
*
* Modification Log (who when and why):
* Michael Apr 17, 2012 updated to conform to documentation standards
*
* Coding standards met: Signed by Michael
* Testing standards met: Signed by Michael
* </pre>
*
* @since Apr 12, 2012
* @author Andrew
* @param args
* are unused command line arguments
*/
public static void main(String[] args) {
// [gui MainView local main swing view used for interactions]
final MainView gui = new MainView();
gui.addAssembleListner(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
assemble(gui);
gui.repaint();
}
});
gui.setVisible(true);
}
}
| michaelgriscom/urban | src/assembler/Urban.java | 1,886 | /**
* <pre>
* Procedure Name: main
* Description: assembles, links, and loads input program.
*
* Specification reference code(s): N/A
* Calling Sequence: Both
*
* Error Conditions Tested: N/A
* Error messages generated: N/A
*
* Modification Log (who when and why):
* Michael Apr 17, 2012 updated to conform to documentation standards
*
* Coding standards met: Signed by Michael
* Testing standards met: Signed by Michael
* </pre>
*
* @since Apr 12, 2012
* @author Andrew
* @param args
* are unused command line arguments
*/ | block_comment | en | true |
212557_2 | import model.ModelManager;
import view.EditorView;
import app.OpenRTSApplication;
import com.jme3.bullet.BulletAppState;
import com.jme3.math.Vector3f;
import com.jme3.niftygui.NiftyJmeDisplay;
import controller.editor.EditorController;
public class Editor extends OpenRTSApplication {
public static void main(String[] args) {
Editor app = new Editor();
OpenRTSApplication.main(app);
}
@Override
public void simpleInitApp() {
BulletAppState bulletAppState = new BulletAppState();
stateManager.attach(bulletAppState);
bulletAppState.getPhysicsSpace().setGravity(new Vector3f(0, 0, -1));
// stateManager.detach(bulletAppState);
flyCam.setUpVector(new Vector3f(0, 0, 1));
flyCam.setEnabled(false);
EditorView view = new EditorView(rootNode, guiNode, bulletAppState.getPhysicsSpace(), assetManager, viewPort);
NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort);
EditorController editorCtrl = new EditorController(view, niftyDisplay.getNifty(), inputManager, cam);
niftyDisplay.getNifty().setIgnoreKeyboardEvents(true);
// TODO: validation is needed to be sure everyting in XML is fine. see http://wiki.jmonkeyengine.org/doku.php/jme3:advanced:nifty_gui_best_practices
// niftyDisplay.getNifty().validateXml("interface/screen.xml");
niftyDisplay.getNifty().fromXml("interface/screen.xml", "editor");
stateManager.attach(editorCtrl);
editorCtrl.setEnabled(true);
ModelManager.setNewBattlefield();
guiViewPort.addProcessor(niftyDisplay);
}
}
| methusalah/OpenRTS | example/src/Editor.java | 460 | // niftyDisplay.getNifty().validateXml("interface/screen.xml"); | line_comment | en | true |
213127_9 | package lll;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashMap;
import edu.wpi.first.wpilibj.vision.VisionPipeline;
import org.opencv.core.*;
import org.opencv.core.Core.*;
import org.opencv.features2d.FeatureDetector;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.*;
import org.opencv.objdetect.*;
/**
* GripPipeline class.
*
* <p>An OpenCV pipeline generated by GRIP.
*
* @author GRIP
*/
public class GripPipeline implements VisionPipeline {
//Outputs
private Mat hsvThresholdOutput = new Mat();
private ArrayList<MatOfPoint> findContoursOutput = new ArrayList<MatOfPoint>();
private ArrayList<MatOfPoint> filterContoursOutput = new ArrayList<MatOfPoint>();
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
/**
* This is the primary method that runs the entire pipeline and updates the outputs.
*/
@Override public void process(Mat source0) {
// Step HSV_Threshold0:
Mat hsvThresholdInput = source0;
double[] hsvThresholdHue = {56.654676258992815, 130.8532423208191};
double[] hsvThresholdSaturation = {11.465827338129495, 152.73890784982936};
double[] hsvThresholdValue = {98.60611510791367, 248.47269624573377};
hsvThreshold(hsvThresholdInput, hsvThresholdHue, hsvThresholdSaturation, hsvThresholdValue, hsvThresholdOutput);
// Step Find_Contours0:
Mat findContoursInput = hsvThresholdOutput;
boolean findContoursExternalOnly = false;
findContours(findContoursInput, findContoursExternalOnly, findContoursOutput);
// Step Filter_Contours0:
ArrayList<MatOfPoint> filterContoursContours = findContoursOutput;
double filterContoursMinArea = 0.0;
double filterContoursMinPerimeter = 15.0;
double filterContoursMinWidth = 0.0;
double filterContoursMaxWidth = 1000;
double filterContoursMinHeight = 0;
double filterContoursMaxHeight = 1000;
double[] filterContoursSolidity = {0, 100};
double filterContoursMaxVertices = 1000000;
double filterContoursMinVertices = 0;
double filterContoursMinRatio = 0;
double filterContoursMaxRatio = 1000;
filterContours(filterContoursContours, filterContoursMinArea, filterContoursMinPerimeter, filterContoursMinWidth, filterContoursMaxWidth, filterContoursMinHeight, filterContoursMaxHeight, filterContoursSolidity, filterContoursMaxVertices, filterContoursMinVertices, filterContoursMinRatio, filterContoursMaxRatio, filterContoursOutput);
}
/**
* This method is a generated getter for the output of a HSV_Threshold.
* @return Mat output from HSV_Threshold.
*/
public Mat hsvThresholdOutput() {
return hsvThresholdOutput;
}
/**
* This method is a generated getter for the output of a Find_Contours.
* @return ArrayList<MatOfPoint> output from Find_Contours.
*/
public ArrayList<MatOfPoint> findContoursOutput() {
return findContoursOutput;
}
/**
* This method is a generated getter for the output of a Filter_Contours.
* @return ArrayList<MatOfPoint> output from Filter_Contours.
*/
public ArrayList<MatOfPoint> filterContoursOutput() {
return filterContoursOutput;
}
/**
* Segment an image based on hue, saturation, and value ranges.
*
* @param input The image on which to perform the HSL threshold.
* @param hue The min and max hue
* @param sat The min and max saturation
* @param val The min and max value
* @param output The image in which to store the output.
*/
private void hsvThreshold(Mat input, double[] hue, double[] sat, double[] val,
Mat out) {
Imgproc.cvtColor(input, out, Imgproc.COLOR_BGR2HSV);
Core.inRange(out, new Scalar(hue[0], sat[0], val[0]),
new Scalar(hue[1], sat[1], val[1]), out);
}
/**
* Sets the values of pixels in a binary image to their distance to the nearest black pixel.
* @param input The image on which to perform the Distance Transform.
* @param type The Transform.
* @param maskSize the size of the mask.
* @param output The image in which to store the output.
*/
private void findContours(Mat input, boolean externalOnly,
List<MatOfPoint> contours) {
Mat hierarchy = new Mat();
contours.clear();
int mode;
if (externalOnly) {
mode = Imgproc.RETR_EXTERNAL;
}
else {
mode = Imgproc.RETR_LIST;
}
int method = Imgproc.CHAIN_APPROX_SIMPLE;
Imgproc.findContours(input, contours, hierarchy, mode, method);
}
/**
* Filters out contours that do not meet certain criteria.
* @param inputContours is the input list of contours
* @param output is the the output list of contours
* @param minArea is the minimum area of a contour that will be kept
* @param minPerimeter is the minimum perimeter of a contour that will be kept
* @param minWidth minimum width of a contour
* @param maxWidth maximum width
* @param minHeight minimum height
* @param maxHeight maximimum height
* @param Solidity the minimum and maximum solidity of a contour
* @param minVertexCount minimum vertex Count of the contours
* @param maxVertexCount maximum vertex Count
* @param minRatio minimum ratio of width to height
* @param maxRatio maximum ratio of width to height
*/
private void filterContours(List<MatOfPoint> inputContours, double minArea,
double minPerimeter, double minWidth, double maxWidth, double minHeight, double
maxHeight, double[] solidity, double maxVertexCount, double minVertexCount, double
minRatio, double maxRatio, List<MatOfPoint> output) {
final MatOfInt hull = new MatOfInt();
output.clear();
//operation
for (int i = 0; i < inputContours.size(); i++) {
final MatOfPoint contour = inputContours.get(i);
final Rect bb = Imgproc.boundingRect(contour);
if (bb.width < minWidth || bb.width > maxWidth) continue;
if (bb.height < minHeight || bb.height > maxHeight) continue;
final double area = Imgproc.contourArea(contour);
if (area < minArea) continue;
if (Imgproc.arcLength(new MatOfPoint2f(contour.toArray()), true) < minPerimeter) continue;
Imgproc.convexHull(contour, hull);
MatOfPoint mopHull = new MatOfPoint();
mopHull.create((int) hull.size().height, 1, CvType.CV_32SC2);
for (int j = 0; j < hull.size().height; j++) {
int index = (int)hull.get(j, 0)[0];
double[] point = new double[] { contour.get(index, 0)[0], contour.get(index, 0)[1]};
mopHull.put(j, 0, point);
}
final double solid = 100 * area / Imgproc.contourArea(mopHull);
if (solid < solidity[0] || solid > solidity[1]) continue;
if (contour.rows() < minVertexCount || contour.rows() > maxVertexCount) continue;
final double ratio = bb.width / (double)bb.height;
if (ratio < minRatio || ratio > maxRatio) continue;
output.add(contour);
}
}
}
| 4627ManningRobotics/2018-Vision | GripPipeline.java | 2,107 | /**
* Segment an image based on hue, saturation, and value ranges.
*
* @param input The image on which to perform the HSL threshold.
* @param hue The min and max hue
* @param sat The min and max saturation
* @param val The min and max value
* @param output The image in which to store the output.
*/ | block_comment | en | true |
214058_18 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ATSGui extends JFrame implements ActionListener {
private JComboBox<String> menuOptions;
private JPanel cardPanel;
private CardLayout cardLayout;
private JTextArea outputArea;
// Events attributes
private JTextField ageRestrictionField;
private JTextField startDateField;
private JTextField startTimeField;
private JTextField durationField;
private JTextField typeIdField;
private JButton addEventButton;
// RegisteredUsers attributes
private JTextField emailField;
private JTextField dobField;
private JTextField usernameField;
private JTextField passwordField;
private JTextField creditCardField;
private JTextField expiryDateField;
private JTextField locationField;
private JTextField preferredTypeField;
private JTextField preferredGenreField;
private JButton registerUserButton;
// Tickets attributes
private JTextField priceField;
private JTextField designatedEntranceField;
private JTextField userIDField;
private JTextField purchaseDateField;
private JTextField EIDField;
private JButton addTicketButton;
// Sponsor attributes
private JTextField sponsorNameField;
private JTextField sponsorTypeField;
private JButton addSponsorButton;
public ATSGui() {
setTitle("Arena Ticketing System (ATS)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
// Menu options
String[] options = {"Add a new event", "Register a new user", "Purchase a ticket",
"Add a new sponsor to an event", "Exit"};
menuOptions = new JComboBox<>(options);
menuOptions.addActionListener(this);
panel.add(menuOptions, BorderLayout.NORTH);
// Output area
outputArea = new JTextArea();
outputArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(outputArea);
panel.add(scrollPane, BorderLayout.CENTER);
// CardLayout for different card panels
cardLayout = new CardLayout();
cardPanel = new JPanel(cardLayout);
panel.add(cardPanel, BorderLayout.SOUTH);
// Components for adding a new event
JPanel addEventPanel = new JPanel(new GridLayout(6, 2));
addEventPanel.add(new JLabel("Age Restriction:"));
ageRestrictionField = new JTextField();
addEventPanel.add(ageRestrictionField);
addEventPanel.add(new JLabel("Start Date (YYYY-MM-DD):"));
startDateField = new JTextField();
addEventPanel.add(startDateField);
addEventPanel.add(new JLabel("Start Time (HH:mm:ss):"));
startTimeField = new JTextField();
addEventPanel.add(startTimeField);
addEventPanel.add(new JLabel("Duration (minutes):"));
durationField = new JTextField();
addEventPanel.add(durationField);
addEventPanel.add(new JLabel("Type ID (Layout):"));
typeIdField = new JTextField();
addEventPanel.add(typeIdField);
addEventButton = new JButton("Submit");
addEventButton.addActionListener(this);
addEventPanel.add(addEventButton);
cardPanel.add(addEventPanel, "AddEvent");
// Components for registering a new user
JPanel registerUserPanel = new JPanel(new GridLayout(10, 2));
registerUserPanel.add(new JLabel("Email Address:"));
emailField = new JTextField();
registerUserPanel.add(emailField);
registerUserPanel.add(new JLabel("Date of Birth (YYYY-MM-DD):"));
dobField = new JTextField();
registerUserPanel.add(dobField);
registerUserPanel.add(new JLabel("Username:"));
usernameField = new JTextField();
registerUserPanel.add(usernameField);
registerUserPanel.add(new JLabel("Password:"));
passwordField = new JTextField();
registerUserPanel.add(passwordField);
registerUserPanel.add(new JLabel("Credit Card Number:"));
creditCardField = new JTextField();
registerUserPanel.add(creditCardField);
registerUserPanel.add(new JLabel("Expiry Date (YYYY-MM-DD):"));
expiryDateField = new JTextField();
registerUserPanel.add(expiryDateField);
registerUserPanel.add(new JLabel("Location:"));
locationField = new JTextField();
registerUserPanel.add(locationField);
registerUserPanel.add(new JLabel("Preferred Type:"));
preferredTypeField = new JTextField();
registerUserPanel.add(preferredTypeField);
registerUserPanel.add(new JLabel("Preferred Genre:"));
preferredGenreField = new JTextField();
registerUserPanel.add(preferredGenreField);
registerUserButton = new JButton("Submit");
registerUserButton.addActionListener(this);
registerUserPanel.add(registerUserButton);
cardPanel.add(registerUserPanel, "RegisterUser");
// Components for purchasing a new ticket
JPanel addTicketPanel = new JPanel(new GridLayout(6, 2));
addTicketPanel.add(new JLabel("Price:"));
priceField = new JTextField();
addTicketPanel.add(priceField);
addTicketPanel.add(new JLabel("Designated Entrance:"));
designatedEntranceField = new JTextField();
addTicketPanel.add(designatedEntranceField);
addTicketPanel.add(new JLabel("User ID:"));
userIDField = new JTextField();
addTicketPanel.add(userIDField);
addTicketPanel.add(new JLabel("Purchase Date:"));
purchaseDateField = new JTextField();
addTicketPanel.add(purchaseDateField);
addTicketPanel.add(new JLabel("EID:"));
EIDField = new JTextField();
addTicketPanel.add(EIDField);
addTicketButton = new JButton("Submit");
addTicketButton.addActionListener(this);
addTicketPanel.add(addTicketButton);
cardPanel.add(addTicketPanel, "AddTicket");
// Components for adding a new sponsor
JPanel addSponsorPanel = new JPanel(new GridLayout(3, 2));
addSponsorPanel.add(new JLabel("Sponsor Name:"));
sponsorNameField = new JTextField();
addSponsorPanel.add(sponsorNameField);
addSponsorPanel.add(new JLabel("Sponsor Type:"));
sponsorTypeField = new JTextField();
addSponsorPanel.add(sponsorTypeField);
addSponsorButton = new JButton("Submit");
addSponsorButton.addActionListener(this);
addSponsorPanel.add(addSponsorButton);
cardPanel.add(addSponsorPanel, "AddSponsor");
// Add panel to frame
add(panel);
}
public void actionPerformed(ActionEvent e) {
String option = (String) menuOptions.getSelectedItem();
String output = "";
switch (option) {
case "Add a new event":
output = "Option 1: Add a new event - Please fill in the details below:";
cardLayout.show(cardPanel, "AddEvent");
break;
case "Register a new user":
output = "Option 2: Register a new user - Please fill in the details below:";
cardLayout.show(cardPanel, "RegisterUser");
break;
case "Purchase a ticket":
output = "Option 3: Purchase a ticket - Please fill in the details below:";
cardLayout.show(cardPanel, "AddTicket");
break;
case "Add a new sponsor to an event":
output = "Option 4: Add a new sponsor to an event - Please fill in the details below:";
cardLayout.show(cardPanel, "AddSponsor");
break;
case "Exit":
System.exit(0);
break;
case "Submit": // Submit button actions for Add Event and Register User
if (e.getSource() == addEventButton) {
// Submit action for Add Event
output = "Adding a new event...\n";
// Get values from fields and perform actions accordingly
String ageRestriction = ageRestrictionField.getText();
String startDate = startDateField.getText();
String startTime = startTimeField.getText();
String duration = durationField.getText();
String typeId = typeIdField.getText();
// Perform actions, e.g., call a method to add event to database
} else if (e.getSource() == registerUserButton) {
// Submit action for Register User
output = "Registering a new user...\n";
// Get values from fields and perform actions accordingly
String emailAddress = emailField.getText();
String dob = dobField.getText();
String username = usernameField.getText();
String password = passwordField.getText();
String creditCard = creditCardField.getText();
String expiryDate = expiryDateField.getText();
String location = locationField.getText();
String preferredType = preferredTypeField.getText();
String preferredGenre = preferredGenreField.getText();
// Perform actions, e.g., call a method to register user to database
}
break;
}
outputArea.setText(output + "\n");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
ATSGui gui = new ATSGui();
gui.setVisible(true);
});
}
}
| rambodazimi/Arena-Ticketing-System | src/ATSGui.java | 2,070 | // Perform actions, e.g., call a method to register user to database | line_comment | en | false |
214166_1 | import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* @author tim
* 中文表达式解析,支持中文公式,支持JS常见语法
* // 如果
* // 那么
* // 否则
* // 取最大(数值1, 数值2)
* // 取最小(数值1, 数值2)
* // > => <= < !===
* // 或者
* // 并且
* // 四舍五入进位(数值, 进位单位)
* // 向上进位(数值, 进位单位)
* // 向下进位(数值, 进位单位)
* TODO::缺少 返回,包含扩展,可用JS自行编写逻辑
*/
public class Formula {
/**
* 预内置函数
* 可增加Lodash之类的引用
*/
static String ADD_JS = "" +
"function round(a,b){return Math.round(a+b)}\n" +
"function floor(a,b){return Math.floor(a+b)}\n" +
"function ceil(a,b){return Math.ceil(a+b)}\n";
/**
* 简单标记,可直接替换
*/
static String[][] SAMPLE_TAGS = {
{"如果", " if( "},
{"那么", " ) "},
{"否则", " else "},
{"或者", " || "},
{"并且", " && "},
{"取最小", "Math.min"},
{"取最大", "Math.max"},
{"四舍五入进位", "round"},
{"向上进位", "ceil"},
{"向下进位", "floor"}
};
/**
* 运行JS,返回结果
*/
static String runs(String js) {
String result = "";
ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("javascript");
try {
//先运行内置函数
scriptEngine.eval(ADD_JS);
result = scriptEngine.eval(js).toString();
} catch (ScriptException e) {
e.printStackTrace();
} finally {
System.out.println("\n\n===> JS START" + js);
System.out.println("<=== JS END\n\n");
}
return result;
}
/**
* 无参数执行
*/
static String eval(String formulaStr) {
String result = formulaStr;
result = parse2js(result);
return runs(result);
}
/**
* 带参数执行
*/
static String eval(String[][] params, String formulaStr) {
String result = formulaStr;
result = parseParams(params, result);
result = parse2js(result);
return runs(result);
}
/**
* 翻译参数
*/
static String parseParams(String[][] params, String formulaStr) {
String result = formulaStr;
System.out.println("\n\n =====> PARAMS START");
for (String[] param : params) {
if (param.length > 1) {
result = result.replaceAll(param[0], "'" + param[1] + "'");
System.out.println("key = " + param[0] + ", value = " + param[1]);
}
}
System.out.println("<===== PARAMS END \n\n");
return result;
}
/**
* 翻译成JS
*/
static String parse2js(String formulaStr) {
String result = formulaStr;
for (String[] tag : SAMPLE_TAGS) {
if (tag.length > 1) {
result = result.replaceAll(tag[0], tag[1]);
}
}
//TODO::增加复杂自定义标签逻辑
return result;
}
}
| timtoday/Formula | Formula.java | 882 | /**
* 预内置函数
* 可增加Lodash之类的引用
*/ | block_comment | en | true |
214339_0 |
/*
* SSW-file parser: Prints mech summaries
* Copyright (C) 2012 Christer Nyfält
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
public class Armor implements Item {
String type;
int tech_base;
int hd;
int ct;
int ctr;
int lt;
int ltr;
int rt;
int rtr;
int la;
int ra;
int ll;
int rl;
int total;
Armor(Element aElement) {
type = Util.getTagValue("type", aElement);
tech_base = Integer.parseInt(aElement.getAttribute("techbase"));
hd = Integer.parseInt(Util.getTagValue("hd", aElement));
ct = Integer.parseInt(Util.getTagValue("ct", aElement));
ctr = Integer.parseInt(Util.getTagValue("ctr", aElement));
lt = Integer.parseInt(Util.getTagValue("lt", aElement));
ltr = Integer.parseInt(Util.getTagValue("ltr", aElement));
rt = Integer.parseInt(Util.getTagValue("rt", aElement));
rtr = Integer.parseInt(Util.getTagValue("rtr", aElement));
la = Integer.parseInt(Util.getTagValue("la", aElement));
ra = Integer.parseInt(Util.getTagValue("ra", aElement));
ll = Integer.parseInt(Util.getTagValue("ll", aElement));
rl = Integer.parseInt(Util.getTagValue("rl", aElement));
total = hd + ct + ctr + lt + ltr + rt + rtr + la + ra + ll + rl;
System.out.println("Armor Type : " + type);
System.out.println("Tech Base : " + tech_base);
System.out.println("Head : " + hd);
System.out.println("Center Torso : " + ct);
System.out.println("Center Torso Rear : " + ctr);
System.out.println("Left Torso : " + lt);
System.out.println("Left Torso Rear : " + ltr);
System.out.println("Right Torso : " + rt);
System.out.println("Right Torso Rear : " + rtr);
System.out.println("Left Arm : " + la);
System.out.println("Right Arm : " + ra);
System.out.println("Left Leg : " + ll);
System.out.println("Right Leg : " + rl);
System.out.println("Total Armor : " + total);
}
public byte get_rules_level()
{
if (type == "Standard Armor")
return INTRO_TECH;
else if (type == "Ferro-Fibrous")
return TOURNAMENT_LEGAL;
else if (type == "Light Ferro-Fibrous")
return TOURNAMENT_LEGAL;
else if (type == "Heavy Ferro-Fibrous")
return TOURNAMENT_LEGAL;
else if (type == "Stealth Armor")
return TOURNAMENT_LEGAL;
else if (type == "Laser-Reflective")
return ADVANCED;
else if (type == "Hardened Armor")
return ADVANCED;
else if (type == "Reactive Armor")
return ADVANCED;
else if (type == "Ferro-Lamellor")
return ADVANCED;
else if (type == "Primitive Armor")
return PRIMITIVE;
else
{
System.out.println("Unknown armor:" + type);
System.exit(-1);
return -1;
}
}
public double get_weight()
{
double wgt, factor;
if (type == "Standard Armor")
factor = 1.0;
else if (type == "Ferro-Fibrous" && tech_base == 0)
factor = 1.12;
else if (type == "Ferro-Fibrous" && tech_base == 1)
factor = 1.2;
else if (type == "Light Ferro-Fibrous")
factor = 1.06;
else if (type == "Heavy Ferro-Fibrous")
factor = 1.24;
else if (type == "Stealth Armor")
factor = 1.0;
else if (type == "Laser-Reflective")
factor = 1.0;
else if (type == "Hardened Armor")
factor = 0.5;
else if (type == "Reactive Armor")
factor = 1.0;
else if (type == "Ferro-Lamellor")
factor = 0.9;
else if (type == "Primitive Armor")
factor = 0.67;
else
{
System.out.println("Unknown armor:" + type);
System.exit(-1);
factor = 0.0;
}
wgt = total / (16.0 * factor);
wgt = Util.ceil_05(wgt);
return wgt;
}
public long get_cost()
{
long factor;
if (type == "Standard Armor")
factor = 10000;
else if (type == "Ferro-Fibrous")
factor = 20000;
else if (type == "Light Ferro-Fibrous")
factor = 15000;
else if (type == "Heavy Ferro-Fibrous")
factor = 25000;
else if (type == "Stealth Armor")
factor = 50000;
else if (type == "Laser-Reflective")
factor = 30000;
else if (type == "Hardened Armor")
factor = 15000;
else if (type == "Reactive Armor")
factor = 30000;
else if (type == "Ferro-Lamellor")
factor = 35000;
else if (type == "Primitive Armor")
factor = 5000;
else
{
System.out.println("Unknown armor:" + type);
System.exit(-1);
factor = 0;
}
return (long)(factor * get_weight());
}
}
| ssw-parser/SSW_Parser | java/Armor.java | 1,828 | /*
* SSW-file parser: Prints mech summaries
* Copyright (C) 2012 Christer Nyfält
*
* 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 2 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, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/ | block_comment | en | true |
214451_9 | package ebms;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class Recovery extends javax.swing.JFrame {
ResultSet rs;ResultSetMetaData rsmd;
Object obj;String str,filename,url;
PreparedStatement stmt,st;
Connection con;
File f;
public Recovery(Object obj) throws SQLException, ClassNotFoundException {
initComponents();
con=connDb.conLink();
this.obj=obj;
rcvr_cmb.setSelectedIndex(0);
this.setLocationRelativeTo(null);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
back_bt = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
rcvr_cmb = new javax.swing.JComboBox<>();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(255, 255, 255));
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
back_bt.setBackground(new java.awt.Color(255, 255, 255));
back_bt.setFont(new java.awt.Font("Century", 1, 18)); // NOI18N
back_bt.setForeground(new java.awt.Color(15, 30, 70));
back_bt.setText("Back");
back_bt.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 0, 102)));
back_bt.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
back_bt.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
back_btActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Century", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(51, 0, 102));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("RECOVERY");
rcvr_cmb.setFont(new java.awt.Font("Century", 1, 18)); // NOI18N
rcvr_cmb.setForeground(new java.awt.Color(51, 0, 102));
rcvr_cmb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Users", "Bill", "Customer Details", "Meter", "Payments", "Arrear", "Connection", "Automatic" }));
rcvr_cmb.setBorder(null);
jButton1.setBackground(new java.awt.Color(255, 255, 255));
jButton1.setFont(new java.awt.Font("Century", 1, 18)); // NOI18N
jButton1.setForeground(new java.awt.Color(51, 0, 102));
jButton1.setText("Recover");
jButton1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(51, 0, 102), 3));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(back_bt, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(0, 111, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(rcvr_cmb, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(104, 104, 104))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(161, 161, 161))))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(back_bt)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(52, 52, 52)
.addComponent(rcvr_cmb, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(54, 54, 54))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, 0)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void back_btActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_back_btActionPerformed
this.dispose();
((mainwindow)obj).setEnabled(true);
((mainwindow)obj).setVisible(true);
}//GEN-LAST:event_back_btActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
str=rcvr_cmb.getSelectedItem().toString();
if(str.equalsIgnoreCase("Customer Details")){
stmt=con.prepareStatement("truncate table customer_details");
stmt.executeUpdate();
f=new File("backup\\customer_details.xls");
st=con.prepareStatement("select * from customer_details");
url="Insert into customer_details values(?,?,?,?,?,?,?,?,?,?,?)";
}
else if(str.equalsIgnoreCase("Users")){
stmt=con.prepareStatement("truncate table login");
stmt.executeUpdate();
f=new File("backup\\login.xls");
st=con.prepareStatement("select * from login");
url="Insert into login(login_user_id,login_role_id,question,login_user_password,answer,user_name,user_mobile,user_email) values(?,?,?,?,?,?,?,?)";
}
else if(str.equalsIgnoreCase("Connection")){
stmt=con.prepareStatement("truncate table connections");
stmt.executeUpdate();
f=new File("backup\\connections.xls");
st=con.prepareStatement("select * from connections");
url="Insert into payment_details values(?,?,?,?)";
}
else if(str.equalsIgnoreCase("Meter")){
stmt=con.prepareStatement("truncate table meter");
stmt.executeUpdate();
f=new File("backup\\meter.xls");
st=con.prepareStatement("select cus_id,meter_no,meter_rent from meter");
url="Insert into meter(cus_id,meter_no,meter_rent) values(?,?,?)";
}
else if(str.equalsIgnoreCase("Bill")){
stmt=con.prepareStatement("truncate table bill_cycle");
stmt.executeUpdate();
st=con.prepareStatement("select * from bill_cycle");
f=new File("backup\\bill_cycle.xls");
url="Insert into bill_cycle values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
}
else if(str.equalsIgnoreCase("Payments")){
stmt=con.prepareStatement("truncate table payment");
stmt.executeUpdate();
st=con.prepareStatement("select * from payment");
f=new File("backup\\payment.xls");
url="Insert into scheme_detail values(?,?,?,?,?)";
}
else if(str.equalsIgnoreCase("Arrear")){
stmt=con.prepareStatement("truncate table arrear_details");
stmt.executeUpdate();
st=con.prepareStatement("select * from arrear_details");
f=new File("backup\\arrear_details.xls");
url="Insert into arrear_details values(?,?,?,?)";
}
else if(str.equalsIgnoreCase("automatic")){
stmt=con.prepareStatement("truncate table automatic");
stmt.executeUpdate();
st=con.prepareStatement("select * from automatic");
f=new File("backup\\autobackup.xls");
url="insert into automatic values(?,?,?)";
}
FileInputStream fs=new FileInputStream(f);
Workbook wb=Workbook.getWorkbook(fs);
Sheet sh=wb.getSheet(0);
stmt=con.prepareStatement(url);
ResultSetMetaData rsmd=st.getMetaData();
for(byte i=1;i<sh.getRows();i++){
for(byte j=0;j<sh.getColumns();j++){
String str=sh.getCell(j,i).getContents();
if(rsmd.getColumnTypeName(j+1).equalsIgnoreCase("blob")){
InputStream inr=new ByteArrayInputStream(str.substring(1,str.length()).getBytes(StandardCharsets.UTF_8));
stmt.setBinaryStream(j+1,inr);
FileInputStream fin=new FileInputStream(str.substring(1,str.length()));
}else
stmt.setString(j+1,str.substring(1,str.length()));
}
stmt.executeUpdate();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(Recovery.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException | BiffException | SQLException ex) {
Logger.getLogger(Recovery.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton back_bt;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JComboBox<String> rcvr_cmb;
// End of variables declaration//GEN-END:variables
}
| intez20/EBMS | EBMS/Recovery.java | 2,870 | //GEN-LAST:event_jButton1ActionPerformed | line_comment | en | true |
214493_0 | /**
* This is a java program that tries to recover crypto hashes using
* a dictionary aka wordlist (not included)
* @author Copyright 2007 rogeriopvl, <http://www.rogeriopvl.com>
* @version 0.2
*
* Changelog:
* v0.2 - minor code corrections, now with GUI hash prompt for better usability.
*
* 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/>.
*
* Instructions: Just compile it as a normal java class and run it. You will need
* a dictionary file not included with the source. The file must have each word in a new line.
*
* PERSONAL DISCLAIMER: This program was made exclusively for educational purposes, therefore
* I can't be held responsible for the actions of others using it.
*/
import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.security.NoSuchAlgorithmException;
import javax.swing.JOptionPane;
public class HashRecovery {
private static final String PROGNAME = "HashRecovery";
private static final String VERSION = "v0.5";
private static final int MIN_HASH_LENGTH = 32;
private static final String EMPTY_HASH = "d41d8cd98f00b204e9800998ecf8427e";
/**
* Main method
* @param args command line arguments
* @throws FileNotFoundException
*/
public static void main (String [] args) throws FileNotFoundException {
String algo = null;
String dictionaryPath = null;
if (args.length < 1) {
usage();
}
else if (args[0].equals("-a")) {
if (args.length != 3) {
usage();
}
else {
algo = args[1];
dictionaryPath = args[2];
}
}
else {
usage();
}
if (algo.equals(null)) {
algo = "MD5";
}
//let's ask for the hash to recover in a fancy dialog :)
String hash = JOptionPane.showInputDialog(null, "Hash to recover: ", PROGNAME+" "+VERSION, 1);
if (hash.length() < MIN_HASH_LENGTH)
System.err.println ("Warning: probably not a valid hash, proceeding anyway...");
Scanner infile = new Scanner(new FileReader(dictionaryPath));
String line;
int count = 0;
while (infile.hasNext()) {
line = infile.nextLine();
count++;
//no need to spend CPU cycles calculating this one...
if (hash.equals(EMPTY_HASH)) {
System.out.println ("Done it! That's the hash of an empty string!");
System.exit(0);
}
try {
if (hash.equals(HashUtils.generateHash(line, algo))) {
System.out.println ("Houston, we've done it!: "+line);
System.out.println ("Sucess after "+count+" words.");
System.exit(0);
}
}
catch(NoSuchAlgorithmException e) {
System.err.println("Error: Unsupported algorithm - "+algo);
System.exit(1);
}
}
infile.close();
System.out.println ("Unable to recover hash. Try using a better dictionary file.");
}//end of main
/**
* Prints the usage example and exits the program
*/
private static void usage() {
System.err.println ("Usage: "+PROGNAME+" [-a <algo>] <dictionary file>");
System.exit(1);
}
}//end of class
| rogeriopvl/HashRecovery | HashRecovery.java | 1,013 | /**
* This is a java program that tries to recover crypto hashes using
* a dictionary aka wordlist (not included)
* @author Copyright 2007 rogeriopvl, <http://www.rogeriopvl.com>
* @version 0.2
*
* Changelog:
* v0.2 - minor code corrections, now with GUI hash prompt for better usability.
*
* 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/>.
*
* Instructions: Just compile it as a normal java class and run it. You will need
* a dictionary file not included with the source. The file must have each word in a new line.
*
* PERSONAL DISCLAIMER: This program was made exclusively for educational purposes, therefore
* I can't be held responsible for the actions of others using it.
*/ | block_comment | en | true |
214667_9 | import java.util.Observable;
import java.util.Observer;
/**
*
*/
/**
* @author chris
*
*/
public abstract class ALevel extends Observable implements I_Levels,
I_Enemies {
private BadGuyFactory _badgroupone;
private BadGuyFactory _badgrouptwo;
private BadGuyFactory _badgroupthree;
private BattleArena _battleArena;
private java.util.List<BadGuyFactory> _badGuysOnLevel;
private GoodGuyFactory _goodGuys;
private String _levelName;
/**
*
* @param levelName
* @param goodGuys
*/
public ALevel(String levelName, GoodGuyFactory goodGuys)
{
_levelName = levelName;
_goodGuys = goodGuys;
_badGuysOnLevel = new java.util.ArrayList<BadGuyFactory>();
_badgroupone = new BadGuyFactory(this);
_badgrouptwo = new BadGuyFactory(this);
_badgroupthree = new BadGuyFactory(this);
for(AGoodGuy gg : goodGuys.get_goodGuys())
{
accept(gg);
gg.set_level(this);
}
play_level(goodGuys);
}
/*
* (non-Javadoc)
* @see I_Enemies#addEnemies(BadGuyFactory, int, int)
*/
@Override
public void addEnemies(BadGuyFactory badGuys, int originX, int originY) {
// adds mobs at specific points on the level
_badGuysOnLevel.add(badGuys);
for(ABadGuy bg : badGuys.get_badGuys())
{
addObserver((Observer) bg);
bg.set_locx(originX);
bg.set_locy(originY);
}
}
/*
* (non-Javadoc)
* @see I_Levels#accept(AGoodGuy)
*/
@Override
public void accept(AGoodGuy goodGuy)
{
System.out.println(goodGuy.get_name() + " has entered " +
get_levelName() + " at location (0, 0)\n");
}
/**
*
* @return
*/
public GoodGuyFactory get_goodGuys() {
return _goodGuys;
}
/**
*
* @param _goodGuys
*/
public void set_goodGuys(GoodGuyFactory _goodGuys) {
this._goodGuys = _goodGuys;
}
/**
*
* @return
*/
public BadGuyFactory get_badgroupone() {
return _badgroupone;
}
/**
*
* @param _badgroupone
*/
public void set_badgroupone(BadGuyFactory _badgroupone) {
this._badgroupone = _badgroupone;
}
/**
*
* @return
*/
public BadGuyFactory get_badgrouptwo() {
return _badgrouptwo;
}
/**
*
* @param _badgrouptwo
*/
public void set_badgrouptwo(BadGuyFactory _badgrouptwo) {
this._badgrouptwo = _badgrouptwo;
}
/**
*
* @return
*/
public BadGuyFactory get_badgroupthree() {
return _badgroupthree;
}
/**
*
* @param _badgroupthree
*/
public void set_badgroupthree(BadGuyFactory _badgroupthree) {
this._badgroupthree = _badgroupthree;
}
/**
*
* @return
*/
public java.util.List<BadGuyFactory> get_badGuysOnLevel() {
return _badGuysOnLevel;
}
/**
*
* @param _badGuysOnLevel
*/
public void set_badGuysOnLevel(java.util.List<BadGuyFactory> _badGuysOnLevel) {
this._badGuysOnLevel = _badGuysOnLevel;
}
/*
* (non-Javadoc)
* @see I_Levels#move(GoodGuyFactory, int, int)
*/
@Override
public void move(GoodGuyFactory goodGuys, int dirx, int diry)
{
//notifies Observers local to level of GoodGuy presence,
//if GoodGuy comes to BadGuy location new BattleArena made
goodGuys.set_grouplocx(goodGuys.get_grouplocx() + dirx);
goodGuys.set_grouplocy(goodGuys.get_grouplocy() + diry);
for(BadGuyFactory badGuys : get_badGuysOnLevel())
{
if(goodGuys.get_grouplocx() == badGuys.get_grouplocx()
&& goodGuys.get_grouplocy() == badGuys.get_grouplocy())
{
for(ABadGuy abg : badGuys.get_badGuys())
{
abg.update();
}
set_battleArena(new BattleArena(goodGuys, badGuys));
get_battleArena().fight();
}
}
}
/**
*
* @return
*/
public BattleArena get_battleArena() {
return _battleArena;
}
/**
*
* @param _battleArena
*/
public void set_battleArena(BattleArena _battleArena) {
this._battleArena = _battleArena;
}
/*
* (non-Javadoc)
* @see I_Levels#play_level(GoodGuyFactory)
*/
@Override
public void play_level(GoodGuyFactory goodGuys) {
// group can move x and y the amount of their combined attack speed
// must wait num moves to attack, i.e combined attack speed 10, x = 3 y = 4
// group waits seven seconds to move again, has to clear entire level of mobs to
// advance, treasure for each group member at end of level based on chartype
// if move to enemy location, group must wait enemy group combined attack speed,
// less combined move, i.e combined move = 7 enemy attack speed = 10, must wait 3 seconds,
// pseudo enemy ambush, each enemy with attack speed <= numMoves - combinedEnemyAttackSpeed
// can attack random member of group, then turn based until goodguys or badguys win
for(AGoodGuy gg : goodGuys.get_goodGuys())
{
System.out.println(gg.get_name() + " has conquered " + get_levelName() + "\n");
}
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AHeavyWarrior)
*/
@Override
public void treasureDrop(AHeavyWarrior hWarrior) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AShadowWarrior)
*/
@Override
public void treasureDrop(AShadowWarrior sWarrior) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AMage)
*/
@Override
public void treasureDrop(AMage mage) {
}
/*
* (non-Javadoc)
* @see I_Levels#treasureDrop(AWizard)
*/
@Override
public void treasureDrop(AWizard wizard) {
}
/**
*
* @return
*/
public String get_levelName() {
return _levelName;
}
/**
*
* @param _levelName
*/
public void set_levelName(String _levelName) {
this._levelName = _levelName;
}
}
| NTonani/DreamStreet | src/ALevel.java | 1,978 | /**
*
* @param _badgroupone
*/ | block_comment | en | false |
214795_0 | import greenfoot.*;
/**
* Write a description of class ButtonHelp here.
*
* @author Rucha Apte
* @version (a version number or a date)
*/
public interface ButtonCommand
{
public void executeCommand();
public void setReceiver(Receiver newReceiver);
} | sowmyav27/cmpe202-monstars-xfer | Final Integrated code/ButtonCommand.java | 71 | /**
* Write a description of class ButtonHelp here.
*
* @author Rucha Apte
* @version (a version number or a date)
*/ | block_comment | en | true |
215230_3 | /*
* This file is part of TiPi (a Toolkit for Inverse Problems and Imaging)
* developed by the MitiV project.
*
* Copyright (c) 2014 the MiTiV project, http://mitiv.univ-lyon1.fr/
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package mitiv.array;
import mitiv.base.Shaped;
import mitiv.base.Typed;
import mitiv.linalg.shaped.ShapedVector;
/**
* A ShapedArray is a shaped object with a primitive type.
*
* <p> A ShapedArray stores rectangular multi-dimensional arrays of elements of
* the same data type. Compared to a {@link ShapedVector}, the elements of a
* ShapedArray reside in conventional memory and may be stored in arbitrary
* order and in a non-contiguous way. </p>
*
* @author Éric Thiébaut.
*/
public interface ShapedArray extends Shaped, Typed {
/**
* Check whether a shaped array is stored as a flat Java array.
*
* @return True if the results of {@code this.flatten(false)} and
* {@code this.flatten()} are guaranteed to yield a direct
* reference (not a copy) to the contents of the array.
*/
public abstract boolean isFlat();
/**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> The contents of a shaped array can be stored in many different
* forms. This storage details are hidden to the end-user in favor of a
* unified and comprehensive interface. This method returns the contents
* of a shaped array as a simple <i>flat</i> array, <i>i.e.</i> successive
* elements are contiguous and the first element has {@code 0}-offset. If
* the shaped array is multi-dimensional, the storage of the returned
* result is column-major order. </p>
*
* @param forceCopy
* Set true to force a copy of the internal data even though it can
* already be in a flat form. Otherwise and if the shaped array is
* in flat form, see {@link #isFlat()}, the data storage of the
* array is directly returned (not a copy).
*
* @return An object which can be recast into a {@code type[]}
* array with {@code type} the generic Java type corresponding
* to the type of the elements of the shaped array: {@code byte},
* {@code short}, {@code int}, {@code long}, {@code float} or
* {@code double}.
*/
public abstract Object flatten(boolean forceCopy);
/**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> This method behaves as if argument {@code forceCopy} was set to
* false in {@link #flatten(boolean)}. Depending on the storage layout,
* the returned array may or may not share the same storage as the
* ${className} array. Call {@code flatten(true)} to make sure that the
* two storage areas are independent. </p>
*
* @return An object (see {@link #flatten(boolean)} for more explanations).
*/
public abstract Object flatten();
/**
* Get a direct access to the elements of a shaped array.
*
* <p> Calling this method should be equivalent to: </p>
*
* <pre>
* (this.isFlat() ? this.flatten() : null)
* </pre>
*
* @return An object which can be {@code null} if direct access is not
* possible (or allowed). If non-{@code null}, the returned value
* can be recast into a {@code type[]} array with {@code type} the
* generic Java type corresponding to the type of the elements of
* the shaped array: {@code byte}, {@code short}, {@code int},
* {@code long}, {@code float} or {@code double}.
*
* @see #flatten()
* @see #isFlat()
*/
public abstract Object getData();
/**
* Convert array elements to type {@code byte}.
*
* @return A {@link ByteArray} object which may be the object itself
* if it is already a ByteArray.
*/
public abstract ByteArray toByte();
/**
* Convert array elements to type {@code short}.
*
* @return A {@link ShortArray} object which may be the object itself
* if it is already a ShortArray.
*/
public abstract ShortArray toShort();
/**
* Convert array elements to type {@code int}.
*
* @return A {@link IntArray} object which may be the object itself
* if it is already an IntArray.
*/
public abstract IntArray toInt();
/**
* Convert array elements to type {@code long}.
*
* @return A {@link LongArray} object which may be the object itself
* if it is already a LongArray.
*/
public abstract LongArray toLong();
/**
* Convert array elements to type {@code float}.
*
* @return A {@link FloatArray} object which may be the object itself
* if it is already a FloatArray.
*/
public abstract FloatArray toFloat();
/**
* Convert array elements to type {@code double}.
*
* @return A {@link DoubleArray} object which may be the object itself
* if it is already a DoubleArray.
*/
public abstract DoubleArray toDouble();
/**
* Create a new array with same element type and shape.
*
* <p> This method yields a new shaped array which has the same element
* type and shape as the object but whose contents is not initialized.
* </p>
*
* @return A new shaped array.
*/
public abstract ShapedArray create();
/**
* Create a copy of the array with the dimension initpos at the position finalpos
* @param initpos
* @param finalpos
* @return the new array
*/
public abstract ShapedArray movedims( int initpos, int finalpos);
/**
* Copy the contents of the object as a new array.
*
* <p> This method yields a new shaped array which has the same shape, type
* and values as the object but whose contents is independent from that of
* the object. If the object is a <i>view</i>, then this method yields a
* compact array in a <i>flat</i> form. </p>
*
* @return A flat shaped array.
*/
public abstract ShapedArray copy();
/**
* Assign the values of the object from those of another shaped array.
*
* <p> The shape of the source and of the destination must match, type
* conversion (to the type of the elements of the destination) is
* automatically done if needed. </p>
*
* @param src
* The source object.
*/
public abstract void assign(ShapedArray src);
/**
* Assign the values of the object from those of a shaped vector.
*
* <p> This operation may be slow. </p>
*
* @param src
* The source object.
*
* @see #assign(ShapedArray) for a discussion of the rules that apply.
*/
public abstract void assign(ShapedVector src);
/**
* Get a view of the object as a 1D array.
*
* <p> The result is a 1D <i>view</i> of its parents, this means that they
* share the same contents. </p>
*
* @return A 1D view of the object.
*/
public abstract Array1D as1D();
/**
* Perform some sanity tests.
*
* <p> For performance reasons, not all errors are checked by TiPi code.
* This means that arguments may be simply trusted for being correct. This
* method can be used for debugging and tracking incorrect
* parameters/arguments. It throws runtime exception(s) if some errors or
* inconsistencies are discovered. </p>
*/
public abstract void checkSanity();
}
| emmt/TiPi | src/mitiv/array/ShapedArray.java | 2,112 | /**
* Flatten the elements of a shaped array in a simple generic array.
*
* <p> The contents of a shaped array can be stored in many different
* forms. This storage details are hidden to the end-user in favor of a
* unified and comprehensive interface. This method returns the contents
* of a shaped array as a simple <i>flat</i> array, <i>i.e.</i> successive
* elements are contiguous and the first element has {@code 0}-offset. If
* the shaped array is multi-dimensional, the storage of the returned
* result is column-major order. </p>
*
* @param forceCopy
* Set true to force a copy of the internal data even though it can
* already be in a flat form. Otherwise and if the shaped array is
* in flat form, see {@link #isFlat()}, the data storage of the
* array is directly returned (not a copy).
*
* @return An object which can be recast into a {@code type[]}
* array with {@code type} the generic Java type corresponding
* to the type of the elements of the shaped array: {@code byte},
* {@code short}, {@code int}, {@code long}, {@code float} or
* {@code double}.
*/ | block_comment | en | false |
215702_1 | package shop2;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import java.util.LinkedList;
import shopU.RegisteredUser;
public class Shop {
protected static Mongo m;
protected DB db;
protected DBCollection books;
protected DBCollection movies;
protected DBCollection cds;
protected DBCollection users;
protected DBCollection admin;
/**
@Shop : constructor de la clase Shop
-m :Recibe una conexión con Mongo
*/
public Shop(Mongo m){
Shop.m = m;
this.db = m.getDB("DataBase");
this.cds = db.getCollection("cds");
this.books = db.getCollection("books");
this.movies = db.getCollection("movies");
this.users=db.getCollection("users");
this.admin=db.getCollection("admin");
}
/**
@addUser: metodo para agregar usuarios, está aqui
* porque cualquier persona (desde la GUI)
* puede crearlo.
*/
public boolean addUser(RegisteredUser user){
DBObject cur = this.getUsers().findOne(new BasicDBObject("id", user.getId()));
if(cur == null){
this.getUsers().insert(user.getDocument());
return true;
}
return false;
}
/**
@hasEnoughStock: Método que comprueba si hay suficiente stock de un producto para la compra
* -b: BasicDBObject, producto a comprar.
* -a: int, Cantidad solicitada.
* @returns:
* -true si hay suficiente stock del producto.
* -false, en caso contrario.
*/
public boolean hasEnoughStock(BasicDBObject b, int a){
if((Integer)b.get("stock")>=a){
return true;
}
else{
return false;
}
}
/**
@find*: Métodos de búsqueda para cada tipo de artículo.
* mediante diferentes criterios.
* -El algoritmo de búsqueda es el implementado en el gestor de DB(Mongo).
* @returns:
* BasicDBObject, en caso de entoncrar el artículo.
* null, en caso contrario.
*/
public BasicDBObject findBookID(String id){
BasicDBObject query=new BasicDBObject();
query.put("id", id);
return (BasicDBObject)getBooks().findOne(query);
}
public BasicDBObject findCDID(String id){
BasicDBObject query=new BasicDBObject();
query.put("id", id);
return (BasicDBObject)getCds().findOne(query);
}
public BasicDBObject findMovieID(String id){
BasicDBObject query=new BasicDBObject();
query.put("id", id);
return (BasicDBObject)getMovies().findOne(query);
}
public BasicDBObject findUserID(String id){
BasicDBObject query=new BasicDBObject();
query.put("id", id);
return (BasicDBObject)getUsers().findOne(query);
}
public LinkedList<BasicDBObject> findBookTitle(String title){
DBCursor cur=getBooks().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("title")).contains(title) || ((String)aux.get("title")).equals(title)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findBookAuthor(String author){
DBCursor cur=getBooks().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("author")).contains(author) || ((String)aux.get("author")).equals(author)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findBookEditorial(String editorial){
DBCursor cur=getBooks().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("editorial")).contains(editorial) || ((String)aux.get("editorial")).equals(editorial)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findCDTitle(String title){
DBCursor cur=getCds().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("title")).contains(title) || ((String)aux.get("title")).equals(title)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findCDAuthor(String author){
DBCursor cur=getCds().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("author")).contains(author) || ((String)aux.get("author")).equals(author)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findCDYear(String year){
DBCursor cur=getCds().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("year")).contains(year) || ((String)aux.get("year")).equals(year)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findMovieTitle(String title){
DBCursor cur=getMovies().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("title")).contains(title) || ((String)aux.get("title")).equals(title)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findMovieAuthor(String author){
DBCursor cur=getMovies().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("author")).contains(author) || ((String)aux.get("author")).equals(author)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findMovieDirector(String director){
DBCursor cur=getMovies().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("director")).contains(director) || ((String)aux.get("director")).equals(director)){
results.add(aux);
}
}
return results;
}
public LinkedList<BasicDBObject> findMovieActor(String actor){
DBCursor cur=getMovies().find();
BasicDBObject aux=new BasicDBObject();
LinkedList<BasicDBObject> results=new LinkedList<BasicDBObject>();
while(cur.hasNext()){
aux=(BasicDBObject)cur.next();
if(((String)aux.get("actors")).contains(actor) || ((String)aux.get("actors")).equals(actor)){
results.add(aux);
}
}
return results;
}
public DBCollection getUsers() {
return users;
}
public DBCollection getBooks() {
return books;
}
public DBCollection getMovies() {
return movies;
}
public DBCollection getCds() {
return cds;
}
public DBCollection getAdmin() {
return admin;
}
public void modifyUser(RegisteredUser user,String oldId){
BasicDBObject update= new BasicDBObject();
// modifyArticle(user.getId(), user.gtitle, author, description, stock, price);
update.put("id", user.getId());
update.put("name", user.getName());
update.put("money", user.getMoney());
update.put("password",user.getPassword());
users.update(new BasicDBObject().append("id", oldId), update);
}
}
| caal-15/Shop | shop2/Shop.java | 2,117 | /**
@addUser: metodo para agregar usuarios, está aqui
* porque cualquier persona (desde la GUI)
* puede crearlo.
*/ | block_comment | en | true |
215727_2 | import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
/**
* Data manager - Implements CourseDBManagerInterface. Allow users to read the
* courses from a file or enter data.
*
* @author Yei Thek Wang
*/
public class CourseDBManager implements CourseDBManagerInterface {
private CourseDBStructure cds;
/**
* Constructor
*/
public CourseDBManager() {
cds = new CourseDBStructure(100);
}
/**
* Add a new class with following the parameters.
*
* @param course
* @param crn
* @param credit
* @param room
* @param instructor
*/
@Override
public void add(String course, int crn, int credit, String room, String instructor) {
CourseDBElement cde = new CourseDBElement(course, crn, credit, room, instructor);
cds.add(cde);
}
/**
* Get method, it uses CourseDBStructure to get a CourseDBElement from the data
* structure.
*
* @param crn
* @return element if found, else return null
*/
@Override
public CourseDBElement get(int crn) {
try {
return cds.get(crn);
} catch (IOException e) {
System.out.println(e.getMessage());
}
return null;
}
/**
* Reads every line from a text file
*
* @param input
* @throws FileNotFoundException
*/
@Override
public void readFile(File input) throws FileNotFoundException {
Scanner sc = new Scanner(input);
int credit, crn;
CourseDBElement cde;
String strings;
String[] course;
while (sc.hasNextLine()) {
strings = sc.nextLine();
course = strings.split(" ", 5);
crn = Integer.parseInt(course[1]);
credit = Integer.parseInt(course[2]);
cde = new CourseDBElement(course[0], crn, credit, course[3], course[4]);
cds.add(cde);
}
}
/**
* Calls the showAll method in courseDBStructure which traverses through the
* hash table and returns them into an array list.
*
* @return ArrayList with elements
*/
@Override
public ArrayList<String> showAll() {
return cds.showAll();
}
} | wyThek/CMSC204_Assignment4 | CourseDBManager.java | 603 | /**
* Add a new class with following the parameters.
*
* @param course
* @param crn
* @param credit
* @param room
* @param instructor
*/ | block_comment | en | true |
215805_1 | /**
* Quad.java
*
* Represents quadrants for the Barnes-Hut algorithm.
*
* Dependencies: StdDraw.java
*
* @author chindesaurus
* @version 1.00
*/
public class Quad {
private double xmid;
private double ymid;
private double length;
/**
* Constructor: creates a new Quad with the given
* parameters (assume it is square).
*
* @param xmid x-coordinate of center of quadrant
* @param ymid y-coordinate of center of quadrant
* @param length the side length of the quadrant
*/
public Quad(double xmid, double ymid, double length) {
this.xmid = xmid;
this.ymid = ymid;
this.length = length;
}
/**
* Returns the length of one side of the square quadrant.
*
* @return side length of the quadrant
*/
public double length() {
return length;
}
/**
* Does this quadrant contain (x, y)?
*
* @param x x-coordinate of point to test
* @param y y-coordinate of point to test
* @return true if quadrant contains (x, y), else false
*/
public boolean contains(double x, double y) {
double halfLen = this.length / 2.0;
return (x <= this.xmid + halfLen &&
x >= this.xmid - halfLen &&
y <= this.ymid + halfLen &&
y >= this.ymid - halfLen);
}
/**
* Returns a new object that represents the northwest quadrant.
*
* @return the northwest quadrant of this Quad
*/
public Quad NW() {
double x = this.xmid - this.length / 4.0;
double y = this.ymid + this.length / 4.0;
double len = this.length / 2.0;
Quad NW = new Quad(x, y, len);
return NW;
}
/**
* Returns a new object that represents the northeast quadrant.
*
* @return the northeast quadrant of this Quad
*/
public Quad NE() {
double x = this.xmid + this.length / 4.0;
double y = this.ymid + this.length / 4.0;
double len = this.length / 2.0;
Quad NE = new Quad(x, y, len);
return NE;
}
/**
* Returns a new object that represents the southwest quadrant.
*
* @return the southwest quadrant of this Quad
*/
public Quad SW() {
double x = this.xmid - this.length / 4.0;
double y = this.ymid - this.length / 4.0;
double len = this.length / 2.0;
Quad SW = new Quad(x, y, len);
return SW;
}
/**
* Returns a new object that represents the southeast quadrant.
*
* @return the southeast quadrant of this Quad
*/
public Quad SE() {
double x = this.xmid + this.length / 4.0;
double y = this.ymid - this.length / 4.0;
double len = this.length / 2.0;
Quad SE = new Quad(x, y, len);
return SE;
}
/**
* Draws an unfilled rectangle that represents the quadrant.
*/
public void draw() {
StdDraw.rectangle(xmid, ymid, length / 2.0, length / 2.0);
}
/**
* Returns a string representation of this quadrant for debugging.
*
* @return string representation of this quadrant
*/
public String toString() {
String ret = "\n";
for (int row = 0; row < this.length; row++) {
for (int col = 0; col < this.length; col++) {
if (row == 0 || col == 0 || row == this.length - 1 || col == this.length - 1)
ret += "*";
else
ret += " ";
}
ret += "\n";
}
return ret;
}
}
| chindesaurus/BarnesHut-N-Body | Quad.java | 989 | /**
* Constructor: creates a new Quad with the given
* parameters (assume it is square).
*
* @param xmid x-coordinate of center of quadrant
* @param ymid y-coordinate of center of quadrant
* @param length the side length of the quadrant
*/ | block_comment | en | false |
216310_1 | /**
* This is in an interface class that has the method kmPerHour, numOfWheels, numOfSeats, renewLicensePlate
*
* @author Muhammad Hameez Iqbal, Shardul Bhardwaj, Brandon Nguyen
* @since jdk 14.02
* @version ide 4.16
*
*/
public interface roadVehicles {
/**
* This method is to print the vehicles max speed
*/
public String kmPerHour();
/**
* This method is to print the vehicles number of wheels
*/
public String numOfWheels();
/**
* This method is to print the vehicles number of seats
*/
public String numOfSeats();
/**
*This method is to print a statement saying license plate has been renewed
*/
public String renewLicensePlate();
}
| Hameez10/JavaClasses-ObjectsAssignment | roadVehicles.java | 199 | /**
* This method is to print the vehicles max speed
*/ | block_comment | en | false |
216630_9 | package Battleship;
// import net.arikia.dev.drpc.*;
/**
*
* The Main Class where the PlayerWindow and GameOverWindow are declared. It
* decides when to display PlayerWindow and GameOverWindow. Also deals with
* Discord Rich Presence.
*
* @author Riya Kumari, Tanav Ohal
* @version May 30, 2019
* @author Period: 5
* @author Assignment: Batttleship_APCSFinalProject
*
* @author Sources:
*/
public class Gamers implements Runnable
{
/**
* Constructor
*/
public Gamers() {}
/**
* Makes a newOver Window behind the main window
*/
GameOverWindow b = new GameOverWindow();
/**
* Thr Flag to check if the game is over
*/
private boolean flag = false;
/**
* Rich presence to check if the system this game is running on is windows
*/
// for Discord Rich Presence
public static boolean runDiscord = System.getProperty( "os.name" )
.toLowerCase()
.indexOf( "win" ) >= 0;
/**
* Makes a playerwindow to show the game content
*/
PlayerWindow a = new PlayerWindow();
/**
* Main Method
*
* @param args the thread of the system
*/
public static void main( String[] args )
{
if ( runDiscord )
{
// DiscordRPC.discordInitialize( "582734573255786507", new DiscordEventHandlers(), true );
// Gamers.updatePresence( "Please appreciate this!", "Hey," );
//Gamers.updatePresence( "Getting Ready to Play", "Title Screen" );
}
new Thread( new Gamers() ).start();
}
/**
* Updates the Rich Presence in discord to show the game status
*
* @param header
* the title of the status
* @param details
* the status detials
*/
// public static void updatePresence( String header, String details )
// {
// if ( Gamers.runDiscord )
// {
// DiscordRPC.discordUpdatePresence(
// new DiscordRichPresence.Builder( header ).setDetails( details ).build() );
// }
// }
/**
* Runs the game as long as neither user wins. When a user wins, then the
* game pauses and a Game Over window opens up which also displays whether
* current user won or lost.
*/
public void run()
{
while ( a.GameOver() == false )
{
a.setVisible( true );
a.repaint();
}
String str = a.getWinner();
if ( str.equals( "Player" ) )
{
flag = true;
}
b.setWinner( flag );
a.setVisible( true );
while ( true )
{
b.repaint();
b.setVisible( true );
}
}
}
| riya-kumari/Battleship | Gamers.java | 691 | // DiscordRPC.discordInitialize( "582734573255786507", new DiscordEventHandlers(), true );
| line_comment | en | true |
217017_3 | public class GradeAverage {
private int [] scores;
public GradeAverage(int [] s)
{
scores = s;
}
// returns the mean (average) of the values in the scores array
// whose indexes are between first and last (including first and last).
//You may assume that first and last are >= 0 and < scores.length
private double mean(int first, int last)
{
double sum = 0;
for(int i = first; i <= last; i++){
sum += scores[i];
}
return sum / (last - first + 1);
}
// returns true if each successive value in scores is greater than
// or equal to the previous value. Otherwise returns false
private boolean showsImprovement()
{
for(int i = 0; i < scores.length - 1; i++) {
if(scores[i] > scores[i+1]) {
return false;
}
}
return true;
}
// if the values in the scores array show improvement, returns the
// average of the elements in scores with indexes greater than or
// equal to scores.length()/2
// You must call mean() and showsImprovement() in your code.
public double finalGrade()
{
if (showsImprovement()==true){
return mean(scores.length/2, scores.length-1);
}
return mean(scores.length-1);
}
public static void main(String[] args) {
int [] s1 = {50,50,20,80,53}; // not improved, finalGrade is 50.6
int [] s2 = {20,50,50,53,80}; // improved, final grade is 61.0
int [] s3 = {20,50,50,85}; // improved, final grade is 67.5
int [] s4 = {35, 50, 45, 60,62}; // not improved, finalGrade is 50.4
int [] s5 = {47, 58, 58, 66, 87, 90,90,90}; // improved, final grade is 89.25
GradeAverage sr1 = new GradeAverage(s1);
System.out.println(sr1.mean(1,3));
System.out.println(sr1.showsImprovement());
System.out.println(sr1.finalGrade());
GradeAverage sr2 = new GradeAverage(s2);
System.out.println(sr2.mean(2,4));
System.out.println(sr2.showsImprovement());
System.out.println(sr2.finalGrade());
GradeAverage sr3 = new GradeAverage(s3);
System.out.println(sr3.mean(0,2));
System.out.println(sr3.showsImprovement());
System.out.println(sr3.finalGrade());
GradeAverage sr4 = new GradeAverage(s4);
System.out.println(sr4.showsImprovement());
System.out.println(sr4.finalGrade());
GradeAverage sr5 = new GradeAverage(s5);
System.out.println(sr5.showsImprovement());
System.out.println(sr5.finalGrade());
}
} | nbailat/CSA | GradeAverage.java | 836 | // returns true if each successive value in scores is greater than
| line_comment | en | true |
217249_6 | package gh2;
import deque.Deque;
import deque.LinkedListDeque;
//Note: This file will not compile until you complete the Deque implementations
public class GuitarString {
/** Constants. Do not change. In case you're curious, the keyword final
* means the values cannot be changed at runtime. We'll discuss this and
* other topics in lecture on Friday. */
private static final int SR = 44100; // Sampling Rate
private static final double DECAY = .996; // energy decay factor
/* Buffer for storing sound data. */
private Deque<Double> buffer;
/* Create a guitar string of the given frequency. */
public GuitarString(double frequency) {
int capacity = (int) Math.round((double) SR / frequency);
buffer = new LinkedListDeque();
for (int i = 0; i < capacity; i++) {
buffer.addFirst(0.0);
}
}
/* Pluck the guitar string by replacing the buffer with white noise. */
public void pluck() {
Deque<Double> buffer2 = new LinkedListDeque();
for (int i = 0; i < buffer.size(); i++) {
double numbers = Math.random() - 0.5;
buffer2.addFirst(numbers);
}
buffer = buffer2;
}
/* Advance the simulation one time step by performing one iteration of
* the Karplus-Strong algorithm.
*/
public void tic() {
double first = buffer.removeFirst();
double getter = buffer.get(0);
double enqueue = DECAY * ((first + getter) / 2);
buffer.addLast(enqueue);
}
/* Return the double at the front of the buffer. */
public double sample() {
return buffer.get(0);
}
}
| angela-rodriguezz/Double-Ended-Deques | gh2/GuitarString.java | 421 | /* Pluck the guitar string by replacing the buffer with white noise. */ | block_comment | en | false |
217451_0 |
/*****************************************************************************************************
*
* Authors:
*
* CWL Java SDK:
*
* * Paul Grosu <[email protected]>, Northeastern University
*
* Alternate SDK (via Avro):
*
* * Denis Yuen <[email protected]>
*
* CWL Draft:
*
* * Peter Amstutz <[email protected]>, Curoverse
* * Nebojsa Tijanic <[email protected]>, Seven Bridges Genomics
*
* Contributors:
*
* * Luka Stojanovic <[email protected]>, Seven Bridges Genomics
* * John Chilton <[email protected]>, Galaxy Project, Pennsylvania State University
* * Michael R. Crusoe <[email protected]>, University of California, Davis
* * Herve Menager <[email protected]>, Institut Pasteur
* * Maxim Mikheev <[email protected]>, BioDatomics
* * Stian Soiland-Reyes <[email protected]>, University of Manchester
*
*****************************************************************************************************/
public interface NamedType {
String name = null;
public void setname( String value );
public String getname();
} | kellrott/cwljava | WIP/paul/sdk/NamedType.java | 378 | /*****************************************************************************************************
*
* Authors:
*
* CWL Java SDK:
*
* * Paul Grosu <[email protected]>, Northeastern University
*
* Alternate SDK (via Avro):
*
* * Denis Yuen <[email protected]>
*
* CWL Draft:
*
* * Peter Amstutz <[email protected]>, Curoverse
* * Nebojsa Tijanic <[email protected]>, Seven Bridges Genomics
*
* Contributors:
*
* * Luka Stojanovic <[email protected]>, Seven Bridges Genomics
* * John Chilton <[email protected]>, Galaxy Project, Pennsylvania State University
* * Michael R. Crusoe <[email protected]>, University of California, Davis
* * Herve Menager <[email protected]>, Institut Pasteur
* * Maxim Mikheev <[email protected]>, BioDatomics
* * Stian Soiland-Reyes <[email protected]>, University of Manchester
*
*****************************************************************************************************/ | block_comment | en | true |
217633_0 | import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Bloco implements Visível{
public static String txt="";
public static byte[] b = txt.getBytes();
private int altura ;
private int largura ;
private boolean colisao = true;
private int x;
private int y;
private static String tipo;
private static int resistencia;
private static Image blocoimagem;
public static List<String> tipodobloco = new ArrayList<>();
public static List<Integer> resistenciadobloco = new ArrayList<>();
public static List<Image> imagemdobloco = new ArrayList<>();
public int resistenciaatual;
public int indice;
public static void abrirblocos() {
/** Essa função é feita para abrir o arquivo blocos.txt**/
String fileName = "C:\\Users\\kaell\\Desktop\\Faculdade\\Disciplinas\\2 ANO\\Programação orientada a Objetos\\Arkanoid-base\\assets\\blocos.txt";
String line;
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
for (int i = 1; i <= 6; i++) {
line = br.readLine();
if (line != null) {
String[] parts = line.split(";");
String tipo = parts[0].trim();
tipodobloco.add(tipo);
int resistencia = Integer.parseInt(parts[1].trim());
resistenciadobloco.add(resistencia);
String imagePath = parts[2].trim();
BufferedImage img = ImageIO.read(new File(imagePath));
imagemdobloco.add(img);
}
}
} catch (IOException e) {
/** cria um painel caso o arquivo não abra OBJETIVO 7 **/
JFrame frame = new JFrame();
JOptionPane.showMessageDialog(frame, "Error reading file: " + e.getMessage());
}
}
public Bloco(int x, int y, int indice,int resistenciaatual) {
/** Construtor do bloco que define a sua resistencia o seu tipo e sua imagem de acordo com o indice obtido ao abrir o ficheiro **/
this.x = x;
this.y = y;
this.indice=indice;
resistencia=resistenciadobloco.get(indice);
if (resistencia >= 0 && resistencia <= 5) {
this.resistencia = resistencia;
} else {
this.resistencia = 5;
}
this.resistenciaatual=resistencia;
this.altura=32;
this.largura=64;
tipo= tipodobloco.get(indice);
blocoimagem = imagemdobloco.get(indice);
}
public boolean colisao() {
return colisao;
}
public void setColisao(boolean colisao) {
this.colisao = colisao;
}
public int getResistencia() {
return resistencia;
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
@Override
public void setX(int x) {
}
@Override
public void setY(int y) {
}
@Override
public int getlargura() {
return largura;
}
@Override
public int getaltura() {
return altura;
}
@Override
public void visivel(Graphics g) {
g.drawImage(blocoimagem, x, y, null);
}
public int getIndice() {
return indice;
}
public void setIndice(int indice) {
this.indice = indice;
}
}
| KayKael/Arkanoid-Java | src/Bloco.java | 947 | /** Essa função é feita para abrir o arquivo blocos.txt**/ | block_comment | en | true |
218369_3 | /*
* Copyright (c) 2008-2009, Motorola, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of the Motorola, Inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package javax.obex;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The <code>Operation</code> interface provides ways to manipulate a single
* OBEX PUT or GET operation. The implementation of this interface sends OBEX
* packets as they are built. If during the operation the peer in the operation
* ends the operation, an <code>IOException</code> is thrown on the next read
* from the input stream, write to the output stream, or call to
* <code>sendHeaders()</code>.
* <P>
* <STRONG>Definition of methods inherited from <code>ContentConnection</code>
* </STRONG>
* <P>
* <code>getEncoding()</code> will always return <code>null</code>. <BR>
* <code>getLength()</code> will return the length specified by the OBEX Length
* header or -1 if the OBEX Length header was not included. <BR>
* <code>getType()</code> will return the value specified in the OBEX Type
* header or <code>null</code> if the OBEX Type header was not included.<BR>
* <P>
* <STRONG>How Headers are Handled</STRONG>
* <P>
* As headers are received, they may be retrieved through the
* <code>getReceivedHeaders()</code> method. If new headers are set during the
* operation, the new headers will be sent during the next packet exchange.
* <P>
* <STRONG>PUT example</STRONG>
* <P>
* <PRE>
* void putObjectViaOBEX(ClientSession conn, HeaderSet head, byte[] obj) throws IOException {
* // Include the length header
* head.setHeader(head.LENGTH, new Long(obj.length));
* // Initiate the PUT request
* Operation op = conn.put(head);
* // Open the output stream to put the object to it
* DataOutputStream out = op.openDataOutputStream();
* // Send the object to the server
* out.write(obj);
* // End the transaction
* out.close();
* op.close();
* }
* </PRE>
* <P>
* <STRONG>GET example</STRONG>
* <P>
* <PRE>
* byte[] getObjectViaOBEX(ClientSession conn, HeaderSet head) throws IOException {
* // Send the initial GET request to the server
* Operation op = conn.get(head);
* // Retrieve the length of the object being sent back
* int length = op.getLength();
* // Create space for the object
* byte[] obj = new byte[length];
* // Get the object from the input stream
* DataInputStream in = trans.openDataInputStream();
* in.read(obj);
* // End the transaction
* in.close();
* op.close();
* return obj;
* }
* </PRE>
*
* <H3>Client PUT Operation Flow</H3> For PUT operations, a call to
* <code>close()</code> the <code>OutputStream</code> returned from
* <code>openOutputStream()</code> or <code>openDataOutputStream()</code> will
* signal that the request is done. (In OBEX terms, the End-Of-Body header
* should be sent and the final bit in the request will be set.) At this point,
* the reply from the server may begin to be processed. A call to
* <code>getResponseCode()</code> will do an implicit close on the
* <code>OutputStream</code> and therefore signal that the request is done.
* <H3>Client GET Operation Flow</H3> For GET operation, a call to
* <code>openInputStream()</code> or <code>openDataInputStream()</code> will
* signal that the request is done. (In OBEX terms, the final bit in the request
* will be set.) A call to <code>getResponseCode()</code> will cause an implicit
* close on the <code>InputStream</code>. No further data may be read at this
* point.
* @hide
*/
public interface Operation {
/**
* Sends an ABORT message to the server. By calling this method, the
* corresponding input and output streams will be closed along with this
* object. No headers are sent in the abort request. This will end the
* operation since <code>close()</code> will be called by this method.
* @throws IOException if the transaction has already ended or if an OBEX
* server calls this method
*/
void abort() throws IOException;
/**
* Returns the headers that have been received during the operation.
* Modifying the object returned has no effect on the headers that are sent
* or retrieved.
* @return the headers received during this <code>Operation</code>
* @throws IOException if this <code>Operation</code> has been closed
*/
HeaderSet getReceivedHeader() throws IOException;
/**
* Specifies the headers that should be sent in the next OBEX message that
* is sent.
* @param headers the headers to send in the next message
* @throws IOException if this <code>Operation</code> has been closed or the
* transaction has ended and no further messages will be exchanged
* @throws IllegalArgumentException if <code>headers</code> was not created
* by a call to <code>ServerRequestHandler.createHeaderSet()</code>
* or <code>ClientSession.createHeaderSet()</code>
* @throws NullPointerException if <code>headers</code> if <code>null</code>
*/
void sendHeaders(HeaderSet headers) throws IOException;
/**
* Returns the response code received from the server. Response codes are
* defined in the <code>ResponseCodes</code> class.
* @see ResponseCodes
* @return the response code retrieved from the server
* @throws IOException if an error occurred in the transport layer during
* the transaction; if this object was created by an OBEX server
*/
int getResponseCode() throws IOException;
String getEncoding();
long getLength();
int getHeaderLength();
String getType();
InputStream openInputStream() throws IOException;
DataInputStream openDataInputStream() throws IOException;
OutputStream openOutputStream() throws IOException;
DataOutputStream openDataOutputStream() throws IOException;
void close() throws IOException;
void noEndofBody();
int getMaxPacketSize();
}
| gp-b2g/frameworks_base | obex/javax/obex/Operation.java | 1,829 | /**
* Returns the headers that have been received during the operation.
* Modifying the object returned has no effect on the headers that are sent
* or retrieved.
* @return the headers received during this <code>Operation</code>
* @throws IOException if this <code>Operation</code> has been closed
*/ | block_comment | en | false |
218486_0 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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 h;
import java.util.Arrays;
import java.util.List;
//2 3h2jjekexv13eg90o5lqy1d0j
public interface GVG_t extends GVG_s {
public static List<String> DEFINITION = Arrays.asList(
"typedef struct GVG_s GVG_t");
}
// typedef struct GVG_s GVG_t; | SevereOverfl0w/plantuml | src/h/GVG_t.java | 559 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* Project Info: http://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* http://plantuml.com/patreon (only 1$ per month!)
* http://plantuml.com/paypal
*
* This file is part of Smetana.
* Smetana is a partial translation of Graphviz/Dot sources from C to Java.
*
* (C) Copyright 2009-2017, Arnaud Roques
*
* This translation is distributed under the same Licence as the original C program:
*
*************************************************************************
* Copyright (c) 2011 AT&T Intellectual Property
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors: See CVS logs. Details at http://www.graphviz.org/
*************************************************************************
*
* THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
* LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0]
*
* ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
* RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
*
* You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* 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.
*
*/ | block_comment | en | true |
219069_0 | /**
* This program is intended to calculate the value of pi by simulating throwing darts at a dart *board.
*
*/
import java.util.Scanner;
import java.util.Random;
import java.lang.Math;
class PiValueMC
{
public static double[] calcPi(int d, int t)
{
int hit = 0;
int miss = 0;
double [] posX = new double[d];
double [] posY = new double[d];
double[] pi = new double[t];
for(int i = 0; i < t; i++)
{
hit = 0;
for(int index = 0; index < d; index++)
{
posX[index] = 2 * Math.random() + - 1;
posY[index] = 2 * Math.random() + - 1;
if((Math.pow(posX[index], 2) + Math.pow(posY[index], 2)) <= 1)
{
hit++;
}
}
pi[i] = (4 * ((double)hit / d));
}
return pi;
}
public static double calcPiAverage(double[] p, double t)
{
double average = 0;
double sum = 0;
for(int i = 0; i < t; i++)
{
sum += p[i];
}
average = sum / t;
return average;
}
public static void printOutput(double [] p, double ave, int t)
{
for(int i = 0; i < t; i++)
{
System.out.print("Trial [" + i + "]: pi = ");
System.out.printf("%5.5f%n", p[i]);
}
System.out.println("After " + t + " trials, Estimate of pi = " + ave);
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("How many darts per trial? ");
int darts = in.nextInt();
System.out.println("How many trials? ");
int trials = in.nextInt();
double [] pi = new double[trials];
pi = calcPi(darts, trials);
double piAverage = calcPiAverage(pi, trials);
printOutput(pi, piAverage, trials);
}
} | sreetamdas/Java | PiValueMC.java | 555 | /**
* This program is intended to calculate the value of pi by simulating throwing darts at a dart *board.
*
*/ | block_comment | en | false |
219082_0 | /**
* Validate if a given string is numeric.
*
* Some examples:
*
* "0" => true
* " 0.1 " => true
* "abc" => false
* "1 a" => false
* "2e10" => true
*
* Note: It is intended for the problem statement to be ambiguous.
* You should gather all requirements up front before implementing one.
*
*/
public class ValidNumber {
public boolean isNumber(String s) {
StringBuffer sb = new StringBuffer(s.trim());
int i = sb.length() - 1;
while (i >= 0 && sb.charAt(i) == ' ') {
i--;
}
sb.delete(i + 1, sb.length());
s = sb.toString();
int length = s.length();
if (length == 0)
return false;
i = 0;
int start = 0;
if (s.charAt(i) == '-' || s.charAt(i) == '+') {
i++;
start++;
}
for (; i < length; i++) {
char c = s.charAt(i);
if (c == 'e' || c == 'E') {
return isDouble(s.substring(start, i)) && isDigitals(s.substring(i + 1, s.length()));
} else if (c != '.' && (c < '0' || c > '9')) {
return false;
}
}
return isDouble(s.substring(start));
}
private boolean isDouble(String s) {
int length = s.length();
if (length == 0 || ((s.charAt(0) == '-' || s.charAt(0) == '+') && length == 1))
return false;
int i = 0, start = 0;
if (s.charAt(i) == '-' || s.charAt(i) == '+') {
i++;
start++;
}
for (; i < length; i++) {
char c = s.charAt(i);
if (c == '.') {
if (i == start && s.length() - i - 1 == 0)
return false;
boolean left = i == start ? true : isDigitals(s.substring(0, i));
boolean right = s.length() - i - 1 == 0 ? true : isDigitals(s.substring(i + 1, s.length()));
return left && right;
} else if (c < '0' || c > '9') {
return false;
}
}
return true;
}
private boolean isDigitals(String s) {
int length = s.length();
if (length == 0 || ((s.charAt(0) == '-' || s.charAt(0) == '+') && length == 1))
return false;
int i = 0;
if (s.charAt(i) == '-' || s.charAt(i) == '+') {
i++;
}
for (; i < length; i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
} | mikezhouhan/leetcode-3 | ValidNumber.java | 801 | /**
* Validate if a given string is numeric.
*
* Some examples:
*
* "0" => true
* " 0.1 " => true
* "abc" => false
* "1 a" => false
* "2e10" => true
*
* Note: It is intended for the problem statement to be ambiguous.
* You should gather all requirements up front before implementing one.
*
*/ | block_comment | en | false |
219562_0 | /*An election is contested by 5 candiades the candiades are numbered 1 to 5 and the voting is done by marking the candiadate in number on paper write a [program to read the paper and count the votes cast for each candiadtes using array variable count in case a number read is outside the range 1 to 5 paper should consider as spoilt paper and the program should also count the number of spoilt paper*/
import java.util.*;
class task4{
public static void main(String arrg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter total number of Voters");
int n=sc.nextInt();
int arr[]=new int[6];
for(int i=0;i<n;i++){
System.out.println("1 BJP 2 AAP 3 ICP 4 BAA 5 UKD");
int op=sc.nextInt();
if(op==1)
arr[0]++;
else if(op==2)
arr[1]++;
else if(op==3)
arr[2]++;
else if(op==4)
arr[3]++;
else if(op==5)
arr[4]++;
else
arr[5]++;
}
System.out.println("BJP total Vote :- "+arr[0]);
System.out.println("AAP total Vote :- "+arr[1]);
System.out.println("ICP total Vote :- "+arr[2]);
System.out.println("BAA total Vote :- "+arr[3]);
System.out.println("UKD total Vote :- "+arr[4]);
System.out.println("NOTA total Vote :- "+arr[5]);
}
}
| KritagyaPainuly/JAVA | POOL.java | 403 | /*An election is contested by 5 candiades the candiades are numbered 1 to 5 and the voting is done by marking the candiadate in number on paper write a [program to read the paper and count the votes cast for each candiadtes using array variable count in case a number read is outside the range 1 to 5 paper should consider as spoilt paper and the program should also count the number of spoilt paper*/ | block_comment | en | true |
220035_0 | /*******************************************************************************
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*
*******************************************************************************/
package org.eclipse.kura.internal.wire.fifo;
import static java.util.Objects.isNull;
import static java.util.Objects.requireNonNull;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import org.eclipse.kura.configuration.ConfigurableComponent;
import org.eclipse.kura.configuration.ConfigurationService;
import org.eclipse.kura.wire.WireEmitter;
import org.eclipse.kura.wire.WireEnvelope;
import org.eclipse.kura.wire.WireHelperService;
import org.eclipse.kura.wire.WireReceiver;
import org.eclipse.kura.wire.WireSupport;
import org.osgi.service.wireadmin.Wire;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Fifo implements WireEmitter, WireReceiver, ConfigurableComponent {
private static final String DISCARD_ENVELOPES_PROP_NAME = "discard.envelopes";
private static final String QUEUE_CAPACITY_PROP_NAME = "queue.capacity";
private static final Logger logger = LoggerFactory.getLogger(Fifo.class);
private volatile WireHelperService wireHelperService;
private WireSupport wireSupport;
private FifoEmitterThread emitterThread;
public void bindWireHelperService(final WireHelperService wireHelperService) {
if (isNull(this.wireHelperService)) {
this.wireHelperService = wireHelperService;
}
}
public void unbindWireHelperService(final WireHelperService wireHelperService) {
if (this.wireHelperService == wireHelperService) {
this.wireHelperService = null;
}
}
public void activate(final Map<String, Object> properties) {
logger.info("Activating Fifo...");
wireSupport = this.wireHelperService.newWireSupport(this);
updated(properties);
logger.info("Activating Fifo... Done");
}
public void deactivate() {
logger.info("Dectivating Fifo...");
stopEmitterThread();
logger.info("Dectivating Fifo... Done");
}
public void updated(final Map<String, Object> properties) {
logger.info("Updating Fifo...");
String threadName = (String) properties.getOrDefault(ConfigurationService.KURA_SERVICE_PID, "Fifo")
+ "-EmitterThread";
int queueCapacity = (Integer) properties.getOrDefault(QUEUE_CAPACITY_PROP_NAME, 50);
boolean discardEnvelopes = (Boolean) properties.getOrDefault(DISCARD_ENVELOPES_PROP_NAME, false);
restartEmitterThread(threadName, queueCapacity, discardEnvelopes);
logger.info("Updating Fifo... Done");
}
private synchronized void stopEmitterThread() {
if (emitterThread != null) {
emitterThread.shutdown();
emitterThread = null;
}
}
private synchronized void restartEmitterThread(String threadName, int queueCapacity, boolean discardEnvelopes) {
stopEmitterThread();
logger.debug("Creating new emitter thread: {}, queue capacity: {}, discard envelopes: {}", threadName,
queueCapacity, discardEnvelopes);
emitterThread = new FifoEmitterThread(threadName, queueCapacity, discardEnvelopes);
emitterThread.start();
}
@Override
public void onWireReceive(WireEnvelope wireEnvelope) {
requireNonNull(wireEnvelope, "Wire Envelope cannot be null");
if (emitterThread != null) {
emitterThread.submit(wireEnvelope);
}
}
@Override
public Object polled(Wire wire) {
return this.wireSupport.polled(wire);
}
@Override
public void consumersConnected(Wire[] wires) {
this.wireSupport.consumersConnected(wires);
}
@Override
public void updated(Wire wire, Object value) {
this.wireSupport.updated(wire, value);
}
@Override
public void producersConnected(Wire[] wires) {
this.wireSupport.producersConnected(wires);
}
private class FifoEmitterThread extends Thread {
private Lock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
private boolean run = true;
private ArrayList<WireEnvelope> queue;
private int queueCapacity;
private Consumer<WireEnvelope> submitter;
public FifoEmitterThread(String threadName, int queueCapacity, boolean discardEnvelopes) {
this.queue = new ArrayList<>();
this.queueCapacity = queueCapacity;
setName(threadName);
if (discardEnvelopes) {
submitter = getEnvelopeDiscardingSubmitter();
} else {
submitter = getEmitterBlockingSubmitter();
}
}
private Consumer<WireEnvelope> getEnvelopeDiscardingSubmitter() {
return (envelope) -> {
try {
lock.lock();
if (!run || queue.size() >= queueCapacity) {
logger.debug("envelope discarded");
return;
} else {
queue.add(envelope);
producer.signal();
logger.debug("envelope submitted");
}
} finally {
lock.unlock();
}
};
}
private Consumer<WireEnvelope> getEmitterBlockingSubmitter() {
return (envelope) -> {
try {
lock.lock();
while (run && queue.size() >= queueCapacity) {
consumer.await();
}
if (!run) {
return;
}
queue.add(envelope);
producer.signal();
logger.debug("envelope submitted");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn("Interrupted while adding new envelope to queue", e);
} finally {
lock.unlock();
}
};
}
public void shutdown() {
try {
lock.lock();
run = false;
producer.signalAll();
consumer.signalAll();
} finally {
lock.unlock();
}
}
public void submit(WireEnvelope envelope) {
submitter.accept(envelope);
}
@Override
public void run() {
while (run) {
try {
WireEnvelope next = null;
try {
lock.lock();
while (run && queue.isEmpty()) {
producer.await();
}
if (!run) {
break;
}
next = queue.remove(0);
consumer.signal();
} finally {
lock.unlock();
}
wireSupport.emit(next.getRecords());
} catch (Exception e) {
logger.warn("Unexpected exception while dispatching envelope", e);
}
}
logger.debug("exiting");
}
}
}
| bellmit/bug_category | data3/Fifo.java | 1,647 | /*******************************************************************************
* Copyright (c) 2017, 2018 Eurotech and/or its affiliates and others
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eurotech
*
*******************************************************************************/ | block_comment | en | true |