blob_id
stringlengths
40
40
__id__
int64
225
39,780B
directory_id
stringlengths
40
40
path
stringlengths
6
313
content_id
stringlengths
40
40
detected_licenses
list
license_type
stringclasses
2 values
repo_name
stringlengths
6
132
repo_url
stringlengths
25
151
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
70
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
7.28k
689M
star_events_count
int64
0
131k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
23 values
gha_fork
bool
2 classes
gha_event_created_at
timestamp[ns]
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_size
int64
0
40.4M
gha_stargazers_count
int32
0
112k
gha_forks_count
int32
0
39.4k
gha_open_issues_count
int32
0
11k
gha_language
stringlengths
1
21
gha_archived
bool
2 classes
gha_disabled
bool
1 class
content
stringlengths
7
4.37M
src_encoding
stringlengths
3
16
language
stringclasses
1 value
length_bytes
int64
7
4.37M
extension
stringclasses
24 values
filename
stringlengths
4
174
language_id
stringclasses
1 value
entities
list
contaminating_dataset
stringclasses
0 values
malware_signatures
list
redacted_content
stringlengths
7
4.37M
redacted_length_bytes
int64
7
4.37M
alphanum_fraction
float32
0.25
0.94
alpha_fraction
float32
0.25
0.94
num_lines
int32
1
84k
avg_line_length
float32
0.76
99.9
std_line_length
float32
0
220
max_line_length
int32
5
998
is_vendor
bool
2 classes
is_generated
bool
1 class
max_hex_length
int32
0
319
hex_fraction
float32
0
0.38
max_unicode_length
int32
0
408
unicode_fraction
float32
0
0.36
max_base64_length
int32
0
506
base64_fraction
float32
0
0.5
avg_csv_sep_count
float32
0
4
is_autogen_header
bool
1 class
is_empty_html
bool
1 class
shard
stringclasses
16 values
519f7d53c4985c2134a8b91240d35b2e551be625
24,979,529,805,048
bf9ebeab417539930d6760317d3373b6b5f664d2
/app/src/main/java/com/field/datamatics/apimodels/AppoinmentResponseBody.java
d046cc1d62974673261db6175b7214ddbf943041
[]
no_license
ItsMeAnoop/FDM
https://github.com/ItsMeAnoop/FDM
e144715beb4e94e5433f71a2a83372a0055451ca
a51cacdd51c07161e95d209273e91f55097a556b
refs/heads/master
2021-12-13T23:56:01.984000
2021-12-05T05:08:07
2021-12-05T05:08:07
62,947,917
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.field.datamatics.apimodels; /** * Created by anoop on 28/10/15. */ public class AppoinmentResponseBody { private String customerid; private String routplanno; private String Clientno; private String remarks; private String appdate; public String getCustomerid () { return customerid; } public void setCustomerid (String customerid) { this.customerid = customerid; } public String getRoutplanno () { return routplanno; } public void setRoutplanno (String routplanno) { this.routplanno = routplanno; } public String getClientno () { return Clientno; } public void setClientno (String Clientno) { this.Clientno = Clientno; } public String getRemarks () { return remarks; } public void setRemarks (String remarks) { this.remarks = remarks; } public String getAppdate () { return appdate; } public void setAppdate (String appdate) { this.appdate = appdate; } @Override public String toString() { return "ClassPojo [customerid = "+customerid+", routplanno = "+routplanno+", Clientno = "+Clientno+", remarks = "+remarks+", appdate = "+appdate+"]"; } }
UTF-8
Java
1,320
java
AppoinmentResponseBody.java
Java
[ { "context": "com.field.datamatics.apimodels;\n\n/**\n * Created by anoop on 28/10/15.\n */\npublic class AppoinmentResponseB", "end": 64, "score": 0.9996203184127808, "start": 59, "tag": "USERNAME", "value": "anoop" } ]
null
[]
package com.field.datamatics.apimodels; /** * Created by anoop on 28/10/15. */ public class AppoinmentResponseBody { private String customerid; private String routplanno; private String Clientno; private String remarks; private String appdate; public String getCustomerid () { return customerid; } public void setCustomerid (String customerid) { this.customerid = customerid; } public String getRoutplanno () { return routplanno; } public void setRoutplanno (String routplanno) { this.routplanno = routplanno; } public String getClientno () { return Clientno; } public void setClientno (String Clientno) { this.Clientno = Clientno; } public String getRemarks () { return remarks; } public void setRemarks (String remarks) { this.remarks = remarks; } public String getAppdate () { return appdate; } public void setAppdate (String appdate) { this.appdate = appdate; } @Override public String toString() { return "ClassPojo [customerid = "+customerid+", routplanno = "+routplanno+", Clientno = "+Clientno+", remarks = "+remarks+", appdate = "+appdate+"]"; } }
1,320
0.602273
0.597727
73
17.068493
22.584593
157
false
false
0
0
0
0
0
0
0.287671
false
false
8
01b1a1beff40ffa8397b317ddb1a4834e7caa90c
24,979,529,803,579
dbe3172623ad433a9246fe2db164bcafb77bbc09
/app/src/main/java/com/example/mauricio/twoweekproject6/GalleryActivity.java
7d130f6e3483cdc0a1693a4901e3f72f9ad1141a
[]
no_license
mvh5/CourseDescriptions
https://github.com/mvh5/CourseDescriptions
c80489a4b0114b614df53dfc3b3027feee64d0e7
39d6efa707807cb7abc4865d428e206bce04741d
refs/heads/master
2020-03-27T22:39:48.632000
2018-09-03T21:21:11
2018-09-03T21:21:11
147,248,625
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.mauricio.twoweekproject6; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * Created by Mauricio on 8/15/18. */ public class GalleryActivity extends AppCompatActivity { private TextView textView; private ImageView imageView; private Button button; private EditText editText; private TextView textView2; private static final String TAG = "GalleryActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); Log.d(TAG, "onCreate: started."); textView = (TextView)findViewById(R.id.image_description); textView2 = (TextView)findViewById(R.id.class_description); imageView = (ImageView)findViewById(R.id.image); Bundle bundle = this.getIntent().getExtras(); String value = bundle.getString("val1"); int value2 = bundle.getInt("val2"); String classDescription = bundle.getString("val4"); textView.setText(value); textView2.setText(classDescription); imageView.setImageResource(value2); editText = (EditText)findViewById(R.id.editText1); button = (Button)findViewById(R.id.button2); //Toast.makeText(this,value,Toast.LENGTH_SHORT).show(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String text1 = ""; Bundle bundle = new Bundle(); bundle.putString("xyz1",editText.getText().toString()); Intent returnIntent = new Intent(view.getContext(),MainActivity.class); returnIntent.putExtras(bundle); view.getContext().startActivity(returnIntent); } }); } }
UTF-8
Java
2,190
java
GalleryActivity.java
Java
[ { "context": "package com.example.mauricio.twoweekproject6;\n\nimport android.app.Activity;\nim", "end": 28, "score": 0.9525471329689026, "start": 20, "tag": "USERNAME", "value": "mauricio" }, { "context": "w;\nimport android.widget.Toast;\n\n/**\n * Created by Mauricio on 8/15/18.\n */\n\npublic class GalleryActivity ext", "end": 460, "score": 0.999728262424469, "start": 452, "tag": "NAME", "value": "Mauricio" } ]
null
[]
package com.example.mauricio.twoweekproject6; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * Created by Mauricio on 8/15/18. */ public class GalleryActivity extends AppCompatActivity { private TextView textView; private ImageView imageView; private Button button; private EditText editText; private TextView textView2; private static final String TAG = "GalleryActivity"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); Log.d(TAG, "onCreate: started."); textView = (TextView)findViewById(R.id.image_description); textView2 = (TextView)findViewById(R.id.class_description); imageView = (ImageView)findViewById(R.id.image); Bundle bundle = this.getIntent().getExtras(); String value = bundle.getString("val1"); int value2 = bundle.getInt("val2"); String classDescription = bundle.getString("val4"); textView.setText(value); textView2.setText(classDescription); imageView.setImageResource(value2); editText = (EditText)findViewById(R.id.editText1); button = (Button)findViewById(R.id.button2); //Toast.makeText(this,value,Toast.LENGTH_SHORT).show(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String text1 = ""; Bundle bundle = new Bundle(); bundle.putString("xyz1",editText.getText().toString()); Intent returnIntent = new Intent(view.getContext(),MainActivity.class); returnIntent.putExtras(bundle); view.getContext().startActivity(returnIntent); } }); } }
2,190
0.676712
0.668037
70
30.285715
23.350218
87
false
false
0
0
0
0
0
0
0.671429
false
false
8
ba816d71e6fd6f893e2df4f684711e8824934a08
14,516,989,466,037
82bda3ed7dfe2ca722e90680fd396935c2b7a49d
/app-meipai/src/main/java/e/c/d/m/e/d/h.java
2ff142cf2e0ec2c1978cd7067c40a82f08321dcd
[]
no_license
cvdnn/PanoramaApp
https://github.com/cvdnn/PanoramaApp
86f8cf36d285af08ba15fb32348423af7f0b7465
dd6bbe0987a46f0b4cfb90697b38f37f5ad47cfc
refs/heads/master
2023-03-03T11:15:40.350000
2021-01-29T09:14:06
2021-01-29T09:14:06
332,968,433
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package e.c.d.m.e.d; import e.c.d.m.a.e; import java.io.File; /* compiled from: SpinPreviewContract */ public interface h extends e<g> { void a(File[] fileArr); void b(String str, String str2); void c(String str); void j(boolean z); }
UTF-8
Java
256
java
h.java
Java
[]
null
[]
package e.c.d.m.e.d; import e.c.d.m.a.e; import java.io.File; /* compiled from: SpinPreviewContract */ public interface h extends e<g> { void a(File[] fileArr); void b(String str, String str2); void c(String str); void j(boolean z); }
256
0.640625
0.636719
15
16.066668
14.181992
40
false
false
0
0
0
0
0
0
0.533333
false
false
8
897a712e8a5b27e0a72fc256d1072d46ac90372c
21,320,217,691,051
4ff8594c1eb441cb9c30785a5e16b2d2e95cb6cd
/Boop-client/src/main/Display.java
dc079164b9667f7ccba6023ce4457a111af65805
[]
no_license
PlankASS/Boop
https://github.com/PlankASS/Boop
ce2453e9ab7e4776f627fe2c5b8902fed280da50
a498605a6026c4931f5aac5ad16bceb7192e48fc
refs/heads/master
2020-06-18T21:14:52.439000
2019-10-19T18:51:52
2019-10-19T18:51:52
196,450,517
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package main; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import physics.Vector; public class Display extends Canvas{ /** * */ private static final long serialVersionUID = 1966192346343139802L; // Create an ArrayList which holds details of all entities which need to be rendered: private ArrayList<float[]> ballData = new ArrayList<float[]>(10000); public ArrayList<Integer> freeIDs = new ArrayList<Integer>(); private DecimalFormat df = new DecimalFormat("#.##"); JFrame frame; public Vector pos = new Vector(0f,0f); //Position of the client on screen. public float width = 1f; //Width of client's screen on server space. public float height = 0.6f;//Height of client's screen on server space. public float k = 1000f;//Ratio of server space to client's screen space. public Display() { // Add placeholder entities to the entities ArrayList: for (int i = 0; i < 10000; i++) { ballData.add(new float[] {-1.0f}); } frame = new JFrame("Boop-client"); // Create a window. // Set the window size to 1000x600 Dimension d = new Dimension(1000, 600); frame.setPreferredSize(d); frame.setMaximumSize(d); frame.setMinimumSize(d); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make the program stop when the window is closed. frame.setResizable(true); // Make the window resizable. frame.setLocationRelativeTo(null); // Centre the window on the screen. frame.setVisible(false); // Make the window visible. frame.setMinimumSize(new Dimension(0,0)); // Set the minimum size of the window to 0, 0. frame.add(this); // Add the canvas to the frame. df.setRoundingMode(RoundingMode.CEILING); } public Display(Menu menu) { MenuComponents(menu); MenuWindow(); } public void render() { BufferStrategy bufS = getBufferStrategy(); if(bufS == null){ createBufferStrategy(3); return; } Graphics g = bufS.getDrawGraphics(); // Draw a black rectangle filling the window: g.setColor(Color.BLACK); g.fillRect(0, 0, 1000, 600); //Render ping g.setColor(Color.WHITE); g.drawString("FPS: " + ClientMain.FPS, 0, 20); g.drawString("Ping: " + df.format(ClientMain.ping) + " ms", 0, 40); // Iterate through each entity: for (float[] ball: ballData) { // If the entity's type is a red ball: if (ball[0] == 0.0f) { g.setColor(Color.RED); g.fillOval((int) ((ball[1] - ball[7] - pos.x)*k), (int) ((ball[2] - ball[7] - pos.y)*k), (int) (2*ball[7]*k), (int)(2*ball[7]*k)); } // If the entity's type is a free ball: if (ball[0] == 1.0f) { g.setColor(Color.WHITE); g.fillOval((int) ((ball[1] - ball[7] - pos.x)*k), (int) ((ball[2] - ball[7] - pos.y)*k), (int) (2*ball[7]*k), (int)(2*ball[7]*k)); } } g.dispose(); bufS.show(); } public void renderStartMenu() { } /** * Updates the properties of an entity * @param id The index of the entity (its ID). * @param type The type of entity. * @param rgb The colour. * @param x The x position. * @param y The y position. * @param w The width. * @param h The height. */ public void updateEntity(int id, int type, int rgb, int x, int y, int w, int h) { //Sets the values of a specific entity (where the 'id' is its index). //ballData.set(id, new int[] {type, rgb, x, y, w, h}); } public void updateBall(int id, int type, float x, float y, float xv, float yv, float xa, float ya, float radius, float mass) { if (type == -1) { freeIDs.add(id); } ballData.set(id, new float[] {type, x, y, xv, yv, xa, ya, radius, mass}); } public void updateBall(int id, int type, float x, float y, float xv, float yv, float xa, float ya, float radius, float mass, float charge, float mag, float bounciness) { if (type == -1) { freeIDs.add(id); } ballData.set(id, new float[] {type, x, y, xv, yv, xa, ya, radius, mass, charge, mag, bounciness}); } public void close() { frame.dispose(); } public JButton Start; public JComboBox<String> HostIP, Username; private void MenuComponents(Menu menu) { Start = new JButton("Start"); Start.setBounds(400, 300, 150, 50); Start.addActionListener(menu); Start.setFocusable(false); HostIP = new JComboBox<String>(); HostIP.setToolTipText("The Host IP Address"); HostIP.setBounds(500, 200, 150, 50); HostIP.addItem("127.0.0.1"); HostIP.addItem("82.16.12.59"); HostIP.setSelectedIndex(0); HostIP.setEditable(true); Username = new JComboBox<String>(); Username.setToolTipText("Your Username"); Username.setBounds(300, 200, 150, 50); Username.addItem("Test"); Username.setSelectedIndex(0); Username.setEditable(true); } private void MenuWindow() { frame = new JFrame("Boop Main-Menu"); frame.setSize(1000, 600); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); frame.add(Start); frame.add(Username); frame.add(HostIP); frame.setVisible(true); } }
UTF-8
Java
5,680
java
Display.java
Java
[ { "context": ".setBounds(500, 200, 150, 50);\r\n\t\tHostIP.addItem(\"127.0.0.1\");\r\n\t\tHostIP.addItem(\"82.16.12.59\");\r\n\t\tHostIP.se", "end": 4987, "score": 0.9997330904006958, "start": 4978, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "\t\tHostIP.addItem(\"127.0.0.1\");\r\n\t\tHostIP.addItem(\"82.16.12.59\");\r\n\t\tHostIP.setSelectedIndex(0);\r\n\t\tHostIP.setEd", "end": 5021, "score": 0.9996540546417236, "start": 5010, "tag": "IP_ADDRESS", "value": "82.16.12.59" }, { "context": " JComboBox<String>();\r\n\t\tUsername.setToolTipText(\"Your Username\");\r\n\t\tUsername.setBounds(300, 200, 150, 50);\r\n\t\tU", "end": 5169, "score": 0.994112491607666, "start": 5156, "tag": "USERNAME", "value": "Your Username" }, { "context": "etBounds(300, 200, 150, 50);\r\n\t\tUsername.addItem(\"Test\");\r\n\t\tUsername.setSelectedIndex(0);\r\n\t\tUsername.s", "end": 5240, "score": 0.9982467889785767, "start": 5236, "tag": "USERNAME", "value": "Test" } ]
null
[]
package main; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import physics.Vector; public class Display extends Canvas{ /** * */ private static final long serialVersionUID = 1966192346343139802L; // Create an ArrayList which holds details of all entities which need to be rendered: private ArrayList<float[]> ballData = new ArrayList<float[]>(10000); public ArrayList<Integer> freeIDs = new ArrayList<Integer>(); private DecimalFormat df = new DecimalFormat("#.##"); JFrame frame; public Vector pos = new Vector(0f,0f); //Position of the client on screen. public float width = 1f; //Width of client's screen on server space. public float height = 0.6f;//Height of client's screen on server space. public float k = 1000f;//Ratio of server space to client's screen space. public Display() { // Add placeholder entities to the entities ArrayList: for (int i = 0; i < 10000; i++) { ballData.add(new float[] {-1.0f}); } frame = new JFrame("Boop-client"); // Create a window. // Set the window size to 1000x600 Dimension d = new Dimension(1000, 600); frame.setPreferredSize(d); frame.setMaximumSize(d); frame.setMinimumSize(d); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Make the program stop when the window is closed. frame.setResizable(true); // Make the window resizable. frame.setLocationRelativeTo(null); // Centre the window on the screen. frame.setVisible(false); // Make the window visible. frame.setMinimumSize(new Dimension(0,0)); // Set the minimum size of the window to 0, 0. frame.add(this); // Add the canvas to the frame. df.setRoundingMode(RoundingMode.CEILING); } public Display(Menu menu) { MenuComponents(menu); MenuWindow(); } public void render() { BufferStrategy bufS = getBufferStrategy(); if(bufS == null){ createBufferStrategy(3); return; } Graphics g = bufS.getDrawGraphics(); // Draw a black rectangle filling the window: g.setColor(Color.BLACK); g.fillRect(0, 0, 1000, 600); //Render ping g.setColor(Color.WHITE); g.drawString("FPS: " + ClientMain.FPS, 0, 20); g.drawString("Ping: " + df.format(ClientMain.ping) + " ms", 0, 40); // Iterate through each entity: for (float[] ball: ballData) { // If the entity's type is a red ball: if (ball[0] == 0.0f) { g.setColor(Color.RED); g.fillOval((int) ((ball[1] - ball[7] - pos.x)*k), (int) ((ball[2] - ball[7] - pos.y)*k), (int) (2*ball[7]*k), (int)(2*ball[7]*k)); } // If the entity's type is a free ball: if (ball[0] == 1.0f) { g.setColor(Color.WHITE); g.fillOval((int) ((ball[1] - ball[7] - pos.x)*k), (int) ((ball[2] - ball[7] - pos.y)*k), (int) (2*ball[7]*k), (int)(2*ball[7]*k)); } } g.dispose(); bufS.show(); } public void renderStartMenu() { } /** * Updates the properties of an entity * @param id The index of the entity (its ID). * @param type The type of entity. * @param rgb The colour. * @param x The x position. * @param y The y position. * @param w The width. * @param h The height. */ public void updateEntity(int id, int type, int rgb, int x, int y, int w, int h) { //Sets the values of a specific entity (where the 'id' is its index). //ballData.set(id, new int[] {type, rgb, x, y, w, h}); } public void updateBall(int id, int type, float x, float y, float xv, float yv, float xa, float ya, float radius, float mass) { if (type == -1) { freeIDs.add(id); } ballData.set(id, new float[] {type, x, y, xv, yv, xa, ya, radius, mass}); } public void updateBall(int id, int type, float x, float y, float xv, float yv, float xa, float ya, float radius, float mass, float charge, float mag, float bounciness) { if (type == -1) { freeIDs.add(id); } ballData.set(id, new float[] {type, x, y, xv, yv, xa, ya, radius, mass, charge, mag, bounciness}); } public void close() { frame.dispose(); } public JButton Start; public JComboBox<String> HostIP, Username; private void MenuComponents(Menu menu) { Start = new JButton("Start"); Start.setBounds(400, 300, 150, 50); Start.addActionListener(menu); Start.setFocusable(false); HostIP = new JComboBox<String>(); HostIP.setToolTipText("The Host IP Address"); HostIP.setBounds(500, 200, 150, 50); HostIP.addItem("127.0.0.1"); HostIP.addItem("172.16.31.10"); HostIP.setSelectedIndex(0); HostIP.setEditable(true); Username = new JComboBox<String>(); Username.setToolTipText("Your Username"); Username.setBounds(300, 200, 150, 50); Username.addItem("Test"); Username.setSelectedIndex(0); Username.setEditable(true); } private void MenuWindow() { frame = new JFrame("Boop Main-Menu"); frame.setSize(1000, 600); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(null); frame.add(Start); frame.add(Username); frame.add(HostIP); frame.setVisible(true); } }
5,681
0.619718
0.59243
191
27.73822
26.442955
140
false
false
0
0
0
0
0
0
2.120419
false
false
8
2935594b23746e1c441709e328d09771a45c109e
14,362,370,680,872
fc9a1a54c9e26bbe8df0b16d080837911a1c0dbc
/weixin/src/com/wt/util/MenuUtil.java
ecc23ff93a7437288629c500e25add3a5537c247
[]
no_license
wtt40122/WeiXin
https://github.com/wtt40122/WeiXin
febe39f5a36a08acf8e6f4a290ff859c54e901b6
6b39b2f33adbec3aca024c5bb2152d1a08ca1e4c
refs/heads/master
2023-02-15T19:58:02.273000
2018-09-19T12:08:31
2018-09-19T12:08:31
138,586,224
0
0
null
false
2023-09-12T11:08:01
2018-06-25T11:32:40
2023-09-11T10:50:32
2023-09-12T11:07:59
7,560
4
0
0
Java
false
false
package com.wt.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.wt.common.CommonUtil; import com.wt.po.menu.Button; import com.wt.po.menu.ClickButton; import com.wt.po.menu.ComplexButton; import com.wt.po.menu.Menu; import com.wt.po.menu.ViewButton; import net.sf.json.JSONObject; /** * @Description:自定义菜单工具类 * @author wt * @date 2018年5月31日 */ public class MenuUtil { private static Logger log = LoggerFactory.getLogger(MenuUtil.class); //菜单创建 private final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?" + "access_token=ACCESS_TOKEN"; //菜单查询 private final static String menu_get_url = "https://api.weixin.qq.com/cgi-bin/menu/get?" + "access_token=ACCESS_TOKEN"; //删除菜单 private final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?" + "access_token=ACCESS_TOKEN"; /** * 创建菜单 * @param menu * @param accessToken * @return */ public static boolean createMenu(Menu menu,String accessToken){ boolean result = false; String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); String jsonMenu = JSONObject.fromObject(menu).toString(); //发送http post请求创建菜单 JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonMenu); if(null != jsonObject){ int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); if(0 == errorCode){ result = true; }else{ result = false; log.error("创建菜单失败 errcode:{} errmsg:{}",errorCode,errorMsg); } } return result; } /** * 查询菜单 * @param accessToken * @return */ public static String getMenu(String accessToken){ String result = null; String requestUrl = menu_get_url.replace("ACCESS_TOKEN", accessToken); //发送get请求查询菜单 JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){ result = jsonObject.toString(); } return result; } /** * 删除失败 * @param accessToken * @return */ public static boolean deleteMenu(String accessToken){ boolean result = false; String requestUrl = menu_delete_url.replace("ACCESS_TOKEN", accessToken); JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){ int errorcode = jsonObject.getInt("errcode"); String errormsg = jsonObject.getString("errmsgs"); if(0 == errorcode){ result = true; }else{ result = false; log.error("删除菜单失败 errcode:{} errmsg:{}",errorcode,errormsg); } } return result; } public static String initMenu(){ ClickButton cBtn1 = new ClickButton(); cBtn1.setName("历史今日"); cBtn1.setType("click"); cBtn1.setKey("V1001_TODAY_HISTORY"); ViewButton vBtn1 = new ViewButton(); vBtn1.setName("英雄人物"); vBtn1.setType("view"); vBtn1.setUrl("http://www.qstheory.cn/politics/2015-09/29/c_1116700869.htm"); ClickButton cBtn2 = new ClickButton(); cBtn2.setName("诗书之家"); cBtn2.setType("click"); cBtn2.setKey("V1001_HOME_POEM"); ClickButton cBtn3 = new ClickButton(); cBtn3.setName("小说家"); cBtn3.setType("click"); cBtn3.setKey("V1001_HOME_NOVEL"); //符合按钮报货两个click类型的按钮 ComplexButton complexButton = new ComplexButton(); complexButton.setName("精彩之家"); complexButton.setSub_button(new Button[]{cBtn2,cBtn3}); //创建菜单对象 Menu menu = new Menu(); menu.setButton(new Button[]{cBtn1,vBtn1,complexButton}); String jsonMenu = JSONObject.fromObject(menu).toString(); System.out.println(jsonMenu); return jsonMenu; } }
UTF-8
Java
3,711
java
MenuUtil.java
Java
[ { "context": "ONObject;\n\n/**\n * @Description:自定义菜单工具类\n * @author wt\n * @date 2018年5月31日\n */\npublic class MenuUtil {\n\t", "end": 353, "score": 0.9952624440193176, "start": 351, "tag": "USERNAME", "value": "wt" }, { "context": "历史今日\");\n\t\tcBtn1.setType(\"click\");\n\t\tcBtn1.setKey(\"V1001_TODAY_HISTORY\");\n\t\t\n\t\tViewButton vBtn1 = new ViewButton();\n\t\tvB", "end": 2686, "score": 0.9751186370849609, "start": 2667, "tag": "KEY", "value": "V1001_TODAY_HISTORY" }, { "context": "诗书之家\");\n\t\tcBtn2.setType(\"click\");\n\t\tcBtn2.setKey(\"V1001_HOME_POEM\");\n\t\t\n\t\tClickButton cBtn3 = new ClickButton();\n\t\t", "end": 2987, "score": 0.9965524673461914, "start": 2972, "tag": "KEY", "value": "V1001_HOME_POEM" }, { "context": "\"小说家\");\n\t\tcBtn3.setType(\"click\");\n\t\tcBtn3.setKey(\"V1001_HOME_NOVEL\");\n\t\t\n\t\t//符合按钮报货两个click类型的按钮\n\t\tComplexButton comp", "end": 3117, "score": 0.9994492530822754, "start": 3101, "tag": "KEY", "value": "V1001_HOME_NOVEL" } ]
null
[]
package com.wt.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.wt.common.CommonUtil; import com.wt.po.menu.Button; import com.wt.po.menu.ClickButton; import com.wt.po.menu.ComplexButton; import com.wt.po.menu.Menu; import com.wt.po.menu.ViewButton; import net.sf.json.JSONObject; /** * @Description:自定义菜单工具类 * @author wt * @date 2018年5月31日 */ public class MenuUtil { private static Logger log = LoggerFactory.getLogger(MenuUtil.class); //菜单创建 private final static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?" + "access_token=ACCESS_TOKEN"; //菜单查询 private final static String menu_get_url = "https://api.weixin.qq.com/cgi-bin/menu/get?" + "access_token=ACCESS_TOKEN"; //删除菜单 private final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?" + "access_token=ACCESS_TOKEN"; /** * 创建菜单 * @param menu * @param accessToken * @return */ public static boolean createMenu(Menu menu,String accessToken){ boolean result = false; String url = menu_create_url.replace("ACCESS_TOKEN", accessToken); String jsonMenu = JSONObject.fromObject(menu).toString(); //发送http post请求创建菜单 JSONObject jsonObject = CommonUtil.httpsRequest(url, "POST", jsonMenu); if(null != jsonObject){ int errorCode = jsonObject.getInt("errcode"); String errorMsg = jsonObject.getString("errmsg"); if(0 == errorCode){ result = true; }else{ result = false; log.error("创建菜单失败 errcode:{} errmsg:{}",errorCode,errorMsg); } } return result; } /** * 查询菜单 * @param accessToken * @return */ public static String getMenu(String accessToken){ String result = null; String requestUrl = menu_get_url.replace("ACCESS_TOKEN", accessToken); //发送get请求查询菜单 JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){ result = jsonObject.toString(); } return result; } /** * 删除失败 * @param accessToken * @return */ public static boolean deleteMenu(String accessToken){ boolean result = false; String requestUrl = menu_delete_url.replace("ACCESS_TOKEN", accessToken); JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null); if(null != jsonObject){ int errorcode = jsonObject.getInt("errcode"); String errormsg = jsonObject.getString("errmsgs"); if(0 == errorcode){ result = true; }else{ result = false; log.error("删除菜单失败 errcode:{} errmsg:{}",errorcode,errormsg); } } return result; } public static String initMenu(){ ClickButton cBtn1 = new ClickButton(); cBtn1.setName("历史今日"); cBtn1.setType("click"); cBtn1.setKey("V1001_TODAY_HISTORY"); ViewButton vBtn1 = new ViewButton(); vBtn1.setName("英雄人物"); vBtn1.setType("view"); vBtn1.setUrl("http://www.qstheory.cn/politics/2015-09/29/c_1116700869.htm"); ClickButton cBtn2 = new ClickButton(); cBtn2.setName("诗书之家"); cBtn2.setType("click"); cBtn2.setKey("V1001_HOME_POEM"); ClickButton cBtn3 = new ClickButton(); cBtn3.setName("小说家"); cBtn3.setType("click"); cBtn3.setKey("V1001_HOME_NOVEL"); //符合按钮报货两个click类型的按钮 ComplexButton complexButton = new ComplexButton(); complexButton.setName("精彩之家"); complexButton.setSub_button(new Button[]{cBtn2,cBtn3}); //创建菜单对象 Menu menu = new Menu(); menu.setButton(new Button[]{cBtn1,vBtn1,complexButton}); String jsonMenu = JSONObject.fromObject(menu).toString(); System.out.println(jsonMenu); return jsonMenu; } }
3,711
0.697635
0.680251
127
26.629921
23.04969
95
false
false
0
0
0
0
0
0
2.244094
false
false
8
2317ece4da8586b7156b2fb483f7f161888a61ad
17,317,308,153,443
04f43f08dd8530a534ba5b1642ed21498a8f5ea8
/QuestProject/src/MapScanner.java
66cca544cb459cba65a1e1d79a1314f49ad710ce
[]
no_license
archanaaniyan1341/Test
https://github.com/archanaaniyan1341/Test
84fde7109b3bd99e6f70ce3551045f382abc2bc4
db01ba16e86262c5c9c816045327777326b5ad5f
refs/heads/master
2023-09-01T18:22:56.856000
2021-09-22T14:45:14
2021-09-22T14:45:14
328,874,629
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.HashMap; import java.util.Scanner; import java.io.*; public class MapScanner{ public static void main(String[] args) throws IOException{ HashMap studentRecord = new HashMap(); String name; String time; Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename to read from: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); while (inputFile.hasNext()) { String line=inputFile.nextLine(); if(line.contains("INSERT")) { String words[]=line.trim().split(" "); name=words[5].replace(',', ' '); time=words[1]; studentRecord.put(name, time); } } inputFile.close(); System.out.println(studentRecord.values()); System.out.println(studentRecord.keySet()); System.out.print("Enter key: "); name = keyboard.next(); if (studentRecord.containsKey(name)){ time = (String) studentRecord.get(name); System.out.println(name + "\t" + time + " found"); } else System.out.println(name+ " not found"); } }
UTF-8
Java
1,682
java
MapScanner.java
Java
[]
null
[]
import java.util.HashMap; import java.util.Scanner; import java.io.*; public class MapScanner{ public static void main(String[] args) throws IOException{ HashMap studentRecord = new HashMap(); String name; String time; Scanner keyboard = new Scanner(System.in); System.out.print("Enter the filename to read from: "); String filename = keyboard.nextLine(); File file = new File(filename); Scanner inputFile = new Scanner(file); while (inputFile.hasNext()) { String line=inputFile.nextLine(); if(line.contains("INSERT")) { String words[]=line.trim().split(" "); name=words[5].replace(',', ' '); time=words[1]; studentRecord.put(name, time); } } inputFile.close(); System.out.println(studentRecord.values()); System.out.println(studentRecord.keySet()); System.out.print("Enter key: "); name = keyboard.next(); if (studentRecord.containsKey(name)){ time = (String) studentRecord.get(name); System.out.println(name + "\t" + time + " found"); } else System.out.println(name+ " not found"); } }
1,682
0.425089
0.4239
44
36.18182
21.596794
76
false
false
0
0
0
0
0
0
0.704545
false
false
8
0a53bb8cc74b09c58b6453d0a627cc02785942a4
3,049,426,796,572
447520f40e82a060368a0802a391697bc00be96f
/apks/malware/app79/source/com/hzpz/pay/jsoup/parser/TokenQueue.java
14095bf590de070c717f71e9912c8adc4a35d5b2
[ "Apache-2.0" ]
permissive
iantal/AndroidPermissions
https://github.com/iantal/AndroidPermissions
7f3343a9c29d82dbcd4ecd98b3a50ddf8d179465
d623b732734243590b5f004d167e542e2e2ae249
refs/heads/master
2023-07-19T01:29:26.689000
2019-09-30T19:01:42
2019-09-30T19:01:42
107,239,248
0
0
Apache-2.0
false
2023-07-16T07:41:38
2017-10-17T08:22:57
2019-09-30T19:01:44
2023-07-16T07:41:38
1,616,319
0
0
1
null
false
false
package com.hzpz.pay.jsoup.parser; import com.hzpz.pay.jsoup.helper.StringUtil; import com.hzpz.pay.jsoup.helper.Validate; public class TokenQueue { private String a; private int b = 0; public TokenQueue(String paramString) { Validate.a(paramString); this.a = paramString; } public static String f(String paramString) { int i = 0; StringBuilder localStringBuilder = new StringBuilder(); paramString = paramString.toCharArray(); int k = paramString.length; int j = 0; if (i < k) { char c = paramString[i]; if (c == '\\') { if ((j != 0) && (j == 92)) { localStringBuilder.append(c); } } for (;;) { i += 1; j = c; break; localStringBuilder.append(c); } } return localStringBuilder.toString(); } private int i() { return this.a.length() - this.b; } public String a(char paramChar1, char paramChar2) { int i1 = 0; int i2 = 0; int i = -1; int j = -1; int n = i; int m = j; Character localCharacter; int k; if (!a()) { localCharacter = Character.valueOf(d()); if (i1 != 0) { k = i2; m = j; if (i1 == 92) {} } else { if (!localCharacter.equals(Character.valueOf(paramChar1))) { break label158; } n = i2 + 1; k = n; m = j; if (j == -1) { m = this.b; k = n; } } } for (;;) { n = i; if (k > 0) { n = i; if (i1 != 0) { n = this.b; } } i1 = localCharacter.charValue(); i2 = k; i = n; j = m; if (k > 0) { break; } if (n < 0) { break label191; } return this.a.substring(m, n); label158: k = i2; m = j; if (localCharacter.equals(Character.valueOf(paramChar2))) { k = i2 - 1; m = j; } } label191: return ""; } public boolean a() { return i() == 0; } public boolean a(String paramString) { return this.a.regionMatches(true, this.b, paramString, 0, paramString.length()); } public boolean a(char... paramVarArgs) { if (a()) {} for (;;) { return false; int j = paramVarArgs.length; int i = 0; while (i < j) { int k = paramVarArgs[i]; if (this.a.charAt(this.b) == k) { return true; } i += 1; } } } public boolean a(String... paramVarArgs) { boolean bool2 = false; int j = paramVarArgs.length; int i = 0; for (;;) { boolean bool1 = bool2; if (i < j) { if (a(paramVarArgs[i])) { bool1 = true; } } else { return bool1; } i += 1; } } public String b(String... paramVarArgs) { int i = this.b; while ((!a()) && (!a(paramVarArgs))) { this.b += 1; } return this.a.substring(i, this.b); } public boolean b() { return (!a()) && (StringUtil.b(this.a.charAt(this.b))); } public boolean b(String paramString) { if (a(paramString)) { this.b += paramString.length(); return true; } return false; } public void c(String paramString) { if (!a(paramString)) { throw new IllegalStateException("Queue did not match expected sequence"); } int i = paramString.length(); if (i > i()) { throw new IllegalStateException("Queue not long enough to consume sequence"); } this.b = (i + this.b); } public boolean c() { return (!a()) && (Character.isLetterOrDigit(this.a.charAt(this.b))); } public char d() { String str = this.a; int i = this.b; this.b = (i + 1); return str.charAt(i); } public String d(String paramString) { int i = this.a.indexOf(paramString, this.b); if (i != -1) { paramString = this.a.substring(this.b, i); this.b += paramString.length(); return paramString; } return h(); } public String e(String paramString) { String str = d(paramString); b(paramString); return str; } public boolean e() { for (boolean bool = false; b(); bool = true) { this.b += 1; } return bool; } public String f() { int i = this.b; while (!a()) { if (!c()) { if (!a(new char[] { 124, 95, 45 })) { break; } } this.b += 1; } return this.a.substring(i, this.b); } public String g() { int i = this.b; while (!a()) { if (!c()) { if (!a(new char[] { 45, 95 })) { break; } } this.b += 1; } return this.a.substring(i, this.b); } public String h() { String str = this.a.substring(this.b, this.a.length()); this.b = this.a.length(); return str; } public String toString() { return this.a.substring(this.b); } }
UTF-8
Java
5,110
java
TokenQueue.java
Java
[]
null
[]
package com.hzpz.pay.jsoup.parser; import com.hzpz.pay.jsoup.helper.StringUtil; import com.hzpz.pay.jsoup.helper.Validate; public class TokenQueue { private String a; private int b = 0; public TokenQueue(String paramString) { Validate.a(paramString); this.a = paramString; } public static String f(String paramString) { int i = 0; StringBuilder localStringBuilder = new StringBuilder(); paramString = paramString.toCharArray(); int k = paramString.length; int j = 0; if (i < k) { char c = paramString[i]; if (c == '\\') { if ((j != 0) && (j == 92)) { localStringBuilder.append(c); } } for (;;) { i += 1; j = c; break; localStringBuilder.append(c); } } return localStringBuilder.toString(); } private int i() { return this.a.length() - this.b; } public String a(char paramChar1, char paramChar2) { int i1 = 0; int i2 = 0; int i = -1; int j = -1; int n = i; int m = j; Character localCharacter; int k; if (!a()) { localCharacter = Character.valueOf(d()); if (i1 != 0) { k = i2; m = j; if (i1 == 92) {} } else { if (!localCharacter.equals(Character.valueOf(paramChar1))) { break label158; } n = i2 + 1; k = n; m = j; if (j == -1) { m = this.b; k = n; } } } for (;;) { n = i; if (k > 0) { n = i; if (i1 != 0) { n = this.b; } } i1 = localCharacter.charValue(); i2 = k; i = n; j = m; if (k > 0) { break; } if (n < 0) { break label191; } return this.a.substring(m, n); label158: k = i2; m = j; if (localCharacter.equals(Character.valueOf(paramChar2))) { k = i2 - 1; m = j; } } label191: return ""; } public boolean a() { return i() == 0; } public boolean a(String paramString) { return this.a.regionMatches(true, this.b, paramString, 0, paramString.length()); } public boolean a(char... paramVarArgs) { if (a()) {} for (;;) { return false; int j = paramVarArgs.length; int i = 0; while (i < j) { int k = paramVarArgs[i]; if (this.a.charAt(this.b) == k) { return true; } i += 1; } } } public boolean a(String... paramVarArgs) { boolean bool2 = false; int j = paramVarArgs.length; int i = 0; for (;;) { boolean bool1 = bool2; if (i < j) { if (a(paramVarArgs[i])) { bool1 = true; } } else { return bool1; } i += 1; } } public String b(String... paramVarArgs) { int i = this.b; while ((!a()) && (!a(paramVarArgs))) { this.b += 1; } return this.a.substring(i, this.b); } public boolean b() { return (!a()) && (StringUtil.b(this.a.charAt(this.b))); } public boolean b(String paramString) { if (a(paramString)) { this.b += paramString.length(); return true; } return false; } public void c(String paramString) { if (!a(paramString)) { throw new IllegalStateException("Queue did not match expected sequence"); } int i = paramString.length(); if (i > i()) { throw new IllegalStateException("Queue not long enough to consume sequence"); } this.b = (i + this.b); } public boolean c() { return (!a()) && (Character.isLetterOrDigit(this.a.charAt(this.b))); } public char d() { String str = this.a; int i = this.b; this.b = (i + 1); return str.charAt(i); } public String d(String paramString) { int i = this.a.indexOf(paramString, this.b); if (i != -1) { paramString = this.a.substring(this.b, i); this.b += paramString.length(); return paramString; } return h(); } public String e(String paramString) { String str = d(paramString); b(paramString); return str; } public boolean e() { for (boolean bool = false; b(); bool = true) { this.b += 1; } return bool; } public String f() { int i = this.b; while (!a()) { if (!c()) { if (!a(new char[] { 124, 95, 45 })) { break; } } this.b += 1; } return this.a.substring(i, this.b); } public String g() { int i = this.b; while (!a()) { if (!c()) { if (!a(new char[] { 45, 95 })) { break; } } this.b += 1; } return this.a.substring(i, this.b); } public String h() { String str = this.a.substring(this.b, this.a.length()); this.b = this.a.length(); return str; } public String toString() { return this.a.substring(this.b); } }
5,110
0.476517
0.461644
283
17.056538
15.726134
84
false
false
0
0
0
0
0
0
0.459364
false
false
8
35efdb35ebace10be5c519d94054bdb0b783f0fb
26,018,911,895,891
c4e6eca253e8de2944231767361f3c341607d3ce
/.svn/pristine/35/35efdb35ebace10be5c519d94054bdb0b783f0fb.svn-base
12913dc7f9521d8033383ca715db0eba3e60d3b9
[]
no_license
jordengerovac/virtual-unix-machine
https://github.com/jordengerovac/virtual-unix-machine
f916d1e9595e6748fd0817789afeb33a6d5d2757
709e6c9830b7c682f40fbc70647193d1ab565325
refs/heads/master
2021-05-02T18:28:22.765000
2021-03-06T21:45:28
2021-03-06T21:45:28
120,664,121
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package test; import static org.junit.Assert.*; import javax.swing.tree.DefaultMutableTreeNode; import org.junit.Test; public class CommandTest { @SuppressWarnings("deprecation") @Test public void testPathToArray() { Command test = new Command(); String[] array; // path will NEVER start from root // empty path array = new String[] {""}; assertEquals(array, test.pathToArray("")); // path with one dir array = new String[] {"a"}; assertEquals(array, test.pathToArray("a")); // path with two dirs array = new String[] {"a", "b"}; assertEquals(array, test.pathToArray("a/b")); } public void testArrayToPath() { Command test = new Command(); String[] array; // empty array array = new String[] {""}; assertEquals("/", test.arrayToPath(array)); // array with one dir array = new String[] {"a"}; assertEquals("/a", test.arrayToPath(array)); // array with two dirs array = new String[] {"a", "b"}; assertEquals("/a/b", test.arrayToPath(array)); } public void testGetParentNode() { Command test = new Command(); DefaultMutableTreeNode parentNode; parentNode = test.getParentNode("/"); // can only test from root without running JShell assertEquals(null, parentNode); // and "this directory" of root parentNode = test.getParentNode("."); assertEquals(null, parentNode); } public void testGetWholePath() { Command test = new Command(); // can only test root assertEquals("/", test.getWholePath("/")); // and "this directory" of root assertEquals("/", test.getWholePath(".")); } public void testGetNode() { Command test = new Command(); // root assertEquals(JShell.os.getRoot(), test.getNode("/")); assertEquals(JShell.os.getRoot(), test.getNode(".")); // null parent assertEquals(null, test.getNode("..")); } public void testChildExists() { Command test = new Command(); // no children assertFalse(test.childExists(JShell.os.getRoot(), "a")); } public void testBuildPath() { Command test = new Command(); // root path assertEquals("/", test.buildPath(JShell.os.getRoot())); } }
UTF-8
Java
2,206
35efdb35ebace10be5c519d94054bdb0b783f0fb.svn-base
Java
[]
null
[]
package test; import static org.junit.Assert.*; import javax.swing.tree.DefaultMutableTreeNode; import org.junit.Test; public class CommandTest { @SuppressWarnings("deprecation") @Test public void testPathToArray() { Command test = new Command(); String[] array; // path will NEVER start from root // empty path array = new String[] {""}; assertEquals(array, test.pathToArray("")); // path with one dir array = new String[] {"a"}; assertEquals(array, test.pathToArray("a")); // path with two dirs array = new String[] {"a", "b"}; assertEquals(array, test.pathToArray("a/b")); } public void testArrayToPath() { Command test = new Command(); String[] array; // empty array array = new String[] {""}; assertEquals("/", test.arrayToPath(array)); // array with one dir array = new String[] {"a"}; assertEquals("/a", test.arrayToPath(array)); // array with two dirs array = new String[] {"a", "b"}; assertEquals("/a/b", test.arrayToPath(array)); } public void testGetParentNode() { Command test = new Command(); DefaultMutableTreeNode parentNode; parentNode = test.getParentNode("/"); // can only test from root without running JShell assertEquals(null, parentNode); // and "this directory" of root parentNode = test.getParentNode("."); assertEquals(null, parentNode); } public void testGetWholePath() { Command test = new Command(); // can only test root assertEquals("/", test.getWholePath("/")); // and "this directory" of root assertEquals("/", test.getWholePath(".")); } public void testGetNode() { Command test = new Command(); // root assertEquals(JShell.os.getRoot(), test.getNode("/")); assertEquals(JShell.os.getRoot(), test.getNode(".")); // null parent assertEquals(null, test.getNode("..")); } public void testChildExists() { Command test = new Command(); // no children assertFalse(test.childExists(JShell.os.getRoot(), "a")); } public void testBuildPath() { Command test = new Command(); // root path assertEquals("/", test.buildPath(JShell.os.getRoot())); } }
2,206
0.63146
0.63146
82
25.902439
17.499554
60
false
false
0
0
0
0
0
0
0.658537
false
false
8
6ad3574587dbc80ba4db9281d58e06307d8ca9d5
2,319,282,375,745
cb7df8f66ab8e126fa568718fc9f2f208f4bfaaf
/acceptance-tests/src/main/java/io/blueocean/ath/pages/blue/PullRequestsPage.java
6300fc275469a6befb265734c4ac9f8fcaf06cc3
[ "MIT" ]
permissive
jenkinsci/blueocean-plugin
https://github.com/jenkinsci/blueocean-plugin
ef2da70d47e966b93497c206cba16d63a6e26907
cffed37074f03ad3be4422d372cb0bb5db5d6f65
refs/heads/master
2023-09-01T08:13:23.781000
2023-08-30T05:12:43
2023-08-30T05:12:43
50,250,915
3,088
723
MIT
false
2023-09-12T21:05:01
2016-01-23T18:02:45
2023-09-12T20:49:13
2023-09-12T21:05:00
31,398
2,858
542
43
Java
false
false
package io.blueocean.ath.pages.blue; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import io.blueocean.ath.WaitUtil; import io.blueocean.ath.WebDriverMixin; import io.blueocean.ath.factory.ActivityPageFactory; import io.blueocean.ath.factory.RunDetailsPipelinePageFactory; import io.blueocean.ath.model.AbstractPipeline; import org.eclipse.jgit.annotations.Nullable; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import javax.inject.Inject; public class PullRequestsPage implements WebDriverMixin { private Logger logger = LoggerFactory.getLogger(PullRequestsPage.class); private WebDriver driver; private AbstractPipeline pipeline; @Inject ActivityPageFactory activityPageFactory; @Inject RunDetailsPipelinePageFactory runDetailsPipelinePageFactory; @Inject WaitUtil wait; @Inject public PullRequestsPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } @AssistedInject public PullRequestsPage(WebDriver driver, @Assisted @Nullable AbstractPipeline pipeline) { this.pipeline = pipeline; this.driver = driver; PageFactory.initElements(driver, this); } /** * Validates a correctly constructed URL. * @return */ public PullRequestsPage checkUrl() { wait.until(ExpectedConditions.urlContains(pipeline.getUrl() + "/pr"), 30000); logger.info("checkUrl: successfully validated our URL"); return this; } /** * Validates that the pipeline object actually exists and can do stuff. * @return */ public void checkPipeline() { Assert.assertNotNull("AbstractPipeline is null", pipeline); } /** * Verifies that the PR tab in the UI is actually selected. * @return */ public void checkPr() { wait.until(By.cssSelector("a.selected.pr")); logger.info("checkPr: success, PR tab is selected"); } /** * Clicks the History button for the specified PR number, taking the * test into that PR's Activity page. * @param prNumber * @return */ public ActivityPage clickHistoryButton(String prNumber) { wait.click(By.cssSelector("a[data-pr='" + prNumber + "'] a.history-button")); logger.info("Clicked history button, which moves us to the Activity page"); return activityPageFactory.withPipeline(pipeline).checkUrl(("PR-" + prNumber)); } /** * Clicks the Run button for the specified PR number, taking the * test into that PR's Run Details page. * @param prNumber * @return */ public RunDetailsPipelinePage clickRunButton(String prNumber) { wait.click(By.cssSelector("a[data-pr='" + prNumber + "'] a.run-button")); logger.info("Clicked Run button to build the PR"); return runDetailsPipelinePageFactory.withPipeline(pipeline); } /** * Opens a PullRequestsPage for the specified pipeline * @param pipelineName * @return */ public void open(String pipelineName) { checkPipeline(); checkUrl(); go("/blue/organizations/jenkins/" + pipelineName + "/pr"); checkPr(); logger.info("PullRequestsPage --> opened PR tab for " + pipelineName); } /** * Open run details for the specified pr (by clicking on its row) * @param prNumber * @return */ public RunDetailsPipelinePage openPrDetails(String prNumber) { findPrRow(prNumber).click(); return runDetailsPipelinePageFactory.withPipeline(pipeline); } /** * Locate the row for the specified pr * @param prNumber * @return */ private WebElement findPrRow(String prNumber) { return wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[data-pr='" + prNumber + "']"))); } }
UTF-8
Java
4,177
java
PullRequestsPage.java
Java
[]
null
[]
package io.blueocean.ath.pages.blue; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; import io.blueocean.ath.WaitUtil; import io.blueocean.ath.WebDriverMixin; import io.blueocean.ath.factory.ActivityPageFactory; import io.blueocean.ath.factory.RunDetailsPipelinePageFactory; import io.blueocean.ath.model.AbstractPipeline; import org.eclipse.jgit.annotations.Nullable; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedConditions; import org.slf4j.LoggerFactory; import org.slf4j.Logger; import javax.inject.Inject; public class PullRequestsPage implements WebDriverMixin { private Logger logger = LoggerFactory.getLogger(PullRequestsPage.class); private WebDriver driver; private AbstractPipeline pipeline; @Inject ActivityPageFactory activityPageFactory; @Inject RunDetailsPipelinePageFactory runDetailsPipelinePageFactory; @Inject WaitUtil wait; @Inject public PullRequestsPage(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); } @AssistedInject public PullRequestsPage(WebDriver driver, @Assisted @Nullable AbstractPipeline pipeline) { this.pipeline = pipeline; this.driver = driver; PageFactory.initElements(driver, this); } /** * Validates a correctly constructed URL. * @return */ public PullRequestsPage checkUrl() { wait.until(ExpectedConditions.urlContains(pipeline.getUrl() + "/pr"), 30000); logger.info("checkUrl: successfully validated our URL"); return this; } /** * Validates that the pipeline object actually exists and can do stuff. * @return */ public void checkPipeline() { Assert.assertNotNull("AbstractPipeline is null", pipeline); } /** * Verifies that the PR tab in the UI is actually selected. * @return */ public void checkPr() { wait.until(By.cssSelector("a.selected.pr")); logger.info("checkPr: success, PR tab is selected"); } /** * Clicks the History button for the specified PR number, taking the * test into that PR's Activity page. * @param prNumber * @return */ public ActivityPage clickHistoryButton(String prNumber) { wait.click(By.cssSelector("a[data-pr='" + prNumber + "'] a.history-button")); logger.info("Clicked history button, which moves us to the Activity page"); return activityPageFactory.withPipeline(pipeline).checkUrl(("PR-" + prNumber)); } /** * Clicks the Run button for the specified PR number, taking the * test into that PR's Run Details page. * @param prNumber * @return */ public RunDetailsPipelinePage clickRunButton(String prNumber) { wait.click(By.cssSelector("a[data-pr='" + prNumber + "'] a.run-button")); logger.info("Clicked Run button to build the PR"); return runDetailsPipelinePageFactory.withPipeline(pipeline); } /** * Opens a PullRequestsPage for the specified pipeline * @param pipelineName * @return */ public void open(String pipelineName) { checkPipeline(); checkUrl(); go("/blue/organizations/jenkins/" + pipelineName + "/pr"); checkPr(); logger.info("PullRequestsPage --> opened PR tab for " + pipelineName); } /** * Open run details for the specified pr (by clicking on its row) * @param prNumber * @return */ public RunDetailsPipelinePage openPrDetails(String prNumber) { findPrRow(prNumber).click(); return runDetailsPipelinePageFactory.withPipeline(pipeline); } /** * Locate the row for the specified pr * @param prNumber * @return */ private WebElement findPrRow(String prNumber) { return wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div[data-pr='" + prNumber + "']"))); } }
4,177
0.683026
0.68135
132
30.64394
27.14192
124
false
false
0
0
0
0
0
0
0.439394
false
false
8
76f2d9828b4b76a9e957544d9a42cf3a0d582d36
3,367,254,390,370
0f7f01ce49f25243b42288a095671d796b04ee78
/wp-android/src/org/multiversewriters/android/ui/prefs/AboutActivity.java
c8af5c3fd0dce1f9bc2d7683669d63fda7726725
[ "MIT" ]
permissive
themultiverseproject/org.multiversewriters.android
https://github.com/themultiverseproject/org.multiversewriters.android
4f4ad0a4832a17a7127f44e717e232162d7e5ec6
a4c0540ed96f78304a1022ea00fa2b0b55ab4c71
refs/heads/master
2015-08-11T05:55:19.305000
2014-04-14T23:20:02
2014-04-14T23:20:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.multiversewriters.android.ui.prefs; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import org.multiversewriters.android.R; import org.multiversewriters.android.WordPress; import org.multiversewriters.android.lockmanager.AppLockManager; import org.multiversewriters.android.util.DeviceUtils; public class AboutActivity extends Activity implements OnClickListener { private static final String URL_TOS = "http://edublogs.org/terms-of-service"; private static final String URL_AUTOMATTIC = "http://edublogs.org"; private static final String URL_PRIVACY_POLICY = "/privacy-policy"; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.about); if (DeviceUtils.getInstance().isBlackBerry()) { TextView appTitle = (TextView) findViewById(R.id.about_first_line); appTitle.setText(getString(R.string.app_title_blackberry)); } TextView version = (TextView) findViewById(R.id.about_version); version.setText(getString(R.string.version) + " " + WordPress.versionName); Button tos = (Button) findViewById(R.id.about_tos); tos.setOnClickListener(this); Button pp = (Button) findViewById(R.id.about_privacy); pp.setOnClickListener(this); } public void onClick(View v) { Uri uri; int id = v.getId(); if (id == R.id.about_url) { uri = Uri.parse(URL_AUTOMATTIC); } else if (id == R.id.about_tos) { uri = Uri.parse(URL_TOS); } else if (id == R.id.about_privacy) { uri = Uri.parse(URL_AUTOMATTIC + URL_PRIVACY_POLICY); } else { return; } AppLockManager.getInstance().setExtendedTimeout(); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }
UTF-8
Java
2,057
java
AboutActivity.java
Java
[]
null
[]
package org.multiversewriters.android.ui.prefs; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import org.multiversewriters.android.R; import org.multiversewriters.android.WordPress; import org.multiversewriters.android.lockmanager.AppLockManager; import org.multiversewriters.android.util.DeviceUtils; public class AboutActivity extends Activity implements OnClickListener { private static final String URL_TOS = "http://edublogs.org/terms-of-service"; private static final String URL_AUTOMATTIC = "http://edublogs.org"; private static final String URL_PRIVACY_POLICY = "/privacy-policy"; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.about); if (DeviceUtils.getInstance().isBlackBerry()) { TextView appTitle = (TextView) findViewById(R.id.about_first_line); appTitle.setText(getString(R.string.app_title_blackberry)); } TextView version = (TextView) findViewById(R.id.about_version); version.setText(getString(R.string.version) + " " + WordPress.versionName); Button tos = (Button) findViewById(R.id.about_tos); tos.setOnClickListener(this); Button pp = (Button) findViewById(R.id.about_privacy); pp.setOnClickListener(this); } public void onClick(View v) { Uri uri; int id = v.getId(); if (id == R.id.about_url) { uri = Uri.parse(URL_AUTOMATTIC); } else if (id == R.id.about_tos) { uri = Uri.parse(URL_TOS); } else if (id == R.id.about_privacy) { uri = Uri.parse(URL_AUTOMATTIC + URL_PRIVACY_POLICY); } else { return; } AppLockManager.getInstance().setExtendedTimeout(); startActivity(new Intent(Intent.ACTION_VIEW, uri)); } }
2,057
0.669421
0.669421
61
32.72131
24.759916
81
false
false
0
0
0
0
0
0
0.57377
false
false
8
0eb72f932abbf18140c50ff9246338a0a7b01f5a
4,784,593,587,034
6f5cd3b2463487f3ff30cbee4941e2ce8e5396eb
/src/permeagility/plus/webgl/ShaderBuilder.java
913b826b211934eaf60517f8cd0b60e813225d03
[ "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
PermeAgility/permeagility-core
https://github.com/PermeAgility/permeagility-core
5388f241fee24bbca0a726f39124c49a946f8157
2d64c93a14873f8947a9b20100a80cb8824e9aa0
refs/heads/master
2021-06-21T12:53:45.512000
2021-03-11T01:17:02
2021-03-11T01:17:02
26,693,682
3
2
NOASSERTION
false
2021-03-11T01:17:03
2014-11-15T20:57:34
2016-11-08T01:10:29
2021-03-11T01:17:02
7,359
2
2
0
Java
false
false
/* * Copyright 2015 PermeAgility Incorporated. * * 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 permeagility.plus.webgl; import java.util.HashMap; import permeagility.util.DatabaseConnection; import com.orientechnologies.orient.core.record.impl.ODocument; import java.util.Date; import java.util.Locale; import java.util.Map; import permeagility.web.Message; import permeagility.web.Security; import permeagility.web.Table; /** * Shader Builder - edits and previews pages using webgl and twgl.js [optional] * @author glenn */ public class ShaderBuilder extends Table { public final String TABLE_NAME = "shader"; @Override public String getPage(DatabaseConnection con, HashMap<String, String> parms) { StringBuilder sb = new StringBuilder(); StringBuilder errors = new StringBuilder(); Locale locale = con.getLocale(); String preview = parms.get("PREVIEW"); // If there was an update do it String update = processSubmit(con, parms, TABLE_NAME, errors); if (update != null) { return update; } // If preview, return the assembled result page (without editors) if (preview != null) { ODocument viewDoc = con.get(preview); if (viewDoc == null) { errors.append(paragraph("Could not retrieve shader details using " + preview)); } else { StringBuilder usesScripts = new StringBuilder(); Map<String,ODocument> uses = viewDoc.field("usesShader"); if (uses != null && uses.size() > 0) { for (String refName : uses.keySet()) { if (DEBUG) System.out.println("Including shader: "+refName); if (viewDoc.field("vertexScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-vs\" type=\"x-shader/x-vertex\">" + uses.get(refName).field("vertexScript") + "</script>\n"); if (viewDoc.field("fragmentScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-fs\" type=\"x-shader/x-fragment\">" + uses.get(refName).field("fragmentScript") + "</script>\n"); } } String vertexScript = (viewDoc.field("vertexScript") != null ? "<script id=\"vs\" type=\"x-shader/x-vertex\">" + viewDoc.field("vertexScript") + "</script>\n" : ""); String fragmentScript = (viewDoc.field("fragmentScript") != null ? "<script id=\"fs\" type=\"x-shader/x-fragment\">" + viewDoc.field("fragmentScript") + "</script>\n" : ""); String script = (viewDoc.field("testScript") != null ? "<script>" + SHADER_CONTROLS_SCRIPT + "\n" + viewDoc.field("testScript") + "</script>" : ""); return head("Shader Builder", getScript("twgl-full.min.js") + getScript("chroma.min.js") + getScript("audiostreamsource.min.js")) + body("<canvas id=\"c\" style=\"width: 100vw; height: calc(100vh - 30px);\"></canvas>") + usesScripts.toString() + vertexScript + fragmentScript + script; } } // If nothing else happened, show the list of Scripts owned by the user if (sb.length() == 0) { try { parms.put("SERVICE", "Shader Builder"); sb.append(getTable(con, parms, TABLE_NAME, "SELECT FROM " + TABLE_NAME, null, 0, "button_VIEW_View,name,description,-")); } catch (Exception e) { e.printStackTrace(); sb.append("Error retrieving Script table: " + e.getMessage()); } } // Return the default page return head("Shader Builder", getScripts(con) ) + body(standardLayout(con, parms, ((Security.getTablePriv(con, TABLE_NAME) & PRIV_CREATE) > 0 ? popupForm("CREATE_NEW_ROW", null, Message.get(locale, "CREATE_ROW"), null, "NAME", paragraph("banner", Message.get(locale, "CREATE_ROW")) + hidden("TABLENAME", TABLE_NAME) + super.getTableRowFields(con, TABLE_NAME, parms, "name,description,usesShader,-") + submitButton(locale, "CREATE_ROW")) : "") + errors.toString() + sb.toString() )); } @Override public String getTableRowForm(DatabaseConnection con, String table, HashMap<String, String> parms) { return getTableRowFields(con, table, parms, null); } /** Returns the default row editor page with Script editors and preview in a split panel */ @Override public String getTableRowFields(DatabaseConnection con, String table, HashMap<String, String> parms, String columnOverride) { String edit_id = (parms != null ? parms.get("EDIT_ID") : null); ODocument initialValues = null; if (edit_id != null) { initialValues = con.get(edit_id); if (initialValues == null) { return paragraph("error", Message.get(con.getLocale(), "ERROR_IN_QUERY",edit_id)); } } boolean readOnly = false; // Assume a new doc if (initialValues != null) { readOnly = Security.isReadOnlyDocument(con, initialValues); } String vertexEditor = ""; String testScriptEditor = ""; String fragmentEditor = ""; String formName = (edit_id == null ? "NEWROW" : "UPDATEROW"); String init = initialValues.field("vertexScript"); if (init == null) init = "/* Vertex Shader */\n"; vertexEditor = getCodeEditorControl(formName, PARM_PREFIX + "vertexScript", init, "text/x-csrc"); init = initialValues.field("fragmentScript"); if (init == null) init = "/* Fragment Shader "+new Date()+" by "+con.getUser()+"*/\n"; fragmentEditor = getCodeEditorControl(formName, PARM_PREFIX + "fragmentScript", init, "text/x-csrc"); init = initialValues.field("testScript"); if (init == null) init = "/* Shader Test "+new Date()+" by "+con.getUser()+"*/\n"; testScriptEditor = getCodeEditorControl(formName, PARM_PREFIX + "testScript", init, "application/javascript"); String resultView = (readOnly ? "" : button("UpdateButton", "UPDATEBUTTON","UPDATE",Message.get(con.getLocale(),"SAVE_AND_RUN")) +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + popupBox("UPDATE_NAME", null, Message.get(con.getLocale(), "DETAILS"), null, "NAME", paragraph("banner", Message.get(con.getLocale(), "DETAILS")) + hidden("TABLENAME", TABLE_NAME) + super.getTableRowFields(con, TABLE_NAME, parms, "name,description,usesShader,-") ) +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ) + popupForm("UPDATE_MORE", null, Message.get(con.getLocale(), "MORE"), null, "NAME", paragraph("banner", Message.get(con.getLocale(), "MORE")) + hidden("TABLENAME", TABLE_NAME) + (readOnly ? "" : deleteButton(con.getLocale())+"<br>") + submitButton(con.getLocale(), "COPY") ) +"<br>"+frame("previewFrame","permeagility.plus.webgl.ShaderBuilder?PREVIEW="+edit_id); return getSplitScript() +div("leftHand","split split-horizontal",div("vertexEditor","split content",vertexEditor)+div("testScriptEditor",testScriptEditor)) +div("rightHand","split split-horizontal",div("fragmentEditor","split content",fragmentEditor)+div("resultView",resultView)) +script("Split(['#leftHand', '#rightHand'], { gutterSize: 8, minSize: [5,5], cursor: 'col-resize' });\n" + "Split(['#vertexEditor', '#testScriptEditor'], { direction: 'vertical', sizes: [50, 50], minSize: [10,10], gutterSize: 8, cursor: 'row-resize' });\n" + "Split(['#fragmentEditor', '#resultView'], { direction: 'vertical', sizes: [50, 50], minSize: [10,10], gutterSize: 8, cursor: 'row-resize' });\n" +(readOnly ? "" : "d3.select('#headerservice').text(document.getElementById('"+PARM_PREFIX+"name').value);\n" + "d3.select('#UpdateButton').on('click', function() { \n" + " "+PARM_PREFIX+"vertexScriptEditor.save();\n" + " "+PARM_PREFIX+"fragmentScriptEditor.save();\n" + " "+PARM_PREFIX+"testScriptEditor.save();\n" + " var formData = new FormData();\n" + " formData.append('SUBMIT','UPDATE');\n" + addFormData(formName,"vertexScript") + addFormData(formName,"fragmentScript") + addFormData(formName,"testScript") + addFormData("name") + addFormData("description") + addFormData("usesShader") + " d3.xhr('').post(formData, function(error,data) { \n" + " d3.select('#previewFrame').attr('src','permeagility.plus.webgl.ShaderBuilder?PREVIEW="+edit_id+"');\n" // Refresh preview + " d3.select('#headerservice').text(document.getElementById('"+PARM_PREFIX+"name').value);\n" // Update name (if changed) + " });\n" + "});\n") ); } public String addFormData(String name) { return "formData.append('"+PARM_PREFIX+name+"',document.getElementById('"+PARM_PREFIX+name+"').value);\n"; } public String addFormData(String formName, String name) { return "formData.append('"+PARM_PREFIX+name+"',document.getElementById('"+formName+PARM_PREFIX+name+"').value);\n"; } public static String SHADER_CONTROLS_SCRIPT = "// Add Shader controls - call SHADER_CONTROLS(myUpdateFunction) in your update function\n" + "var SHADER_STOP = false;\n" + "var SHADER_STEP = false;\n" + "var SHADER_SLOW = false;\n" + "var SHADER_DEFAULT_INTERVAL = 250;\n" + "var SHADER_SLOW_INTERVAL;\n" + "var SHADER_LOOP_FUNCTION; // Set when shader loop is called\n" + "const SHADER_CONTROLS = (fun) => {\n" + " if (SHADER_SLOW_INTERVAL == undefined) {\n" + " var butdiv = document.createElement(\"div\");\n" + " butdiv.setAttribute(\"style\",\"position: absolute; top: 0;\");\n" + " function createButton(name, code) {\n" + " var but = document.createElement(\"button\");\n" + " but.setAttribute(\"onClick\",code);\n" + " but.appendChild(document.createTextNode(name));\n" + " butdiv.appendChild(but);\n" + " }\n" + " createButton(\"Stop\",\"SHADER_STOP = true;\");\n" + " createButton(\"Go\",\"SHADER_STOP = false; SHADER_SLOW = false; SHADER_LOOP_FUNCTION();\");\n" + " createButton(\"Step\",\"SHADER_SLOW = false; SHADER_STOP = false; SHADER_STEP = true; SHADER_LOOP_FUNCTION();\");\n" + " createButton(\"Slow\",\"SHADER_SLOW = true; SHADER_SLOW_INTERVAL.value = \"+SHADER_DEFAULT_INTERVAL+\"; SHADER_STOP = false; SHADER_LOOP_FUNCTION();\");\n" + " SHADER_SLOW_INTERVAL = document.createElement(\"input\");\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"type\",\"range\");\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"min\",0);\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"max\",2000);\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"value\",SHADER_DEFAULT_INTERVAL);\n" + " butdiv.appendChild(SHADER_SLOW_INTERVAL);\n" + " document.body.appendChild(butdiv);\n" + " }\n" + " SHADER_LOOP_FUNCTION = fun;\n" + " if (!SHADER_STOP) \n" + " if (SHADER_SLOW) {\n" + " window.setTimeout(function() { requestAnimationFrame(fun); } , SHADER_SLOW_INTERVAL.value);\n" + " } else {" + " if (SHADER_STEP) {" + " SHADER_STOP = true;\n" + " SHADER_STEP = false;\n" + " }\n" + " requestAnimationFrame(fun);\n" + " }" + "};"; public static String getAsComponent(DatabaseConnection con, String id) { ODocument viewDoc = con.get(id); if (viewDoc == null) { System.out.println(paragraph("Could not retrieve shader details using " + id)); } else { StringBuilder usesScripts = new StringBuilder(); Map<String,ODocument> uses = viewDoc.field("usesShader"); if (uses != null && uses.size() > 0) { for (String refName : uses.keySet()) { if (DEBUG) System.out.println("Including shader: "+refName); if (viewDoc.field("vertexScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-vs\" type=\"x-shader/x-vertex\">" + uses.get(refName).field("vertexScript") + "</script>\n"); if (viewDoc.field("fragmentScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-fs\" type=\"x-shader/x-fragment\">" + uses.get(refName).field("fragmentScript") + "</script>\n"); } } String vertexScript = (viewDoc.field("vertexScript") != null ? "<script id=\"vs\" type=\"x-shader/x-vertex\">" + viewDoc.field("vertexScript") + "</script>\n" : ""); String fragmentScript = (viewDoc.field("fragmentScript") != null ? "<script id=\"fs\" type=\"x-shader/x-fragment\">" + viewDoc.field("fragmentScript") + "</script>\n" : ""); String script = (viewDoc.field("testScript") != null ? "<script>" + SHADER_CONTROLS_SCRIPT + "\n" + viewDoc.field("testScript") + "</script>" : ""); return getScript("twgl-full.min.js") + getScript("chroma.min.js") + getScript("audiostreamsource.min.js") + "<canvas id=\"c\" style=\"width: 100vw; height: calc(100vh - 30px);\"></canvas>" + usesScripts.toString() + vertexScript + fragmentScript + script; } return "N/A no-doc"; } }
UTF-8
Java
15,085
java
ShaderBuilder.java
Java
[ { "context": "ages using webgl and twgl.js [optional]\n * @author glenn\n */\npublic class ShaderBuilder extends Table {\n\n ", "end": 1052, "score": 0.9960141181945801, "start": 1047, "tag": "USERNAME", "value": "glenn" } ]
null
[]
/* * Copyright 2015 PermeAgility Incorporated. * * 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 permeagility.plus.webgl; import java.util.HashMap; import permeagility.util.DatabaseConnection; import com.orientechnologies.orient.core.record.impl.ODocument; import java.util.Date; import java.util.Locale; import java.util.Map; import permeagility.web.Message; import permeagility.web.Security; import permeagility.web.Table; /** * Shader Builder - edits and previews pages using webgl and twgl.js [optional] * @author glenn */ public class ShaderBuilder extends Table { public final String TABLE_NAME = "shader"; @Override public String getPage(DatabaseConnection con, HashMap<String, String> parms) { StringBuilder sb = new StringBuilder(); StringBuilder errors = new StringBuilder(); Locale locale = con.getLocale(); String preview = parms.get("PREVIEW"); // If there was an update do it String update = processSubmit(con, parms, TABLE_NAME, errors); if (update != null) { return update; } // If preview, return the assembled result page (without editors) if (preview != null) { ODocument viewDoc = con.get(preview); if (viewDoc == null) { errors.append(paragraph("Could not retrieve shader details using " + preview)); } else { StringBuilder usesScripts = new StringBuilder(); Map<String,ODocument> uses = viewDoc.field("usesShader"); if (uses != null && uses.size() > 0) { for (String refName : uses.keySet()) { if (DEBUG) System.out.println("Including shader: "+refName); if (viewDoc.field("vertexScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-vs\" type=\"x-shader/x-vertex\">" + uses.get(refName).field("vertexScript") + "</script>\n"); if (viewDoc.field("fragmentScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-fs\" type=\"x-shader/x-fragment\">" + uses.get(refName).field("fragmentScript") + "</script>\n"); } } String vertexScript = (viewDoc.field("vertexScript") != null ? "<script id=\"vs\" type=\"x-shader/x-vertex\">" + viewDoc.field("vertexScript") + "</script>\n" : ""); String fragmentScript = (viewDoc.field("fragmentScript") != null ? "<script id=\"fs\" type=\"x-shader/x-fragment\">" + viewDoc.field("fragmentScript") + "</script>\n" : ""); String script = (viewDoc.field("testScript") != null ? "<script>" + SHADER_CONTROLS_SCRIPT + "\n" + viewDoc.field("testScript") + "</script>" : ""); return head("Shader Builder", getScript("twgl-full.min.js") + getScript("chroma.min.js") + getScript("audiostreamsource.min.js")) + body("<canvas id=\"c\" style=\"width: 100vw; height: calc(100vh - 30px);\"></canvas>") + usesScripts.toString() + vertexScript + fragmentScript + script; } } // If nothing else happened, show the list of Scripts owned by the user if (sb.length() == 0) { try { parms.put("SERVICE", "Shader Builder"); sb.append(getTable(con, parms, TABLE_NAME, "SELECT FROM " + TABLE_NAME, null, 0, "button_VIEW_View,name,description,-")); } catch (Exception e) { e.printStackTrace(); sb.append("Error retrieving Script table: " + e.getMessage()); } } // Return the default page return head("Shader Builder", getScripts(con) ) + body(standardLayout(con, parms, ((Security.getTablePriv(con, TABLE_NAME) & PRIV_CREATE) > 0 ? popupForm("CREATE_NEW_ROW", null, Message.get(locale, "CREATE_ROW"), null, "NAME", paragraph("banner", Message.get(locale, "CREATE_ROW")) + hidden("TABLENAME", TABLE_NAME) + super.getTableRowFields(con, TABLE_NAME, parms, "name,description,usesShader,-") + submitButton(locale, "CREATE_ROW")) : "") + errors.toString() + sb.toString() )); } @Override public String getTableRowForm(DatabaseConnection con, String table, HashMap<String, String> parms) { return getTableRowFields(con, table, parms, null); } /** Returns the default row editor page with Script editors and preview in a split panel */ @Override public String getTableRowFields(DatabaseConnection con, String table, HashMap<String, String> parms, String columnOverride) { String edit_id = (parms != null ? parms.get("EDIT_ID") : null); ODocument initialValues = null; if (edit_id != null) { initialValues = con.get(edit_id); if (initialValues == null) { return paragraph("error", Message.get(con.getLocale(), "ERROR_IN_QUERY",edit_id)); } } boolean readOnly = false; // Assume a new doc if (initialValues != null) { readOnly = Security.isReadOnlyDocument(con, initialValues); } String vertexEditor = ""; String testScriptEditor = ""; String fragmentEditor = ""; String formName = (edit_id == null ? "NEWROW" : "UPDATEROW"); String init = initialValues.field("vertexScript"); if (init == null) init = "/* Vertex Shader */\n"; vertexEditor = getCodeEditorControl(formName, PARM_PREFIX + "vertexScript", init, "text/x-csrc"); init = initialValues.field("fragmentScript"); if (init == null) init = "/* Fragment Shader "+new Date()+" by "+con.getUser()+"*/\n"; fragmentEditor = getCodeEditorControl(formName, PARM_PREFIX + "fragmentScript", init, "text/x-csrc"); init = initialValues.field("testScript"); if (init == null) init = "/* Shader Test "+new Date()+" by "+con.getUser()+"*/\n"; testScriptEditor = getCodeEditorControl(formName, PARM_PREFIX + "testScript", init, "application/javascript"); String resultView = (readOnly ? "" : button("UpdateButton", "UPDATEBUTTON","UPDATE",Message.get(con.getLocale(),"SAVE_AND_RUN")) +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + popupBox("UPDATE_NAME", null, Message.get(con.getLocale(), "DETAILS"), null, "NAME", paragraph("banner", Message.get(con.getLocale(), "DETAILS")) + hidden("TABLENAME", TABLE_NAME) + super.getTableRowFields(con, TABLE_NAME, parms, "name,description,usesShader,-") ) +"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ) + popupForm("UPDATE_MORE", null, Message.get(con.getLocale(), "MORE"), null, "NAME", paragraph("banner", Message.get(con.getLocale(), "MORE")) + hidden("TABLENAME", TABLE_NAME) + (readOnly ? "" : deleteButton(con.getLocale())+"<br>") + submitButton(con.getLocale(), "COPY") ) +"<br>"+frame("previewFrame","permeagility.plus.webgl.ShaderBuilder?PREVIEW="+edit_id); return getSplitScript() +div("leftHand","split split-horizontal",div("vertexEditor","split content",vertexEditor)+div("testScriptEditor",testScriptEditor)) +div("rightHand","split split-horizontal",div("fragmentEditor","split content",fragmentEditor)+div("resultView",resultView)) +script("Split(['#leftHand', '#rightHand'], { gutterSize: 8, minSize: [5,5], cursor: 'col-resize' });\n" + "Split(['#vertexEditor', '#testScriptEditor'], { direction: 'vertical', sizes: [50, 50], minSize: [10,10], gutterSize: 8, cursor: 'row-resize' });\n" + "Split(['#fragmentEditor', '#resultView'], { direction: 'vertical', sizes: [50, 50], minSize: [10,10], gutterSize: 8, cursor: 'row-resize' });\n" +(readOnly ? "" : "d3.select('#headerservice').text(document.getElementById('"+PARM_PREFIX+"name').value);\n" + "d3.select('#UpdateButton').on('click', function() { \n" + " "+PARM_PREFIX+"vertexScriptEditor.save();\n" + " "+PARM_PREFIX+"fragmentScriptEditor.save();\n" + " "+PARM_PREFIX+"testScriptEditor.save();\n" + " var formData = new FormData();\n" + " formData.append('SUBMIT','UPDATE');\n" + addFormData(formName,"vertexScript") + addFormData(formName,"fragmentScript") + addFormData(formName,"testScript") + addFormData("name") + addFormData("description") + addFormData("usesShader") + " d3.xhr('').post(formData, function(error,data) { \n" + " d3.select('#previewFrame').attr('src','permeagility.plus.webgl.ShaderBuilder?PREVIEW="+edit_id+"');\n" // Refresh preview + " d3.select('#headerservice').text(document.getElementById('"+PARM_PREFIX+"name').value);\n" // Update name (if changed) + " });\n" + "});\n") ); } public String addFormData(String name) { return "formData.append('"+PARM_PREFIX+name+"',document.getElementById('"+PARM_PREFIX+name+"').value);\n"; } public String addFormData(String formName, String name) { return "formData.append('"+PARM_PREFIX+name+"',document.getElementById('"+formName+PARM_PREFIX+name+"').value);\n"; } public static String SHADER_CONTROLS_SCRIPT = "// Add Shader controls - call SHADER_CONTROLS(myUpdateFunction) in your update function\n" + "var SHADER_STOP = false;\n" + "var SHADER_STEP = false;\n" + "var SHADER_SLOW = false;\n" + "var SHADER_DEFAULT_INTERVAL = 250;\n" + "var SHADER_SLOW_INTERVAL;\n" + "var SHADER_LOOP_FUNCTION; // Set when shader loop is called\n" + "const SHADER_CONTROLS = (fun) => {\n" + " if (SHADER_SLOW_INTERVAL == undefined) {\n" + " var butdiv = document.createElement(\"div\");\n" + " butdiv.setAttribute(\"style\",\"position: absolute; top: 0;\");\n" + " function createButton(name, code) {\n" + " var but = document.createElement(\"button\");\n" + " but.setAttribute(\"onClick\",code);\n" + " but.appendChild(document.createTextNode(name));\n" + " butdiv.appendChild(but);\n" + " }\n" + " createButton(\"Stop\",\"SHADER_STOP = true;\");\n" + " createButton(\"Go\",\"SHADER_STOP = false; SHADER_SLOW = false; SHADER_LOOP_FUNCTION();\");\n" + " createButton(\"Step\",\"SHADER_SLOW = false; SHADER_STOP = false; SHADER_STEP = true; SHADER_LOOP_FUNCTION();\");\n" + " createButton(\"Slow\",\"SHADER_SLOW = true; SHADER_SLOW_INTERVAL.value = \"+SHADER_DEFAULT_INTERVAL+\"; SHADER_STOP = false; SHADER_LOOP_FUNCTION();\");\n" + " SHADER_SLOW_INTERVAL = document.createElement(\"input\");\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"type\",\"range\");\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"min\",0);\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"max\",2000);\n" + " SHADER_SLOW_INTERVAL.setAttribute(\"value\",SHADER_DEFAULT_INTERVAL);\n" + " butdiv.appendChild(SHADER_SLOW_INTERVAL);\n" + " document.body.appendChild(butdiv);\n" + " }\n" + " SHADER_LOOP_FUNCTION = fun;\n" + " if (!SHADER_STOP) \n" + " if (SHADER_SLOW) {\n" + " window.setTimeout(function() { requestAnimationFrame(fun); } , SHADER_SLOW_INTERVAL.value);\n" + " } else {" + " if (SHADER_STEP) {" + " SHADER_STOP = true;\n" + " SHADER_STEP = false;\n" + " }\n" + " requestAnimationFrame(fun);\n" + " }" + "};"; public static String getAsComponent(DatabaseConnection con, String id) { ODocument viewDoc = con.get(id); if (viewDoc == null) { System.out.println(paragraph("Could not retrieve shader details using " + id)); } else { StringBuilder usesScripts = new StringBuilder(); Map<String,ODocument> uses = viewDoc.field("usesShader"); if (uses != null && uses.size() > 0) { for (String refName : uses.keySet()) { if (DEBUG) System.out.println("Including shader: "+refName); if (viewDoc.field("vertexScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-vs\" type=\"x-shader/x-vertex\">" + uses.get(refName).field("vertexScript") + "</script>\n"); if (viewDoc.field("fragmentScript") != null) usesScripts.append("<script id=\""+refName.substring(1,refName.length()-1)+"-fs\" type=\"x-shader/x-fragment\">" + uses.get(refName).field("fragmentScript") + "</script>\n"); } } String vertexScript = (viewDoc.field("vertexScript") != null ? "<script id=\"vs\" type=\"x-shader/x-vertex\">" + viewDoc.field("vertexScript") + "</script>\n" : ""); String fragmentScript = (viewDoc.field("fragmentScript") != null ? "<script id=\"fs\" type=\"x-shader/x-fragment\">" + viewDoc.field("fragmentScript") + "</script>\n" : ""); String script = (viewDoc.field("testScript") != null ? "<script>" + SHADER_CONTROLS_SCRIPT + "\n" + viewDoc.field("testScript") + "</script>" : ""); return getScript("twgl-full.min.js") + getScript("chroma.min.js") + getScript("audiostreamsource.min.js") + "<canvas id=\"c\" style=\"width: 100vw; height: calc(100vh - 30px);\"></canvas>" + usesScripts.toString() + vertexScript + fragmentScript + script; } return "N/A no-doc"; } }
15,085
0.560557
0.555784
258
57.468994
48.234177
243
false
false
0
0
0
0
0
0
1.170543
false
false
8
a16e9a3750016fbb9dd85606d45db44d05f7b1f0
38,268,158,637,967
1d5af05b5d3d16e7b67f2e5227af9b730468e0e4
/src/main/java/br/com/taxajurosservice/api/handler/TaxaJurosServiceException.java
344f190d135ed62623949b7f2491feb533f10fe3
[]
no_license
ibrazil7/taxa-juros-service
https://github.com/ibrazil7/taxa-juros-service
ec84ec124196a8b83e24c5b7e0641eed28c280af
b5d684f87d79fc678db448dd3d6300cb474b555c
refs/heads/master
2020-05-15T22:58:30.099000
2019-04-21T19:55:03
2019-04-21T19:55:03
182,539,965
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.taxajurosservice.api.handler; /** * @author italo * */ public class TaxaJurosServiceException extends Exception { private static final long serialVersionUID = -2986775985755027286L; public TaxaJurosServiceException() { } public TaxaJurosServiceException(String message, Throwable cause) { super(message, cause); } public TaxaJurosServiceException(String message) { super(message); } public TaxaJurosServiceException(Throwable cause) { super(cause); } }
UTF-8
Java
493
java
TaxaJurosServiceException.java
Java
[ { "context": ".com.taxajurosservice.api.handler;\n\n/**\n * @author italo\n *\n */\npublic class TaxaJurosServiceException ext", "end": 66, "score": 0.9965279698371887, "start": 61, "tag": "USERNAME", "value": "italo" } ]
null
[]
package br.com.taxajurosservice.api.handler; /** * @author italo * */ public class TaxaJurosServiceException extends Exception { private static final long serialVersionUID = -2986775985755027286L; public TaxaJurosServiceException() { } public TaxaJurosServiceException(String message, Throwable cause) { super(message, cause); } public TaxaJurosServiceException(String message) { super(message); } public TaxaJurosServiceException(Throwable cause) { super(cause); } }
493
0.762677
0.724138
26
17.961538
23.385532
68
false
false
0
0
0
0
0
0
0.846154
false
false
8
efd9046c25103f0046c8afd09aca7b11aa06d321
35,940,286,382,475
868839e6e7e4552220dddbcd43447fb1184d7f3c
/http/src/main/java/org/zyq/http/entity/Config.java
6184715c3ec3f840e401d7ffa776fc76966e7eae
[]
no_license
iready/utils
https://github.com/iready/utils
e434ca584f7df03b5316d515ec9660f12fcfe80e
2347ff3bec4e2ba095ba8d73cbe10b55ac252568
refs/heads/master
2020-12-12T02:49:29.341000
2016-10-24T02:51:18
2016-10-24T02:51:18
53,189,078
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.zyq.http.entity; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; public class Config { private String defaultEncoding = "UTF-8"; private HttpContext httpContext = new BasicHttpContext(); private Header[] headers = new Header[]{new BasicHeader("Content-Type","charset=utf-8")}; private int repeatCount = 2; private int outTimes = 10000; public String getDefaultEncoding() { return defaultEncoding; } public Config setDefaultEncoding(String defaultEncoding) { this.defaultEncoding = defaultEncoding; return this; } public HttpContext getHttpContext() { return httpContext; } public Config setHttpContext(HttpContext httpContext) { this.httpContext = httpContext; return this; } public Header[] getHeaders() { return headers; } public Config setHeaders(Header[] headers) { this.headers = headers; return this; } public int getRepeatCount() { return repeatCount; } public Config setRepeatCount(int repeatCount) { this.repeatCount = repeatCount; return this; } public int getOutTimes() { return outTimes; } public Config setOutTimes(int outTimes) { this.outTimes = outTimes; return this; } }
UTF-8
Java
1,454
java
Config.java
Java
[]
null
[]
package org.zyq.http.entity; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; public class Config { private String defaultEncoding = "UTF-8"; private HttpContext httpContext = new BasicHttpContext(); private Header[] headers = new Header[]{new BasicHeader("Content-Type","charset=utf-8")}; private int repeatCount = 2; private int outTimes = 10000; public String getDefaultEncoding() { return defaultEncoding; } public Config setDefaultEncoding(String defaultEncoding) { this.defaultEncoding = defaultEncoding; return this; } public HttpContext getHttpContext() { return httpContext; } public Config setHttpContext(HttpContext httpContext) { this.httpContext = httpContext; return this; } public Header[] getHeaders() { return headers; } public Config setHeaders(Header[] headers) { this.headers = headers; return this; } public int getRepeatCount() { return repeatCount; } public Config setRepeatCount(int repeatCount) { this.repeatCount = repeatCount; return this; } public int getOutTimes() { return outTimes; } public Config setOutTimes(int outTimes) { this.outTimes = outTimes; return this; } }
1,454
0.662311
0.656809
60
23.233334
20.892076
93
false
false
0
0
0
0
0
0
0.433333
false
false
8
6753592d209d81db202928bb9ef025551363c69c
36,584,531,470,019
3aa2bca1fc573e0254c2bbf961b0c1e3eac4b6bb
/src/main/java/com/vip/yll/service/ShopService.java
5b7e8ee3e0e8e68905d31921a222fd6e1b2ac2cf
[]
no_license
QIONGXUAN/yll_shop
https://github.com/QIONGXUAN/yll_shop
ae40bdd0e57d7d85813bd5099df11214761ade2d
80adb7a6ab86e8f112d4c0cf9103ae95605d550c
refs/heads/master
2022-12-21T00:20:27.817000
2019-09-10T00:40:13
2019-09-10T00:40:13
207,430,391
1
0
null
false
2022-12-16T00:41:33
2019-09-10T00:32:34
2019-10-25T05:18:12
2022-12-16T00:41:29
8,194
0
0
6
CSS
false
false
package com.vip.yll.service; import com.vip.yll.domain.vo.ShopPropertyVo; import java.util.List; public interface ShopService { public List<ShopPropertyVo> showAllValues(int shopId); public List<Integer> showNextValues(List<Integer> shopPropertyValueIds); }
UTF-8
Java
272
java
ShopService.java
Java
[]
null
[]
package com.vip.yll.service; import com.vip.yll.domain.vo.ShopPropertyVo; import java.util.List; public interface ShopService { public List<ShopPropertyVo> showAllValues(int shopId); public List<Integer> showNextValues(List<Integer> shopPropertyValueIds); }
272
0.779412
0.779412
13
19.923077
24.938267
76
false
false
0
0
0
0
0
0
0.384615
false
false
8
95d4864605d111ed0b7c13428f5c31c22808d772
39,195,871,559,400
c6769e178b3c998413ddea943d65afbb96d9e68f
/src/main/java/seedu/address/logic/parser/duties/DutyShiftCommandParser.java
8aa67dee71b4a98fc9df6e8b72a72c60ecb96005
[ "MIT" ]
permissive
AY1920S1-CS2103T-T09-3/main
https://github.com/AY1920S1-CS2103T-T09-3/main
aea4a71c171a6efb1b849c6201d203de71a2f7b0
13809e2b96e548e6edabfc1ebfcc33db435e2fc7
refs/heads/master
2022-03-02T15:41:23.927000
2019-11-11T15:55:37
2019-11-11T15:55:37
206,784,225
2
3
NOASSERTION
true
2019-11-11T15:55:38
2019-09-06T11:58:30
2019-11-11T14:15:37
2019-11-11T15:55:37
20,098
1
4
8
Java
false
false
//@@author SakuraBlossom package seedu.address.logic.parser.duties; import seedu.address.logic.commands.duties.DutyShiftCommand; import seedu.address.logic.parser.Parser; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.events.predicates.EventApprovedPredicate; import seedu.address.model.events.predicates.EventContainsKeywordPredicate; /** * Parses input arguments and creates a new FindCommand object */ public class DutyShiftCommandParser implements Parser<DutyShiftCommand> { /** * Parses the given {@code String} of arguments in the context of the DutyShiftCommand * and returns a DutyShiftCommand object for execution. * * @throws ParseException if the user input does not conform the expected format */ public DutyShiftCommand parse(String args) throws ParseException { String trimmedArgs = args.trim(); if (trimmedArgs.isEmpty()) { return new DutyShiftCommand(new EventApprovedPredicate()); } return new DutyShiftCommand(new EventContainsKeywordPredicate(trimmedArgs)); } }
UTF-8
Java
1,108
java
DutyShiftCommandParser.java
Java
[ { "context": "//@@author SakuraBlossom\npackage seedu.address.logic.parser.duties;\n\nimpor", "end": 24, "score": 0.9998089671134949, "start": 11, "tag": "NAME", "value": "SakuraBlossom" } ]
null
[]
//@@author SakuraBlossom package seedu.address.logic.parser.duties; import seedu.address.logic.commands.duties.DutyShiftCommand; import seedu.address.logic.parser.Parser; import seedu.address.logic.parser.exceptions.ParseException; import seedu.address.model.events.predicates.EventApprovedPredicate; import seedu.address.model.events.predicates.EventContainsKeywordPredicate; /** * Parses input arguments and creates a new FindCommand object */ public class DutyShiftCommandParser implements Parser<DutyShiftCommand> { /** * Parses the given {@code String} of arguments in the context of the DutyShiftCommand * and returns a DutyShiftCommand object for execution. * * @throws ParseException if the user input does not conform the expected format */ public DutyShiftCommand parse(String args) throws ParseException { String trimmedArgs = args.trim(); if (trimmedArgs.isEmpty()) { return new DutyShiftCommand(new EventApprovedPredicate()); } return new DutyShiftCommand(new EventContainsKeywordPredicate(trimmedArgs)); } }
1,108
0.75722
0.75722
28
38.57143
31.461346
90
false
false
0
0
0
0
0
0
0.321429
false
false
8
80723eb60b348b573b58af785eb232d7d7484fdd
39,195,871,558,987
b452113280399e11569aaab69dc74db95af9cadc
/app/src/main/java/com/example/samodejnecestitke/Contact.java
68afcce9b45364e5b75328165a82a1628cbccf08
[]
no_license
miloskekovic/SamodejneCestitke
https://github.com/miloskekovic/SamodejneCestitke
bb9e2818e1b71a26c8f4a4073d6ed61f6938716f
11c9f2b85214d7795f8975501f0ceda55f1570c9
refs/heads/master
2021-07-16T12:58:54.905000
2017-10-21T01:12:00
2017-10-21T01:12:00
107,740,159
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.samodejnecestitke; import java.util.ArrayList; import java.util.List; /** * Created by milos_000 on 17.10.2017.. */ public class Contact { //private variables int id; String ime_in_priimek; int dan_rojstva; int mesec_rojstva; int leto_rojstva; int telefonska_stevilka; String vera; String sporocilo_za_rojstni_dan; String sporocilo_za_bozic; // Empty constructor public Contact(){ } // constructor public Contact(int id, String imeInPriimek, int danRojstva, int mesecRojstva, int letoRojstva, int telefonskaStevilka, String vera, String sporociloZaRojstniDan, String sporociloZaBozic){ this.id = id; this.ime_in_priimek = imeInPriimek; this.dan_rojstva = danRojstva; this.mesec_rojstva = mesecRojstva; this.leto_rojstva = letoRojstva; this.telefonska_stevilka = telefonskaStevilka; this.vera = vera; this.sporocilo_za_rojstni_dan = sporociloZaRojstniDan; this.sporocilo_za_bozic = sporociloZaBozic; } // getting ID public int getID(){ return this.id; } // setting id public void setID(int id){ this.id = id; } public int getIdByName(ArrayList<Contact> vsiKontakti, String iskaniKontakt){ int iskaniID = 0; for(Contact kontakt:vsiKontakti){ if(kontakt.getName().equals(iskaniKontakt)){ iskaniID=kontakt.getID(); break; } } return iskaniID; } // getting name public String getName(){ return this.ime_in_priimek; } // setting name public void setName(String name){ this.ime_in_priimek = name; } // getting day of birth public int getDay(){ return this.dan_rojstva; } // setting day of birth public void setDay(int day){ this.dan_rojstva = day; } // getting month of birth public int getMonth(){ return this.mesec_rojstva; } // setting month of birth public void setMonth(int month){ this.mesec_rojstva = month; } // getting year of birth public int getYear(){ return this.leto_rojstva; } // setting year of birth public void setYear(int year){ this.leto_rojstva = year; } // getting phone number public int getPhoneNumber(){ return this.telefonska_stevilka; } // setting phone number public void setPhoneNumber(int phone_number){ this.telefonska_stevilka = phone_number; } // getting religion public String getReligion(){ return this.vera; } // setting religion public void setReligion(String religion){ this.vera = religion; } // getting birthdayMessage public String getBirthdayMessage(){ return this.sporocilo_za_rojstni_dan; } // setting birthdayMessage public void setBirthdayMessage(String birthdayMessage){ this.sporocilo_za_rojstni_dan = birthdayMessage; } // getting christmasMessage public String getChristmasMessage(){ return this.sporocilo_za_bozic; } // setting christmasMessage public void setChristmasMessage(String christmasMessage){ this.sporocilo_za_bozic = christmasMessage; } public ArrayList<String> vrniImenaInPriimkeVsehKontaktov(List<Contact> vsiKontakti){ ArrayList<String> imenaKontaktov = new ArrayList<String>(); for(Contact kontakt:vsiKontakti){ imenaKontaktov.add(kontakt.getName()); } return imenaKontaktov; } }
UTF-8
Java
3,634
java
Contact.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by milos_000 on 17.10.2017..\n */\n\npublic class Contact {\n\n ", "end": 119, "score": 0.9996757507324219, "start": 110, "tag": "USERNAME", "value": "milos_000" } ]
null
[]
package com.example.samodejnecestitke; import java.util.ArrayList; import java.util.List; /** * Created by milos_000 on 17.10.2017.. */ public class Contact { //private variables int id; String ime_in_priimek; int dan_rojstva; int mesec_rojstva; int leto_rojstva; int telefonska_stevilka; String vera; String sporocilo_za_rojstni_dan; String sporocilo_za_bozic; // Empty constructor public Contact(){ } // constructor public Contact(int id, String imeInPriimek, int danRojstva, int mesecRojstva, int letoRojstva, int telefonskaStevilka, String vera, String sporociloZaRojstniDan, String sporociloZaBozic){ this.id = id; this.ime_in_priimek = imeInPriimek; this.dan_rojstva = danRojstva; this.mesec_rojstva = mesecRojstva; this.leto_rojstva = letoRojstva; this.telefonska_stevilka = telefonskaStevilka; this.vera = vera; this.sporocilo_za_rojstni_dan = sporociloZaRojstniDan; this.sporocilo_za_bozic = sporociloZaBozic; } // getting ID public int getID(){ return this.id; } // setting id public void setID(int id){ this.id = id; } public int getIdByName(ArrayList<Contact> vsiKontakti, String iskaniKontakt){ int iskaniID = 0; for(Contact kontakt:vsiKontakti){ if(kontakt.getName().equals(iskaniKontakt)){ iskaniID=kontakt.getID(); break; } } return iskaniID; } // getting name public String getName(){ return this.ime_in_priimek; } // setting name public void setName(String name){ this.ime_in_priimek = name; } // getting day of birth public int getDay(){ return this.dan_rojstva; } // setting day of birth public void setDay(int day){ this.dan_rojstva = day; } // getting month of birth public int getMonth(){ return this.mesec_rojstva; } // setting month of birth public void setMonth(int month){ this.mesec_rojstva = month; } // getting year of birth public int getYear(){ return this.leto_rojstva; } // setting year of birth public void setYear(int year){ this.leto_rojstva = year; } // getting phone number public int getPhoneNumber(){ return this.telefonska_stevilka; } // setting phone number public void setPhoneNumber(int phone_number){ this.telefonska_stevilka = phone_number; } // getting religion public String getReligion(){ return this.vera; } // setting religion public void setReligion(String religion){ this.vera = religion; } // getting birthdayMessage public String getBirthdayMessage(){ return this.sporocilo_za_rojstni_dan; } // setting birthdayMessage public void setBirthdayMessage(String birthdayMessage){ this.sporocilo_za_rojstni_dan = birthdayMessage; } // getting christmasMessage public String getChristmasMessage(){ return this.sporocilo_za_bozic; } // setting christmasMessage public void setChristmasMessage(String christmasMessage){ this.sporocilo_za_bozic = christmasMessage; } public ArrayList<String> vrniImenaInPriimkeVsehKontaktov(List<Contact> vsiKontakti){ ArrayList<String> imenaKontaktov = new ArrayList<String>(); for(Contact kontakt:vsiKontakti){ imenaKontaktov.add(kontakt.getName()); } return imenaKontaktov; } }
3,634
0.632086
0.628784
150
23.226667
23.106462
191
false
false
0
0
0
0
0
0
0.366667
false
false
8
68b4043c33e01ce91e855d5048bbdd8c87b1cf51
39,539,468,953,511
b6c57eaa0597dff6377ca65cccbededa7b58bbc9
/src/AnimeNinja/Scraper.java
ebb7b43f544e78b517c182ab810c97c18dc22e0a
[]
no_license
khalidwaleed0/Anime_Ninja
https://github.com/khalidwaleed0/Anime_Ninja
b41b32ac9edad0c8ac7a631189ab1a483825ca8d
838dc065cab526761c1ac488c39fa25fddc26335
refs/heads/master
2022-11-10T19:51:23.641000
2022-10-27T11:23:47
2022-10-27T11:23:47
248,883,646
6
3
null
null
null
null
null
null
null
null
null
null
null
null
null
package AnimeNinja; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class Scraper { private static WebDriver driver; private static List <WebElement> seasons = new ArrayList<WebElement>(); private static List <String> seasonLinks = new ArrayList<String>(); private static List <File> seasonPhotos = new ArrayList<File>(); private static List <String> similarLinks = new ArrayList<String>(); private static List <File> similarPhotos = new ArrayList<File>(); protected static List <WebElement> episodes; protected static boolean showSimilar = false; protected static boolean onlyOneSimilar = false; protected static List <String> similarTexts = new ArrayList<String>(); protected static void setup() { System.setProperty("webdriver.chrome.driver", OsDetector.installationDirectory +File.separator+OsDetector.driverName); ChromeOptions chromeOptions = new ChromeOptions(); HashMap<String, Object> chromePrefs = new HashMap<String, Object>(); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("profile.default_content_setting_values.notifications", 2); chromeOptions.setExperimentalOption("prefs", chromePrefs); chromeOptions.addArguments("--headless"); chromeOptions.addArguments("--disable-gpu"); chromeOptions.addArguments("--unlimited-storage"); driver = new ChromeDriver(chromeOptions); driver.manage().window().setSize(new Dimension(1900,980)); driver.get("https://w.animesanka.com/search?q=haikyuu"); } protected static void close() { driver.close(); driver.quit(); } protected static File getPhoto(int num,boolean isSimilar) { if(isSimilar) return similarPhotos.get(num); else return seasonPhotos.get(num); } protected static boolean search(String animeName) //returns whether or not anime exists { seasons.removeAll(seasons); driver.navigate().to("https://w.animesanka.com/search?q="+animeName.trim().replaceAll("\\s", "+")); JavascriptExecutor js1 = ((JavascriptExecutor) driver); js1.executeScript("window.scrollTo(0, document.body.scrollHeight)"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } seasons = driver.findElements(By.cssSelector(".entry-content.rct-cards")); if(seasons.size() != 0) return true; else return false; } private static void clearOldData() { seasonLinks.removeAll(seasonLinks); seasonPhotos.removeAll(seasonPhotos); similarTexts.removeAll(similarTexts); similarLinks.removeAll(similarLinks); similarPhotos.removeAll(similarPhotos); } protected static List<String> getSeasons() // returns number of seasons (in order) (without ova , specials) { clearOldData(); Boolean isArabicOrder = false; List <String> seasonNames = new ArrayList<String>(); for(int i=0; i<seasons.size() ; i++) //gets seasonNames without ova,specials or movies { seasonNames.add(seasons.get(i).findElement(By.tagName("h2")).getText()); if(seasonNames.get(i).contains("الموسم")) isArabicOrder = true; else if(seasonNames.get(i).contains("season") || seasonNames.get(i).contains("Season")) {} else if((seasonNames.get(i).contains("أوفا") || seasonNames.get(i).toLowerCase().contains("movie") || seasonNames.get(i).contains("فيلم")|| seasonNames.get(i).contains("الخاصة")|| seasonNames.get(i).contains("الخاصه")) && (!seasonNames.get(i).contains("جميع حلقات"))) { seasonNames.remove(i); seasons.remove(i); i--; } else { similarTexts.add(seasonNames.get(i).replaceAll("(season \\d|FHD|BluRay|1080P|[^\\w\\s])", "").trim()); similarLinks.add(seasons.get(i).findElement(By.className("RecentThumb")).getAttribute("href")); similarPhotos.add(seasons.get(i).findElement(By.className("RecentThumb")).getScreenshotAs(OutputType.FILE)); seasons.remove(i); seasonNames.remove(i); i--; } } ArrayList<String> seasonOrder = orderArrange(isArabicOrder,seasonNames); return seasonReturn(seasonOrder); } private static void getLinkandPhoto(int j) { seasonLinks.add(seasons.get(j).findElement(By.className("RecentThumb")).getAttribute("href")); seasonPhotos.add(seasons.get(j).findElement(By.className("RecentThumb")).getScreenshotAs(OutputType.FILE)); } private static ArrayList<String> orderArrange(Boolean arabicOrder,List<String> seasonNames) // puts seasons in order because they are not ordered { // in the website ArrayList<String> seasonOrder; ArrayList<String> orderedSeasonNames = new ArrayList<String>(); if(arabicOrder) seasonOrder = new ArrayList<String>(Arrays.asList(new String[]{"الموسم الأول","الموسم الثان","الموسم الثالث","الموسم الرابع","الموسم الخامس","الموسم السادس"})); else seasonOrder = new ArrayList<String>(Arrays.asList(new String[]{"season 1","season 2","season 3","season 4","season 5","season 6"})); for(int i=0 ; i<6 ; i++) { for(int j=0 ; j<seasons.size() ; j++) { if(seasonNames.get(j).toLowerCase().contains(seasonOrder.get(i))) { if(seasonNames.get(j).contains("الجزء الأول") || seasonNames.get(j).toLowerCase().contains("part 1")) { orderedSeasonNames.add("Season "+(i+1)+" Part 1"); getLinkandPhoto(j); continue; } else if(seasonNames.get(j).contains("الجزء الثان") || seasonNames.get(j).toLowerCase().contains("part 2")) { orderedSeasonNames.add("Season "+(i+1)+" Part 2"); getLinkandPhoto(j); continue; } else orderedSeasonNames.add("Season "+(i+1)); getLinkandPhoto(j); break; } } } return orderedSeasonNames; } private static List<String> seasonReturn(ArrayList<String> orderedSeasonNames) { if(seasons.size()!=0) { if(similarTexts.size()!=0) { similarTexts.add(0, "Choose"); showSimilar = true; } orderedSeasonNames.add(0,"Choose"); return orderedSeasonNames; } else { if(similarTexts.size()==1) { onlyOneSimilar = true; similarTexts.add(0, "Choose"); return similarTexts; } else if(similarTexts.size() > 1) { similarTexts.add(0, "Choose"); showSimilar = true; return orderedSeasonNames; } else { JOptionPane.showMessageDialog(null, "NO Result"); return orderedSeasonNames; } } } protected static void selectSeason(int seasonNumber) { driver.get(seasonLinks.get(seasonNumber)); } protected static void selectSimilar(int num) { driver.get(similarLinks.get(num)); } protected static ArrayList<String> getEpisodes() //returns an Array containing episode numbers { try { String tvLink = driver.findElement(By.cssSelector(".tab-content-sanka.content3-sanka .ibtn.iNor.ibtn-4")).getAttribute("href"); Pattern pat = Pattern.compile("(animesanka\\.club.+)"); Matcher mat = pat.matcher(tvLink); if(mat.find()) driver.navigate().to("https://www."+mat.group(1).replaceAll("%2F", "/")); }catch(Exception e) { } ArrayList<String> episodeNumbers = new ArrayList<String>(); episodes = driver.findElements(By.cssSelector(".selective select option")); Collections.reverse(episodes); for(int i=0 ; i<episodes.size() ; i++) { episodeNumbers.add(episodes.get(i).getText().replaceAll("\\D+", "")); } episodeNumbers.add(0, "Choose"); return episodeNumbers; } }
UTF-8
Java
7,964
java
Scraper.java
Java
[]
null
[]
package AnimeNinja; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JOptionPane; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.OutputType; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; public class Scraper { private static WebDriver driver; private static List <WebElement> seasons = new ArrayList<WebElement>(); private static List <String> seasonLinks = new ArrayList<String>(); private static List <File> seasonPhotos = new ArrayList<File>(); private static List <String> similarLinks = new ArrayList<String>(); private static List <File> similarPhotos = new ArrayList<File>(); protected static List <WebElement> episodes; protected static boolean showSimilar = false; protected static boolean onlyOneSimilar = false; protected static List <String> similarTexts = new ArrayList<String>(); protected static void setup() { System.setProperty("webdriver.chrome.driver", OsDetector.installationDirectory +File.separator+OsDetector.driverName); ChromeOptions chromeOptions = new ChromeOptions(); HashMap<String, Object> chromePrefs = new HashMap<String, Object>(); chromePrefs.put("profile.default_content_settings.popups", 0); chromePrefs.put("profile.default_content_setting_values.notifications", 2); chromeOptions.setExperimentalOption("prefs", chromePrefs); chromeOptions.addArguments("--headless"); chromeOptions.addArguments("--disable-gpu"); chromeOptions.addArguments("--unlimited-storage"); driver = new ChromeDriver(chromeOptions); driver.manage().window().setSize(new Dimension(1900,980)); driver.get("https://w.animesanka.com/search?q=haikyuu"); } protected static void close() { driver.close(); driver.quit(); } protected static File getPhoto(int num,boolean isSimilar) { if(isSimilar) return similarPhotos.get(num); else return seasonPhotos.get(num); } protected static boolean search(String animeName) //returns whether or not anime exists { seasons.removeAll(seasons); driver.navigate().to("https://w.animesanka.com/search?q="+animeName.trim().replaceAll("\\s", "+")); JavascriptExecutor js1 = ((JavascriptExecutor) driver); js1.executeScript("window.scrollTo(0, document.body.scrollHeight)"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } seasons = driver.findElements(By.cssSelector(".entry-content.rct-cards")); if(seasons.size() != 0) return true; else return false; } private static void clearOldData() { seasonLinks.removeAll(seasonLinks); seasonPhotos.removeAll(seasonPhotos); similarTexts.removeAll(similarTexts); similarLinks.removeAll(similarLinks); similarPhotos.removeAll(similarPhotos); } protected static List<String> getSeasons() // returns number of seasons (in order) (without ova , specials) { clearOldData(); Boolean isArabicOrder = false; List <String> seasonNames = new ArrayList<String>(); for(int i=0; i<seasons.size() ; i++) //gets seasonNames without ova,specials or movies { seasonNames.add(seasons.get(i).findElement(By.tagName("h2")).getText()); if(seasonNames.get(i).contains("الموسم")) isArabicOrder = true; else if(seasonNames.get(i).contains("season") || seasonNames.get(i).contains("Season")) {} else if((seasonNames.get(i).contains("أوفا") || seasonNames.get(i).toLowerCase().contains("movie") || seasonNames.get(i).contains("فيلم")|| seasonNames.get(i).contains("الخاصة")|| seasonNames.get(i).contains("الخاصه")) && (!seasonNames.get(i).contains("جميع حلقات"))) { seasonNames.remove(i); seasons.remove(i); i--; } else { similarTexts.add(seasonNames.get(i).replaceAll("(season \\d|FHD|BluRay|1080P|[^\\w\\s])", "").trim()); similarLinks.add(seasons.get(i).findElement(By.className("RecentThumb")).getAttribute("href")); similarPhotos.add(seasons.get(i).findElement(By.className("RecentThumb")).getScreenshotAs(OutputType.FILE)); seasons.remove(i); seasonNames.remove(i); i--; } } ArrayList<String> seasonOrder = orderArrange(isArabicOrder,seasonNames); return seasonReturn(seasonOrder); } private static void getLinkandPhoto(int j) { seasonLinks.add(seasons.get(j).findElement(By.className("RecentThumb")).getAttribute("href")); seasonPhotos.add(seasons.get(j).findElement(By.className("RecentThumb")).getScreenshotAs(OutputType.FILE)); } private static ArrayList<String> orderArrange(Boolean arabicOrder,List<String> seasonNames) // puts seasons in order because they are not ordered { // in the website ArrayList<String> seasonOrder; ArrayList<String> orderedSeasonNames = new ArrayList<String>(); if(arabicOrder) seasonOrder = new ArrayList<String>(Arrays.asList(new String[]{"الموسم الأول","الموسم الثان","الموسم الثالث","الموسم الرابع","الموسم الخامس","الموسم السادس"})); else seasonOrder = new ArrayList<String>(Arrays.asList(new String[]{"season 1","season 2","season 3","season 4","season 5","season 6"})); for(int i=0 ; i<6 ; i++) { for(int j=0 ; j<seasons.size() ; j++) { if(seasonNames.get(j).toLowerCase().contains(seasonOrder.get(i))) { if(seasonNames.get(j).contains("الجزء الأول") || seasonNames.get(j).toLowerCase().contains("part 1")) { orderedSeasonNames.add("Season "+(i+1)+" Part 1"); getLinkandPhoto(j); continue; } else if(seasonNames.get(j).contains("الجزء الثان") || seasonNames.get(j).toLowerCase().contains("part 2")) { orderedSeasonNames.add("Season "+(i+1)+" Part 2"); getLinkandPhoto(j); continue; } else orderedSeasonNames.add("Season "+(i+1)); getLinkandPhoto(j); break; } } } return orderedSeasonNames; } private static List<String> seasonReturn(ArrayList<String> orderedSeasonNames) { if(seasons.size()!=0) { if(similarTexts.size()!=0) { similarTexts.add(0, "Choose"); showSimilar = true; } orderedSeasonNames.add(0,"Choose"); return orderedSeasonNames; } else { if(similarTexts.size()==1) { onlyOneSimilar = true; similarTexts.add(0, "Choose"); return similarTexts; } else if(similarTexts.size() > 1) { similarTexts.add(0, "Choose"); showSimilar = true; return orderedSeasonNames; } else { JOptionPane.showMessageDialog(null, "NO Result"); return orderedSeasonNames; } } } protected static void selectSeason(int seasonNumber) { driver.get(seasonLinks.get(seasonNumber)); } protected static void selectSimilar(int num) { driver.get(similarLinks.get(num)); } protected static ArrayList<String> getEpisodes() //returns an Array containing episode numbers { try { String tvLink = driver.findElement(By.cssSelector(".tab-content-sanka.content3-sanka .ibtn.iNor.ibtn-4")).getAttribute("href"); Pattern pat = Pattern.compile("(animesanka\\.club.+)"); Matcher mat = pat.matcher(tvLink); if(mat.find()) driver.navigate().to("https://www."+mat.group(1).replaceAll("%2F", "/")); }catch(Exception e) { } ArrayList<String> episodeNumbers = new ArrayList<String>(); episodes = driver.findElements(By.cssSelector(".selective select option")); Collections.reverse(episodes); for(int i=0 ; i<episodes.size() ; i++) { episodeNumbers.add(episodes.get(i).getText().replaceAll("\\D+", "")); } episodeNumbers.add(0, "Choose"); return episodeNumbers; } }
7,964
0.704044
0.697283
231
32.935066
33.730537
163
false
false
0
0
0
0
0
0
3.116883
false
false
8
1e5009b121274323e60f8f51b8a8109d9c6bbfee
5,918,464,969,743
6bcaeb4d0e7e48629404d57e1590c69dd4754498
/MK-WebApp-Library/src/main/java/by/training/nc/dev5/command/commandimpl/navigation/ToLoginCommand.java
05adcd131ee247ceddd26b7f64f30e333f3c4f22
[]
no_license
ATPod/nc-training
https://github.com/ATPod/nc-training
56a03fa01f96ebaa075f93134485180a069b0407
75dffd524be61f2675c0bda2bfacfbbad66c993b
refs/heads/master
2020-05-23T08:36:57.766000
2017-07-11T07:26:37
2017-07-11T07:26:37
84,756,625
1
6
null
false
2017-03-17T15:17:22
2017-03-12T20:52:38
2017-03-12T21:09:28
2017-03-17T15:17:22
33
0
0
0
Java
null
null
package by.training.nc.dev5.command.commandimpl.navigation; import by.training.nc.dev5.command.Command; import by.training.nc.dev5.util.ConstantsUtil; import javax.servlet.http.HttpServletRequest; public class ToLoginCommand implements Command { @Override public String execute(HttpServletRequest request) { return ConstantsUtil.LOGIN_PAGE; } }
UTF-8
Java
369
java
ToLoginCommand.java
Java
[]
null
[]
package by.training.nc.dev5.command.commandimpl.navigation; import by.training.nc.dev5.command.Command; import by.training.nc.dev5.util.ConstantsUtil; import javax.servlet.http.HttpServletRequest; public class ToLoginCommand implements Command { @Override public String execute(HttpServletRequest request) { return ConstantsUtil.LOGIN_PAGE; } }
369
0.780488
0.772358
14
25.357143
23.288891
59
false
false
0
0
0
0
0
0
0.357143
false
false
8
76f9ccaa091d8780e6bdf6d340d9934d96658ed8
29,669,634,136,405
5295a64e9dd5795b01fed1e2ec010df5d129b6ec
/src/org/mitre/svmp/protocol/SVMPMagneticFieldEventMessage.java
ace8c7308da010ca2694ca898946f07c7d196683
[ "Apache-2.0" ]
permissive
dkeppler/android_external_svmp_protocol
https://github.com/dkeppler/android_external_svmp_protocol
c07c8a74322b7ae71cac3d0d247ca87201607b84
21fc96c0f88391e40283483ced226071632ffd2d
refs/heads/master
2021-01-16T18:14:53.562000
2013-07-10T17:01:40
2013-07-10T17:01:40
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* Copyright 2013 The MITRE Corporation, All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.mitre.svmp.protocol; import java.io.Serializable; import java.nio.ByteBuffer; /** * See http://developer.android.com/reference/android/hardware/SensorEvent.html * * "All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and Z axis." * Presumably in that order in the values array. * * @author dkeppler * */ public class SVMPMagneticFieldEventMessage extends SVMPSensorEventMessage implements Serializable { private static final long serialVersionUID = 1L; private SVMPMagneticFieldEventMessage() { super(); this.type = SVMPSensorType.TYPE_MAGNETIC_FIELD; this.values = new float[3]; } public SVMPMagneticFieldEventMessage(ByteBuffer buf) { this(); decode(buf); } public SVMPMagneticFieldEventMessage(int accuracy, long timestamp, float values[]) { this(); this.accuracy = accuracy; this.timestamp = timestamp; if (values.length != 3) throw new IllegalArgumentException("MagneticField SensorEvents should have a 3-element 'value' input"); this.values[0] = values[0]; this.values[1] = values[1]; this.values[2] = values[2]; } }
UTF-8
Java
1,773
java
SVMPMagneticFieldEventMessage.java
Java
[ { "context": "n that order in the values array.\r\n * \r\n * @author dkeppler\r\n *\r\n */\r\npublic class SVMPMagneticFieldEventMess", "end": 973, "score": 0.9996381402015686, "start": 965, "tag": "USERNAME", "value": "dkeppler" } ]
null
[]
/* Copyright 2013 The MITRE Corporation, All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.mitre.svmp.protocol; import java.io.Serializable; import java.nio.ByteBuffer; /** * See http://developer.android.com/reference/android/hardware/SensorEvent.html * * "All values are in micro-Tesla (uT) and measure the ambient magnetic field in the X, Y and Z axis." * Presumably in that order in the values array. * * @author dkeppler * */ public class SVMPMagneticFieldEventMessage extends SVMPSensorEventMessage implements Serializable { private static final long serialVersionUID = 1L; private SVMPMagneticFieldEventMessage() { super(); this.type = SVMPSensorType.TYPE_MAGNETIC_FIELD; this.values = new float[3]; } public SVMPMagneticFieldEventMessage(ByteBuffer buf) { this(); decode(buf); } public SVMPMagneticFieldEventMessage(int accuracy, long timestamp, float values[]) { this(); this.accuracy = accuracy; this.timestamp = timestamp; if (values.length != 3) throw new IllegalArgumentException("MagneticField SensorEvents should have a 3-element 'value' input"); this.values[0] = values[0]; this.values[1] = values[1]; this.values[2] = values[2]; } }
1,773
0.728144
0.717992
57
29.105263
30.160788
106
false
false
0
0
0
0
0
0
1.105263
false
false
8
9a63f674b16237ab0b6f9039f146d7e284e487ee
23,072,564,365,000
f328426e360d6b6f404e30e1bdaf29f1ff6abdbe
/src/main/java/es/minetsii/wetsponge/event/plugin/WSPluginDisableEvent.java
ee8669d95b08c80da522f96f738bf2bfaa4dff83
[]
no_license
gaelitoelquesito/WetSponge
https://github.com/gaelitoelquesito/WetSponge
522a94642c451b71a26cd2bc865472bbaeac0b35
8725ef45f39bb26444f2b72aa6f262bca15c5554
refs/heads/master
2020-12-31T07:55:03.078000
2017-05-28T15:10:15
2017-05-28T15:10:15
86,510,993
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.minetsii.wetsponge.event.plugin; import es.minetsii.wetsponge.event.WSEvent; import es.minetsii.wetsponge.plugin.WSPlugin; public class WSPluginDisableEvent extends WSEvent { private WSPlugin plugin; public WSPluginDisableEvent (WSPlugin plugin) { this.plugin = plugin; } public WSPlugin getPlugin () { return plugin; } }
UTF-8
Java
351
java
WSPluginDisableEvent.java
Java
[]
null
[]
package es.minetsii.wetsponge.event.plugin; import es.minetsii.wetsponge.event.WSEvent; import es.minetsii.wetsponge.plugin.WSPlugin; public class WSPluginDisableEvent extends WSEvent { private WSPlugin plugin; public WSPluginDisableEvent (WSPlugin plugin) { this.plugin = plugin; } public WSPlugin getPlugin () { return plugin; } }
351
0.769231
0.769231
21
15.714286
19.299995
51
false
false
0
0
0
0
0
0
0.714286
false
false
8
51ee166cbe5bdba73681faa66942e46a65bcfb41
23,656,679,882,498
718a46fb5eb93496ca7fe80547eab52c2d7674a4
/src/main/java/scam/validation/SubCategoryValidator.java
bb41f99150e6236cfbf3078c7f741c50acd30de8
[]
no_license
ValoGenev/NewsBox-bg
https://github.com/ValoGenev/NewsBox-bg
d549aa268eb3033d134bba8b8a35fe392a969625
e25c3dc50c83a70be36e4d6bdba5f0e610461539
refs/heads/master
2023-08-25T11:17:44.980000
2021-10-18T20:05:16
2021-10-18T20:05:16
418,644,335
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package scam.validation; import org.apache.commons.lang3.EnumUtils; import scam.model.Category; import scam.model.SubCategory; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Set; public class SubCategoryValidator implements ConstraintValidator<ValidPostSubCategories, Set<String>> { @Override public boolean isValid(Set<String> subCategories, ConstraintValidatorContext constraintValidatorContext) { for (String category: subCategories) { if(!EnumUtils.isValidEnum(SubCategory.class,category)){ return false; } } return true; } }
UTF-8
Java
677
java
SubCategoryValidator.java
Java
[]
null
[]
package scam.validation; import org.apache.commons.lang3.EnumUtils; import scam.model.Category; import scam.model.SubCategory; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.Set; public class SubCategoryValidator implements ConstraintValidator<ValidPostSubCategories, Set<String>> { @Override public boolean isValid(Set<String> subCategories, ConstraintValidatorContext constraintValidatorContext) { for (String category: subCategories) { if(!EnumUtils.isValidEnum(SubCategory.class,category)){ return false; } } return true; } }
677
0.738552
0.737075
22
29.772728
30.485365
110
false
false
0
0
0
0
0
0
0.545455
false
false
8
5b8bcc329a1ba10301c6e1b5e65815b86ac7b11c
33,449,205,321,995
ea8e24092cb6c2453906b70d32227b4f59f71691
/src/easy/string/ReverseString.java
6812e0bc6559272d87bd4b9ef14655be3f0f2307
[]
no_license
wenhanglei/leetcode
https://github.com/wenhanglei/leetcode
0d5875c142809c0730ab580cd97ce0d45544366b
7b0f9f72e95fcdd493558c2db00561dcb0a498c2
refs/heads/master
2022-07-26T04:55:09.514000
2022-06-24T09:40:50
2022-06-24T09:40:50
123,376,817
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package easy.string; /** * Write a function that takes a string as input * and returns the string reversed. * @author wenhanglei */ public class ReverseString { /* * 思路: */ public String reverseString(String s) { //边界检查 if(s == null) return null; StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } // public String reverseString(String s) { // //边界检查 // if(s == null) return null; // char[] ca = s.toCharArray(); // StringBuilder sb = new StringBuilder(); // for(int i = ca.length-1; i >= 0; i--){ // sb.append(ca[i]); // } // return sb.toString(); // } /** * 测试函数 */ public static void main(String[] args) { ReverseString sol = new ReverseString(); String ret = sol.reverseString("hello"); System.out.println(ret); } }
UTF-8
Java
835
java
ReverseString.java
Java
[ { "context": "ut \n * and returns the string reversed.\n * @author wenhanglei\n */\npublic class ReverseString {\n\t/*\n\t * 思路:\n\t */", "end": 132, "score": 0.9189488887786865, "start": 122, "tag": "USERNAME", "value": "wenhanglei" } ]
null
[]
package easy.string; /** * Write a function that takes a string as input * and returns the string reversed. * @author wenhanglei */ public class ReverseString { /* * 思路: */ public String reverseString(String s) { //边界检查 if(s == null) return null; StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } // public String reverseString(String s) { // //边界检查 // if(s == null) return null; // char[] ca = s.toCharArray(); // StringBuilder sb = new StringBuilder(); // for(int i = ca.length-1; i >= 0; i--){ // sb.append(ca[i]); // } // return sb.toString(); // } /** * 测试函数 */ public static void main(String[] args) { ReverseString sol = new ReverseString(); String ret = sol.reverseString("hello"); System.out.println(ret); } }
835
0.613665
0.61118
37
20.756756
16.635042
49
false
false
0
0
0
0
0
0
1.459459
false
false
8
6eab633cba3482d9f52c741bbb07771e4acad771
32,804,960,252,678
112c43d2d5786aaf680744b4ea7d1319ed7ec7ca
/src/main/java/com/yin/crm/shop/controller/small/SmallShopGoodsCategoryController.java
6e2e4ad4445ccdd9a2ba8eb3f2ab11a3c4c84074
[]
no_license
xlyinweilong/crm-server
https://github.com/xlyinweilong/crm-server
90a562c34e2dd989107e0744d8fc5591f4c93e0f
d3750f2a8f7d9449d84b6ec8fc09c382d979768d
refs/heads/master
2020-06-11T00:30:32.479000
2020-06-10T04:05:24
2020-06-10T04:05:24
193,801,857
0
0
null
false
2020-07-01T18:49:48
2019-06-26T00:31:02
2020-06-24T01:36:52
2020-07-01T18:49:46
2,426
0
0
1
Java
false
false
package com.yin.crm.shop.controller.small; import com.yin.common.controller.BaseJson; import com.yin.common.exceptions.MessageException; import com.yin.crm.dao.ErpGoodsCategory2Dao; import com.yin.crm.dao.ErpGoodsCategoryDao; import com.yin.crm.entity.po.ErpGoodsCategory2Po; import com.yin.crm.entity.po.ErpGoodsCategoryPo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; /** * 分类 */ @RestController @RequestMapping(value = "api/small/shop/category") @Transactional(rollbackFor = Throwable.class) public class SmallShopGoodsCategoryController { @Autowired private ErpGoodsCategoryDao erpGoodsCategoryDao; @Autowired private ErpGoodsCategory2Dao erpGoodsCategory2Dao; /** * 查询首页 * * @return * @throws MessageException */ @GetMapping(value = "all") public BaseJson all() throws MessageException { List<ErpGoodsCategoryPo> list = erpGoodsCategoryDao.findAllByIsShowOrderBySortIndexAsc(true); List<ErpGoodsCategory2Po> subList = erpGoodsCategory2Dao.findAllByIsShowOrderBySortIndexAsc(true); list.stream().forEach(c -> c.setSubList(subList.stream().filter(c2 -> c.getId().equals(c2.getPid())).collect(Collectors.toList()))); return BaseJson.getSuccess(list); } }
UTF-8
Java
1,594
java
SmallShopGoodsCategoryController.java
Java
[]
null
[]
package com.yin.crm.shop.controller.small; import com.yin.common.controller.BaseJson; import com.yin.common.exceptions.MessageException; import com.yin.crm.dao.ErpGoodsCategory2Dao; import com.yin.crm.dao.ErpGoodsCategoryDao; import com.yin.crm.entity.po.ErpGoodsCategory2Po; import com.yin.crm.entity.po.ErpGoodsCategoryPo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; import java.util.stream.Collectors; /** * 分类 */ @RestController @RequestMapping(value = "api/small/shop/category") @Transactional(rollbackFor = Throwable.class) public class SmallShopGoodsCategoryController { @Autowired private ErpGoodsCategoryDao erpGoodsCategoryDao; @Autowired private ErpGoodsCategory2Dao erpGoodsCategory2Dao; /** * 查询首页 * * @return * @throws MessageException */ @GetMapping(value = "all") public BaseJson all() throws MessageException { List<ErpGoodsCategoryPo> list = erpGoodsCategoryDao.findAllByIsShowOrderBySortIndexAsc(true); List<ErpGoodsCategory2Po> subList = erpGoodsCategory2Dao.findAllByIsShowOrderBySortIndexAsc(true); list.stream().forEach(c -> c.setSubList(subList.stream().filter(c2 -> c.getId().equals(c2.getPid())).collect(Collectors.toList()))); return BaseJson.getSuccess(list); } }
1,594
0.77244
0.767383
46
33.391304
31.138176
140
false
false
0
0
0
0
0
0
0.434783
false
false
8
2727d010b43a3d0b837548dd94b383db420a7fc8
12,343,736,062,072
53dbfb708f7cbdcb01ef93b71a043af76d6e899a
/back/IoTBackend/src/main/java/com/ssafy/IoTBackend/mapper/ChoiceMapper.java
81bd3950c2e11ea94488dfb0d1afbf27b3f0954f
[ "MIT" ]
permissive
taerok/nongbunae
https://github.com/taerok/nongbunae
8a516487ece768668e6877a1f5d3e39f757d2272
a04f019a6ab2ac6107bc3b051126df72ae68139c
refs/heads/master
2023-01-29T10:20:07.471000
2020-11-25T07:49:22
2020-11-25T07:49:22
315,864,275
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ssafy.IoTBackend.mapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import com.ssafy.IoTBackend.model.Choice; @Repository @Mapper public interface ChoiceMapper { public int insertChoice(Choice choice) throws Exception; public int stopChoice(String choice_id) throws Exception; public Choice selectChoice(String user_id) throws Exception; }
UTF-8
Java
416
java
ChoiceMapper.java
Java
[]
null
[]
package com.ssafy.IoTBackend.mapper; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository; import com.ssafy.IoTBackend.model.Choice; @Repository @Mapper public interface ChoiceMapper { public int insertChoice(Choice choice) throws Exception; public int stopChoice(String choice_id) throws Exception; public Choice selectChoice(String user_id) throws Exception; }
416
0.8125
0.8125
17
23.470589
23.537498
61
false
false
0
0
0
0
0
0
0.764706
false
false
8
671dd68f81be5a0c1080710692f1668dd3bdba19
4,346,506,971,834
0ef3622d64aeee7dfb3c8647eaa5015bba220858
/src/Chapter1/ArrayAndString/Q2.java
eda77079f3bf732c6c1c23db721e048732483d52
[]
no_license
zfu/PlayAlgo
https://github.com/zfu/PlayAlgo
1e1b0790a49729e360271636925aefee417008fe
e113e9f5f81205109043eb2d20830b9352eb4c3a
refs/heads/master
2016-09-06T07:24:36.853000
2014-01-27T05:06:10
2014-01-27T05:06:10
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Chapter1.ArrayAndString; /** * question 2 * Write code to reverse a C-Style String. * (C-String means that “abcd” is represented as five characters, * including the null character.) * 写代码翻转一个C风格的字符串。(C风格的意思是"abcd"需要用5个字符来表示,包含末尾的 结束字符) * * 考虑: * 字符串是如何存储的,是利用数组存储,还是利用链表来存储? * 如果字符串是用数组存储,对于c语言,因为不像java,对数组存储了长度,所以,需要首先遍历到数组的末尾(遇到'\0'字符),找到末尾字符后, * 然后交换头尾字符。 * * 如果字符串是用含有头结点的链表存储(可能性基本没有,这里只是为了尝试头插法,来翻转字符串),遇到'\0'就结束了。 * * method1:用数组存储 * method2:用链表存储 */ public class Q2 { public static void main(String[] args) { System.out.println(ReverseCStyleString1("abcdefg")); System.out.println(ReverseCStyleString2("abcdefg")); System.out.println(ReverseCStyleString3("abcdefg")); } /** * 1. in-place * time: O(n), space: O(1) * @param s * @return */ public static String ReverseCStyleString1(String s){ char[] result = s.toCharArray(); for(int i = 0; i <= (s.length() - 1) / 2; i++){ char temp = result[i]; result[i] = result[s.length() - 1 - i]; result[s.length() - 1 - i] = temp; } return new String(result); } /** * 2. time: O(n), space: O(n) * @param s * @return */ public static String ReverseCStyleString2(String s){ StringBuilder sb = new StringBuilder(); //sb.append("null"); for(int i = s.length() - 1; i >= 0; i --){ char c = s.charAt(i); sb.append(c); } return sb.toString(); } public static String ReverseCStyleString3(String s){ char[] c = s.toCharArray(); int head = 0; int tail = s.length() - 1; System.out.println(tail); while(head < tail){ char temp = c[head]; c[head] = c[tail]; c[tail] = temp; ++head; --tail; } return new String(c); } }
GB18030
Java
2,173
java
Q2.java
Java
[]
null
[]
package Chapter1.ArrayAndString; /** * question 2 * Write code to reverse a C-Style String. * (C-String means that “abcd” is represented as five characters, * including the null character.) * 写代码翻转一个C风格的字符串。(C风格的意思是"abcd"需要用5个字符来表示,包含末尾的 结束字符) * * 考虑: * 字符串是如何存储的,是利用数组存储,还是利用链表来存储? * 如果字符串是用数组存储,对于c语言,因为不像java,对数组存储了长度,所以,需要首先遍历到数组的末尾(遇到'\0'字符),找到末尾字符后, * 然后交换头尾字符。 * * 如果字符串是用含有头结点的链表存储(可能性基本没有,这里只是为了尝试头插法,来翻转字符串),遇到'\0'就结束了。 * * method1:用数组存储 * method2:用链表存储 */ public class Q2 { public static void main(String[] args) { System.out.println(ReverseCStyleString1("abcdefg")); System.out.println(ReverseCStyleString2("abcdefg")); System.out.println(ReverseCStyleString3("abcdefg")); } /** * 1. in-place * time: O(n), space: O(1) * @param s * @return */ public static String ReverseCStyleString1(String s){ char[] result = s.toCharArray(); for(int i = 0; i <= (s.length() - 1) / 2; i++){ char temp = result[i]; result[i] = result[s.length() - 1 - i]; result[s.length() - 1 - i] = temp; } return new String(result); } /** * 2. time: O(n), space: O(n) * @param s * @return */ public static String ReverseCStyleString2(String s){ StringBuilder sb = new StringBuilder(); //sb.append("null"); for(int i = s.length() - 1; i >= 0; i --){ char c = s.charAt(i); sb.append(c); } return sb.toString(); } public static String ReverseCStyleString3(String s){ char[] c = s.toCharArray(); int head = 0; int tail = s.length() - 1; System.out.println(tail); while(head < tail){ char temp = c[head]; c[head] = c[tail]; c[tail] = temp; ++head; --tail; } return new String(c); } }
2,173
0.600113
0.585448
77
21.025974
19.054245
73
false
false
0
0
0
0
0
0
1.675325
false
false
8
b9326c3c30a75d21061bc88722b1ac44a552ca0d
11,914,239,339,277
e0ee69769ab7b6049b759becbf07471ece07cc63
/eyun-union-base/src/main/java/com/rainsoft/union/web/sysmanage/model/ParamFilter.java
91d18b1a1c49718122f40dea7df398420e5abc42
[]
no_license
joshLV/eyun
https://github.com/joshLV/eyun
558ec79f24103c57c94625bc8fa9f7c330378699
dcfd2a9eca8836712a44e12c17d0d2dc077e1544
refs/heads/master
2021-05-14T15:10:35.707000
2017-09-01T10:47:02
2017-09-01T10:47:02
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.rainsoft.union.web.sysmanage.model; import com.rainsoft.base.common.model.IdEntity; import com.rainsoft.union.web.pubdata.model.PlaceEnum; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class ParamFilter extends IdEntity { private int placeId; private String placeCode; //场所编号 private String placeName; //场所名称 private String serialNum; //设备序列号 private Integer memberID; //用户id private String memberName; //用户名 //for place Sms recharge private String smsFeeOwnerFlag; //场所短信付费方式 S:自费,Y:公司付费 private Integer placeDeviceId; //场所设备Id //for whiteList manage(白名单管理) private String mobile; //手机号 private int entityId; //对象主键 private String eyunId; //易韵账号 private String idCard; //身份证号 private String devMac; //设备Mac地址 public int getPlaceId() { return placeId; } public void setPlaceId(int placeId) { this.placeId = placeId; } public String getPlaceName() { return placeName; } public void setPlaceName(String placeName) { this.placeName = placeName; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getEntityId() { return entityId; } public void setEntityId(int entityId) { this.entityId = entityId; } public String getEyunId() { return eyunId; } public void setEyunId(String eyunId) { this.eyunId = eyunId; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } @Override public String getPlaceCode() { return placeCode; } @Override public void setPlaceCode(String placeCode) { this.placeCode = placeCode; } public Integer getMemberID() { return memberID; } public void setMemberID(Integer memberID) { this.memberID = memberID; } public String getDevMac() { return devMac; } public void setDevMac(String devMac) { this.devMac = devMac; } public String getSerialNum() { return serialNum; } public void setSerialNum(String serialNum) { this.serialNum = serialNum; } public String getSmsFeeOwnerFlag() { if(smsFeeOwnerFlag==null || "".equals(smsFeeOwnerFlag.trim())){ setSmsFeeOwnerFlag(PlaceEnum.SMSFEE_PLACE.getCode());//默认场所付费 } return smsFeeOwnerFlag; } public void setSmsFeeOwnerFlag(String smsFeeOwnerFlag) { this.smsFeeOwnerFlag = smsFeeOwnerFlag; } public Integer getPlaceDeviceId() { return placeDeviceId; } public void setPlaceDeviceId(Integer placeDeviceId) { this.placeDeviceId = placeDeviceId; } //-------------------------------------------------------------------------- // add by qianna //-------------------------------------------------------------------------- public Map<String,Object> toMap(){ Field[] fields = getClass().getDeclaredFields(); Map<String, Object> map = new HashMap<String, Object>(); if(fields != null && fields.length > 0 ){ Field tempField = null; //每个属性对象 String fieldName = "";//属性名称 Object fieldVal = null;//属性值 for( int i = 0 ; i < fields.length ; i++ ){ tempField = fields[i]; if(tempField != null){ try { fieldVal = tempField.get(this); if(fieldVal != null && !"".equals(fieldVal) && !"null".equals(fieldVal)){ map.put(tempField.getName(), fieldVal); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } return map; } }
UTF-8
Java
3,780
java
ParamFilter.java
Java
[ { "context": "r memberID; //用户id\n\tprivate String memberName; //用户名\n\t//for place Sms recharge\n\tprivate String smsFeeO", "end": 473, "score": 0.8013774156570435, "start": 470, "tag": "USERNAME", "value": "用户名" }, { "context": "int entityId; //对象主键\n\tprivate String eyunId; //易韵账号\n\tprivate String idCard; //身份证号\n\tprivate Strin", "end": 729, "score": 0.5985506772994995, "start": 728, "tag": "NAME", "value": "易" }, { "context": "nt entityId; //对象主键\n\tprivate String eyunId; //易韵账号\n\tprivate String idCard; //身份证号\n\tprivate String", "end": 730, "score": 0.5276695489883423, "start": 729, "tag": "NAME", "value": "韵" }, { "context": "---------------------------------------\n\t// add by qianna\n\t//----------------------------------------------", "end": 2781, "score": 0.9979494214057922, "start": 2775, "tag": "USERNAME", "value": "qianna" } ]
null
[]
package com.rainsoft.union.web.sysmanage.model; import com.rainsoft.base.common.model.IdEntity; import com.rainsoft.union.web.pubdata.model.PlaceEnum; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class ParamFilter extends IdEntity { private int placeId; private String placeCode; //场所编号 private String placeName; //场所名称 private String serialNum; //设备序列号 private Integer memberID; //用户id private String memberName; //用户名 //for place Sms recharge private String smsFeeOwnerFlag; //场所短信付费方式 S:自费,Y:公司付费 private Integer placeDeviceId; //场所设备Id //for whiteList manage(白名单管理) private String mobile; //手机号 private int entityId; //对象主键 private String eyunId; //易韵账号 private String idCard; //身份证号 private String devMac; //设备Mac地址 public int getPlaceId() { return placeId; } public void setPlaceId(int placeId) { this.placeId = placeId; } public String getPlaceName() { return placeName; } public void setPlaceName(String placeName) { this.placeName = placeName; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getEntityId() { return entityId; } public void setEntityId(int entityId) { this.entityId = entityId; } public String getEyunId() { return eyunId; } public void setEyunId(String eyunId) { this.eyunId = eyunId; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } @Override public String getPlaceCode() { return placeCode; } @Override public void setPlaceCode(String placeCode) { this.placeCode = placeCode; } public Integer getMemberID() { return memberID; } public void setMemberID(Integer memberID) { this.memberID = memberID; } public String getDevMac() { return devMac; } public void setDevMac(String devMac) { this.devMac = devMac; } public String getSerialNum() { return serialNum; } public void setSerialNum(String serialNum) { this.serialNum = serialNum; } public String getSmsFeeOwnerFlag() { if(smsFeeOwnerFlag==null || "".equals(smsFeeOwnerFlag.trim())){ setSmsFeeOwnerFlag(PlaceEnum.SMSFEE_PLACE.getCode());//默认场所付费 } return smsFeeOwnerFlag; } public void setSmsFeeOwnerFlag(String smsFeeOwnerFlag) { this.smsFeeOwnerFlag = smsFeeOwnerFlag; } public Integer getPlaceDeviceId() { return placeDeviceId; } public void setPlaceDeviceId(Integer placeDeviceId) { this.placeDeviceId = placeDeviceId; } //-------------------------------------------------------------------------- // add by qianna //-------------------------------------------------------------------------- public Map<String,Object> toMap(){ Field[] fields = getClass().getDeclaredFields(); Map<String, Object> map = new HashMap<String, Object>(); if(fields != null && fields.length > 0 ){ Field tempField = null; //每个属性对象 String fieldName = "";//属性名称 Object fieldVal = null;//属性值 for( int i = 0 ; i < fields.length ; i++ ){ tempField = fields[i]; if(tempField != null){ try { fieldVal = tempField.get(this); if(fieldVal != null && !"".equals(fieldVal) && !"null".equals(fieldVal)){ map.put(tempField.getName(), fieldVal); } } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } return map; } }
3,780
0.667772
0.667219
163
21.19632
18.947735
79
false
false
0
0
0
0
0
0
1.815951
false
false
8
b1393e91fd826804b9d6d6807961f6126a9a0344
11,416,023,133,941
6e272ec8d0429d9eba84e8ceb88eff566de4c9cd
/PatronMaestrodetalleOrientacionPantalla/app/src/main/java/com/example/gamer/patronmaestrodetalleorientacionpantalla/fragmentos/ListaPersonajeFragment.java
e1a0d52daf34879939be2518650c797958a856fe
[]
no_license
chirreescate/PatronMaestrpDetalle
https://github.com/chirreescate/PatronMaestrpDetalle
29b18d2a4b794c53cd4cee5ee8f106301ae26c04
56a9830b70271742882edaa23b95256a20eab548
refs/heads/master
2020-03-22T22:49:48.718000
2018-12-17T06:27:47
2018-12-17T06:27:47
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.gamer.patronmaestrodetalleorientacionpantalla.fragmentos; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.gamer.patronmaestrodetalleorientacionpantalla.R; import com.example.gamer.patronmaestrodetalleorientacionpantalla.adaptadores.AdaptadorPersonajes; import com.example.gamer.patronmaestrodetalleorientacionpantalla.entidades.Personajes; import com.example.gamer.patronmaestrodetalleorientacionpantalla.interfaces.ComunicacionFragments; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class ListaPersonajeFragment extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; ArrayList<Personajes> listapersonajes; @BindView(R.id.reciclador) RecyclerView reciclador; Activity activity;//referencia a un activity para obterner el contexto ComunicacionFragments comunicacionfragments;//instancio la interface private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public ListaPersonajeFragment() { // Required empty public constructor } public static ListaPersonajeFragment newInstance(String param1, String param2) { ListaPersonajeFragment fragment = new ListaPersonajeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v=inflater.inflate(R.layout.fragment_lista_personaje, container, false); listapersonajes = new ArrayList<>(); ButterKnife.bind(this,v); reciclador.setLayoutManager(new LinearLayoutManager(getContext())); llenarlistapersonajes(); AdaptadorPersonajes miadapter = new AdaptadorPersonajes(listapersonajes); miadapter.setonclickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(),"seleccionado: "+listapersonajes.get(reciclador.getChildAdapterPosition(v)).getNombre(),Toast.LENGTH_SHORT).show(); comunicacionfragments.enviarpersonajes(listapersonajes.get(reciclador.getChildAdapterPosition(v)));//con esto enviamos el objeto completo. pero para que esto funcione se debe dar un implements en el main activity a esa interfaz } }); reciclador.setAdapter(miadapter); return v; } public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { if(context instanceof Activity){ this.activity=(Activity)context;//si el contexto es una instacia de un activity la referencia a la actividad sera = a ese contexto comunicacionfragments = (ComunicacionFragments)activity;//con esto esatablecemos la comunicacion entre la lista y el detalle } super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } public void llenarlistapersonajes(){ listapersonajes.add(new Personajes("Goku","te pega o te le pegas , se convierte en super tallarin y te saca la recsm",R.drawable.goku_cara,R.drawable.goku_detalle,"descripcion larga")); listapersonajes.add(new Personajes("Vegueta","se cree macho te le pegas ,y se pone a llorar como zuripanta",R.drawable.vegueta_cara,R.drawable.vegueta_detalle,"descri larga")); listapersonajes.add(new Personajes("Gohan","es gay y lo violo picoro",R.drawable.gohan_cara,R.drawable.gohan_detalle,"descri larga")); listapersonajes.add(new Personajes("Picoro","violo a gohan",R.drawable.picoro_cara,R.drawable.picoro_detalle,"descri larga")); listapersonajes.add(new Personajes("Krilin","el keni de DBZ",R.drawable.krilin_cara,R.drawable.krilin_detalle,"descri larga")); listapersonajes.add(new Personajes("Trunks","violado por 17 y 18 del fituro alterno",R.drawable.trunks_cara,R.drawable.trunks_detalle,"descri larga")); } }
UTF-8
Java
5,365
java
ListaPersonajeFragment.java
Java
[ { "context": "s(){\n\n listapersonajes.add(new Personajes(\"Goku\",\"te pega o te le pegas , se convierte en super t", "end": 4449, "score": 0.9753469824790955, "start": 4445, "tag": "NAME", "value": "Goku" }, { "context": "a\"));\n listapersonajes.add(new Personajes(\"Vegueta\",\"se cree macho te le pegas ,y se pone a llorar ", "end": 4646, "score": 0.9861201047897339, "start": 4639, "tag": "NAME", "value": "Vegueta" }, { "context": "a\"));\n listapersonajes.add(new Personajes(\"Gohan\",\"es gay y lo violo picoro\",R.drawable.gohan_cara", "end": 4830, "score": 0.9743380546569824, "start": 4825, "tag": "NAME", "value": "Gohan" }, { "context": "a\"));\n listapersonajes.add(new Personajes(\"Picoro\",\"violo a gohan\",R.drawable.picoro_cara,R.drawabl", "end": 4974, "score": 0.9735463261604309, "start": 4968, "tag": "NAME", "value": "Picoro" }, { "context": "a\"));\n listapersonajes.add(new Personajes(\"Krilin\",\"el keni de DBZ\",R.drawable.krilin_cara,R.drawab", "end": 5109, "score": 0.9906458258628845, "start": 5103, "tag": "NAME", "value": "Krilin" }, { "context": "\"));\n\n listapersonajes.add(new Personajes(\"Trunks\",\"violado por 17 y 18 del fituro alterno\",R.drawa", "end": 5246, "score": 0.8507553935050964, "start": 5240, "tag": "NAME", "value": "Trunks" } ]
null
[]
package com.example.gamer.patronmaestrodetalleorientacionpantalla.fragmentos; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.gamer.patronmaestrodetalleorientacionpantalla.R; import com.example.gamer.patronmaestrodetalleorientacionpantalla.adaptadores.AdaptadorPersonajes; import com.example.gamer.patronmaestrodetalleorientacionpantalla.entidades.Personajes; import com.example.gamer.patronmaestrodetalleorientacionpantalla.interfaces.ComunicacionFragments; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; public class ListaPersonajeFragment extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; ArrayList<Personajes> listapersonajes; @BindView(R.id.reciclador) RecyclerView reciclador; Activity activity;//referencia a un activity para obterner el contexto ComunicacionFragments comunicacionfragments;//instancio la interface private String mParam1; private String mParam2; private OnFragmentInteractionListener mListener; public ListaPersonajeFragment() { // Required empty public constructor } public static ListaPersonajeFragment newInstance(String param1, String param2) { ListaPersonajeFragment fragment = new ListaPersonajeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v=inflater.inflate(R.layout.fragment_lista_personaje, container, false); listapersonajes = new ArrayList<>(); ButterKnife.bind(this,v); reciclador.setLayoutManager(new LinearLayoutManager(getContext())); llenarlistapersonajes(); AdaptadorPersonajes miadapter = new AdaptadorPersonajes(listapersonajes); miadapter.setonclickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getContext(),"seleccionado: "+listapersonajes.get(reciclador.getChildAdapterPosition(v)).getNombre(),Toast.LENGTH_SHORT).show(); comunicacionfragments.enviarpersonajes(listapersonajes.get(reciclador.getChildAdapterPosition(v)));//con esto enviamos el objeto completo. pero para que esto funcione se debe dar un implements en el main activity a esa interfaz } }); reciclador.setAdapter(miadapter); return v; } public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onFragmentInteraction(uri); } } @Override public void onAttach(Context context) { if(context instanceof Activity){ this.activity=(Activity)context;//si el contexto es una instacia de un activity la referencia a la actividad sera = a ese contexto comunicacionfragments = (ComunicacionFragments)activity;//con esto esatablecemos la comunicacion entre la lista y el detalle } super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } public void llenarlistapersonajes(){ listapersonajes.add(new Personajes("Goku","te pega o te le pegas , se convierte en super tallarin y te saca la recsm",R.drawable.goku_cara,R.drawable.goku_detalle,"descripcion larga")); listapersonajes.add(new Personajes("Vegueta","se cree macho te le pegas ,y se pone a llorar como zuripanta",R.drawable.vegueta_cara,R.drawable.vegueta_detalle,"descri larga")); listapersonajes.add(new Personajes("Gohan","es gay y lo violo picoro",R.drawable.gohan_cara,R.drawable.gohan_detalle,"descri larga")); listapersonajes.add(new Personajes("Picoro","violo a gohan",R.drawable.picoro_cara,R.drawable.picoro_detalle,"descri larga")); listapersonajes.add(new Personajes("Krilin","el keni de DBZ",R.drawable.krilin_cara,R.drawable.krilin_detalle,"descri larga")); listapersonajes.add(new Personajes("Trunks","violado por 17 y 18 del fituro alterno",R.drawable.trunks_cara,R.drawable.trunks_detalle,"descri larga")); } }
5,365
0.717428
0.713141
133
39.338345
44.324654
243
false
false
0
0
0
0
0
0
0.744361
false
false
8
e3f15fb54aa942329160aa308c12e5559724ece8
26,190,710,620,095
56ce6493952e02339090e775e2e286252f609657
/bf_seller/src/com/dt/bf_seller/main/ShopActivity.java
5684fc707004fe74d2446611cdef20b29cc85445
[]
no_license
shunsonglong/BF_Android
https://github.com/shunsonglong/BF_Android
6244dc8f9e5c07290882c5969bbbe02d3c6cb8bc
9c3d16f46fc5b2cccabfed03fdc212bc4608d6c5
refs/heads/master
2021-01-01T16:30:12.827000
2015-05-20T14:16:24
2015-05-20T14:16:24
34,986,024
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.dt.bf_seller.main; import com.dt.bf_seller.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ListView; public class ShopActivity extends Activity { private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop); initHeaderView(); } public void initHeaderView() { mListView = (ListView) findViewById(R.id.listview); LayoutInflater lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View headerView = lif.inflate(R.layout.shop_header_item, mListView, false); mListView.addHeaderView(headerView); mListView.setAdapter(null); } }
UTF-8
Java
822
java
ShopActivity.java
Java
[]
null
[]
package com.dt.bf_seller.main; import com.dt.bf_seller.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ListView; public class ShopActivity extends Activity { private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shop); initHeaderView(); } public void initHeaderView() { mListView = (ListView) findViewById(R.id.listview); LayoutInflater lif = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); View headerView = lif.inflate(R.layout.shop_header_item, mListView, false); mListView.addHeaderView(headerView); mListView.setAdapter(null); } }
822
0.779805
0.779805
33
23.90909
22.004633
90
false
false
0
0
0
0
0
0
1.363636
false
false
9
df027d0f300b09d446e9c2d36e710ea3b1868bf6
13,417,477,885,272
57bde89397505368a9c1dd0bbf5dfe2d881cf939
/javaee-api/src/main/java/com/intellij/javaee/model/enums/TimeUnitType.java
065773ed3229ed8432552c253a59c3197e6ffc7d
[ "Apache-2.0" ]
permissive
consulo/consulo-javaee
https://github.com/consulo/consulo-javaee
a8f669e102dff1792e0cc52c8f3f15d14c5c495c
b6c38fccd7cdbc4a2ce79d20fd6b0d5b5c3d7a6b
refs/heads/master
2021-07-23T06:03:35.101000
2021-06-16T14:22:41
2021-06-16T14:22:41
14,228,572
3
1
null
false
2017-07-15T11:53:12
2013-11-08T09:14:15
2017-05-28T19:55:41
2017-07-15T11:53:11
860
0
0
4
Java
null
null
/* * Copyright 2000-2009 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. */ // Generated on Tue Apr 28 15:56:22 MSD 2009 // DTD/Schema : http://java.sun.com/xml/ns/javaee package com.intellij.javaee.model.enums; /** * http://java.sun.com/xml/ns/javaee:time-unit-typeType enumeration. * <pre> * <h3>Enumeration http://java.sun.com/xml/ns/javaee:time-unit-typeType documentation</h3> * The time-unit-typeType represents a time duration at a given * unit of granularity. * The time unit type must be one of the following : * Days * Hours * Minutes * Seconds * Milliseconds * Microseconds * Nanoseconds * </pre> */ public enum TimeUnitType implements com.intellij.util.xml.NamedEnum { DAYS ("Days"), HOURS ("Hours"), MICROSECONDS ("Microseconds"), MILLISECONDS ("Milliseconds"), MINUTES ("Minutes"), NANOSECONDS ("Nanoseconds"), SECONDS ("Seconds"); private final String value; private TimeUnitType(String value) { this.value = value; } public String getValue() { return value; } }
UTF-8
Java
1,583
java
TimeUnitType.java
Java
[]
null
[]
/* * Copyright 2000-2009 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. */ // Generated on Tue Apr 28 15:56:22 MSD 2009 // DTD/Schema : http://java.sun.com/xml/ns/javaee package com.intellij.javaee.model.enums; /** * http://java.sun.com/xml/ns/javaee:time-unit-typeType enumeration. * <pre> * <h3>Enumeration http://java.sun.com/xml/ns/javaee:time-unit-typeType documentation</h3> * The time-unit-typeType represents a time duration at a given * unit of granularity. * The time unit type must be one of the following : * Days * Hours * Minutes * Seconds * Milliseconds * Microseconds * Nanoseconds * </pre> */ public enum TimeUnitType implements com.intellij.util.xml.NamedEnum { DAYS ("Days"), HOURS ("Hours"), MICROSECONDS ("Microseconds"), MILLISECONDS ("Milliseconds"), MINUTES ("Minutes"), NANOSECONDS ("Nanoseconds"), SECONDS ("Seconds"); private final String value; private TimeUnitType(String value) { this.value = value; } public String getValue() { return value; } }
1,583
0.699937
0.683512
51
30.039215
25.790985
90
false
false
0
0
0
0
0
0
0.686275
false
false
9
b5ca3da84b87d42905e44f846193ade06e672960
29,480,655,561,675
139c2f0477170cd96af2bda7921a2a1dd82b03f0
/src/main/java/com/jagrosh/vortex/database/managers/StrikeManager.java
9ab516d63af360c4aa94b9c83f31c33cbdf6eb82
[ "Apache-2.0" ]
permissive
Rxflex/vortmod
https://github.com/Rxflex/vortmod
b77b09b819536d6c0db9dfb967ff9e7b9e69ff4f
87fa89e926844ee8a61e630c370cd1a44aa14a04
refs/heads/master
2020-12-01T13:43:56.363000
2019-12-28T18:23:33
2019-12-28T18:23:33
230,645,991
1
0
Apache-2.0
false
2020-10-13T18:30:33
2019-12-28T18:14:44
2019-12-28T18:28:22
2020-10-13T18:30:31
1,025
1
0
1
Java
false
false
/* * Copyright 2018 John Grosh (john.a.grosh@gmail.com). * * 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.jagrosh.vortex.database.managers; import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.DatabaseConnector; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; /** * * @author John Grosh (john.a.grosh@gmail.com) */ public class StrikeManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0L); public final static SQLColumn<Long> USER_ID = new LongColumn("USER_ID", false, 0L); public final static SQLColumn<Integer> STRIKES = new IntegerColumn("STRIKES", false, 0); public StrikeManager(DatabaseConnector connector) { super(connector, "STRIKES"); } @Override protected String primaryKey() { return GUILD_ID+", "+USER_ID; } public int[] addStrikes(Guild guild, long targetId, int strikes) { return readWrite(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) { int current = STRIKES.getValue(rs); STRIKES.updateValue(rs, current+strikes<0 ? 0 : current+strikes); rs.updateRow(); return new int[]{current, current+strikes<0 ? 0 : current+strikes}; } else { rs.moveToInsertRow(); GUILD_ID.updateValue(rs, guild.getIdLong()); USER_ID.updateValue(rs, targetId); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.insertRow(); return new int[]{0, strikes<0 ? 0 : strikes}; } }); } /*public int[] setStrikes(Member target, int strikes) { return setStrikes(target.getGuild(), target.getUser().getIdLong(), strikes); } public int[] setStrikes(Guild guild, long targetId, int strikes) { return readWrite(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) { int current = STRIKES.getValue(rs); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.updateRow(); return new int[]{current, strikes<0 ? 0 : strikes}; } else { rs.moveToInsertRow(); GUILD_ID.updateValue(rs, guild.getIdLong()); USER_ID.updateValue(rs, targetId); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.insertRow(); return new int[]{0, strikes<0 ? 0 : strikes}; } }); }//*/ public int[] removeStrikes(Member target, int strikes) { return removeStrikes(target.getGuild(), target.getUser().getIdLong(), strikes); } public int[] removeStrikes(Guild guild, long targetId, int strikes) { return addStrikes(guild, targetId, -1*strikes); } public int getStrikes(Member target) { return getStrikes(target.getGuild(), target.getUser().getIdLong()); } public int getStrikes(Guild guild, long targetId) { return read(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) return STRIKES.getValue(rs); return 0; }); } }
UTF-8
Java
4,097
java
StrikeManager.java
Java
[ { "context": "/*\n * Copyright 2018 John Grosh (john.a.grosh@gmail.com).\n *\n * Licensed under th", "end": 31, "score": 0.9998819231987, "start": 21, "tag": "NAME", "value": "John Grosh" }, { "context": "/*\n * Copyright 2018 John Grosh (john.a.grosh@gmail.com).\n *\n * Licensed under the Apache License, Versio", "end": 55, "score": 0.9999324679374695, "start": 33, "tag": "EMAIL", "value": "john.a.grosh@gmail.com" }, { "context": "8tion.jda.core.entities.Member;\n\n/**\n *\n * @author John Grosh (john.a.grosh@gmail.com)\n */\npublic class StrikeM", "end": 948, "score": 0.9998804926872253, "start": 938, "tag": "NAME", "value": "John Grosh" }, { "context": "e.entities.Member;\n\n/**\n *\n * @author John Grosh (john.a.grosh@gmail.com)\n */\npublic class StrikeManager extends DataManag", "end": 972, "score": 0.9999316930770874, "start": 950, "tag": "EMAIL", "value": "john.a.grosh@gmail.com" } ]
null
[]
/* * Copyright 2018 <NAME> (<EMAIL>). * * 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.jagrosh.vortex.database.managers; import com.jagrosh.easysql.DataManager; import com.jagrosh.easysql.DatabaseConnector; import com.jagrosh.easysql.SQLColumn; import com.jagrosh.easysql.columns.*; import net.dv8tion.jda.core.entities.Guild; import net.dv8tion.jda.core.entities.Member; /** * * @author <NAME> (<EMAIL>) */ public class StrikeManager extends DataManager { public final static SQLColumn<Long> GUILD_ID = new LongColumn("GUILD_ID", false, 0L); public final static SQLColumn<Long> USER_ID = new LongColumn("USER_ID", false, 0L); public final static SQLColumn<Integer> STRIKES = new IntegerColumn("STRIKES", false, 0); public StrikeManager(DatabaseConnector connector) { super(connector, "STRIKES"); } @Override protected String primaryKey() { return GUILD_ID+", "+USER_ID; } public int[] addStrikes(Guild guild, long targetId, int strikes) { return readWrite(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) { int current = STRIKES.getValue(rs); STRIKES.updateValue(rs, current+strikes<0 ? 0 : current+strikes); rs.updateRow(); return new int[]{current, current+strikes<0 ? 0 : current+strikes}; } else { rs.moveToInsertRow(); GUILD_ID.updateValue(rs, guild.getIdLong()); USER_ID.updateValue(rs, targetId); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.insertRow(); return new int[]{0, strikes<0 ? 0 : strikes}; } }); } /*public int[] setStrikes(Member target, int strikes) { return setStrikes(target.getGuild(), target.getUser().getIdLong(), strikes); } public int[] setStrikes(Guild guild, long targetId, int strikes) { return readWrite(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) { int current = STRIKES.getValue(rs); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.updateRow(); return new int[]{current, strikes<0 ? 0 : strikes}; } else { rs.moveToInsertRow(); GUILD_ID.updateValue(rs, guild.getIdLong()); USER_ID.updateValue(rs, targetId); STRIKES.updateValue(rs, strikes<0 ? 0 : strikes); rs.insertRow(); return new int[]{0, strikes<0 ? 0 : strikes}; } }); }//*/ public int[] removeStrikes(Member target, int strikes) { return removeStrikes(target.getGuild(), target.getUser().getIdLong(), strikes); } public int[] removeStrikes(Guild guild, long targetId, int strikes) { return addStrikes(guild, targetId, -1*strikes); } public int getStrikes(Member target) { return getStrikes(target.getGuild(), target.getUser().getIdLong()); } public int getStrikes(Guild guild, long targetId) { return read(selectAll(GUILD_ID.is(guild.getId())+" AND "+USER_ID.is(targetId)), rs -> { if(rs.next()) return STRIKES.getValue(rs); return 0; }); } }
4,059
0.590188
0.582133
121
32.859505
28.747204
99
false
false
0
0
0
0
0
0
0.702479
false
false
9
7bc542e058c6321eb0f8072994a4b12363c5f9f9
33,586,644,272,958
777263f7f0abe4e101111e5d66dfe79d422047e3
/src/cz/zcu/viteja/uur/views/ControlMenu.java
ac0377f85b6db00330718c09004bc4f595a83538
[ "MIT" ]
permissive
Sognus/KIV_UUR
https://github.com/Sognus/KIV_UUR
4c477676cc0f2ab1ec96bea9a09ea02561ce3072
73b5d32c85022d6e66dc0e660e1c88a29d0efd9c
refs/heads/master
2020-12-23T09:51:15.388000
2020-01-30T01:23:09
2020-01-30T01:23:09
237,116,133
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cz.zcu.viteja.uur.views; import cz.zcu.viteja.uur.main.Main; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; public class ControlMenu { public static MenuBar getControlMenu() { MenuBar menu = new MenuBar(); Menu aplikace = new Menu("Aplikace"); MenuItem ukoncit = new MenuItem("Ukončit"); ukoncit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { Platform.exit(); } }); MenuItem pridatAkci = new MenuItem("Přidat akci"); pridatAkci.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { CreateFormView cfw = CreateFormView.getInstance(); Scene scene = cfw.setup(); Main.getInstance().setScene(scene); } }); aplikace.getItems().addAll(pridatAkci, new SeparatorMenuItem(), ukoncit); Menu zobrazit = new Menu("Zobrazit"); MenuItem rok = new MenuItem("Rok"); rok.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { YearCalendarView ycw = YearCalendarView.getInstance(); Scene scene = ycw.setup(); Main.getInstance().setScene(scene); } }); MenuItem mesic = new MenuItem("Měsíc"); mesic.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { MonthCalendarView mcw = MonthCalendarView.getInstance(); Scene scene = mcw.setup(); Main.getInstance().setScene(scene); } }); MenuItem agenda = new MenuItem("Agenda"); agenda.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { AgendaView aw = AgendaView.getInstance(); Scene scene = aw.setup(); Main.getInstance().setScene(scene); } }); MenuItem zobrazitData = new MenuItem("Uložená data"); zobrazitData.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { StoredDataView sdw = StoredDataView.getInstance(); Scene scene = sdw.setup(); Main.getInstance().setScene(scene); } }); zobrazit.getItems().addAll(rok, mesic, agenda, new SeparatorMenuItem(), zobrazitData); // Menus menu.getMenus().add(aplikace); menu.getMenus().add(zobrazit); return menu; } }
WINDOWS-1250
Java
2,444
java
ControlMenu.java
Java
[]
null
[]
package cz.zcu.viteja.uur.views; import cz.zcu.viteja.uur.main.Main; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.scene.control.SeparatorMenuItem; public class ControlMenu { public static MenuBar getControlMenu() { MenuBar menu = new MenuBar(); Menu aplikace = new Menu("Aplikace"); MenuItem ukoncit = new MenuItem("Ukončit"); ukoncit.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { Platform.exit(); } }); MenuItem pridatAkci = new MenuItem("Přidat akci"); pridatAkci.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { CreateFormView cfw = CreateFormView.getInstance(); Scene scene = cfw.setup(); Main.getInstance().setScene(scene); } }); aplikace.getItems().addAll(pridatAkci, new SeparatorMenuItem(), ukoncit); Menu zobrazit = new Menu("Zobrazit"); MenuItem rok = new MenuItem("Rok"); rok.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { YearCalendarView ycw = YearCalendarView.getInstance(); Scene scene = ycw.setup(); Main.getInstance().setScene(scene); } }); MenuItem mesic = new MenuItem("Měsíc"); mesic.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { MonthCalendarView mcw = MonthCalendarView.getInstance(); Scene scene = mcw.setup(); Main.getInstance().setScene(scene); } }); MenuItem agenda = new MenuItem("Agenda"); agenda.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent t) { AgendaView aw = AgendaView.getInstance(); Scene scene = aw.setup(); Main.getInstance().setScene(scene); } }); MenuItem zobrazitData = new MenuItem("Uložená data"); zobrazitData.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { StoredDataView sdw = StoredDataView.getInstance(); Scene scene = sdw.setup(); Main.getInstance().setScene(scene); } }); zobrazit.getItems().addAll(rok, mesic, agenda, new SeparatorMenuItem(), zobrazitData); // Menus menu.getMenus().add(aplikace); menu.getMenus().add(zobrazit); return menu; } }
2,444
0.710008
0.708778
97
24.13402
21.777046
88
false
false
0
0
0
0
0
0
2.237113
false
false
9
0f53f9bd5c3093ab26c4ae6212a1a20f7b1ac92b
11,519,102,329,215
61647060473692867ae30925278beea3d7faa381
/GameSupplyGUI/src/com/gamesupply/swing/NewSale.java
d4e24d6f7b519138eb495003d6d7a59edd3aa22e
[]
no_license
daniell1988/gamesupply
https://github.com/daniell1988/gamesupply
3162cb96e2aa22d1e1adb3c6eff0c68aff3f4c2f
3d9124c57d4b39b289d089aef1296f353c6b5e97
refs/heads/master
2016-09-06T21:23:27.768000
2013-06-11T14:03:19
2013-06-11T14:03:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gamesupply.swing; import com.gamesupply.controller.SaleController; import com.gamesupply.controller.StockController; import com.gamesupply.dto.SaleDTO; import com.gamesupply.dto.StockDTO; import java.util.ArrayList; import java.util.List; /** * * @author 40836665 */ public class NewSale extends javax.swing.JInternalFrame { private List<StockDTO> stockList = new ArrayList<StockDTO>(); private StockDTO selectedStockDTO = new StockDTO(); private SaleDTO saleDTO = new SaleDTO(); private String store; /** * Creates new form NewSale */ public NewSale(String store) { this.store = store; getBranchStock(store); initComponents(); } private void getBranchStock(String store) { this.stockList = new ArrayList<StockDTO>(); List<StockDTO> tmpStock = new ArrayList<StockDTO>(); tmpStock = StockController.findall(); for(StockDTO stockTmp : tmpStock){ StockDTO stockDTO = new StockDTO(); stockDTO.setBranch1(stockTmp.getBranch1()); stockDTO.setBranch2(stockTmp.getBranch2()); stockDTO.setBranch3(stockTmp.getBranch3()); stockDTO.setDescription(stockTmp.getDescription()); stockDTO.setGenre(stockTmp.getGenre()); stockDTO.setIdProduct(stockTmp.getIdProduct()); stockDTO.setName(stockTmp.getName()); stockDTO.setPlatform(stockTmp.getPlatform()); stockDTO.setPrice(stockTmp.getPrice()); stockDTO.setType(stockTmp.getType()); if(store.endsWith("A")){ stockDTO.setBranchQuantity(stockTmp.getBranch1()); } if(store.endsWith("B")){ stockDTO.setBranchQuantity(stockTmp.getBranch2()); } if(store.endsWith("C")){ stockDTO.setBranchQuantity(stockTmp.getBranch3()); } this.stockList.add(stockDTO); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); setClosable(true); setTitle("Nova Venda"); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${stockList}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}")); columnBinding.setColumnName("Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${platform}")); columnBinding.setColumnName("Plataforma"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${type}")); columnBinding.setColumnName("Tipo"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}")); columnBinding.setColumnName("Preço"); columnBinding.setColumnClass(Double.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${branchQuantity}")); columnBinding.setColumnName("Estoque Disponível"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedStock}"), jTable1, org.jdesktop.beansbinding.BeanProperty.create("selectedElement")); bindingGroup.addBinding(binding); jScrollPane1.setViewportView(jTable1); jButton1.setText("Finalizar Venda"); jButton1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jButton1StateChanged(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField1FocusGained(evt); } }); jLabel1.setText("Quantidade"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(153, 153, 153) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // this.selectedStockDTO.setIdProduct(Integer.parseInt(selecttedProductId.getText())); if(this.store.toUpperCase().endsWith("A")){ this.selectedStockDTO.setBranch1(this.selectedStockDTO.getBranch1() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial A"); } if(this.store.toUpperCase().endsWith("B")){ this.selectedStockDTO.setBranch2(this.selectedStockDTO.getBranch2() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial B"); } if(this.store.toUpperCase().endsWith("C")){ this.selectedStockDTO.setBranch3(this.selectedStockDTO.getBranch3() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial C"); } this.saleDTO.setQuantity(Integer.parseInt(jTextField1.getText())); this.saleDTO.setName(this.selectedStockDTO.getName()); this.saleDTO.setPlatform(this.selectedStockDTO.getPlatform()); this.saleDTO.setPrice(this.selectedStockDTO.getPrice().toString()); this.saleDTO.setType(this.selectedStockDTO.getType()); StockController.updateStock(this.selectedStockDTO); SaleController.create(this.saleDTO); getBranchStock(store); jTable1.repaint(); jScrollPane1.repaint(); }//GEN-LAST:event_jButton1ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jButton1StateChanged // TODO add your handling code here: }//GEN-LAST:event_jButton1StateChanged private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained // TODO add your handling code here: }//GEN-LAST:event_jTextField1FocusGained // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables public List<StockDTO> getStockList() { return stockList; } public void setStockList(List<StockDTO> stockList) { this.stockList = stockList; } public StockDTO getSelectedStock() { return selectedStockDTO; } public void setSelectedStock(StockDTO selectedStock) { this.selectedStockDTO = selectedStock; } public SaleDTO getSaleDTO() { return saleDTO; } public void setSaleDTO(SaleDTO saleDTO) { this.saleDTO = saleDTO; } }
UTF-8
Java
10,928
java
NewSale.java
Java
[ { "context": "ayList;\nimport java.util.List;\n\n/**\n *\n * @author 40836665\n */\npublic class NewSale extends javax.swing.JInt", "end": 379, "score": 0.9816304445266724, "start": 371, "tag": "USERNAME", "value": "40836665" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.gamesupply.swing; import com.gamesupply.controller.SaleController; import com.gamesupply.controller.StockController; import com.gamesupply.dto.SaleDTO; import com.gamesupply.dto.StockDTO; import java.util.ArrayList; import java.util.List; /** * * @author 40836665 */ public class NewSale extends javax.swing.JInternalFrame { private List<StockDTO> stockList = new ArrayList<StockDTO>(); private StockDTO selectedStockDTO = new StockDTO(); private SaleDTO saleDTO = new SaleDTO(); private String store; /** * Creates new form NewSale */ public NewSale(String store) { this.store = store; getBranchStock(store); initComponents(); } private void getBranchStock(String store) { this.stockList = new ArrayList<StockDTO>(); List<StockDTO> tmpStock = new ArrayList<StockDTO>(); tmpStock = StockController.findall(); for(StockDTO stockTmp : tmpStock){ StockDTO stockDTO = new StockDTO(); stockDTO.setBranch1(stockTmp.getBranch1()); stockDTO.setBranch2(stockTmp.getBranch2()); stockDTO.setBranch3(stockTmp.getBranch3()); stockDTO.setDescription(stockTmp.getDescription()); stockDTO.setGenre(stockTmp.getGenre()); stockDTO.setIdProduct(stockTmp.getIdProduct()); stockDTO.setName(stockTmp.getName()); stockDTO.setPlatform(stockTmp.getPlatform()); stockDTO.setPrice(stockTmp.getPrice()); stockDTO.setType(stockTmp.getType()); if(store.endsWith("A")){ stockDTO.setBranchQuantity(stockTmp.getBranch1()); } if(store.endsWith("B")){ stockDTO.setBranchQuantity(stockTmp.getBranch2()); } if(store.endsWith("C")){ stockDTO.setBranchQuantity(stockTmp.getBranch3()); } this.stockList.add(stockDTO); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); setClosable(true); setTitle("Nova Venda"); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${stockList}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, jTable1); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${name}")); columnBinding.setColumnName("Name"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${platform}")); columnBinding.setColumnName("Plataforma"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${type}")); columnBinding.setColumnName("Tipo"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${price}")); columnBinding.setColumnName("Preço"); columnBinding.setColumnClass(Double.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${branchQuantity}")); columnBinding.setColumnName("Estoque Disponível"); columnBinding.setColumnClass(Integer.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind();org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${selectedStock}"), jTable1, org.jdesktop.beansbinding.BeanProperty.create("selectedElement")); bindingGroup.addBinding(binding); jScrollPane1.setViewportView(jTable1); jButton1.setText("Finalizar Venda"); jButton1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jButton1StateChanged(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jTextField1.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { jTextField1FocusGained(evt); } }); jLabel1.setText("Quantidade"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 541, Short.MAX_VALUE) .addContainerGap()) .addGroup(layout.createSequentialGroup() .addGap(153, 153, 153) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // this.selectedStockDTO.setIdProduct(Integer.parseInt(selecttedProductId.getText())); if(this.store.toUpperCase().endsWith("A")){ this.selectedStockDTO.setBranch1(this.selectedStockDTO.getBranch1() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial A"); } if(this.store.toUpperCase().endsWith("B")){ this.selectedStockDTO.setBranch2(this.selectedStockDTO.getBranch2() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial B"); } if(this.store.toUpperCase().endsWith("C")){ this.selectedStockDTO.setBranch3(this.selectedStockDTO.getBranch3() - Integer.parseInt(jTextField1.getText())); this.saleDTO.setBranch("Filial C"); } this.saleDTO.setQuantity(Integer.parseInt(jTextField1.getText())); this.saleDTO.setName(this.selectedStockDTO.getName()); this.saleDTO.setPlatform(this.selectedStockDTO.getPlatform()); this.saleDTO.setPrice(this.selectedStockDTO.getPrice().toString()); this.saleDTO.setType(this.selectedStockDTO.getType()); StockController.updateStock(this.selectedStockDTO); SaleController.create(this.saleDTO); getBranchStock(store); jTable1.repaint(); jScrollPane1.repaint(); }//GEN-LAST:event_jButton1ActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void jButton1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jButton1StateChanged // TODO add your handling code here: }//GEN-LAST:event_jButton1StateChanged private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1FocusGained // TODO add your handling code here: }//GEN-LAST:event_jTextField1FocusGained // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables public List<StockDTO> getStockList() { return stockList; } public void setStockList(List<StockDTO> stockList) { this.stockList = stockList; } public StockDTO getSelectedStock() { return selectedStockDTO; } public void setSelectedStock(StockDTO selectedStock) { this.selectedStockDTO = selectedStock; } public SaleDTO getSaleDTO() { return saleDTO; } public void setSaleDTO(SaleDTO saleDTO) { this.saleDTO = saleDTO; } }
10,928
0.665111
0.656324
256
41.679688
39.608223
337
false
false
0
0
0
0
0
0
0.519531
false
false
9
6c054dd34f052a479f0378798b23cbe58ae91964
18,296,560,681,732
53b3ed3e80107e6022540166721b635d29400059
/src/MergeOrAdd/MergeSortedArray.java
9eef99c78f71a91f32b6b58aaf75e8a13c8ed2d1
[]
no_license
ohyeahfanfan/Questions
https://github.com/ohyeahfanfan/Questions
1a9724cc8a999f49891cb1a6b2b2d31355a09588
2b0461015a5032afdf1636239fb589b4730eac3e
refs/heads/master
2016-09-02T03:11:18.194000
2014-01-26T02:36:19
2014-01-26T02:36:19
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package MergeOrAdd; public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. while(n > 0){ if(m > 0 && A[m-1] > B[n-1]){// A = [], B = [1] !!! m > 0 A[m + n -1] = A[m - 1]; m--; }else{ A[m + n -1] = B[n - 1]; n--; } } } }
UTF-8
Java
467
java
MergeSortedArray.java
Java
[]
null
[]
package MergeOrAdd; public class MergeSortedArray { public void merge(int A[], int m, int B[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. while(n > 0){ if(m > 0 && A[m-1] > B[n-1]){// A = [], B = [1] !!! m > 0 A[m + n -1] = A[m - 1]; m--; }else{ A[m + n -1] = B[n - 1]; n--; } } } }
467
0.396146
0.374732
16
28.1875
24.978037
95
false
false
0
0
0
0
0
0
0.625
false
false
9
4dce39e39cfe9bada37ca4be2dc01bd0f64ca521
16,071,767,688,065
14d710a15ab34db9442fac4c45b3d3ca00c6466e
/SpringBoot/src/test/java/com/mosen/ApplicationTests.java
39b59eeabdedad2395360ddeed05e99f16ea1905
[]
no_license
MosenNiu/CodeRepository
https://github.com/MosenNiu/CodeRepository
6d2c22eda6f04227ee81d1f2dc23735cb9e6cd04
30561cc592f2dbacd3fad0759c70b18351369a72
refs/heads/master
2022-12-25T23:19:00.717000
2021-01-20T10:34:20
2021-01-20T10:34:20
101,155,210
0
0
null
false
2022-12-16T08:39:43
2017-08-23T08:10:23
2021-01-20T10:36:18
2022-12-16T08:39:41
294
0
0
22
Java
false
false
package com.mosen; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.Future; @RunWith(SpringRunner.class) @SpringBootTest() public class ApplicationTests { @Autowired private MyThreadTest myThreadTest; @Test public void contextLoads() { } @Test // @Async("myExecutor") public void myThreadTest() { System.out.println(Thread.currentThread().getId()+"for开始"); int j= 0; int k= 0; for (int i = 0; i < 100; i++) { // int finalI = i; // FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable() { // @Override // public String call() throws Exception { // return myThreadTest.test(finalI); // } // }); // myExecutor.execute(futureTask); // try { // //返回结果,最长等待5S // futureTask.get(5,TimeUnit.SECONDS); // } catch (Exception e) { // e.printStackTrace(); // } finally { // //关闭进程,防止阻塞 // futureTask.cancel(true); // } myThreadTest.test(i); Future future = myThreadTest.test1(i); myThreadTest.overOne(future); j++; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getId()+"for结束"); System.out.println("over"+j+","+k); } }
UTF-8
Java
1,467
java
ApplicationTests.java
Java
[]
null
[]
package com.mosen; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.concurrent.Future; @RunWith(SpringRunner.class) @SpringBootTest() public class ApplicationTests { @Autowired private MyThreadTest myThreadTest; @Test public void contextLoads() { } @Test // @Async("myExecutor") public void myThreadTest() { System.out.println(Thread.currentThread().getId()+"for开始"); int j= 0; int k= 0; for (int i = 0; i < 100; i++) { // int finalI = i; // FutureTask<Boolean> futureTask = new FutureTask<Boolean>(new Callable() { // @Override // public String call() throws Exception { // return myThreadTest.test(finalI); // } // }); // myExecutor.execute(futureTask); // try { // //返回结果,最长等待5S // futureTask.get(5,TimeUnit.SECONDS); // } catch (Exception e) { // e.printStackTrace(); // } finally { // //关闭进程,防止阻塞 // futureTask.cancel(true); // } myThreadTest.test(i); Future future = myThreadTest.test1(i); myThreadTest.overOne(future); j++; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getId()+"for结束"); System.out.println("over"+j+","+k); } }
1,467
0.675334
0.665495
60
22.716667
18.922729
78
false
false
0
0
0
0
0
0
2.3
false
false
9
0bf780974264f38cae6e45676dd2dbc34c912dd2
7,937,099,564,961
e067bc368a9590944efda8ce87bddee097e5fd05
/zk-web/src/main/java/com/quanle/service/impl/ArticleServiceImpl.java
76a36ec75dd1be66f0578e7f56208a8e4369beb5
[]
no_license
zhanlele/zdyRPC
https://github.com/zhanlele/zdyRPC
bd24d1d069782dcc577c27d7cc825d107697a2d6
61177c8a8f71b58909584ff907d9f4116680f17c
refs/heads/master
2022-07-02T04:39:07.856000
2020-05-10T07:58:47
2020-05-10T07:58:47
259,364,753
0
0
null
false
2022-06-17T03:34:47
2020-04-27T15:03:54
2020-05-10T07:59:07
2022-06-17T03:34:47
15,062
0
0
2
JavaScript
false
false
package com.quanle.service.impl; import com.quanle.pojo.Article; import com.quanle.repository.ArticleRepository; import com.quanle.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; /** * @author quanle */ @Service public class ArticleServiceImpl implements ArticleService { @Autowired private ArticleRepository articleRepository; @Override public Page<Article> findByPage(Integer pageNo, Integer pageSize) { Pageable pageable = PageRequest.of(pageNo - 1, pageSize); return articleRepository.findAll(pageable); } }
UTF-8
Java
786
java
ArticleServiceImpl.java
Java
[ { "context": "pringframework.stereotype.Service;\n\n/**\n * @author quanle\n */\n@Service\npublic class ArticleServiceImpl impl", "end": 434, "score": 0.9994382858276367, "start": 428, "tag": "USERNAME", "value": "quanle" } ]
null
[]
package com.quanle.service.impl; import com.quanle.pojo.Article; import com.quanle.repository.ArticleRepository; import com.quanle.service.ArticleService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; /** * @author quanle */ @Service public class ArticleServiceImpl implements ArticleService { @Autowired private ArticleRepository articleRepository; @Override public Page<Article> findByPage(Integer pageNo, Integer pageSize) { Pageable pageable = PageRequest.of(pageNo - 1, pageSize); return articleRepository.findAll(pageable); } }
786
0.787532
0.78626
26
29.23077
23.918625
71
false
false
0
0
0
0
0
0
0.538462
false
false
9
95f9df20d077a07aa70d31f86efc7326d2843bf9
20,340,965,164,638
cd77cd3de8ba7f09a7a3e6a28006f3dea4cbe7ad
/src/Publisher.java
107912b68a93d04532af6e584436e70d81f14134
[]
no_license
jingedawang/PublisherSubscriberDemo-Java
https://github.com/jingedawang/PublisherSubscriberDemo-Java
12beb004756e890c2a1dd3e8d25619d6b110a727
7b955b96217399052d4723ba24c846c520b6d54e
refs/heads/master
2020-12-03T03:54:10.352000
2017-06-29T14:58:04
2017-06-29T14:58:04
95,787,702
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.ArrayList; import java.util.List; /** * Created by wjg on 2017/6/29. */ public class Publisher { private List<MessageArriveListener> listeners = new ArrayList<MessageArriveListener>(); public interface MessageArriveListener { void MessageArrived(String message); } public void addOnMessageArriveListener(MessageArriveListener listener) { listeners.add(listener); } public void start() { while (true) { for (MessageArriveListener listener : listeners) { listener.MessageArrived("Some message from publisher."); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
UTF-8
Java
799
java
Publisher.java
Java
[ { "context": "rayList;\nimport java.util.List;\n\n/**\n * Created by wjg on 2017/6/29.\n */\npublic class Publisher {\n\n p", "end": 73, "score": 0.9995992183685303, "start": 70, "tag": "USERNAME", "value": "wjg" } ]
null
[]
import java.util.ArrayList; import java.util.List; /** * Created by wjg on 2017/6/29. */ public class Publisher { private List<MessageArriveListener> listeners = new ArrayList<MessageArriveListener>(); public interface MessageArriveListener { void MessageArrived(String message); } public void addOnMessageArriveListener(MessageArriveListener listener) { listeners.add(listener); } public void start() { while (true) { for (MessageArriveListener listener : listeners) { listener.MessageArrived("Some message from publisher."); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
799
0.599499
0.585732
33
23.212122
24.263399
91
false
false
0
0
0
0
0
0
0.242424
false
false
9
f4d58a8b5a4dc236df82ccbf6cbba881eaca7f53
29,446,295,843,660
0612a474904ab3ce22f084672d72b5781c754114
/west.twouse.language.owl2fs/src/west/twouse/language/owl2fs/impl/DLSafeRuleImpl.java
008a44bef3eef49098641872609c8d322569e863
[]
no_license
harendra-kumar/twouse
https://github.com/harendra-kumar/twouse
170683464f100e5da3cfa2ba2017014bcef5cadd
0505d5dedd8c605f117158a5d8dea19a9ca37d6b
refs/heads/master
2021-01-10T11:33:21.651000
2010-12-10T09:12:13
2010-12-10T09:12:13
50,262,555
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <copyright> * </copyright> * * $Id$ */ package west.twouse.language.owl2fs.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import west.twouse.language.owl2fs.Annotation; import west.twouse.language.owl2fs.Atom; import west.twouse.language.owl2fs.DLSafeRule; import west.twouse.language.owl2fs.Owl2fsPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>DL Safe Rule</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getAnnotation <em>Annotation</em>}</li> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getBodyAtom <em>Body Atom</em>}</li> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getHeadAtom <em>Head Atom</em>}</li> * </ul> * </p> * * @generated */ public class DLSafeRuleImpl extends RuleImpl implements DLSafeRule { /** * The cached value of the '{@link #getAnnotation() <em>Annotation</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAnnotation() * @generated * @ordered */ protected EList<Annotation> annotation; /** * The cached value of the '{@link #getBodyAtom() <em>Body Atom</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBodyAtom() * @generated * @ordered */ protected EList<Atom> bodyAtom; /** * The cached value of the '{@link #getHeadAtom() <em>Head Atom</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHeadAtom() * @generated * @ordered */ protected EList<Atom> headAtom; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DLSafeRuleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Owl2fsPackage.Literals.DL_SAFE_RULE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Annotation> getAnnotation() { if (annotation == null) { annotation = new EObjectContainmentEList<Annotation>(Annotation.class, this, Owl2fsPackage.DL_SAFE_RULE__ANNOTATION); } return annotation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Atom> getBodyAtom() { if (bodyAtom == null) { bodyAtom = new EObjectContainmentEList<Atom>(Atom.class, this, Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM); } return bodyAtom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Atom> getHeadAtom() { if (headAtom == null) { headAtom = new EObjectContainmentEList<Atom>(Atom.class, this, Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM); } return headAtom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return ((InternalEList<?>)getAnnotation()).basicRemove(otherEnd, msgs); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return ((InternalEList<?>)getBodyAtom()).basicRemove(otherEnd, msgs); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return ((InternalEList<?>)getHeadAtom()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return getAnnotation(); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return getBodyAtom(); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return getHeadAtom(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: getAnnotation().clear(); getAnnotation().addAll((Collection<? extends Annotation>)newValue); return; case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: getBodyAtom().clear(); getBodyAtom().addAll((Collection<? extends Atom>)newValue); return; case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: getHeadAtom().clear(); getHeadAtom().addAll((Collection<? extends Atom>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: getAnnotation().clear(); return; case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: getBodyAtom().clear(); return; case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: getHeadAtom().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return annotation != null && !annotation.isEmpty(); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return bodyAtom != null && !bodyAtom.isEmpty(); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return headAtom != null && !headAtom.isEmpty(); } return super.eIsSet(featureID); } } //DLSafeRuleImpl
UTF-8
Java
6,499
java
DLSafeRuleImpl.java
Java
[]
null
[]
/** * <copyright> * </copyright> * * $Id$ */ package west.twouse.language.owl2fs.impl; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import west.twouse.language.owl2fs.Annotation; import west.twouse.language.owl2fs.Atom; import west.twouse.language.owl2fs.DLSafeRule; import west.twouse.language.owl2fs.Owl2fsPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>DL Safe Rule</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getAnnotation <em>Annotation</em>}</li> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getBodyAtom <em>Body Atom</em>}</li> * <li>{@link west.twouse.language.owl2fs.impl.DLSafeRuleImpl#getHeadAtom <em>Head Atom</em>}</li> * </ul> * </p> * * @generated */ public class DLSafeRuleImpl extends RuleImpl implements DLSafeRule { /** * The cached value of the '{@link #getAnnotation() <em>Annotation</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getAnnotation() * @generated * @ordered */ protected EList<Annotation> annotation; /** * The cached value of the '{@link #getBodyAtom() <em>Body Atom</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getBodyAtom() * @generated * @ordered */ protected EList<Atom> bodyAtom; /** * The cached value of the '{@link #getHeadAtom() <em>Head Atom</em>}' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getHeadAtom() * @generated * @ordered */ protected EList<Atom> headAtom; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DLSafeRuleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Owl2fsPackage.Literals.DL_SAFE_RULE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Annotation> getAnnotation() { if (annotation == null) { annotation = new EObjectContainmentEList<Annotation>(Annotation.class, this, Owl2fsPackage.DL_SAFE_RULE__ANNOTATION); } return annotation; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Atom> getBodyAtom() { if (bodyAtom == null) { bodyAtom = new EObjectContainmentEList<Atom>(Atom.class, this, Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM); } return bodyAtom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public EList<Atom> getHeadAtom() { if (headAtom == null) { headAtom = new EObjectContainmentEList<Atom>(Atom.class, this, Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM); } return headAtom; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return ((InternalEList<?>)getAnnotation()).basicRemove(otherEnd, msgs); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return ((InternalEList<?>)getBodyAtom()).basicRemove(otherEnd, msgs); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return ((InternalEList<?>)getHeadAtom()).basicRemove(otherEnd, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return getAnnotation(); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return getBodyAtom(); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return getHeadAtom(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: getAnnotation().clear(); getAnnotation().addAll((Collection<? extends Annotation>)newValue); return; case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: getBodyAtom().clear(); getBodyAtom().addAll((Collection<? extends Atom>)newValue); return; case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: getHeadAtom().clear(); getHeadAtom().addAll((Collection<? extends Atom>)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: getAnnotation().clear(); return; case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: getBodyAtom().clear(); return; case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: getHeadAtom().clear(); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Owl2fsPackage.DL_SAFE_RULE__ANNOTATION: return annotation != null && !annotation.isEmpty(); case Owl2fsPackage.DL_SAFE_RULE__BODY_ATOM: return bodyAtom != null && !bodyAtom.isEmpty(); case Owl2fsPackage.DL_SAFE_RULE__HEAD_ATOM: return headAtom != null && !headAtom.isEmpty(); } return super.eIsSet(featureID); } } //DLSafeRuleImpl
6,499
0.596861
0.592553
246
24.418699
25.132969
123
false
false
0
0
0
0
0
0
0.288618
false
false
9
39353fff06a8bdfa55218b710a17d58fdab413b6
19,473,381,732,850
ecf9f1c89e4a3be6a1a11c106461db7afa24240a
/udemy/curso-java/exercicios/src/fundamentos/Aritmeticos.java
ff8d3d405f9ab41f1cf645b534c12d9d306a2ef1
[ "MIT" ]
permissive
pedrolpsouza/curso-java-udemy
https://github.com/pedrolpsouza/curso-java-udemy
cb53955c9575594fba2134b2eeaf23e7b11b7056
587982f4550289766a0e5e415eef9454aee93ff7
refs/heads/master
2022-11-26T20:42:21.994000
2020-08-03T19:09:08
2020-08-03T19:09:08
284,785,211
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package fundamentos; public class Aritmeticos { public static void main(String[] args) { System.out.println(2+3); int a = 7; int b = 5; System.out.println(a/ (double)b); System.out.println(a%b);// operador de módulo - resto da divisão } }
ISO-8859-1
Java
257
java
Aritmeticos.java
Java
[]
null
[]
package fundamentos; public class Aritmeticos { public static void main(String[] args) { System.out.println(2+3); int a = 7; int b = 5; System.out.println(a/ (double)b); System.out.println(a%b);// operador de módulo - resto da divisão } }
257
0.666667
0.65098
12
20.25
19.175179
66
false
false
0
0
0
0
0
0
1.583333
false
false
9
6565d413f814f7957ffca483d12497812b8a5df7
6,640,019,446,253
58aac8e031c06806f5b44225b99b4b5c854b127b
/core/src/com/pocketbattles/game/UserInterface/Actors/TextButton.java
57743a0b338d7a87568b1761414c26354a0f6d25
[]
no_license
TheDeepestSpace/PocketBattlesV4
https://github.com/TheDeepestSpace/PocketBattlesV4
b016609e2f4d7bf12a3e111d051d9757e85350af
6929283619bd85285fd10acb9624b31ade440025
refs/heads/master
2021-03-30T17:10:33.780000
2017-01-20T00:16:26
2017-01-20T00:16:26
65,903,487
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pocketbattles.game.UserInterface.Actors; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.pocketbattles.game.Game; import com.pocketbattles.game.UserInterface.UserInterface; import java.util.ArrayList; /** * Created by Boris on 25.08.2016. * Project: PocketBattlesV4 */ public class TextButton extends com.badlogic.gdx.scenes.scene2d.ui.TextButton { public static ArrayList<TextButton> list; private String name; /** INITIALISING */ public static void initialiseClass() { list = new ArrayList<TextButton>(); } /** CREATING AND SETTING UP */ public static TextButton addInstance(String name, String text, ClickListener clickListener) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin); button.setUp(name); button.addListener(clickListener); list.add(button); return button; }else return null; } public static TextButton addInstance( String name, String text, String style, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin, style); button.setUp(name); button.addListener(clickListener); list.add(button); return button; }else return null; } public static TextButton addInstance( String name, String text, int pad, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin); button.setUp(name); button.addListener(clickListener); button.pad(pad); list.add(button); return button; } else return null; } public static TextButton addInstance( String name, String text, String style, int pad, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin, style); button.setUp(name); button.addListener(clickListener); button.pad(pad); list.add(button); return button; } else return null; } public TextButton(String text, Skin skin, String styleName) { super(text, skin, styleName); } public TextButton(String text, Skin skin) { super(text, skin); } private void setUp(String name) { this.name = name; Game.stage.addActor(this); } /** UPDATING */ /** GETTERS / SETTERS */ public static TextButton getButton(String name) { for (int i = 0; i < list.size(); i++) { if (name.equals(list.get(i).name)) { return list.get(i); } } return null; } private static boolean nameAvailable(String name) { for (int i = 0; i < list.size(); i++) { if (name.equals(list.get(i).name)) return false; } return true; } /** INTERACTING */ /** RENDERING */ /** DISPOSING */ public static void disposeClass() { list.clear(); } public static void disposeInstances() { for (int i = 0; i < list.size(); i++) { list.get(i).dispose(); } } public static void disposeInstance(String name) { getButton(name).dispose(); } private void dispose() { this.clear(); this.remove(); this.name = null; } }
UTF-8
Java
3,627
java
TextButton.java
Java
[ { "context": "e;\n\nimport java.util.ArrayList;\n\n/**\n * Created by Boris on 25.08.2016.\n * Project: PocketBattlesV4\n */\npu", "end": 310, "score": 0.9986139535903931, "start": 305, "tag": "NAME", "value": "Boris" } ]
null
[]
package com.pocketbattles.game.UserInterface.Actors; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.pocketbattles.game.Game; import com.pocketbattles.game.UserInterface.UserInterface; import java.util.ArrayList; /** * Created by Boris on 25.08.2016. * Project: PocketBattlesV4 */ public class TextButton extends com.badlogic.gdx.scenes.scene2d.ui.TextButton { public static ArrayList<TextButton> list; private String name; /** INITIALISING */ public static void initialiseClass() { list = new ArrayList<TextButton>(); } /** CREATING AND SETTING UP */ public static TextButton addInstance(String name, String text, ClickListener clickListener) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin); button.setUp(name); button.addListener(clickListener); list.add(button); return button; }else return null; } public static TextButton addInstance( String name, String text, String style, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin, style); button.setUp(name); button.addListener(clickListener); list.add(button); return button; }else return null; } public static TextButton addInstance( String name, String text, int pad, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin); button.setUp(name); button.addListener(clickListener); button.pad(pad); list.add(button); return button; } else return null; } public static TextButton addInstance( String name, String text, String style, int pad, ClickListener clickListener ) { if (nameAvailable(name)) { TextButton button = new TextButton(text, UserInterface.skin, style); button.setUp(name); button.addListener(clickListener); button.pad(pad); list.add(button); return button; } else return null; } public TextButton(String text, Skin skin, String styleName) { super(text, skin, styleName); } public TextButton(String text, Skin skin) { super(text, skin); } private void setUp(String name) { this.name = name; Game.stage.addActor(this); } /** UPDATING */ /** GETTERS / SETTERS */ public static TextButton getButton(String name) { for (int i = 0; i < list.size(); i++) { if (name.equals(list.get(i).name)) { return list.get(i); } } return null; } private static boolean nameAvailable(String name) { for (int i = 0; i < list.size(); i++) { if (name.equals(list.get(i).name)) return false; } return true; } /** INTERACTING */ /** RENDERING */ /** DISPOSING */ public static void disposeClass() { list.clear(); } public static void disposeInstances() { for (int i = 0; i < list.size(); i++) { list.get(i).dispose(); } } public static void disposeInstance(String name) { getButton(name).dispose(); } private void dispose() { this.clear(); this.remove(); this.name = null; } }
3,627
0.591122
0.586986
135
25.866667
22.901011
97
false
false
0
0
0
0
0
0
0.585185
false
false
9
c1e18c6c803a58f6fb120b88178a98e60520c215
8,349,416,431,767
4a409d5e21062b87c16f7999fa1fb0e5b688efc1
/2-javaee/Ticket2Rock_Interfaces/src/main/java/dhbwka/wwi/vertsys/javaee/ticket2rock_interfaces/remote/EventNotFoundException.java
fffc5ff5ed814be6619be880293811d467c33eed
[ "CC-BY-4.0" ]
permissive
DennisSchulmeister/dhbwka-wwi-vertsys-2018-quellcodes
https://github.com/DennisSchulmeister/dhbwka-wwi-vertsys-2018-quellcodes
6752d23f373f2024cffd16c9b454a51632293845
32ff15142dd3a49358119fc1f388e1af370a3695
refs/heads/master
2022-12-22T13:42:31.051000
2019-12-12T22:52:19
2019-12-12T22:52:19
226,732,812
0
0
CC-BY-4.0
false
2022-12-15T23:55:53
2019-12-08T21:15:16
2019-12-12T22:52:27
2022-12-15T23:55:51
24,044
0
0
14
JavaScript
false
false
/* * Copyright © 2019 Dennis Schulmeister-Zimolong * * E-Mail: dhbw@windows3.de * Webseite: https://www.wpvs.de/ * * Dieser Quellcode ist lizenziert unter einer * Creative Commons Namensnennung 4.0 International Lizenz. */ package dhbwka.wwi.vertsys.javaee.ticket2rock_interfaces.remote; /** * Ausnahme: Gesuchte Veranstaltung wurde nicht gefunden */ public class EventNotFoundException extends Exception { public EventNotFoundException() { super(); } public EventNotFoundException(String message) { super(message); } }
UTF-8
Java
571
java
EventNotFoundException.java
Java
[ { "context": "/*\n * Copyright © 2019 Dennis Schulmeister-Zimolong\n * \n * E-Mail: dhbw@windows3.de\n * Webseite: http", "end": 51, "score": 0.9998381733894348, "start": 23, "tag": "NAME", "value": "Dennis Schulmeister-Zimolong" }, { "context": "© 2019 Dennis Schulmeister-Zimolong\n * \n * E-Mail: dhbw@windows3.de\n * Webseite: https://www.wpvs.de/\n * \n * Dieser Q", "end": 83, "score": 0.9999346733093262, "start": 67, "tag": "EMAIL", "value": "dhbw@windows3.de" } ]
null
[]
/* * Copyright © 2019 <NAME> * * E-Mail: <EMAIL> * Webseite: https://www.wpvs.de/ * * Dieser Quellcode ist lizenziert unter einer * Creative Commons Namensnennung 4.0 International Lizenz. */ package dhbwka.wwi.vertsys.javaee.ticket2rock_interfaces.remote; /** * Ausnahme: Gesuchte Veranstaltung wurde nicht gefunden */ public class EventNotFoundException extends Exception { public EventNotFoundException() { super(); } public EventNotFoundException(String message) { super(message); } }
540
0.710526
0.696491
23
23.782608
22.686821
64
false
false
0
0
0
0
0
0
0.130435
false
false
9
f73351103237cd92aaac56f95eb46ce3e5b9865f
8,478,265,451,682
42ac9ec4f808c33c28ae243458f8c45ed880fb06
/src/brs/db/BurstIterator.java
90cf292aea7a13a63a90686cda105bc9c5ff2c7b
[ "MIT" ]
permissive
maxweng/burstcoin
https://github.com/maxweng/burstcoin
d2583c15a3f8d4c5b57ac3fd29035fb3b2836ac1
4cdbddfabced4328af499b55ec09899529b7117c
refs/heads/master
2021-09-01T05:42:59.054000
2017-12-24T14:25:21
2017-12-24T14:25:21
98,264,937
0
0
null
true
2017-07-25T04:41:14
2017-07-25T04:41:14
2017-07-25T04:41:12
2017-07-22T04:53:26
32,268
0
0
0
null
null
null
package brs.db; import java.sql.Connection; import java.sql.ResultSet; import java.util.Iterator; public interface BurstIterator<T> extends Iterator<T>, Iterable<T>, AutoCloseable { @Override boolean hasNext(); @Override T next(); @Override void remove(); @Override void close(); @Override Iterator<T> iterator(); public interface ResultSetReader<T> { T get(Connection con, ResultSet rs) throws Exception; } }
UTF-8
Java
445
java
BurstIterator.java
Java
[]
null
[]
package brs.db; import java.sql.Connection; import java.sql.ResultSet; import java.util.Iterator; public interface BurstIterator<T> extends Iterator<T>, Iterable<T>, AutoCloseable { @Override boolean hasNext(); @Override T next(); @Override void remove(); @Override void close(); @Override Iterator<T> iterator(); public interface ResultSetReader<T> { T get(Connection con, ResultSet rs) throws Exception; } }
445
0.707865
0.707865
26
16.115385
19.069361
83
false
false
0
0
0
0
0
0
0.5
false
false
9
a4432b9657e543b2748e11cc5bf00235c2eb1775
30,932,354,473,494
9b2606ef92ec5ecdd7470e8292f8a3ff47c6b70d
/src/analizadorlexico/ScannerController.java
1aca4f2fe4a592b1600e14e6347a34ce7c7c0ace
[ "MIT" ]
permissive
cleristonos/compilador-EXA869
https://github.com/cleristonos/compilador-EXA869
2ed0270e43385b521dd4aa1fbf9bdc3f62439149
4f46eb917543c2c9de97e2b2d03de9a1e638be90
refs/heads/master
2021-01-17T16:41:49.228000
2014-04-10T13:16:22
2014-04-10T13:16:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package analizadorlexico; /** * * @author Netto */ public class ScannerController { private ScannerAF scanner; private Terminal terminal; public void inicializa() { scanner = new ScannerAF(); terminal = new Terminal(this); } public ScannerAF getScanner() { return scanner; } public void setScanner(ScannerAF scanner) { this.scanner = scanner; } public Terminal getTerminal() { return terminal; } public void setTerminal(Terminal terminal) { this.terminal = terminal; } }
UTF-8
Java
697
java
ScannerController.java
Java
[ { "context": ".\n */\npackage analizadorlexico;\n\n/**\n *\n * @author Netto\n */\npublic class ScannerController {\n\n private", "end": 150, "score": 0.9996163845062256, "start": 145, "tag": "NAME", "value": "Netto" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package analizadorlexico; /** * * @author Netto */ public class ScannerController { private ScannerAF scanner; private Terminal terminal; public void inicializa() { scanner = new ScannerAF(); terminal = new Terminal(this); } public ScannerAF getScanner() { return scanner; } public void setScanner(ScannerAF scanner) { this.scanner = scanner; } public Terminal getTerminal() { return terminal; } public void setTerminal(Terminal terminal) { this.terminal = terminal; } }
697
0.612626
0.612626
40
16.424999
16.56938
52
false
false
0
0
0
0
0
0
0.275
false
false
9
110c781d4563acd0ce7a105470aed89e0bac80ce
12,309,376,324,478
86bd99b8a3c1d6e2cfdca0fb27ec6710b28d89fe
/src/main/java/com/google/sps/data/Term.java
276cd545f953a08d81060f569a220dedfc9b847d
[]
no_license
hailed748/step159-2020
https://github.com/hailed748/step159-2020
aad0fad1b2a73f0585c9e688121a1da796cffe75
0ddbacf744150e0abf53cd7154367cfd3cbf12e7
refs/heads/master
2022-12-08T16:44:10.454000
2020-09-03T17:12:23
2020-09-03T17:12:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.sps.data; import java.util.*; public class Term implements Comparable<Term> { String season; int year; ListIterator termIterator; int numTerms; int currTerm; ArrayList<String> termList; Boolean isQuarter; final List<String> QTR_SCHOOLS = Arrays.asList("caltech", "calpoly", "stanford", "berkeley"); final ArrayList<String> QTR_TERMS = new ArrayList<String>(Arrays.asList("Winter", "Spring", "Summer", "Fall")); final ArrayList<String> SEMESTER_TERMS = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Fall")); public Term(String termString, Boolean isQuarterSystem) { season = termString.split(" ")[0]; year = Integer.parseInt(termString.split(" ")[1]); isQuarter = isQuarterSystem; if (isQuarter) { termList = QTR_TERMS; } else { termList = SEMESTER_TERMS; } numTerms = termList.size(); currTerm = termList.indexOf(season); } public String getSeason() { return season; } public int getYear() { return year; } public Term getNext() { if (currTerm + 1 < numTerms) { return new Term(termList.get(currTerm + 1) + " " + String.valueOf(year), isQuarter); } else { return new Term(termList.get(0) + " " + String.valueOf(year + 1), isQuarter); } } public Term getPrev() { if (currTerm == 0) { return new Term(termList.get(numTerms - 1) + " " + String.valueOf(year - 1), isQuarter); } else { return new Term(termList.get(currTerm - 1) + " " + String.valueOf(year), isQuarter); } } public Boolean isQuarter() { return isQuarter; } public String toString() { return season + " " + String.valueOf(year); } @Override public int compareTo(Term term) { if (year == term.year) { return term.termList.indexOf(term.season) - termList.indexOf(season); } else { return term.year - year; } } public int compare(Term one, Term two) { return one.compareTo(two); } }
UTF-8
Java
1,989
java
Term.java
Java
[]
null
[]
package com.google.sps.data; import java.util.*; public class Term implements Comparable<Term> { String season; int year; ListIterator termIterator; int numTerms; int currTerm; ArrayList<String> termList; Boolean isQuarter; final List<String> QTR_SCHOOLS = Arrays.asList("caltech", "calpoly", "stanford", "berkeley"); final ArrayList<String> QTR_TERMS = new ArrayList<String>(Arrays.asList("Winter", "Spring", "Summer", "Fall")); final ArrayList<String> SEMESTER_TERMS = new ArrayList<String>(Arrays.asList("Spring", "Summer", "Fall")); public Term(String termString, Boolean isQuarterSystem) { season = termString.split(" ")[0]; year = Integer.parseInt(termString.split(" ")[1]); isQuarter = isQuarterSystem; if (isQuarter) { termList = QTR_TERMS; } else { termList = SEMESTER_TERMS; } numTerms = termList.size(); currTerm = termList.indexOf(season); } public String getSeason() { return season; } public int getYear() { return year; } public Term getNext() { if (currTerm + 1 < numTerms) { return new Term(termList.get(currTerm + 1) + " " + String.valueOf(year), isQuarter); } else { return new Term(termList.get(0) + " " + String.valueOf(year + 1), isQuarter); } } public Term getPrev() { if (currTerm == 0) { return new Term(termList.get(numTerms - 1) + " " + String.valueOf(year - 1), isQuarter); } else { return new Term(termList.get(currTerm - 1) + " " + String.valueOf(year), isQuarter); } } public Boolean isQuarter() { return isQuarter; } public String toString() { return season + " " + String.valueOf(year); } @Override public int compareTo(Term term) { if (year == term.year) { return term.termList.indexOf(term.season) - termList.indexOf(season); } else { return term.year - year; } } public int compare(Term one, Term two) { return one.compareTo(two); } }
1,989
0.633484
0.628457
77
24.831169
25.324594
95
false
false
0
0
0
0
0
0
0.571429
false
false
9
481ab49424f9f256de98bfc28fe377a26b29b3ee
37,391,985,282,124
6f431761901823c73535593951e3f8eb491de6ef
/gmall-api/src/main/java/com/zrq/gmall/api/vo/product/ProductCategoryWithChildrenItem.java
a74f0c90f04f92cfb09276d3a548fa73b9880340
[]
no_license
zrqHazard/gmall1
https://github.com/zrqHazard/gmall1
230d11a62d94e4be73f925a333b80f4442d6ce89
d1fd42551f26ddc525fcc03d4ab3bc4d20126097
refs/heads/master
2022-06-30T05:11:24.074000
2020-03-20T11:18:47
2020-03-20T11:18:47
247,693,604
0
0
null
false
2022-06-21T03:00:00
2020-03-16T12:13:48
2020-03-20T11:19:09
2022-06-21T03:00:00
343
0
0
3
Java
false
false
package com.zrq.gmall.api.vo.product; import com.zrq.gmall.api.pms.entity.ProductCategory; import lombok.Data; import java.util.List; /** */ @Data public class ProductCategoryWithChildrenItem extends ProductCategory { private List<ProductCategory> children; }
UTF-8
Java
268
java
ProductCategoryWithChildrenItem.java
Java
[]
null
[]
package com.zrq.gmall.api.vo.product; import com.zrq.gmall.api.pms.entity.ProductCategory; import lombok.Data; import java.util.List; /** */ @Data public class ProductCategoryWithChildrenItem extends ProductCategory { private List<ProductCategory> children; }
268
0.783582
0.783582
13
19.615385
22.717457
70
false
false
0
0
0
0
0
0
0.384615
false
false
9
3a2825e4f90172ffa42b4f46244e68b10db97e45
35,287,451,325,326
930c759c66e30a065d47dfa17118d58294b2543d
/COROUTINE/src/de/heinerkuecker/coroutine/exprs/bool/CoroBooleanExpression.java
60e444890e3c9cd74d7acf4acd642707540e7bf1
[ "Unlicense" ]
permissive
HeinerKuecker/Coroutine-in-pure-Java
https://github.com/HeinerKuecker/Coroutine-in-pure-Java
2ec428790f7c84d8ccd7d748f5e718b121c05875
de7a0f17764d8cc263607752438ee1cd6cb12601
refs/heads/master
2020-04-10T13:41:35.581000
2019-02-21T05:50:26
2019-02-21T05:50:26
161,057,106
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package de.heinerkuecker.coroutine.exprs.bool; import de.heinerkuecker.coroutine.exprs.SimpleExpression; abstract public class CoroBooleanExpression<COROUTINE_RETURN , RESUME_ARGUMENT> implements SimpleExpression<Boolean , COROUTINE_RETURN , RESUME_ARGUMENT> { ///** // * Execute the condition and return the result. // * // * @param parent the {@link CoroutineOrFunctioncallOrComplexstmt} instance // * @return condition result // */ //@Override //boolean execute( // final HasArgumentsAndVariables<? extends RESUME_ARGUMENT>/*CoroutineOrFunctioncallOrComplexstmt<?, ?>*/ parent ); @SuppressWarnings("unchecked") @Override public Class<? extends Boolean>[] type() { return new Class[]{ Boolean.class }; } }
UTF-8
Java
808
java
CoroBooleanExpression.java
Java
[]
null
[]
package de.heinerkuecker.coroutine.exprs.bool; import de.heinerkuecker.coroutine.exprs.SimpleExpression; abstract public class CoroBooleanExpression<COROUTINE_RETURN , RESUME_ARGUMENT> implements SimpleExpression<Boolean , COROUTINE_RETURN , RESUME_ARGUMENT> { ///** // * Execute the condition and return the result. // * // * @param parent the {@link CoroutineOrFunctioncallOrComplexstmt} instance // * @return condition result // */ //@Override //boolean execute( // final HasArgumentsAndVariables<? extends RESUME_ARGUMENT>/*CoroutineOrFunctioncallOrComplexstmt<?, ?>*/ parent ); @SuppressWarnings("unchecked") @Override public Class<? extends Boolean>[] type() { return new Class[]{ Boolean.class }; } }
808
0.673267
0.673267
25
30.32
32.596588
127
false
false
0
0
0
0
0
0
0.32
false
false
9
358be5f857896bb4931517f6e17f08b35209838c
10,015,863,765,165
c7d8510dbfe91f9f35e1c6325fae0d4f42e2d084
/matrix-kafka/src/main/java/org/matrix/framework/core/kafka/consumer/setting/MatrixConsumerSetting.java
b04e644252ce9d6c8e9ca51efa713dfeaf3a6eda
[]
no_license
fightingBilling/matrix-framework
https://github.com/fightingBilling/matrix-framework
b2dcd91994fc5cdb79b1a2bda9c9b1a5bc0b5f24
460ead8688e9738afcca8976121fbf3d902994e6
refs/heads/master
2021-01-19T11:48:50.649000
2016-12-06T07:52:07
2016-12-06T07:52:07
82,266,639
1
0
null
true
2017-02-17T06:49:55
2017-02-17T06:49:55
2016-10-17T05:57:38
2016-12-06T07:52:27
252
0
0
0
null
null
null
package org.matrix.framework.core.kafka.consumer.setting; /** * 消息消费器配置集中管理. * * @author pankai 2015年8月17日 */ public class MatrixConsumerSetting { // 服务器字符串 private String servers; // 组别 private String group; // 分区数量 private Integer partitionCount; // 订阅的主题 private String topic; // 关闭时最大等待(ms) private Long awaitTermination; /** * @param servers * 服务器字符串 * @param group * 组别 * @param partitionCount * 分区数量 * @param topic * 订阅的主题 * @param awaitTermination * 关闭时最大等待(ms) */ public MatrixConsumerSetting(String servers, String group, Integer partitionCount, String topic, Long awaitTermination) { this.servers = servers; this.group = group; this.partitionCount = partitionCount; this.topic = topic; this.awaitTermination = awaitTermination; } public String getServers() { return servers; } public String getGroup() { return group; } public Integer getPartitionCount() { return partitionCount; } public String getTopic() { return topic; } public Long getAwaitTermination() { return awaitTermination; } }
UTF-8
Java
1,420
java
MatrixConsumerSetting.java
Java
[ { "context": "nsumer.setting;\n\n/**\n * 消息消费器配置集中管理.\n *\n * @author pankai 2015年8月17日\n */\npublic class MatrixConsumerSetting", "end": 99, "score": 0.9987303614616394, "start": 93, "tag": "USERNAME", "value": "pankai" } ]
null
[]
package org.matrix.framework.core.kafka.consumer.setting; /** * 消息消费器配置集中管理. * * @author pankai 2015年8月17日 */ public class MatrixConsumerSetting { // 服务器字符串 private String servers; // 组别 private String group; // 分区数量 private Integer partitionCount; // 订阅的主题 private String topic; // 关闭时最大等待(ms) private Long awaitTermination; /** * @param servers * 服务器字符串 * @param group * 组别 * @param partitionCount * 分区数量 * @param topic * 订阅的主题 * @param awaitTermination * 关闭时最大等待(ms) */ public MatrixConsumerSetting(String servers, String group, Integer partitionCount, String topic, Long awaitTermination) { this.servers = servers; this.group = group; this.partitionCount = partitionCount; this.topic = topic; this.awaitTermination = awaitTermination; } public String getServers() { return servers; } public String getGroup() { return group; } public Integer getPartitionCount() { return partitionCount; } public String getTopic() { return topic; } public Long getAwaitTermination() { return awaitTermination; } }
1,420
0.589506
0.584105
61
20.245901
19.605667
125
false
false
0
0
0
0
0
0
0.327869
false
false
9
0010d0ef975856c1b7945aeb5a34aeb1a34ab806
13,855,564,565,112
58a8ed34f613c281a5faaaefe5da1788f5739d17
/Application_code_source/eMybaby/sources/com/tuya/smart/common/o00000o000.java
a65a4484563b2526aeed3d1fcd66f7d4e8787716
[]
no_license
wagnerwave/Dossier_Hacking_de_peluche
https://github.com/wagnerwave/Dossier_Hacking_de_peluche
01c78629e52a94ed6a208e11ff7fcd268e10956e
514f81b1e72d88e2b8835126b2151e368dcad7fb
refs/heads/main
2023-03-31T13:28:06.247000
2021-03-25T23:03:38
2021-03-25T23:03:38
351,597,654
5
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.tuya.smart.common; import a.a.a.a.a; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.tuya.sdk.sigmesh.bean.AccessMessage; import com.tuya.sdk.sigmesh.transport.ConfigStatusMessage; import com.tuya.smart.android.blemesh.bean.Element; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; public class o00000o000 extends ConfigStatusMessage implements Parcelable { public static final String O00000oO = o00000o000.class.getSimpleName(); public static final int O00000oo = 2; public static final int O0000O0o = 12; public static final Parcelable.Creator<o00000o000> O0000OOo = new Parcelable.Creator<o00000o000>() { /* renamed from: O000000o */ public o00000o000 createFromParcel(Parcel parcel) { return new o00000o000((AccessMessage) parcel.readValue(AccessMessage.class.getClassLoader())); } /* renamed from: O000000o */ public o00000o000[] newArray(int i) { return new o00000o000[i]; } }; public int O0000Oo; public int O0000Oo0; public int O0000OoO; public int O0000Ooo; public boolean O0000o; public boolean O0000o0; public int O0000o00; public boolean O0000o0O; public boolean O0000o0o; public Map<Integer, Element> O0000oO0 = new LinkedHashMap(); public o00000o000(AccessMessage accessMessage) { super(accessMessage); this.O00000o = accessMessage.getParameters(); O000000o(); } private int O000000o(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private void O000000o(byte[] bArr, byte[] bArr2) { byte[] bArr3 = bArr; char c2 = 0; int i = 12; byte[] bArr4 = null; int i2 = 0; while (i < bArr3.length) { LinkedHashMap linkedHashMap = new LinkedHashMap(); byte b2 = (bArr3[i + 1] << 8) | bArr3[i]; String str = O00000oO; StringBuilder n = a.n("Location identifier: "); Locale locale = Locale.US; Object[] objArr = new Object[1]; objArr[c2] = Integer.valueOf(b2); n.append(String.format(locale, "%04X", objArr)); o00oo0oo00.O00000o(str, n.toString()); int i3 = i + 2; byte b3 = bArr3[i3]; String str2 = O00000oO; StringBuilder n2 = a.n("Number of sig models: "); Locale locale2 = Locale.US; Object[] objArr2 = new Object[1]; objArr2[c2] = Integer.valueOf(b3); n2.append(String.format(locale2, "%04X", objArr2)); o00oo0oo00.O00000o(str2, n2.toString()); int i4 = i3 + 1; byte b4 = bArr3[i4]; String str3 = O00000oO; StringBuilder n3 = a.n("Number of vendor models: "); Locale locale3 = Locale.US; Object[] objArr3 = new Object[1]; objArr3[c2] = Integer.valueOf(b4); n3.append(String.format(locale3, "%04X", objArr3)); o00oo0oo00.O00000o(str3, n3.toString()); i = i4 + 1; if (b3 > 0) { int i5 = 0; while (i5 < b3) { int O000000o = o00o0000oo.O000000o(bArr3[i], bArr3[i + 1]); linkedHashMap.put(Integer.valueOf(O000000o), oooooo000.O000000o(O000000o)); String str4 = O00000oO; StringBuilder o = a.o("Sig model ID ", i5, " : "); o.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(O000000o)})); o00oo0oo00.O00000o(str4, o.toString()); i += 2; i5++; b3 = b3; } } if (b4 > 0) { for (int i6 = 0; i6 < b4; i6++) { int O000000o2 = (o00o0000oo.O000000o(bArr3[i], bArr3[i + 1]) << 16) | o00o0000oo.O000000o(bArr3[i + 2], bArr3[i + 3]); linkedHashMap.put(Integer.valueOf(O000000o2), new oooooo0o0(O000000o2)); String str5 = O00000oO; StringBuilder o2 = a.o("Vendor - model ID ", i6, " : "); o2.append(String.format(Locale.US, "%08X", new Object[]{Integer.valueOf(O000000o2)})); o00oo0oo00.O00000o(str5, o2.toString()); i += 4; } } bArr4 = i2 == 0 ? bArr2 : o000oo0o0o.O000000o(bArr4); i2++; this.O0000oO0.put(Integer.valueOf(o000oo0o0o.O00000Oo(bArr4)), new Element(bArr4, b2, linkedHashMap)); c2 = 0; } } private int O00000Oo(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000o(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000o0(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000oO(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private void O0000o00() { AccessMessage accessMessage = (AccessMessage) this.O00000o0; byte[] accessPdu = accessMessage.getAccessPdu(); this.O0000Oo0 = o00o0000oo.O000000o(accessPdu[2], accessPdu[3]); String str = O00000oO; StringBuilder n = a.n("Company identifier: "); n.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Oo0)})); o00oo0oo00.O00000o(str, n.toString()); this.O0000Oo = o00o0000oo.O000000o(accessPdu[4], accessPdu[5]); String str2 = O00000oO; StringBuilder n2 = a.n("Product identifier: "); n2.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Oo)})); o00oo0oo00.O00000o(str2, n2.toString()); this.O0000OoO = o00o0000oo.O000000o(accessPdu[6], accessPdu[7]); String str3 = O00000oO; StringBuilder n3 = a.n("Version identifier: "); n3.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000OoO)})); o00oo0oo00.O00000o(str3, n3.toString()); this.O0000Ooo = o00o0000oo.O000000o(accessPdu[8], accessPdu[9]); String str4 = O00000oO; StringBuilder n4 = a.n("crpl: "); n4.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Ooo)})); o00oo0oo00.O00000o(str4, n4.toString()); this.O0000o00 = o00o0000oo.O000000o(accessPdu[10], accessPdu[11]); String str5 = O00000oO; StringBuilder n5 = a.n("Features: "); n5.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000o00)})); Log.v(str5, n5.toString()); this.O0000o0 = o000ooo000.O000000o(this.O0000o00); String str6 = O00000oO; StringBuilder n6 = a.n("Relay feature: "); n6.append(this.O0000o0); Log.v(str6, n6.toString()); this.O0000o0O = o000ooo000.O00000Oo(this.O0000o00); String str7 = O00000oO; StringBuilder n7 = a.n("Proxy feature: "); n7.append(this.O0000o0O); Log.v(str7, n7.toString()); this.O0000o0o = o000ooo000.O00000o0(this.O0000o00); String str8 = O00000oO; StringBuilder n8 = a.n("Friend feature: "); n8.append(this.O0000o0o); Log.v(str8, n8.toString()); this.O0000o = o000ooo000.O00000o(this.O0000o00); String str9 = O00000oO; StringBuilder n9 = a.n("Low power feature: "); n9.append(this.O0000o); Log.v(str9, n9.toString()); O000000o(accessPdu, accessMessage.getSrc()); String str10 = O00000oO; StringBuilder n10 = a.n("Number of elements: "); n10.append(this.O0000oO0.size()); Log.v(str10, n10.toString()); } public final void O000000o() { O0000o00(); } public int O00000Oo() { return 2; } public int O00000oo() { return this.O0000Ooo; } public int O0000O0o() { return this.O0000o00; } public boolean O0000OOo() { return this.O0000o0; } public boolean O0000Oo() { return this.O0000o0o; } public boolean O0000Oo0() { return this.O0000o0O; } public boolean O0000OoO() { return this.O0000o; } public Map<Integer, Element> O0000Ooo() { return this.O0000oO0; } public int describeContents() { return 0; } public int e_() { return this.O0000Oo0; } public int f_() { return this.O0000Oo; } public int g_() { return this.O0000OoO; } public void writeToParcel(Parcel parcel, int i) { parcel.writeValue(this.O00000o0); } }
UTF-8
Java
9,012
java
o00000o000.java
Java
[]
null
[]
package com.tuya.smart.common; import a.a.a.a.a; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import com.tuya.sdk.sigmesh.bean.AccessMessage; import com.tuya.sdk.sigmesh.transport.ConfigStatusMessage; import com.tuya.smart.android.blemesh.bean.Element; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; public class o00000o000 extends ConfigStatusMessage implements Parcelable { public static final String O00000oO = o00000o000.class.getSimpleName(); public static final int O00000oo = 2; public static final int O0000O0o = 12; public static final Parcelable.Creator<o00000o000> O0000OOo = new Parcelable.Creator<o00000o000>() { /* renamed from: O000000o */ public o00000o000 createFromParcel(Parcel parcel) { return new o00000o000((AccessMessage) parcel.readValue(AccessMessage.class.getClassLoader())); } /* renamed from: O000000o */ public o00000o000[] newArray(int i) { return new o00000o000[i]; } }; public int O0000Oo; public int O0000Oo0; public int O0000OoO; public int O0000Ooo; public boolean O0000o; public boolean O0000o0; public int O0000o00; public boolean O0000o0O; public boolean O0000o0o; public Map<Integer, Element> O0000oO0 = new LinkedHashMap(); public o00000o000(AccessMessage accessMessage) { super(accessMessage); this.O00000o = accessMessage.getParameters(); O000000o(); } private int O000000o(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private void O000000o(byte[] bArr, byte[] bArr2) { byte[] bArr3 = bArr; char c2 = 0; int i = 12; byte[] bArr4 = null; int i2 = 0; while (i < bArr3.length) { LinkedHashMap linkedHashMap = new LinkedHashMap(); byte b2 = (bArr3[i + 1] << 8) | bArr3[i]; String str = O00000oO; StringBuilder n = a.n("Location identifier: "); Locale locale = Locale.US; Object[] objArr = new Object[1]; objArr[c2] = Integer.valueOf(b2); n.append(String.format(locale, "%04X", objArr)); o00oo0oo00.O00000o(str, n.toString()); int i3 = i + 2; byte b3 = bArr3[i3]; String str2 = O00000oO; StringBuilder n2 = a.n("Number of sig models: "); Locale locale2 = Locale.US; Object[] objArr2 = new Object[1]; objArr2[c2] = Integer.valueOf(b3); n2.append(String.format(locale2, "%04X", objArr2)); o00oo0oo00.O00000o(str2, n2.toString()); int i4 = i3 + 1; byte b4 = bArr3[i4]; String str3 = O00000oO; StringBuilder n3 = a.n("Number of vendor models: "); Locale locale3 = Locale.US; Object[] objArr3 = new Object[1]; objArr3[c2] = Integer.valueOf(b4); n3.append(String.format(locale3, "%04X", objArr3)); o00oo0oo00.O00000o(str3, n3.toString()); i = i4 + 1; if (b3 > 0) { int i5 = 0; while (i5 < b3) { int O000000o = o00o0000oo.O000000o(bArr3[i], bArr3[i + 1]); linkedHashMap.put(Integer.valueOf(O000000o), oooooo000.O000000o(O000000o)); String str4 = O00000oO; StringBuilder o = a.o("Sig model ID ", i5, " : "); o.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(O000000o)})); o00oo0oo00.O00000o(str4, o.toString()); i += 2; i5++; b3 = b3; } } if (b4 > 0) { for (int i6 = 0; i6 < b4; i6++) { int O000000o2 = (o00o0000oo.O000000o(bArr3[i], bArr3[i + 1]) << 16) | o00o0000oo.O000000o(bArr3[i + 2], bArr3[i + 3]); linkedHashMap.put(Integer.valueOf(O000000o2), new oooooo0o0(O000000o2)); String str5 = O00000oO; StringBuilder o2 = a.o("Vendor - model ID ", i6, " : "); o2.append(String.format(Locale.US, "%08X", new Object[]{Integer.valueOf(O000000o2)})); o00oo0oo00.O00000o(str5, o2.toString()); i += 4; } } bArr4 = i2 == 0 ? bArr2 : o000oo0o0o.O000000o(bArr4); i2++; this.O0000oO0.put(Integer.valueOf(o000oo0o0o.O00000Oo(bArr4)), new Element(bArr4, b2, linkedHashMap)); c2 = 0; } } private int O00000Oo(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000o(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000o0(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private int O00000oO(short s) { return ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN).putShort(s).getShort(0); } private void O0000o00() { AccessMessage accessMessage = (AccessMessage) this.O00000o0; byte[] accessPdu = accessMessage.getAccessPdu(); this.O0000Oo0 = o00o0000oo.O000000o(accessPdu[2], accessPdu[3]); String str = O00000oO; StringBuilder n = a.n("Company identifier: "); n.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Oo0)})); o00oo0oo00.O00000o(str, n.toString()); this.O0000Oo = o00o0000oo.O000000o(accessPdu[4], accessPdu[5]); String str2 = O00000oO; StringBuilder n2 = a.n("Product identifier: "); n2.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Oo)})); o00oo0oo00.O00000o(str2, n2.toString()); this.O0000OoO = o00o0000oo.O000000o(accessPdu[6], accessPdu[7]); String str3 = O00000oO; StringBuilder n3 = a.n("Version identifier: "); n3.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000OoO)})); o00oo0oo00.O00000o(str3, n3.toString()); this.O0000Ooo = o00o0000oo.O000000o(accessPdu[8], accessPdu[9]); String str4 = O00000oO; StringBuilder n4 = a.n("crpl: "); n4.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000Ooo)})); o00oo0oo00.O00000o(str4, n4.toString()); this.O0000o00 = o00o0000oo.O000000o(accessPdu[10], accessPdu[11]); String str5 = O00000oO; StringBuilder n5 = a.n("Features: "); n5.append(String.format(Locale.US, "%04X", new Object[]{Integer.valueOf(this.O0000o00)})); Log.v(str5, n5.toString()); this.O0000o0 = o000ooo000.O000000o(this.O0000o00); String str6 = O00000oO; StringBuilder n6 = a.n("Relay feature: "); n6.append(this.O0000o0); Log.v(str6, n6.toString()); this.O0000o0O = o000ooo000.O00000Oo(this.O0000o00); String str7 = O00000oO; StringBuilder n7 = a.n("Proxy feature: "); n7.append(this.O0000o0O); Log.v(str7, n7.toString()); this.O0000o0o = o000ooo000.O00000o0(this.O0000o00); String str8 = O00000oO; StringBuilder n8 = a.n("Friend feature: "); n8.append(this.O0000o0o); Log.v(str8, n8.toString()); this.O0000o = o000ooo000.O00000o(this.O0000o00); String str9 = O00000oO; StringBuilder n9 = a.n("Low power feature: "); n9.append(this.O0000o); Log.v(str9, n9.toString()); O000000o(accessPdu, accessMessage.getSrc()); String str10 = O00000oO; StringBuilder n10 = a.n("Number of elements: "); n10.append(this.O0000oO0.size()); Log.v(str10, n10.toString()); } public final void O000000o() { O0000o00(); } public int O00000Oo() { return 2; } public int O00000oo() { return this.O0000Ooo; } public int O0000O0o() { return this.O0000o00; } public boolean O0000OOo() { return this.O0000o0; } public boolean O0000Oo() { return this.O0000o0o; } public boolean O0000Oo0() { return this.O0000o0O; } public boolean O0000OoO() { return this.O0000o; } public Map<Integer, Element> O0000Ooo() { return this.O0000oO0; } public int describeContents() { return 0; } public int e_() { return this.O0000Oo0; } public int f_() { return this.O0000Oo; } public int g_() { return this.O0000OoO; } public void writeToParcel(Parcel parcel, int i) { parcel.writeValue(this.O00000o0); } }
9,012
0.58522
0.471372
245
35.783672
26.96207
138
false
false
0
0
0
0
0
0
0.889796
false
false
9
a027afafa25d13e59be9c50bb5ad9ce3a1044d45
37,589,553,778,206
e87b54f5ce80cc224d97e594e217f48c93899072
/src/main/java/com/example/vo/Fo.java
ced7f7fd5f645d579e163442288b2e1b87a8d0fe
[]
no_license
dyangx/interview
https://github.com/dyangx/interview
001c5d73f9802c799a1ea493102c0aef23b63b57
f51b381d586611c73f8a1609b28b0540e48f690b
refs/heads/master
2023-06-09T18:23:40.632000
2023-05-30T06:52:05
2023-05-30T06:52:05
173,584,242
2
0
null
false
2022-08-16T10:30:11
2019-03-03T14:17:54
2022-08-06T03:39:40
2022-08-16T10:30:10
11,147
1
0
1
Java
false
false
package com.example.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Objects; @Data @AllArgsConstructor @NoArgsConstructor public class Fo implements Comparable<Fo> { private String name; private Integer age; public int compareTo() { return age; } @Override public int compareTo(Fo o) { return age; } }
UTF-8
Java
414
java
Fo.java
Java
[]
null
[]
package com.example.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Objects; @Data @AllArgsConstructor @NoArgsConstructor public class Fo implements Comparable<Fo> { private String name; private Integer age; public int compareTo() { return age; } @Override public int compareTo(Fo o) { return age; } }
414
0.695652
0.695652
27
14.333333
12.970051
43
false
false
0
0
0
0
0
0
0.333333
false
false
9
65a796683c2e200e0c899e3103f8fa4e07248605
37,589,553,777,151
8e3eab316d6eb33ce8cd05cbbc2e234b3027d502
/src/main/java/it/polimi/ingsw/controller/Game.java
f066c80e5565ea047f5eb36498e45223e87b64bb
[]
no_license
antonypascalino/ing-sw-2021-pascalino-pestrin-nebolosi
https://github.com/antonypascalino/ing-sw-2021-pascalino-pestrin-nebolosi
5ee926c3ad7e727dc2827bd0324c10f1b3f801b5
de76d085c862bda163a0059e00c1cf8215c68068
refs/heads/main
2023-06-07T02:07:36.876000
2021-07-02T21:32:47
2021-07-02T21:32:47
346,312,768
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package it.polimi.ingsw.controller; import it.polimi.ingsw.controller.Request.InitialPlayersSetRequest; import it.polimi.ingsw.controller.Request.Request; import it.polimi.ingsw.model.Board.FaithPath; import it.polimi.ingsw.Updates.*; import it.polimi.ingsw.model.card.DevCard; import it.polimi.ingsw.model.Player.Player; import it.polimi.ingsw.model.Table.Table; import it.polimi.ingsw.model.card.LeaderCard; import java.util.ArrayList; import java.util.Collections; /** * An object {@link Game} is created every time some players start a game. It contains the references to all the {@link Player}s * and the information about the game in progress, such for example the {@link DevCard}s available on the {@link Table} * or the actions done by the players during their turns. * <p> * It also receive the information from the server containing what a player wants to do and, in case it is possible, * handle them modifying the players' status on the server. */ public class Game { public int maxPlayer; private ArrayList<Player> players; private int currPlayerInt; protected Table table; protected ArrayList<TurnState> turnStates; private Player currPlayer; private Player nextPlayer; protected int currPopeSpace; private final int gameId; private boolean lastTurn; public int playerReady; //Players ready to start the game that have chosen their leaderCards /** * Instantiates a new {@link Game} saving all the information about it, such for example the reference to the {@link Player}s, * and handing out all the necessary for the game like the table's development card or the market's resources. * * @param players the players joined to this game. * @param cards the development cards to place on the {@link Table}. * @param gameId the ID on the server of this particular game. * @param maxPlayer the number of {@link Player}s in this game. */ public Game(ArrayList<Player> players, ArrayList<DevCard> cards, int gameId, int maxPlayer) { playerReady = 0; currPlayerInt = 0; currPlayer = players.get(currPlayerInt); this.maxPlayer = maxPlayer; this.gameId = gameId; this.players = players; Collections.shuffle(cards); this.table = new Table(cards); this.turnStates = new ArrayList<>(); this.currPlayer = players.get(0); this.currPopeSpace = 1; } /** * Gets the GameID. * * @return the GameID. */ public int getGameId() { return gameId; } /** * When a new {@link Player} with a new abilities gets created, replace him, in the * {@link Game}'s list of players, in the same position of the original one. * * @param original the {@link Player} that is going to be substituted. * @param newPlayer the new {@link Player}'s reference. */ public void changePlayer(Player original, Player newPlayer) { int pos = players.indexOf(original); players.set(pos, newPlayer); if(original.getNickName().equals(currPlayer.getNickName())) currPlayer = newPlayer; } /** * Gets {@link Table}. * * @return the {@link Table} */ public Table getTable() { return table; } /** * Receives from the {@link Player}, client side, a {@link Request} containing what the player would like to do. * For each of them controls: if the player who send the request is the current player on the game, * if the player can do those actions in this moment if the player can do those action according to his * status' possibilities. * <p> * If all the conditions are satisfied modifies the player's status on the server and create an {@link Update} * containing all the modifies bring by the player's action. Otherwise if only one of the requirements isn't * satisfied create an {@link ErrorUpdate}. * <p> * It also controls if the requirements for ending the game are satisfied by the current player. * * @param req the request received from the {@link Player}, client side. */ public synchronized void notify(Request req) { //In the case the game is starting every game can send the request if (req.getPlayerID().equals(currPlayer.getNickName()) || req instanceof InitialPlayersSetRequest) { if (req.validRequest(turnStates)) { if (req.canBePlayed(currPlayer)) { turnStates.add(req.handle(getPlayerFromID(req.getPlayerID()), this)); if (turnStates.contains(TurnState.END_TURN)) { turnStates.clear(); currPlayer = nextPlayer; } if (lastTurn) { if (currPlayerInt == 0) { endgame(); } } //Notify all players except for the newGame req which is handled separately if(!(req instanceof InitialPlayersSetRequest)) notifyAllPlayers(req.createUpdate(currPlayer, this)); //Check if the game is finished if ((currPlayer.getBoard().getSlot().getAllCards().size() == 7 || currPlayer.getBoard().getFaithPath().checkPopeSpace(3)) && !lastTurn) { lastTurn = true; if (currPlayer.getBoard().getSlot().getAllCards().size() == 7) notifyAllPlayers(new LastTurnUpdate("\n" + currPlayer.getNickName() + " has bought 7 cards, it's last turn!\n")); if (currPlayer.getBoard().getFaithPath().checkPopeSpace(3)) notifyAllPlayers(new LastTurnUpdate("\n" + currPlayer.getNickName() + " has reached 30 Faith Points, it's last turn!\n")); } } else { Update error = new ErrorUpdate("You can't do that!", req.getPlayerID()); notifyAllPlayers(error); } } else { Update error = new ErrorUpdate("You can't do this action in this moment!", req.getPlayerID()); notifyAllPlayers(error); } } else { Update error = new ErrorUpdate("It's not your turn", req.getPlayerID()); notifyAllPlayers(error); } } /** * Calls all the {@link Player}s, different by the curr player, to make them moveForward on their {@link FaithPath} of a number * of steps equal to the discarded resources by the current player in this turn; * calls the current player to make him move forward of a number of steps equal to the number of all faith points * obtained by the player in his turn. * <p> * After every movement of someone, check if it has reached a Pope Space, in this case check the advancement of * every player on their Faith Path and add them or not some Victory Points. * * @param discardedSteps the number of FAITH resources discarded by the current player that make other players move. * @param playerSteps the number of FAITH resources obtained by the player in his turn that make him move. */ public void fpAdvancement(int discardedSteps, int playerSteps) { //Other players move as much as resources are discarded by the current player if (discardedSteps != 0) { for (Player player : players) { if (player != currPlayer) { player.getBoard().getFaithPath().moveForward(discardedSteps); player.getBoard().getFaithPath().checkVictoryPoints(); } } } //Current player moves as much as faith points are gained in their turn if (playerSteps != 0) { currPlayer.getBoard().getFaithPath().moveForward(playerSteps); currPlayer.getBoard().getFaithPath().checkVictoryPoints(); } boolean popeSpace = false; //checks whether the nearest pope space was reached by one of the players for (Player player : players) { if (player.getBoard().getFaithPath().checkPopeSpace(currPopeSpace)) { popeSpace = true; break; } } //Calls checkVaticanSection for every single player if (popeSpace) { for (Player player : players) { player.getBoard().getFaithPath().checkVaticanSection(currPopeSpace); } currPopeSpace++; //Recursive call needed if a player has enough faith points to pass through multiple pope spaces this.fpAdvancement(0, 0); } } /** * Add {@link Player} to this {@link Game}. * * @param newPlayer the new player */ //Synchronized player because two players can't register at the same time public synchronized void addPlayer(Player newPlayer) { if(players.size() < maxPlayer) players.add(newPlayer); } /** * Called when the last turn of the {@link Game} is finished. Create an {@link EndgameUpdate} containing the winner * and the victory points of each {@link Player}s. */ public void endgame() { int winnerPoints = 0; String winnerNickname = null; ArrayList<PlayerVP> playersVP = new ArrayList<>(); for (Player player : players) { player.addVictoryPoints(player.getAllResources().size() /5); playersVP.add(new PlayerVP(player.getNickName(), player.getVictoryPoints())); if (player.getVictoryPoints() > winnerPoints) { winnerPoints = player.getVictoryPoints(); winnerNickname = player.getNickName(); } } notifyAllPlayers(new EndgameUpdate(winnerNickname, playersVP)); } /** * Gets the {@link Player}s in this {@link Game}. * * @return the {@link Player}s' list. */ public ArrayList<Player> getPlayers() { return players; } /** * Gets the number of {@link Player}s in this {@link Game}. * * @return the number of {@link Player}. */ public int getMax() { return maxPlayer; } /** * Gets all the action done by the current {@link Player} on his turn till this moment. * * @return the list of done actions. */ public ArrayList<TurnState> getTurnStates() { return turnStates; } /** * When tha {@link Game} starts create an {@link NewGameUpdate} containing for each {@link Player}, 4 different * {@link LeaderCard}s from which he has to choose 2 and, according to the number of players in the game, * some resources of their choice and some Faith Points. * * @return the {@link NewGameUpdate}. */ public Update createNewGameUpdate() { ArrayList<LeaderCard> allLeaderCards = new ArrayList<>(); allLeaderCards.addAll(DefaultCreator.produceLeaderCard()); //creates all leader cards Collections.shuffle(allLeaderCards); //shuffles the cards //Creates an array of players and it makes them choose 2 cards out of the 4 assigned ArrayList<PlayerLC> playersLC = new ArrayList<>(); for (Player player : players) { player.setTable(table); ArrayList<String> leadersToChoose = new ArrayList<>(); for (int addedCard = 0; addedCard < 4; addedCard++) { leadersToChoose.add(allLeaderCards.remove(0).getID()); } playersLC.add(new PlayerLC(player.getNickName(), leadersToChoose)); } ArrayList<PlayerST> playersST = new ArrayList<>(); switch (players.size()) { case (1): PlayerST player11 = new PlayerST(players.get(0).getNickName(), 0, 0); playersST.add(player11); break; case (2): PlayerST player21 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player22 = new PlayerST(players.get(1).getNickName(), 1, 0); playersST.add(player21); playersST.add(player22); break; case (3): PlayerST player31 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player32 = new PlayerST(players.get(1).getNickName(), 1, 0); PlayerST player33 = new PlayerST(players.get(2).getNickName(), 1, 1); players.get(2).addVictoryPoints(1); playersST.add(player31); playersST.add(player32); playersST.add(player33); break; case (4): PlayerST player41 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player42 = new PlayerST(players.get(1).getNickName(), 1, 0); PlayerST player43 = new PlayerST(players.get(2).getNickName(), 1, 1); PlayerST player44 = new PlayerST(players.get(3).getNickName(), 2, 1); players.get(2).addVictoryPoints(1); players.get(3).addVictoryPoints(1); playersST.add(player41); playersST.add(player42); playersST.add(player43); playersST.add(player44); break; } return new NewGameUpdate(this.gameId, table.getFrontIDs(), table.market.getMarket(), playersLC, playersST); } /** * Gets the position of the curr {@link Player} on the {@link Game}'s list of players. * * @return the position. */ public int getCurrPlayerInt() { return currPlayerInt; } /** * Sets the position of the curr {@link Player} on the {@link Game}'s list of players. * * @param currPlayerInt the position tu set. */ public void setCurrPlayerInt(int currPlayerInt) { this.currPlayerInt = currPlayerInt; } /** * Gets curr {@link Player}. * * @return the curr {@link Player}. */ public Player getCurrPlayer() { return currPlayer; } /** * Sends to all the {@link Player}s the last {@link Update} created by the {@link Game}. * * @param update the {@link Update} to send. */ public void notifyAllPlayers(Update update){ System.out.println("Sending "+update+ "to all players"); for (Player p: players) p.notifyView(update); } /** * Sets next {@link Player}. * * @param nextPlayer the next {@link Player} */ public void setNextPlayer(Player nextPlayer) { this.nextPlayer = nextPlayer; } /** * Gets the reference of a {@link Player} having the received ID. * * @param playerID the {@link Player}'s ID. * @return the reference to the {@link Player}. */ public Player getPlayerFromID(String playerID) { for (Player p : players) { if (p.getNickName().equals(playerID)) { return p; } } return null; } /** * Start the {@link Game}. */ public void start() { currPlayer = players.get(0); notifyAllPlayers(new StartGameUpdate(players.get(0).getNickName())); } }
UTF-8
Java
15,318
java
Game.java
Java
[]
null
[]
package it.polimi.ingsw.controller; import it.polimi.ingsw.controller.Request.InitialPlayersSetRequest; import it.polimi.ingsw.controller.Request.Request; import it.polimi.ingsw.model.Board.FaithPath; import it.polimi.ingsw.Updates.*; import it.polimi.ingsw.model.card.DevCard; import it.polimi.ingsw.model.Player.Player; import it.polimi.ingsw.model.Table.Table; import it.polimi.ingsw.model.card.LeaderCard; import java.util.ArrayList; import java.util.Collections; /** * An object {@link Game} is created every time some players start a game. It contains the references to all the {@link Player}s * and the information about the game in progress, such for example the {@link DevCard}s available on the {@link Table} * or the actions done by the players during their turns. * <p> * It also receive the information from the server containing what a player wants to do and, in case it is possible, * handle them modifying the players' status on the server. */ public class Game { public int maxPlayer; private ArrayList<Player> players; private int currPlayerInt; protected Table table; protected ArrayList<TurnState> turnStates; private Player currPlayer; private Player nextPlayer; protected int currPopeSpace; private final int gameId; private boolean lastTurn; public int playerReady; //Players ready to start the game that have chosen their leaderCards /** * Instantiates a new {@link Game} saving all the information about it, such for example the reference to the {@link Player}s, * and handing out all the necessary for the game like the table's development card or the market's resources. * * @param players the players joined to this game. * @param cards the development cards to place on the {@link Table}. * @param gameId the ID on the server of this particular game. * @param maxPlayer the number of {@link Player}s in this game. */ public Game(ArrayList<Player> players, ArrayList<DevCard> cards, int gameId, int maxPlayer) { playerReady = 0; currPlayerInt = 0; currPlayer = players.get(currPlayerInt); this.maxPlayer = maxPlayer; this.gameId = gameId; this.players = players; Collections.shuffle(cards); this.table = new Table(cards); this.turnStates = new ArrayList<>(); this.currPlayer = players.get(0); this.currPopeSpace = 1; } /** * Gets the GameID. * * @return the GameID. */ public int getGameId() { return gameId; } /** * When a new {@link Player} with a new abilities gets created, replace him, in the * {@link Game}'s list of players, in the same position of the original one. * * @param original the {@link Player} that is going to be substituted. * @param newPlayer the new {@link Player}'s reference. */ public void changePlayer(Player original, Player newPlayer) { int pos = players.indexOf(original); players.set(pos, newPlayer); if(original.getNickName().equals(currPlayer.getNickName())) currPlayer = newPlayer; } /** * Gets {@link Table}. * * @return the {@link Table} */ public Table getTable() { return table; } /** * Receives from the {@link Player}, client side, a {@link Request} containing what the player would like to do. * For each of them controls: if the player who send the request is the current player on the game, * if the player can do those actions in this moment if the player can do those action according to his * status' possibilities. * <p> * If all the conditions are satisfied modifies the player's status on the server and create an {@link Update} * containing all the modifies bring by the player's action. Otherwise if only one of the requirements isn't * satisfied create an {@link ErrorUpdate}. * <p> * It also controls if the requirements for ending the game are satisfied by the current player. * * @param req the request received from the {@link Player}, client side. */ public synchronized void notify(Request req) { //In the case the game is starting every game can send the request if (req.getPlayerID().equals(currPlayer.getNickName()) || req instanceof InitialPlayersSetRequest) { if (req.validRequest(turnStates)) { if (req.canBePlayed(currPlayer)) { turnStates.add(req.handle(getPlayerFromID(req.getPlayerID()), this)); if (turnStates.contains(TurnState.END_TURN)) { turnStates.clear(); currPlayer = nextPlayer; } if (lastTurn) { if (currPlayerInt == 0) { endgame(); } } //Notify all players except for the newGame req which is handled separately if(!(req instanceof InitialPlayersSetRequest)) notifyAllPlayers(req.createUpdate(currPlayer, this)); //Check if the game is finished if ((currPlayer.getBoard().getSlot().getAllCards().size() == 7 || currPlayer.getBoard().getFaithPath().checkPopeSpace(3)) && !lastTurn) { lastTurn = true; if (currPlayer.getBoard().getSlot().getAllCards().size() == 7) notifyAllPlayers(new LastTurnUpdate("\n" + currPlayer.getNickName() + " has bought 7 cards, it's last turn!\n")); if (currPlayer.getBoard().getFaithPath().checkPopeSpace(3)) notifyAllPlayers(new LastTurnUpdate("\n" + currPlayer.getNickName() + " has reached 30 Faith Points, it's last turn!\n")); } } else { Update error = new ErrorUpdate("You can't do that!", req.getPlayerID()); notifyAllPlayers(error); } } else { Update error = new ErrorUpdate("You can't do this action in this moment!", req.getPlayerID()); notifyAllPlayers(error); } } else { Update error = new ErrorUpdate("It's not your turn", req.getPlayerID()); notifyAllPlayers(error); } } /** * Calls all the {@link Player}s, different by the curr player, to make them moveForward on their {@link FaithPath} of a number * of steps equal to the discarded resources by the current player in this turn; * calls the current player to make him move forward of a number of steps equal to the number of all faith points * obtained by the player in his turn. * <p> * After every movement of someone, check if it has reached a Pope Space, in this case check the advancement of * every player on their Faith Path and add them or not some Victory Points. * * @param discardedSteps the number of FAITH resources discarded by the current player that make other players move. * @param playerSteps the number of FAITH resources obtained by the player in his turn that make him move. */ public void fpAdvancement(int discardedSteps, int playerSteps) { //Other players move as much as resources are discarded by the current player if (discardedSteps != 0) { for (Player player : players) { if (player != currPlayer) { player.getBoard().getFaithPath().moveForward(discardedSteps); player.getBoard().getFaithPath().checkVictoryPoints(); } } } //Current player moves as much as faith points are gained in their turn if (playerSteps != 0) { currPlayer.getBoard().getFaithPath().moveForward(playerSteps); currPlayer.getBoard().getFaithPath().checkVictoryPoints(); } boolean popeSpace = false; //checks whether the nearest pope space was reached by one of the players for (Player player : players) { if (player.getBoard().getFaithPath().checkPopeSpace(currPopeSpace)) { popeSpace = true; break; } } //Calls checkVaticanSection for every single player if (popeSpace) { for (Player player : players) { player.getBoard().getFaithPath().checkVaticanSection(currPopeSpace); } currPopeSpace++; //Recursive call needed if a player has enough faith points to pass through multiple pope spaces this.fpAdvancement(0, 0); } } /** * Add {@link Player} to this {@link Game}. * * @param newPlayer the new player */ //Synchronized player because two players can't register at the same time public synchronized void addPlayer(Player newPlayer) { if(players.size() < maxPlayer) players.add(newPlayer); } /** * Called when the last turn of the {@link Game} is finished. Create an {@link EndgameUpdate} containing the winner * and the victory points of each {@link Player}s. */ public void endgame() { int winnerPoints = 0; String winnerNickname = null; ArrayList<PlayerVP> playersVP = new ArrayList<>(); for (Player player : players) { player.addVictoryPoints(player.getAllResources().size() /5); playersVP.add(new PlayerVP(player.getNickName(), player.getVictoryPoints())); if (player.getVictoryPoints() > winnerPoints) { winnerPoints = player.getVictoryPoints(); winnerNickname = player.getNickName(); } } notifyAllPlayers(new EndgameUpdate(winnerNickname, playersVP)); } /** * Gets the {@link Player}s in this {@link Game}. * * @return the {@link Player}s' list. */ public ArrayList<Player> getPlayers() { return players; } /** * Gets the number of {@link Player}s in this {@link Game}. * * @return the number of {@link Player}. */ public int getMax() { return maxPlayer; } /** * Gets all the action done by the current {@link Player} on his turn till this moment. * * @return the list of done actions. */ public ArrayList<TurnState> getTurnStates() { return turnStates; } /** * When tha {@link Game} starts create an {@link NewGameUpdate} containing for each {@link Player}, 4 different * {@link LeaderCard}s from which he has to choose 2 and, according to the number of players in the game, * some resources of their choice and some Faith Points. * * @return the {@link NewGameUpdate}. */ public Update createNewGameUpdate() { ArrayList<LeaderCard> allLeaderCards = new ArrayList<>(); allLeaderCards.addAll(DefaultCreator.produceLeaderCard()); //creates all leader cards Collections.shuffle(allLeaderCards); //shuffles the cards //Creates an array of players and it makes them choose 2 cards out of the 4 assigned ArrayList<PlayerLC> playersLC = new ArrayList<>(); for (Player player : players) { player.setTable(table); ArrayList<String> leadersToChoose = new ArrayList<>(); for (int addedCard = 0; addedCard < 4; addedCard++) { leadersToChoose.add(allLeaderCards.remove(0).getID()); } playersLC.add(new PlayerLC(player.getNickName(), leadersToChoose)); } ArrayList<PlayerST> playersST = new ArrayList<>(); switch (players.size()) { case (1): PlayerST player11 = new PlayerST(players.get(0).getNickName(), 0, 0); playersST.add(player11); break; case (2): PlayerST player21 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player22 = new PlayerST(players.get(1).getNickName(), 1, 0); playersST.add(player21); playersST.add(player22); break; case (3): PlayerST player31 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player32 = new PlayerST(players.get(1).getNickName(), 1, 0); PlayerST player33 = new PlayerST(players.get(2).getNickName(), 1, 1); players.get(2).addVictoryPoints(1); playersST.add(player31); playersST.add(player32); playersST.add(player33); break; case (4): PlayerST player41 = new PlayerST(players.get(0).getNickName(), 0, 0); PlayerST player42 = new PlayerST(players.get(1).getNickName(), 1, 0); PlayerST player43 = new PlayerST(players.get(2).getNickName(), 1, 1); PlayerST player44 = new PlayerST(players.get(3).getNickName(), 2, 1); players.get(2).addVictoryPoints(1); players.get(3).addVictoryPoints(1); playersST.add(player41); playersST.add(player42); playersST.add(player43); playersST.add(player44); break; } return new NewGameUpdate(this.gameId, table.getFrontIDs(), table.market.getMarket(), playersLC, playersST); } /** * Gets the position of the curr {@link Player} on the {@link Game}'s list of players. * * @return the position. */ public int getCurrPlayerInt() { return currPlayerInt; } /** * Sets the position of the curr {@link Player} on the {@link Game}'s list of players. * * @param currPlayerInt the position tu set. */ public void setCurrPlayerInt(int currPlayerInt) { this.currPlayerInt = currPlayerInt; } /** * Gets curr {@link Player}. * * @return the curr {@link Player}. */ public Player getCurrPlayer() { return currPlayer; } /** * Sends to all the {@link Player}s the last {@link Update} created by the {@link Game}. * * @param update the {@link Update} to send. */ public void notifyAllPlayers(Update update){ System.out.println("Sending "+update+ "to all players"); for (Player p: players) p.notifyView(update); } /** * Sets next {@link Player}. * * @param nextPlayer the next {@link Player} */ public void setNextPlayer(Player nextPlayer) { this.nextPlayer = nextPlayer; } /** * Gets the reference of a {@link Player} having the received ID. * * @param playerID the {@link Player}'s ID. * @return the reference to the {@link Player}. */ public Player getPlayerFromID(String playerID) { for (Player p : players) { if (p.getNickName().equals(playerID)) { return p; } } return null; } /** * Start the {@link Game}. */ public void start() { currPlayer = players.get(0); notifyAllPlayers(new StartGameUpdate(players.get(0).getNickName())); } }
15,318
0.604648
0.597663
382
39.099476
35.166405
206
false
false
0
0
0
0
0
0
0.492147
false
false
9
e8fefef89041aaa41ff72111d93848c0930cc9f7
15,358,803,116,989
0ab3b39fe591c0fefec6b04efda5372fd02a270a
/android/info-transport/app/src/main/java/ro/gov/httpithub/infotransport/search/SearchPresenter.java
bf32cc4772d8374ae0514385e203982149586838
[]
no_license
raztd/info-transport
https://github.com/raztd/info-transport
c22eebe9bdd3fda8493ff79421e9ec9dfc0a982a
2552ba2f9dcf4dd8b313db6b95f7e522a81754b3
refs/heads/master
2018-01-06T18:59:45.483000
2016-10-09T07:19:59
2016-10-09T07:19:59
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ro.gov.httpithub.infotransport.search; class SearchPresenter implements SearchContract.Presenter { private SearchContract.View mSearchView; SearchPresenter(SearchContract.View searchView) { this.mSearchView = searchView; mSearchView.setPresenter(this); } @Override public void start() { // do something } @Override public void getRoute() { // TODO: get the route via an api call mSearchView.showRoute(); } }
UTF-8
Java
497
java
SearchPresenter.java
Java
[]
null
[]
package ro.gov.httpithub.infotransport.search; class SearchPresenter implements SearchContract.Presenter { private SearchContract.View mSearchView; SearchPresenter(SearchContract.View searchView) { this.mSearchView = searchView; mSearchView.setPresenter(this); } @Override public void start() { // do something } @Override public void getRoute() { // TODO: get the route via an api call mSearchView.showRoute(); } }
497
0.665996
0.665996
22
21.59091
19.706158
59
false
false
0
0
0
0
0
0
0.227273
false
false
9
5bfb9f4940e271922682a5e9342adb6bbc2b7d97
18,665,927,928,245
cd5e46fdc764ca36f8c4572c73c4e4e3e1e67c17
/src/main/java/com/yjpfj1203/statistics/document/mongo/repository/OptLogMongoRepositoryCustom.java
f6d5252aaf71df03e8ef1a8060550539885add11
[]
no_license
yjpfj1203/statistics-service
https://github.com/yjpfj1203/statistics-service
4e702829167e364e2503a34e19c29c0f1a6c91f0
85fabbb67b98a168d6f9072082710f8173d94f4a
refs/heads/master
2020-03-27T14:49:56.086000
2018-09-27T11:35:31
2018-09-27T11:35:31
146,681,618
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yjpfj1203.statistics.document.mongo.repository; import com.yjpfj1203.statistics.document.mongo.OptLogMG; import org.springframework.data.domain.Pageable; import java.util.List; public interface OptLogMongoRepositoryCustom { public List<OptLogMG> findActive(Pageable pageable); }
UTF-8
Java
298
java
OptLogMongoRepositoryCustom.java
Java
[]
null
[]
package com.yjpfj1203.statistics.document.mongo.repository; import com.yjpfj1203.statistics.document.mongo.OptLogMG; import org.springframework.data.domain.Pageable; import java.util.List; public interface OptLogMongoRepositoryCustom { public List<OptLogMG> findActive(Pageable pageable); }
298
0.828859
0.802013
10
28.799999
25.226177
59
false
false
0
0
0
0
0
0
0.5
false
false
9
4ab1a566133473b425a79ea7167959fbe2dc0576
18,013,092,880,106
4ff612b13f71d99956bc86a76309a553581780ae
/ly/133.Clone_Graph.java
5f8925f4c9b5ba36760cf0c7b938a9237c22c3f7
[]
no_license
wanderring/Algorithm-In-Leetcode
https://github.com/wanderring/Algorithm-In-Leetcode
c263540d3fee5118d70928bf8caf31b9976d46ee
6509bf9eb8687fbc9e4493bcc4dc9e5363321fd5
refs/heads/master
2020-06-02T07:29:14.695000
2019-06-21T17:06:18
2019-06-21T17:06:18
191,083,708
0
0
null
true
2019-06-10T02:37:05
2019-06-10T02:37:05
2019-05-20T10:08:11
2019-05-20T10:08:10
286
0
0
0
null
false
false
/*Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. Example: 1--2 | | 3--4 Input: {"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1} Explanation: Node 1's value is 1, and it has two neighbors: Node 2 and 4. Node 2's value is 2, and it has two neighbors: Node 1 and 3. Node 3's value is 3, and it has two neighbors: Node 2 and 4. Node 4's value is 4, and it has two neighbors: Node 1 and 3. Note: The number of nodes will be between 1 and 100. The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph. Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too. You must return the copy of the given node as a reference to the cloned graph. 使用两个list模拟队列广度优先遍历整个图,遍历的过程中复制,并使用map存储复制后的节点,以方便 迅速找到复制后的neighbors Runtime: 1 ms, faster than 100.00% of Java online submissions for Clone Graph. Memory Usage: 32.7 MB, less than 98.85% of Java online submissions for Clone Graph. */ /* // Definition for a Node. class Node { public int val; public List<Node> neighbors; public Node() {} public Node(int _val,List<Node> _neighbors) { val = _val; neighbors = _neighbors; } }; */ class Solution { public Node cloneGraph(Node node) { ArrayList<Node> temp1 = new ArrayList<>(); ArrayList<Node> temp2 = new ArrayList<>(); ArrayList<Node> tempCopy = new ArrayList<>(); HashMap<Node,Node> origin = new HashMap<>(); temp1.add(node); Node nodeCopy = new Node(node.val, new ArrayList<Node>()); tempCopy.add(nodeCopy); origin.put(node,nodeCopy); while (temp1.size()>0) { Node tempNode = temp1.get(0); Node tempCopyNode = tempCopy.get(0); temp1.remove(0); tempCopy.remove(0); for (Node item : tempNode.neighbors) { if (!origin.containsKey(item)) { Node itemCopy = new Node(item.val, new ArrayList<Node>()); origin.put(item,itemCopy); tempCopy.add(itemCopy); tempCopyNode.neighbors.add(itemCopy); temp2.add(item); } else { tempCopyNode.neighbors.add(origin.get(item)); } } if (temp1.size()==0) { temp1 = temp2; temp2 = new ArrayList<>(); } } return nodeCopy; } }
UTF-8
Java
2,869
java
133.Clone_Graph.java
Java
[]
null
[]
/*Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors. Example: 1--2 | | 3--4 Input: {"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1} Explanation: Node 1's value is 1, and it has two neighbors: Node 2 and 4. Node 2's value is 2, and it has two neighbors: Node 1 and 3. Node 3's value is 3, and it has two neighbors: Node 2 and 4. Node 4's value is 4, and it has two neighbors: Node 1 and 3. Note: The number of nodes will be between 1 and 100. The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph. Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too. You must return the copy of the given node as a reference to the cloned graph. 使用两个list模拟队列广度优先遍历整个图,遍历的过程中复制,并使用map存储复制后的节点,以方便 迅速找到复制后的neighbors Runtime: 1 ms, faster than 100.00% of Java online submissions for Clone Graph. Memory Usage: 32.7 MB, less than 98.85% of Java online submissions for Clone Graph. */ /* // Definition for a Node. class Node { public int val; public List<Node> neighbors; public Node() {} public Node(int _val,List<Node> _neighbors) { val = _val; neighbors = _neighbors; } }; */ class Solution { public Node cloneGraph(Node node) { ArrayList<Node> temp1 = new ArrayList<>(); ArrayList<Node> temp2 = new ArrayList<>(); ArrayList<Node> tempCopy = new ArrayList<>(); HashMap<Node,Node> origin = new HashMap<>(); temp1.add(node); Node nodeCopy = new Node(node.val, new ArrayList<Node>()); tempCopy.add(nodeCopy); origin.put(node,nodeCopy); while (temp1.size()>0) { Node tempNode = temp1.get(0); Node tempCopyNode = tempCopy.get(0); temp1.remove(0); tempCopy.remove(0); for (Node item : tempNode.neighbors) { if (!origin.containsKey(item)) { Node itemCopy = new Node(item.val, new ArrayList<Node>()); origin.put(item,itemCopy); tempCopy.add(itemCopy); tempCopyNode.neighbors.add(itemCopy); temp2.add(item); } else { tempCopyNode.neighbors.add(origin.get(item)); } } if (temp1.size()==0) { temp1 = temp2; temp2 = new ArrayList<>(); } } return nodeCopy; } }
2,869
0.589021
0.564825
83
32.361446
36.639099
200
false
false
0
0
0
0
0
0
0.674699
false
false
9
74d81e3ee713bbd0a989b47e1609e0eacc691ab9
24,489,903,590,038
c3c90a81fefd62e267c6d4885f69c0f182b44c0f
/src/main/java/com/thinkgem/jeesite/modules/books/entity/Subsidiaryledge.java
89d1dbcd1c98b5206f19c8a32f679a5d103fb143
[]
no_license
yangxiaodong1/yunzh
https://github.com/yangxiaodong1/yunzh
8a2ce3763093d069fad9b6f78cd76882c091a32d
89ae810c6da464d5aa361cd312480d4cf9f21528
refs/heads/master
2021-07-11T05:40:59.442000
2017-10-13T08:10:46
2017-10-13T08:10:46
106,795,747
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.books.entity; import org.hibernate.validator.constraints.Length; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonBackReference; import com.thinkgem.jeesite.common.persistence.DataEntity; /** * 凭证摘要和科目Entity * @author zhangtong * @version 2015-12-04 */ public class Subsidiaryledge extends DataEntity<Subsidiaryledge> { private static final long serialVersionUID = 1L; private String voucherTitleName; // 凭证字名称 private String voucherTitleNumber; // 凭证字号 private Date accountDate; // 记账日期 private String accountPeriod; // 账期 private String recieptNumber; // 单据数 private String recieptInfo; // 单据信息 private String totalAmount; // 合计金额 private String userName; // 制单人 private Date touchingDate; // 制单时间 private String checker; // 审核人 private Date checkDate; // 审核时间 private String isCheck; // 审核状态 private String tVId; // 记账凭_凭证编号 private String expRowNumber; // 摘要行号 private String exp; // 摘要 private String debit; // 借方金额 private String credit; // 贷方金额 private String accId; // 科目编号 private String fdbid; // 公司客户编号 private String accuntId; // 公司编码 private String accountName; // 科目名称 private String accLevel; // 科目级别 private String detail; // 科目是否有子文件 private Subsidiaryledge parent; // 上一级科目id private String rootId; // 根节点id private String groupId; // 科目组ID private String dc; // 借贷方向 private String periodEnd; //账期后 public String getPeriodEnd() { return periodEnd; } public void setPeriodEnd(String periodEnd) { this.periodEnd = periodEnd; } public Subsidiaryledge() { super(); } public Subsidiaryledge(String id){ super(id); } @Length(min=0, max=64, message="凭证字名称长度必须介于 0 和 64 之间") public String getVoucherTitleName() { return voucherTitleName; } public void setVoucherTitleName(String voucherTitleName) { this.voucherTitleName = voucherTitleName; } @Length(min=0, max=4, message="凭证字号长度必须介于 0 和 4 之间") public String getVoucherTitleNumber() { return voucherTitleNumber; } public void setVoucherTitleNumber(String voucherTitleNumber) { this.voucherTitleNumber = voucherTitleNumber; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getAccountDate() { return accountDate; } public void setAccountDate(Date accountDate) { this.accountDate = accountDate; } @Length(min=0, max=6, message="账期长度必须介于 0 和 6 之间") public String getAccountPeriod() { return accountPeriod; } public void setAccountPeriod(String accountPeriod) { this.accountPeriod = accountPeriod; } @Length(min=0, max=4, message="单据数长度必须介于 0 和 4 之间") public String getRecieptNumber() { return recieptNumber; } public void setRecieptNumber(String recieptNumber) { this.recieptNumber = recieptNumber; } @Length(min=0, max=200, message="单据信息长度必须介于 0 和 200 之间") public String getRecieptInfo() { return recieptInfo; } public void setRecieptInfo(String recieptInfo) { this.recieptInfo = recieptInfo; } public String getTotalAmount() { return totalAmount; } public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; } @Length(min=0, max=100, message="制单人长度必须介于 0 和 100 之间") public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getTouchingDate() { return touchingDate; } public void setTouchingDate(Date touchingDate) { this.touchingDate = touchingDate; } @Length(min=0, max=100, message="审核人长度必须介于 0 和 100 之间") public String getChecker() { return checker; } public void setChecker(String checker) { this.checker = checker; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCheckDate() { return checkDate; } public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } @Length(min=0, max=20, message="审核状态长度必须介于 0 和 20 之间") public String getIsCheck() { return isCheck; } public void setIsCheck(String isCheck) { this.isCheck = isCheck; } @Length(min=0, max=64, message="记账凭_凭证编号长度必须介于 0 和 64 之间") public String getTVId() { return tVId; } public void setTVId(String tVId) { this.tVId = tVId; } @Length(min=0, max=64, message="摘要行号长度必须介于 0 和 64 之间") public String getExpRowNumber() { return expRowNumber; } public void setExpRowNumber(String expRowNumber) { this.expRowNumber = expRowNumber; } @Length(min=0, max=64, message="摘要长度必须介于 0 和 64 之间") public String getExp() { return exp; } public void setExp(String exp) { this.exp = exp; } public String getDebit() { return debit; } public void setDebit(String debit) { this.debit = debit; } public String getCredit() { return credit; } public void setCredit(String credit) { this.credit = credit; } @Length(min=1, max=11, message="科目编号长度必须介于 1 和 11 之间") public String getAccId() { return accId; } public void setAccId(String accId) { this.accId = accId; } @Length(min=0, max=64, message="公司客户编号长度必须介于 0 和 64 之间") public String getFdbid() { return fdbid; } public void setFdbid(String fdbid) { this.fdbid = fdbid; } @Length(min=0, max=64, message="公司编码长度必须介于 0 和 64 之间") public String getAccuntId() { return accuntId; } public void setAccuntId(String accuntId) { this.accuntId = accuntId; } @Length(min=0, max=64, message="科目名称长度必须介于 0 和 64 之间") public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } @Length(min=0, max=64, message="科目级别长度必须介于 0 和 64 之间") public String getAccLevel() { return accLevel; } public void setAccLevel(String accLevel) { this.accLevel = accLevel; } @Length(min=0, max=64, message="科目是否有子文件长度必须介于 0 和 64 之间") public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @JsonBackReference public Subsidiaryledge getParent() { return parent; } public void setParent(Subsidiaryledge parent) { this.parent = parent; } @Length(min=0, max=64, message="根节点id长度必须介于 0 和 64 之间") public String getRootId() { return rootId; } public void setRootId(String rootId) { this.rootId = rootId; } @Length(min=0, max=64, message="科目组ID长度必须介于 0 和 64 之间") public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @Length(min=0, max=20, message="借贷方向长度必须介于 0 和 20 之间") public String getDc() { return dc; } public void setDc(String dc) { this.dc = dc; } }
UTF-8
Java
7,514
java
Subsidiaryledge.java
Java
[ { "context": "ight &copy; 2012-2014 <a href=\"https://github.com/thinkgem/jeesite\">JeeSite</a> All rights reserved.\n */\npac", "end": 70, "score": 0.9972076416015625, "start": 62, "tag": "USERNAME", "value": "thinkgem" }, { "context": "tence.DataEntity;\n\n/**\n * 凭证摘要和科目Entity\n * @author zhangtong\n * @version 2015-12-04\n */\npublic class Subsidiar", "end": 456, "score": 0.9995129108428955, "start": 447, "tag": "USERNAME", "value": "zhangtong" }, { "context": "和 100 之间\")\n\tpublic String getUserName() {\n\t\treturn userName;\n\t}\n\n\tpublic void setUserName(String userName) {\n", "end": 3400, "score": 0.794973611831665, "start": 3392, "tag": "USERNAME", "value": "userName" }, { "context": "d setUserName(String userName) {\n\t\tthis.userName = userName;\n\t}\n\t\n\t@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss", "end": 3476, "score": 0.6897159218788147, "start": 3468, "tag": "USERNAME", "value": "userName" } ]
null
[]
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.books.entity; import org.hibernate.validator.constraints.Length; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonBackReference; import com.thinkgem.jeesite.common.persistence.DataEntity; /** * 凭证摘要和科目Entity * @author zhangtong * @version 2015-12-04 */ public class Subsidiaryledge extends DataEntity<Subsidiaryledge> { private static final long serialVersionUID = 1L; private String voucherTitleName; // 凭证字名称 private String voucherTitleNumber; // 凭证字号 private Date accountDate; // 记账日期 private String accountPeriod; // 账期 private String recieptNumber; // 单据数 private String recieptInfo; // 单据信息 private String totalAmount; // 合计金额 private String userName; // 制单人 private Date touchingDate; // 制单时间 private String checker; // 审核人 private Date checkDate; // 审核时间 private String isCheck; // 审核状态 private String tVId; // 记账凭_凭证编号 private String expRowNumber; // 摘要行号 private String exp; // 摘要 private String debit; // 借方金额 private String credit; // 贷方金额 private String accId; // 科目编号 private String fdbid; // 公司客户编号 private String accuntId; // 公司编码 private String accountName; // 科目名称 private String accLevel; // 科目级别 private String detail; // 科目是否有子文件 private Subsidiaryledge parent; // 上一级科目id private String rootId; // 根节点id private String groupId; // 科目组ID private String dc; // 借贷方向 private String periodEnd; //账期后 public String getPeriodEnd() { return periodEnd; } public void setPeriodEnd(String periodEnd) { this.periodEnd = periodEnd; } public Subsidiaryledge() { super(); } public Subsidiaryledge(String id){ super(id); } @Length(min=0, max=64, message="凭证字名称长度必须介于 0 和 64 之间") public String getVoucherTitleName() { return voucherTitleName; } public void setVoucherTitleName(String voucherTitleName) { this.voucherTitleName = voucherTitleName; } @Length(min=0, max=4, message="凭证字号长度必须介于 0 和 4 之间") public String getVoucherTitleNumber() { return voucherTitleNumber; } public void setVoucherTitleNumber(String voucherTitleNumber) { this.voucherTitleNumber = voucherTitleNumber; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getAccountDate() { return accountDate; } public void setAccountDate(Date accountDate) { this.accountDate = accountDate; } @Length(min=0, max=6, message="账期长度必须介于 0 和 6 之间") public String getAccountPeriod() { return accountPeriod; } public void setAccountPeriod(String accountPeriod) { this.accountPeriod = accountPeriod; } @Length(min=0, max=4, message="单据数长度必须介于 0 和 4 之间") public String getRecieptNumber() { return recieptNumber; } public void setRecieptNumber(String recieptNumber) { this.recieptNumber = recieptNumber; } @Length(min=0, max=200, message="单据信息长度必须介于 0 和 200 之间") public String getRecieptInfo() { return recieptInfo; } public void setRecieptInfo(String recieptInfo) { this.recieptInfo = recieptInfo; } public String getTotalAmount() { return totalAmount; } public void setTotalAmount(String totalAmount) { this.totalAmount = totalAmount; } @Length(min=0, max=100, message="制单人长度必须介于 0 和 100 之间") public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getTouchingDate() { return touchingDate; } public void setTouchingDate(Date touchingDate) { this.touchingDate = touchingDate; } @Length(min=0, max=100, message="审核人长度必须介于 0 和 100 之间") public String getChecker() { return checker; } public void setChecker(String checker) { this.checker = checker; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getCheckDate() { return checkDate; } public void setCheckDate(Date checkDate) { this.checkDate = checkDate; } @Length(min=0, max=20, message="审核状态长度必须介于 0 和 20 之间") public String getIsCheck() { return isCheck; } public void setIsCheck(String isCheck) { this.isCheck = isCheck; } @Length(min=0, max=64, message="记账凭_凭证编号长度必须介于 0 和 64 之间") public String getTVId() { return tVId; } public void setTVId(String tVId) { this.tVId = tVId; } @Length(min=0, max=64, message="摘要行号长度必须介于 0 和 64 之间") public String getExpRowNumber() { return expRowNumber; } public void setExpRowNumber(String expRowNumber) { this.expRowNumber = expRowNumber; } @Length(min=0, max=64, message="摘要长度必须介于 0 和 64 之间") public String getExp() { return exp; } public void setExp(String exp) { this.exp = exp; } public String getDebit() { return debit; } public void setDebit(String debit) { this.debit = debit; } public String getCredit() { return credit; } public void setCredit(String credit) { this.credit = credit; } @Length(min=1, max=11, message="科目编号长度必须介于 1 和 11 之间") public String getAccId() { return accId; } public void setAccId(String accId) { this.accId = accId; } @Length(min=0, max=64, message="公司客户编号长度必须介于 0 和 64 之间") public String getFdbid() { return fdbid; } public void setFdbid(String fdbid) { this.fdbid = fdbid; } @Length(min=0, max=64, message="公司编码长度必须介于 0 和 64 之间") public String getAccuntId() { return accuntId; } public void setAccuntId(String accuntId) { this.accuntId = accuntId; } @Length(min=0, max=64, message="科目名称长度必须介于 0 和 64 之间") public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } @Length(min=0, max=64, message="科目级别长度必须介于 0 和 64 之间") public String getAccLevel() { return accLevel; } public void setAccLevel(String accLevel) { this.accLevel = accLevel; } @Length(min=0, max=64, message="科目是否有子文件长度必须介于 0 和 64 之间") public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } @JsonBackReference public Subsidiaryledge getParent() { return parent; } public void setParent(Subsidiaryledge parent) { this.parent = parent; } @Length(min=0, max=64, message="根节点id长度必须介于 0 和 64 之间") public String getRootId() { return rootId; } public void setRootId(String rootId) { this.rootId = rootId; } @Length(min=0, max=64, message="科目组ID长度必须介于 0 和 64 之间") public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } @Length(min=0, max=20, message="借贷方向长度必须介于 0 和 20 之间") public String getDc() { return dc; } public void setDc(String dc) { this.dc = dc; } }
7,514
0.712085
0.691795
304
21.213816
19.773811
108
false
false
0
0
0
0
0
0
1.651316
false
false
9
42ed3ec967a1bc37b4c8b148b255019d64d9ba09
23,802,708,817,433
70daf318d027f371ada3abeaaa31dd47651640d7
/src/jdo/inv/INVValidAndQtyWarnTool.java
5b54f0eb5172443748ccf7bcbff032250dfeb620
[]
no_license
wangqing123654/web
https://github.com/wangqing123654/web
00613f6db653562e2e8edc14327649dc18b2aae6
bd447877400291d3f35715ca9c7c7b1e79653531
refs/heads/master
2023-04-07T15:23:34.705000
2020-11-02T10:10:57
2020-11-02T10:10:57
309,329,277
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jdo.inv; import com.dongyang.jdo.TJDOTool; import com.dongyang.data.TParm; /** * <p>Title: 近效期及库存量提示</p> * * <p>Description: 近效期及库存量提示</p> * * <p>Copyright: Copyright (c) 2008</p> * * <p>Company: JavaHis</p> * * @author zhangh 2013.7.12 * @version 1.0 */ public class INVValidAndQtyWarnTool extends TJDOTool { /** * 实例 */ public static INVValidAndQtyWarnTool instanceObject; /** * 得到实例 * * @return IndValidAndQtyWarnTool */ public static INVValidAndQtyWarnTool getInstance() { if (instanceObject == null) instanceObject = new INVValidAndQtyWarnTool(); return instanceObject; } /** * 构造器 */ public INVValidAndQtyWarnTool() { setModuleName("inv\\INVValidAndQtyWarnModule.x"); onInit(); } /** * 近效期查询 * * @param parm * @return */ public TParm onQueryValid(TParm parm) { TParm result = this.query("queryValid", parm); if (result.getErrCode() < 0) { err("ERR:" + result.getErrCode() + result.getErrText() + result.getErrName()); return result; } return result; } /** * 库存量查询 * * @param parm * @return */ public TParm onQueryQty(TParm parm) { TParm result = this.query("queryQty", parm); if (result.getErrCode() < 0) { err("ERR:" + result.getErrCode() + result.getErrText() + result.getErrName()); return result; } return result; } }
GB18030
Java
1,666
java
INVValidAndQtyWarnTool.java
Java
[ { "context": "08</p>\n *\n * <p>Company: JavaHis</p>\n *\n * @author zhangh 2013.7.12\n * @version 1.0\n */\npublic class INVVal", "end": 245, "score": 0.9962563514709473, "start": 239, "tag": "USERNAME", "value": "zhangh" } ]
null
[]
package jdo.inv; import com.dongyang.jdo.TJDOTool; import com.dongyang.data.TParm; /** * <p>Title: 近效期及库存量提示</p> * * <p>Description: 近效期及库存量提示</p> * * <p>Copyright: Copyright (c) 2008</p> * * <p>Company: JavaHis</p> * * @author zhangh 2013.7.12 * @version 1.0 */ public class INVValidAndQtyWarnTool extends TJDOTool { /** * 实例 */ public static INVValidAndQtyWarnTool instanceObject; /** * 得到实例 * * @return IndValidAndQtyWarnTool */ public static INVValidAndQtyWarnTool getInstance() { if (instanceObject == null) instanceObject = new INVValidAndQtyWarnTool(); return instanceObject; } /** * 构造器 */ public INVValidAndQtyWarnTool() { setModuleName("inv\\INVValidAndQtyWarnModule.x"); onInit(); } /** * 近效期查询 * * @param parm * @return */ public TParm onQueryValid(TParm parm) { TParm result = this.query("queryValid", parm); if (result.getErrCode() < 0) { err("ERR:" + result.getErrCode() + result.getErrText() + result.getErrName()); return result; } return result; } /** * 库存量查询 * * @param parm * @return */ public TParm onQueryQty(TParm parm) { TParm result = this.query("queryQty", parm); if (result.getErrCode() < 0) { err("ERR:" + result.getErrCode() + result.getErrText() + result.getErrName()); return result; } return result; } }
1,666
0.545226
0.535804
75
20.226667
18.221287
66
false
false
0
0
0
0
0
0
0.24
false
false
9
3fc4aff6f96ed3733e3b416e612935c5c4f425ed
13,838,384,630,201
22c2eead68ef6f93c137256e78e0defb7b8d79f1
/src/main/java/sparkstarter/SparkStarterApp.java
a2320bbc878e39213ed3447d353e936901dd131b
[]
no_license
nicolasdasriaux/spark-starter-java
https://github.com/nicolasdasriaux/spark-starter-java
79efad1bf015d21878886f05765087ceacb19822
6aa185203187ec1dea9acb1fc990e3f67bacc685
refs/heads/master
2020-07-14T21:41:27.029000
2019-08-30T15:43:14
2019-08-30T15:43:14
205,409,220
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package sparkstarter; import org.apache.spark.sql.SparkSession; public class SparkStarterApp { public static void main(final String[] args) { final SparkSession spark = SparkSession.builder() .appName("Spark Starter") .master("local[*]") .enableHiveSupport() .getOrCreate(); final SparkStarterJob job = new SparkStarterJob(spark); System.out.println(job.sum()); spark.close(); } }
UTF-8
Java
488
java
SparkStarterApp.java
Java
[]
null
[]
package sparkstarter; import org.apache.spark.sql.SparkSession; public class SparkStarterApp { public static void main(final String[] args) { final SparkSession spark = SparkSession.builder() .appName("Spark Starter") .master("local[*]") .enableHiveSupport() .getOrCreate(); final SparkStarterJob job = new SparkStarterJob(spark); System.out.println(job.sum()); spark.close(); } }
488
0.598361
0.598361
17
27.705883
20.01107
63
false
false
0
0
0
0
0
0
0.352941
false
false
9
50e1e212980eb9a48eb0380b01d528bfa7c2ac87
15,650,860,829,554
6714e565423ba2e3af6353b6f5a18f278021aaa9
/LeMobileSafe/src/main/java/com/le/safe/activity/SetUpBaseActivity.java
2af9fb98549ca4a6cf25eef9ef27d9b5b2dea8d9
[]
no_license
Saturnkk/MobileBodyguard
https://github.com/Saturnkk/MobileBodyguard
35991cf361705bd6ebfc31eb74c23136bed2477e
6f9cf4e941a247fb62201e25139236da1deafb31
refs/heads/master
2021-01-12T11:44:25.974000
2017-03-11T13:18:26
2017-03-11T13:18:26
72,287,505
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.le.safe.activity; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Toast; import com.example.dell.myapplication.R; import com.le.safe.utils.StatusBarCompat; public abstract class SetUpBaseActivity extends AppCompatActivity { private GestureDetector gestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { //手势识别器 //要想手势识别器生效,必须将手势识别器注册到界面的触摸事件中 gestureDetector = new GestureDetector(this, new MyOnGestureListener()); super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE);//隐藏标题 //设置沉浸式状态栏 StatusBarCompat.compat(this, Color.parseColor("#429ED6")); } //界面的触摸事件 //MotionEvent : 界面触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { gestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } private class MyOnGestureListener extends SimpleOnGestureListener{ //滑动的监听事件,左右,滚动:上下 //e1 : 按下的事件,保存有按下的坐标 //e2 : 抬起的事件,保存有抬起的坐标 //velocity : 速度 滑动的速率 @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { //1.获取按下和抬起事件的坐标,强转成int类型,方便计算 int downX = (int) e1.getRawX(); int upX = (int) e2.getRawX(); //获取按下和抬起的y的坐标 int downY = (int) e1.getRawY(); int upY = (int) e2.getRawY(); //屏蔽侧滑 if ((Math.abs(downY-upY)) > 50) { //屏蔽侧滑 Toast.makeText(getApplicationContext(), "你小子又乱滑了....", Toast.LENGTH_SHORT).show(); return true; } //上一步 if ((upX-downX)>100) { dopre(); } //下一步操作 if ((downX - upX) > 100) { donext(); } //true if the event is consumed, else false //返回true:事件执行,返回false:事件拦截不执行 return false; } } // 1.抽取上一步和下一步的按钮的点击事件到父类 // 但是,父类不知道子类应该跳转到那个activity // 父类创建两个抽象方法,子类根据自己的特性去实现抽象方法,来实现自己的需求 /** * 下一步按钮的点击事件 * * @param v */ public void next(View v) { donext(); } /** * 上一步 按钮点击事件 * * @param v */ public void pre(View v) { dopre(); } // 2.因为父类不知道类具体的跳转执行操作,所以创建抽象方法,具体的操作,还是有子类完成 /** * 下一步的具体操作方法 * true:屏蔽跳转操作,false:执行跳转操作 */ public abstract boolean next_activity(); /** * 上一步的具体操作 * true:屏蔽跳转操作,false:执行跳转操作 */ public abstract boolean pre_activity(); /** * 下一步操作 */ private void donext() { if (next_activity()) { return; } finish(); // 执行界面切换动画 // enterAnim : 新的界面进入的动画 // exitAnim : 旧的界面退出的动画 overridePendingTransition(R.anim.setup_next_enter, R.anim.setup_next_exit); } /** * 上一步操作 */ private void dopre() { //如果返回true,表示是屏蔽跳转操作,不会执行移出界面和界面切换动画操作 if (pre_activity()) { return; } finish(); overridePendingTransition(R.anim.setup_pre_enter, R.anim.setup_pre_exit); } /** * 是对物理按钮的点击事件的监听 keyCode : 执行事件的按钮的标示 KeyEvent : 事件 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { dopre(); } return super.onKeyDown(keyCode, event); } }
UTF-8
Java
4,108
java
SetUpBaseActivity.java
Java
[]
null
[]
package com.le.safe.activity; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.Toast; import com.example.dell.myapplication.R; import com.le.safe.utils.StatusBarCompat; public abstract class SetUpBaseActivity extends AppCompatActivity { private GestureDetector gestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { //手势识别器 //要想手势识别器生效,必须将手势识别器注册到界面的触摸事件中 gestureDetector = new GestureDetector(this, new MyOnGestureListener()); super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_NO_TITLE);//隐藏标题 //设置沉浸式状态栏 StatusBarCompat.compat(this, Color.parseColor("#429ED6")); } //界面的触摸事件 //MotionEvent : 界面触摸事件 @Override public boolean onTouchEvent(MotionEvent event) { gestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } private class MyOnGestureListener extends SimpleOnGestureListener{ //滑动的监听事件,左右,滚动:上下 //e1 : 按下的事件,保存有按下的坐标 //e2 : 抬起的事件,保存有抬起的坐标 //velocity : 速度 滑动的速率 @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { //1.获取按下和抬起事件的坐标,强转成int类型,方便计算 int downX = (int) e1.getRawX(); int upX = (int) e2.getRawX(); //获取按下和抬起的y的坐标 int downY = (int) e1.getRawY(); int upY = (int) e2.getRawY(); //屏蔽侧滑 if ((Math.abs(downY-upY)) > 50) { //屏蔽侧滑 Toast.makeText(getApplicationContext(), "你小子又乱滑了....", Toast.LENGTH_SHORT).show(); return true; } //上一步 if ((upX-downX)>100) { dopre(); } //下一步操作 if ((downX - upX) > 100) { donext(); } //true if the event is consumed, else false //返回true:事件执行,返回false:事件拦截不执行 return false; } } // 1.抽取上一步和下一步的按钮的点击事件到父类 // 但是,父类不知道子类应该跳转到那个activity // 父类创建两个抽象方法,子类根据自己的特性去实现抽象方法,来实现自己的需求 /** * 下一步按钮的点击事件 * * @param v */ public void next(View v) { donext(); } /** * 上一步 按钮点击事件 * * @param v */ public void pre(View v) { dopre(); } // 2.因为父类不知道类具体的跳转执行操作,所以创建抽象方法,具体的操作,还是有子类完成 /** * 下一步的具体操作方法 * true:屏蔽跳转操作,false:执行跳转操作 */ public abstract boolean next_activity(); /** * 上一步的具体操作 * true:屏蔽跳转操作,false:执行跳转操作 */ public abstract boolean pre_activity(); /** * 下一步操作 */ private void donext() { if (next_activity()) { return; } finish(); // 执行界面切换动画 // enterAnim : 新的界面进入的动画 // exitAnim : 旧的界面退出的动画 overridePendingTransition(R.anim.setup_next_enter, R.anim.setup_next_exit); } /** * 上一步操作 */ private void dopre() { //如果返回true,表示是屏蔽跳转操作,不会执行移出界面和界面切换动画操作 if (pre_activity()) { return; } finish(); overridePendingTransition(R.anim.setup_pre_enter, R.anim.setup_pre_exit); } /** * 是对物理按钮的点击事件的监听 keyCode : 执行事件的按钮的标示 KeyEvent : 事件 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { dopre(); } return super.onKeyDown(keyCode, event); } }
4,108
0.685938
0.678437
158
19.253164
19.281702
86
false
false
0
0
0
0
0
0
1.797468
false
false
9
fbd441f1d2af30c33a0ac3e10e8544ab940dfdc9
5,703,716,574,205
73a27b1f26abe250b67b5f16692c457037dc1f87
/Iteration 3/Course Project/ProfileScreen.java
59e11095708de59f29b55987493c4ce83bdbf389
[]
no_license
leevanrell/COMP-3700-Course-Project
https://github.com/leevanrell/COMP-3700-Course-Project
7c3b2ed054c1a6635037ba696d840c7029562083
d7a97d4f57a10e54a9c330e7a79d7180bb1459fa
refs/heads/master
2021-08-30T09:01:07.455000
2017-12-17T05:04:49
2017-12-17T05:04:49
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import javax.swing.*; import java.awt.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; public class ProfileScreen extends JFrame { private JButton btnPicture = new JButton("Edit Picture"); private JButton btnPassword = new JButton("Edit Password"); private User user; public ProfileScreen() { this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); this.setSize(500, 400); JLabel title = new JLabel("Store Management System"); title.setFont(new Font("Sans Serif", Font.BOLD, 24)); JPanel panelTitle = new JPanel(); panelTitle.add(title); this.getContentPane().add(panelTitle); btnPicture.setPreferredSize(new Dimension(150, 50)); btnPassword.setPreferredSize(new Dimension(150, 50)); JPanel panelButton = new JPanel(); panelButton.add(btnPicture); panelButton.add(btnPassword); this.getContentPane().add(panelButton); btnPassword.addActionListener( new ActionListener() { // when controller is simple, we can declare it on the fly public void actionPerformed(ActionEvent e) { Application.getInstance().getPasswordScreen().setVisible(true); } }); btnPicture.addActionListener( new ActionListener() { // when controller is simple, we can declare it on the fly public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); File selectedfile = chooser.getSelectedFile(); String filePath = selectedfile.getAbsolutePath(); File source = new File(filePath); File dest = new File(System.getProperty("user.dir") + "/image/" + user.getName() + ".png"); try { //Files.copy(filePath,dest.toPath(),REPLACE_EXISTING); FileInputStream inStream = new FileInputStream(source); FileOutputStream outStream = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } if (inStream != null)inStream.close(); if (outStream != null)outStream.close(); System.out.println("File Copied.."); Application.getInstance().UpdateImage(user); } catch (IOException ex) { System.out.println(ex); } } else { JOptionPane.showMessageDialog(null, "File Failed to Load"); } } }); } private JLabel img_label = new JLabel(); public void setImage(User user) { String file_name = "image/" + user.getName() + ".png"; File tmpDir = new File(file_name); if(!tmpDir.exists()) { file_name = "image/default.png"; } ImageIcon image = new ImageIcon(file_name); img_label.setIcon(image); //img_panel.add(img_label, BorderLayout.CENTER); this.add(img_label); } //TODO MAKE THIS SHIT WORK public void UpdateImage(User user) { String file_name = "image/" + user.getName() + ".png"; ImageIcon image = new ImageIcon(file_name); img_label.setIcon(image); //this.getContentPane().remove(img_label); this.getContentPane().repaint(); img_label.repaint(); //img_label.setIcon(image); } public User getUser() { return user; } public void setUser(User user_in) { user = user_in; } }
UTF-8
Java
4,434
java
ProfileScreen.java
Java
[]
null
[]
import javax.swing.*; import java.awt.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; public class ProfileScreen extends JFrame { private JButton btnPicture = new JButton("Edit Picture"); private JButton btnPassword = new JButton("Edit Password"); private User user; public ProfileScreen() { this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS)); this.setSize(500, 400); JLabel title = new JLabel("Store Management System"); title.setFont(new Font("Sans Serif", Font.BOLD, 24)); JPanel panelTitle = new JPanel(); panelTitle.add(title); this.getContentPane().add(panelTitle); btnPicture.setPreferredSize(new Dimension(150, 50)); btnPassword.setPreferredSize(new Dimension(150, 50)); JPanel panelButton = new JPanel(); panelButton.add(btnPicture); panelButton.add(btnPassword); this.getContentPane().add(panelButton); btnPassword.addActionListener( new ActionListener() { // when controller is simple, we can declare it on the fly public void actionPerformed(ActionEvent e) { Application.getInstance().getPasswordScreen().setVisible(true); } }); btnPicture.addActionListener( new ActionListener() { // when controller is simple, we can declare it on the fly public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png"); chooser.setFileFilter(filter); int returnVal = chooser.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); File selectedfile = chooser.getSelectedFile(); String filePath = selectedfile.getAbsolutePath(); File source = new File(filePath); File dest = new File(System.getProperty("user.dir") + "/image/" + user.getName() + ".png"); try { //Files.copy(filePath,dest.toPath(),REPLACE_EXISTING); FileInputStream inStream = new FileInputStream(source); FileOutputStream outStream = new FileOutputStream(dest); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } if (inStream != null)inStream.close(); if (outStream != null)outStream.close(); System.out.println("File Copied.."); Application.getInstance().UpdateImage(user); } catch (IOException ex) { System.out.println(ex); } } else { JOptionPane.showMessageDialog(null, "File Failed to Load"); } } }); } private JLabel img_label = new JLabel(); public void setImage(User user) { String file_name = "image/" + user.getName() + ".png"; File tmpDir = new File(file_name); if(!tmpDir.exists()) { file_name = "image/default.png"; } ImageIcon image = new ImageIcon(file_name); img_label.setIcon(image); //img_panel.add(img_label, BorderLayout.CENTER); this.add(img_label); } //TODO MAKE THIS SHIT WORK public void UpdateImage(User user) { String file_name = "image/" + user.getName() + ".png"; ImageIcon image = new ImageIcon(file_name); img_label.setIcon(image); //this.getContentPane().remove(img_label); this.getContentPane().repaint(); img_label.repaint(); //img_label.setIcon(image); } public User getUser() { return user; } public void setUser(User user_in) { user = user_in; } }
4,434
0.568787
0.563374
116
37.232758
24.696907
109
false
false
0
0
0
0
0
0
0.706897
false
false
9
8b6d2dae88b2120c62e85d7080e94286b8f43e2c
7,430,293,424,697
2c36ec02cb8878d0d5f6e481e5acef4e07056b0d
/proxy/src/main/java/com/zhang/proxy/pass/TestInteger.java
56fbeb304859575e15c6eb51d8204cc3b45624a1
[]
no_license
zypk123/learning-database
https://github.com/zypk123/learning-database
4238182e1ca12b332e9904bf5e4a852503e6f723
b5e69abc8c21e6cfb116f850afdf7fd5da3b58cb
refs/heads/master
2020-04-05T20:41:36.611000
2018-12-26T09:33:26
2018-12-26T09:33:26
157,191,816
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhang.proxy.pass; import java.util.concurrent.TimeUnit; /** * 包装类的传递问题 * * @author zhangyu * @create 2018-12-26 16:55 **/ public class TestInteger { public static void main(String[] args) throws InterruptedException { Integer index = 0; TestObject runable = new TestObject(index); synchronized (index) { new Thread(runable).start(); index.wait(); } System.out.println("end"); /** * * 多线程锁中,synchronized后面必须是同一个对象才可以解锁成功 * 以上代码 证实了,Integer中传入的是同一个对象 * 即,包装类传递的也是引用,但是由于包装类以及String中,value是没有setter的,是用final修饰的,所以无法改变值,不要错以为传递的是值 * * */ } static class TestObject implements Runnable { private Integer index; public TestObject(Integer index) { this.index = index; } @Override public void run() { try { // sleep个5秒 TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (index) { // 唤醒 index.notify(); } } } }
UTF-8
Java
1,440
java
TestInteger.java
Java
[ { "context": "oncurrent.TimeUnit;\n\n/**\n * 包装类的传递问题\n *\n * @author zhangyu\n * @create 2018-12-26 16:55\n **/\npublic class Tes", "end": 107, "score": 0.9558649063110352, "start": 100, "tag": "USERNAME", "value": "zhangyu" } ]
null
[]
package com.zhang.proxy.pass; import java.util.concurrent.TimeUnit; /** * 包装类的传递问题 * * @author zhangyu * @create 2018-12-26 16:55 **/ public class TestInteger { public static void main(String[] args) throws InterruptedException { Integer index = 0; TestObject runable = new TestObject(index); synchronized (index) { new Thread(runable).start(); index.wait(); } System.out.println("end"); /** * * 多线程锁中,synchronized后面必须是同一个对象才可以解锁成功 * 以上代码 证实了,Integer中传入的是同一个对象 * 即,包装类传递的也是引用,但是由于包装类以及String中,value是没有setter的,是用final修饰的,所以无法改变值,不要错以为传递的是值 * * */ } static class TestObject implements Runnable { private Integer index; public TestObject(Integer index) { this.index = index; } @Override public void run() { try { // sleep个5秒 TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (index) { // 唤醒 index.notify(); } } } }
1,440
0.520358
0.508143
58
20.172413
19.064444
86
false
false
0
0
0
0
0
0
0.206897
false
false
9
badb78ea0643b7980f7448ce3b848b34888b50a0
27,101,243,650,538
f2f0e4da2579db91745ad651a910081891625745
/app/src/main/java/com/Schedo/db/Task.java
b7ae57c9c040f0cf68b6a9a999b589159181ee4a
[]
no_license
rizkyajitomip10/Schedo-kelompok-8
https://github.com/rizkyajitomip10/Schedo-kelompok-8
292e367f681a9ee9ce68794514d0d9c941ba0dd4
589582aec3090b8000c291b872203990994016f5
refs/heads/main
2023-09-02T06:54:44.983000
2021-11-14T14:36:02
2021-11-14T14:36:02
427,942,044
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.Schedo.db; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = AppDb.TABLE) public class Task { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "task_id") private int task_id; @ColumnInfo(name = "title") private String title; @ColumnInfo(name = "description") private String description; @ColumnInfo(name = "due_date") private String due_date; @ColumnInfo(name = "status") private boolean status; public int getTask_id() { return task_id; } public void setTask_id(int task_id) { this.task_id = task_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDue_date() { return due_date; } public void setDue_date(String due_date) { this.due_date = due_date; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
UTF-8
Java
1,271
java
Task.java
Java
[]
null
[]
package com.Schedo.db; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; @Entity(tableName = AppDb.TABLE) public class Task { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "task_id") private int task_id; @ColumnInfo(name = "title") private String title; @ColumnInfo(name = "description") private String description; @ColumnInfo(name = "due_date") private String due_date; @ColumnInfo(name = "status") private boolean status; public int getTask_id() { return task_id; } public void setTask_id(int task_id) { this.task_id = task_id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDue_date() { return due_date; } public void setDue_date(String due_date) { this.due_date = due_date; } public boolean isStatus() { return status; } public void setStatus(boolean status) { this.status = status; } }
1,271
0.623131
0.623131
60
20.183332
15.284514
52
false
false
0
0
0
0
0
0
0.316667
false
false
9
5bfe1bf672d4d6dcbb9ed7ef932c18a77f8c7109
3,324,304,745,491
2d6933c53426000ed3c072f97e61d858458c6bdb
/src/main/java/problems/q81/Solution.java
b2b07b9c3be15394b10d4882674f261df3efc073
[]
no_license
chaibin0/leetCode-Java
https://github.com/chaibin0/leetCode-Java
2d8644762770e8911af96a6c31e1763c6feba9d3
ae1feba5c10a211ba577c4cb065458da713a6067
refs/heads/master
2022-03-12T21:36:48.554000
2022-03-08T11:00:11
2022-03-08T11:00:11
241,042,858
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package problems.q81; class Solution { public boolean search(int[] nums, int target) { return search(0, nums.length - 1, nums, target); } public boolean search(int low, int high, int[] nums, int target) { if (low < 0 || low >= nums.length || high < 0 || high >= nums.length) { return false; } if (low >= high) { return nums[low] == target; } int mid = (low + high) / 2; if (nums[mid] == target) { return true; } if (mid - 1 >= 0 && nums[low] >= nums[mid - 1] && search(low, mid - 1, nums, target)) { return true; } if (mid + 1 <= nums.length && nums[mid + 1] >= nums[high] && search(mid + 1, high, nums, target)) { return true; } if (mid - 1 >= 0 && target >= nums[low] && target <= nums[mid - 1] && binarySearch(low, mid - 1, nums, target)) { return true; } if (mid + 1 <= nums.length && target >= nums[mid + 1] && target <= nums[high] && binarySearch(mid + 1, high, nums, target)) { return true; } return false; } private boolean binarySearch(int low, int high, int[] nums, int target) { int mid; while (low <= high) { mid = (low + high) / 2; if (nums[mid] == target) { return true; } if (target > nums[mid]) { low = mid + 1; } else { high = mid - 1; } } return false; } }
UTF-8
Java
1,586
java
Solution.java
Java
[]
null
[]
package problems.q81; class Solution { public boolean search(int[] nums, int target) { return search(0, nums.length - 1, nums, target); } public boolean search(int low, int high, int[] nums, int target) { if (low < 0 || low >= nums.length || high < 0 || high >= nums.length) { return false; } if (low >= high) { return nums[low] == target; } int mid = (low + high) / 2; if (nums[mid] == target) { return true; } if (mid - 1 >= 0 && nums[low] >= nums[mid - 1] && search(low, mid - 1, nums, target)) { return true; } if (mid + 1 <= nums.length && nums[mid + 1] >= nums[high] && search(mid + 1, high, nums, target)) { return true; } if (mid - 1 >= 0 && target >= nums[low] && target <= nums[mid - 1] && binarySearch(low, mid - 1, nums, target)) { return true; } if (mid + 1 <= nums.length && target >= nums[mid + 1] && target <= nums[high] && binarySearch(mid + 1, high, nums, target)) { return true; } return false; } private boolean binarySearch(int low, int high, int[] nums, int target) { int mid; while (low <= high) { mid = (low + high) / 2; if (nums[mid] == target) { return true; } if (target > nums[mid]) { low = mid + 1; } else { high = mid - 1; } } return false; } }
1,586
0.445776
0.430643
62
24.596775
30.322174
133
false
false
0
0
0
0
0
0
0.725806
false
false
9
1fa369f91dd190f7af060d84a2a5048c8e5dbdf8
21,921,513,084,113
8b2bee920bee63d783bb5c450b0981a79bb51aa2
/src/main/java/com/okiimport/app/service/seguridad/SHistorial.java
247bbfa70212bd20cf6f83ad8feaf67cb7ea3937
[]
no_license
ubicapartes/ubicapartes-back
https://github.com/ubicapartes/ubicapartes-back
80dbbf94ee5e8c77468a25fd1c898e43b095c0fb
aafa00a3497430c4b595ea951064322e30451d7d
refs/heads/master
2021-06-14T15:43:22.193000
2016-10-07T02:53:26
2016-10-07T02:53:26
66,521,013
0
1
null
false
2017-02-26T19:31:56
2016-08-25T03:24:14
2016-10-04T01:23:52
2017-02-26T19:31:56
170
0
1
0
Java
null
null
package com.okiimport.app.service.seguridad; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.okiimport.app.model.HistoryLogin; import com.okiimport.app.model.Usuario; @Service @Transactional public interface SHistorial { //Historial de Session HistoryLogin historicoSessionNoTerminada(String username); @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) void registrarHistorialSession(Usuario usuario); void cerarHistorialSession(Usuario usuario); }
UTF-8
Java
627
java
SHistorial.java
Java
[]
null
[]
package com.okiimport.app.service.seguridad; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.okiimport.app.model.HistoryLogin; import com.okiimport.app.model.Usuario; @Service @Transactional public interface SHistorial { //Historial de Session HistoryLogin historicoSessionNoTerminada(String username); @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) void registrarHistorialSession(Usuario usuario); void cerarHistorialSession(Usuario usuario); }
627
0.845295
0.845295
20
30.35
25.150099
78
false
false
0
0
0
0
0
0
0.85
false
false
9
343bd6c4282029c2d10320e954b6e613a83b6d3c
27,960,237,102,661
d2c5953f71980be1e451ce038b0cea4176638bf9
/src/myMath/MonomTest.java
a9de67f0616279a3aa4a6e3360ddd8cfdae824a4
[]
no_license
israelBuskila/myMath
https://github.com/israelBuskila/myMath
5e69ba520a80511a5eec1b788831a8e9a45b2e78
0716f0df38888e6ce6dc204d6f2f4c866b08e63a
refs/heads/master
2021-06-23T18:27:16.326000
2020-11-16T11:20:19
2020-11-16T11:20:19
156,751,734
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package myMath; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class MonomTest { @Test void constructortest() { double coe = 2; int pow = 1; assertNotNull(pow); assertNotNull(pow); if(coe == 0) fail("coe shouldnt be zero"); if(pow < 0) fail("power is smaller then 0"); Monom m = new Monom(coe,pow); assertEquals(coe, 2.0); assertEquals(pow, 1); } @Test void StringConsTest() { Monom m1 = new Monom("3x^2"); Monom ans = new Monom(3,2); assertEquals(ans.get_coefficient(), m1.get_coefficient()); assertEquals(ans.get_power(), m1.get_power()); } @Test void FXTest () { Monom m1 = new Monom(3,1); double m1f = m1.f(5); double ans = 15; assertEquals(ans, m1f); } @Test void AddTest() { Monom m1 = new Monom(2,5); Monom m2 = new Monom(4,5); Monom m3 = new Monom(6,5); m1.add(m2); assertEquals(m3.get_coefficient(), m1.get_coefficient()); assertEquals(m3.get_power(), m1.get_power()); } @Test void MultTest() { Monom m1 = new Monom(3,4); Monom m2 = new Monom(4,1); Monom ans = new Monom(12,5); Monom expected = m1.multiply(m2); assertEquals(ans.get_coefficient(), expected.get_coefficient()); assertEquals(ans.get_power(), expected.get_power()); } @Test void derivativeTest() { Monom m1 = new Monom(3,4); m1.derivative(); Monom ans = new Monom(12,3); assertEquals(ans.get_coefficient(), m1.get_coefficient()); assertEquals(ans.get_power(), m1.get_power()); } @Test void toStringTest() { Monom m1 = new Monom(3,4); String str = m1.toString(); String ans = "3.0*x^4"; if (!str.equals(ans)) { fail("the ToString of this monom is WRONG!"); } } }
UTF-8
Java
1,691
java
MonomTest.java
Java
[]
null
[]
package myMath; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class MonomTest { @Test void constructortest() { double coe = 2; int pow = 1; assertNotNull(pow); assertNotNull(pow); if(coe == 0) fail("coe shouldnt be zero"); if(pow < 0) fail("power is smaller then 0"); Monom m = new Monom(coe,pow); assertEquals(coe, 2.0); assertEquals(pow, 1); } @Test void StringConsTest() { Monom m1 = new Monom("3x^2"); Monom ans = new Monom(3,2); assertEquals(ans.get_coefficient(), m1.get_coefficient()); assertEquals(ans.get_power(), m1.get_power()); } @Test void FXTest () { Monom m1 = new Monom(3,1); double m1f = m1.f(5); double ans = 15; assertEquals(ans, m1f); } @Test void AddTest() { Monom m1 = new Monom(2,5); Monom m2 = new Monom(4,5); Monom m3 = new Monom(6,5); m1.add(m2); assertEquals(m3.get_coefficient(), m1.get_coefficient()); assertEquals(m3.get_power(), m1.get_power()); } @Test void MultTest() { Monom m1 = new Monom(3,4); Monom m2 = new Monom(4,1); Monom ans = new Monom(12,5); Monom expected = m1.multiply(m2); assertEquals(ans.get_coefficient(), expected.get_coefficient()); assertEquals(ans.get_power(), expected.get_power()); } @Test void derivativeTest() { Monom m1 = new Monom(3,4); m1.derivative(); Monom ans = new Monom(12,3); assertEquals(ans.get_coefficient(), m1.get_coefficient()); assertEquals(ans.get_power(), m1.get_power()); } @Test void toStringTest() { Monom m1 = new Monom(3,4); String str = m1.toString(); String ans = "3.0*x^4"; if (!str.equals(ans)) { fail("the ToString of this monom is WRONG!"); } } }
1,691
0.639858
0.600828
76
21.25
17.40699
66
false
false
0
0
0
0
0
0
2.25
false
false
9
64208cf99c6c27154f43a74bac1bd48f17f39839
1,176,821,050,397
8f23129c6ab49f725dcd51f0858db86f4d52d336
/anxinpha-item/anxinpha-item-service/src/main/java/com/anxinpha/item/mapper/ExpressMapper.java
9f408e8a226aff9164e60820c63a7797fedd047b
[]
no_license
wuxiemian/anxinpha
https://github.com/wuxiemian/anxinpha
1a071d3d39c4e1975cc4b890be6ab89f70a8e0de
614ee49ace981402169b373148d8bc01c71ce196
refs/heads/master
2022-09-05T11:51:32.477000
2020-06-02T06:40:11
2020-06-02T06:40:11
267,289,322
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.anxinpha.item.mapper; import com.anxinpha.item.pojo.Express; import tk.mybatis.mapper.common.Mapper; /** * @author 尹硕硕 * @description **/ public interface ExpressMapper extends Mapper<Express> { }
UTF-8
Java
220
java
ExpressMapper.java
Java
[ { "context": " tk.mybatis.mapper.common.Mapper;\n\n/**\n * @author 尹硕硕\n * @description\n **/\npublic interface ExpressMapp", "end": 133, "score": 0.999810516834259, "start": 130, "tag": "NAME", "value": "尹硕硕" } ]
null
[]
package com.anxinpha.item.mapper; import com.anxinpha.item.pojo.Express; import tk.mybatis.mapper.common.Mapper; /** * @author 尹硕硕 * @description **/ public interface ExpressMapper extends Mapper<Express> { }
220
0.752336
0.752336
11
18.454546
18.80698
56
false
false
0
0
0
0
0
0
0.272727
false
false
9
70201f58760989e6975f47575dbf5b0039c287ab
14,096,082,677,051
d5974ff20b697ad1da3d8e7ba5db1bd704d6046c
/Bit-mask/IncredibleHulk.java
7ed321deb073fa1179b20e29f8575fe582c70493
[]
no_license
satyap54/Data_Structures
https://github.com/satyap54/Data_Structures
beb095500a74abeaeaa8ac5928f227f4c5338490
ac0b3ac5825a9562889d5e428a4bd0a16d3f51a7
refs/heads/Only-.java
2022-12-19T21:04:41.167000
2020-09-30T18:45:08
2020-09-30T18:45:08
203,433,213
3
1
null
false
2020-09-30T18:45:09
2019-08-20T18:34:46
2020-09-29T16:49:35
2020-09-30T18:45:09
139
8
3
0
Java
false
false
import java.util.*; //The problem set is : You are given Hulk and your enemy is at some level x. You've to reach there by using jumps which are //in the powers of 2. What will be the min. no. of jumps required ? //To solve it , use bit-masking . No. of set bits in binary representation of x gives the answer . Eg. 13 = 1101 , 3 is the ans. class IncredibleHulk { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int level=sc.nextInt(); String s=Integer.toBinaryString(level); int count=0; for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(c=='1') count++; } System.out.println(count); } }
UTF-8
Java
652
java
IncredibleHulk.java
Java
[]
null
[]
import java.util.*; //The problem set is : You are given Hulk and your enemy is at some level x. You've to reach there by using jumps which are //in the powers of 2. What will be the min. no. of jumps required ? //To solve it , use bit-masking . No. of set bits in binary representation of x gives the answer . Eg. 13 = 1101 , 3 is the ans. class IncredibleHulk { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int level=sc.nextInt(); String s=Integer.toBinaryString(level); int count=0; for(int i=0;i<s.length();i++) { char c=s.charAt(i); if(c=='1') count++; } System.out.println(count); } }
652
0.671779
0.654908
21
30.095238
35.301296
128
false
false
0
0
0
0
0
0
1.904762
false
false
9
7b1f414587c0621168ce3617b06bf009a56e5972
26,688,926,789,198
b0d0d0b5cbed0a24d5f41d951089b2f03951a125
/HibernateExample/src/main/java/com/test/App.java
764768b43cecc9d502e14068c25d2ff141267cbd
[]
no_license
sanjar/Day_Today
https://github.com/sanjar/Day_Today
afb84a1016e0122001b790d9a152934c6b358dfc
a8b9f63b3f26231f42953088fce068d4ad39ded0
refs/heads/master
2020-12-24T19:27:06.668000
2017-10-18T17:52:29
2017-10-18T17:52:29
23,060,527
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.test; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import com.test.user.DBUser; import com.test.util.HibernateUtil; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.Marshaller; public class App { public static void main(String[] args) throws JAXBException { //System.out.println("Maven + Hibernate Annotation + Oracle"); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); /*DBUser user = new DBUser(); user.setUserId(101); user.setUsername("Hibernate102"); user.setCreatedBy("system"); user.setCreatedDate(new Date()); session.save(user); session.getTransaction().commit();*/ Criteria criteria = session.createCriteria(DBUser.class); List<DBUser> users = criteria.list(); JAXBContext jaxbContext = JAXBContext.newInstance(DBUser.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); for(DBUser u : users){ System.out.println(u.getUserId()); jaxbMarshaller.marshal(u, System.out); } } }
UTF-8
Java
1,311
java
App.java
Java
[ { "context": "er();\n\n\t\tuser.setUserId(101);\n\t\tuser.setUsername(\"Hibernate102\");\n\t\tuser.setCreatedBy(\"system\");\n\t\tuser.setCreat", "end": 673, "score": 0.9994307160377502, "start": 661, "tag": "USERNAME", "value": "Hibernate102" } ]
null
[]
package com.test; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import com.test.user.DBUser; import com.test.util.HibernateUtil; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.Marshaller; public class App { public static void main(String[] args) throws JAXBException { //System.out.println("Maven + Hibernate Annotation + Oracle"); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); /*DBUser user = new DBUser(); user.setUserId(101); user.setUsername("Hibernate102"); user.setCreatedBy("system"); user.setCreatedDate(new Date()); session.save(user); session.getTransaction().commit();*/ Criteria criteria = session.createCriteria(DBUser.class); List<DBUser> users = criteria.list(); JAXBContext jaxbContext = JAXBContext.newInstance(DBUser.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); for(DBUser u : users){ System.out.println(u.getUserId()); jaxbMarshaller.marshal(u, System.out); } } }
1,311
0.738368
0.733791
52
24.211538
22.910643
77
false
false
0
0
0
0
0
0
1.826923
false
false
9
5d4774e660afa9fd6bb6369063341eab74ce3438
28,389,733,832,902
596db21e4111ed249178701cdeb46cbbc9ff8feb
/17 Hard/10 Majority Element.java
4e2b95d5d348ca6954ed647c31d316875946863f
[ "MIT" ]
permissive
JayakrishnaThota/CTCI
https://github.com/JayakrishnaThota/CTCI
83981f416915baecf54ec3086ee5e94b87c93654
47b6b4dae99c50e5ef62bb09d1be35b2e121b549
refs/heads/master
2021-09-08T02:12:50.167000
2018-03-05T20:58:35
2018-03-05T20:58:35
111,362,019
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
//O(n) and O(1) class Solution { public int majorityElement(int[] nums) { if(nums==null || nums.length==0) return 0; int maj = nums[0],count=1; for(int i=1;i<nums.length;i++){ if(nums[i]==maj) count++; else{ count--; if(count==0){ maj = nums[i]; count = 1; } } } return validate(nums, maj)?maj:-1; } public boolean validate(int[] nums, int maj){ int count = 0; for(int n:nums){ if(maj==n) count++; } return (count>nums.length/2); } }
UTF-8
Java
667
java
10 Majority Element.java
Java
[]
null
[]
//O(n) and O(1) class Solution { public int majorityElement(int[] nums) { if(nums==null || nums.length==0) return 0; int maj = nums[0],count=1; for(int i=1;i<nums.length;i++){ if(nums[i]==maj) count++; else{ count--; if(count==0){ maj = nums[i]; count = 1; } } } return validate(nums, maj)?maj:-1; } public boolean validate(int[] nums, int maj){ int count = 0; for(int n:nums){ if(maj==n) count++; } return (count>nums.length/2); } }
667
0.410795
0.394303
27
23.703703
13.882616
50
false
false
0
0
0
0
0
0
0.62963
false
false
9
6447bcc152e86a8b943bdc4b0eb608fc6b1af96a
25,512,105,758,861
062c2598c0c39d50ff5fb2055946d33bdef9738f
/src/main/java/aka/jmediainspector/controllers/tabs/AbstractSearchCriteriaController.java
5518e707fda7c8f060518676016c3754cf21d37b
[]
no_license
welle/JMediaInspector
https://github.com/welle/JMediaInspector
6aa1a7fbfe7c00ab3f94a09015e21960df6a53fb
ff3b678e0531368f7674c990de62231913065e2b
refs/heads/master
2021-05-14T19:15:44.366000
2018-02-06T12:55:21
2018-02-06T12:55:21
116,103,406
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package aka.jmediainspector.controllers.tabs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import aka.jmediainspector.JMediaInspector; import aka.jmediainspector.config.Configuration; import aka.jmediainspector.config.Criteria; import aka.jmediainspector.config.Paths; import aka.jmediainspector.config.Search; import aka.jmediainspector.config.helpers.JAXBHelper; import aka.jmediainspector.config.helpers.MetadataSearchConfigurationHelper; import aka.jmediainspector.config.helpers.MetadataSearchConfigurationHelper.Type; import aka.jmediainspector.config.helpers.PlexConfigurationHelper; import aka.jmediainspector.context.ApplicationContext; import aka.jmediainspector.helpers.dialogs.DialogsHelper; import aka.jmediainspector.helpers.search.SearchEventHandler; import aka.jmediainspector.helpers.search.SearchHelper; import aka.jmediainspector.helpers.search.interfaces.AbstractInterface; import aka.jmediainspector.helpers.search.interfaces.SearchInterface; import aka.jmediainspector.helpers.search.types.audio.SearchAudioEnum; import aka.jmediainspector.helpers.search.types.general.SearchGeneralEnum; import aka.jmediainspector.helpers.search.types.text.SearchTextEnum; import aka.jmediainspector.helpers.search.types.video.SearchVideoEnum; import aka.jmediainspector.listeners.ApplicationConfigurationsListener; import javafx.beans.value.ChangeListener; import javafx.concurrent.Service; import javafx.concurrent.Worker.State; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.TextInputDialog; import javafx.scene.effect.BoxBlur; import javafx.scene.effect.Effect; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.stage.Window; /** * Abstract class for SearchCriteria Controllers. * * @author Cha */ public abstract class AbstractSearchCriteriaController extends AnchorPane implements ApplicationConfigurationsListener { private MetadataSearchConfigurationHelper metadataSearchCriteriaHelper; @FXML private AnchorPane leftPane; @FXML private AnchorPane rightPane; @FXML private Menu menuGeneral; @FXML private Menu menuVideo; @FXML private Menu menuAudio; @FXML private Menu menuText; @FXML private Button runButton; /** * SearchHelper. */ protected SearchHelper searchHelper; private PlexConfigurationHelper configurationHelper; @FXML private ListView<Search> existingSearchListView; private Type searchType; /** * Initialize component. * Internal use only. */ @FXML public void initialize() { this.configurationHelper = ApplicationContext.getInstance().getCurrentPlexConfigurationHelper(); // TODO link searchhelper with related search final AnchorPane currentLeftPane = this.leftPane; assert currentLeftPane != null; final AnchorPane currentRightPane = this.rightPane; assert currentRightPane != null; this.searchHelper = new SearchHelper(new Search(), currentLeftPane, currentRightPane); this.metadataSearchCriteriaHelper = ApplicationContext.getInstance().getCurrentMetadataSearchConfigurationHelper(); this.existingSearchListView.setCellFactory(p -> new SearchCellListView(this.existingSearchListView)); initMenuVideo(); initMenuGeneral(); initMenuAudio(); initMenuText(); // this.configurationsList.setButtonCell(new ConfigurationListCell()); // this.configurationsList.setCellFactory(p -> new ConfigurationListCell()); // // refreshConfigurationList(); // setSelectedConfiguration(); } private void initMenuVideo() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchVideoEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuVideo.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuVideo", e.getMessage(), e); } } private void initMenuGeneral() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchGeneralEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuGeneral.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuGeneral", e.getMessage(), e); } } @NonNull private Map<String, AbstractInterface<?>> getSearchItemMenuMap(final @NonNull SearchInterface @NonNull [] searchInterfaceArray) throws InstantiationException, IllegalAccessException { final Map<String, AbstractInterface<?>> map = new HashMap<>(); for (final @NonNull SearchInterface entry : searchInterfaceArray) { final AbstractInterface<?> newInstance = entry.getFiltersInterface().newInstance(); assert newInstance != null; final String fullName = newInstance.getFullName(); map.put(fullName, newInstance); } return map; } private void initMenuAudio() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchAudioEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuAudio.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuAudio", e.getMessage(), e); } } private void initMenuText() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchTextEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuText.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuText", e.getMessage(), e); } } /** * Init existing searches. * * @param type */ void initExistingSearches(@NonNull final Type type) { // FIXME this method and all relevant methods must be in a upper controler so each searchhelper correspond to a search and we just have to set visible true/false on left list view click this.searchType = type; this.existingSearchListView.getItems().clear(); final List<Search> list = this.metadataSearchCriteriaHelper.getSearchByType(type); for (final Search search : list) { this.existingSearchListView.getItems().add(search); } } private final class SearchCellListView extends ListCell<Search> { public SearchCellListView(final ListView<Search> listView) { setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (listView.getItems().size() > 0)) { final Search rowData = listView.getSelectionModel().getSelectedItem(); System.out.println(rowData); } }); } @Override protected void updateItem(final Search item, final boolean empty) { super.updateItem(item, empty); if (item != null) { setText(item.getName()); } } } /** * Get new criteria. * * @return new criteria */ @NonNull public Criteria getNewCriteria() { final Criteria newCriteria = this.metadataSearchCriteriaHelper.getNewCriteria(); assert newCriteria != null; newCriteria.setSelected(true); return newCriteria; } @FXML private void runSearch() { // PUT IN SERVICE, disable run button final List<@NonNull AbstractInterface<?>> filterList = this.searchHelper.getFiltersList(); if (!filterList.isEmpty()) { @Nullable final Configuration selectedConfiguration = this.configurationHelper.getSelectedConfiguration(); if (selectedConfiguration == null) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "No configuration selected!"); alert.showAndWait(); } else { final Paths paths = selectedConfiguration.getPaths(); if (paths == null || paths.getPath().size() == 0) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "No path(s) in the selected configuration!"); alert.showAndWait(); } else { final List<@NonNull String> pathsList = new ArrayList<>(); for (final String path : paths.getPath()) { if (path != null && path.trim().length() > 0) { pathsList.add(path); } } callSearchService(selectedConfiguration, pathsList); } } } } /** * Get search service. * * @param selectedConfiguration current selected configuration * @param pathsList path list directories * @return Service */ @NonNull abstract Service<?> getSearchService(@Nullable Configuration selectedConfiguration, @NonNull final List<@NonNull String> pathsList); private void callSearchService(@Nullable final Configuration selectedConfiguration, @NonNull final List<@NonNull String> pathsList) { final Service<?> service = getSearchService(selectedConfiguration, pathsList); final Stage stage = (Stage) JMediaInspector.getPrimaryStage().getScene().getWindow(); assert stage != null; final Dialog<String> progressDialog = DialogsHelper.createProgressRunSearchServiceDialog(service, stage); final Effect parentEffect = new BoxBlur(); this.runButton.setDisable(true); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(parentEffect); service.stateProperty().addListener((ChangeListener<State>) (observable, oldValue, newValue) -> { if (newValue == State.CANCELLED || newValue == State.FAILED || newValue == State.SUCCEEDED) { final Window window = progressDialog.getDialogPane().getScene().getWindow(); window.hide(); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(null); } }); progressDialog.show(); service.reset(); service.setOnSucceeded(e -> { final Window window = progressDialog.getDialogPane().getScene().getWindow(); window.hide(); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(null); handleSearchResult(service.getValue()); }); this.runButton.setDisable(false); service.start(); } /** * Handle the result. * * @param object result of the service */ abstract void handleSearchResult(Object object); @FXML private void saveSearch() { processSave(false); } @FXML private void saveAsSearch() { processSave(true); } private void processSave(final boolean saveAs) { boolean processSave = true; final Search currentSearch = this.existingSearchListView.getSelectionModel().getSelectedItem(); Search newSearch; if (currentSearch == null) { final TextInputDialog dialog = DialogsHelper.getSaveAsDialog(); final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String searchName = result.get(); newSearch = this.metadataSearchCriteriaHelper.addNewSearch(getSearchType()); newSearch.setName(searchName); this.metadataSearchCriteriaHelper.getSearchByType(getSearchType()).add(newSearch); } else { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "Cancel saving..."); alert.showAndWait(); processSave = false; } } else { if (!saveAs) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.CONFIRMATION, "Override current search ?"); final Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()) { final ButtonType button = result.get(); if (button == ButtonType.CANCEL) { processSave = false; } else { newSearch = JAXBHelper.deepCopyJAXB(currentSearch); } } } } if (processSave) { this.metadataSearchCriteriaHelper.saveConfig(); // refresh table view initExistingSearches(getSearchType()); } } @NonNull private Type getSearchType() { final Type currentType = this.searchType; assert currentType != null; return currentType; } @Override public void onChanges() { // reload file } }
UTF-8
Java
16,163
java
AbstractSearchCriteriaController.java
Java
[ { "context": "ss for SearchCriteria Controllers.\r\n *\r\n * @author Cha\r\n */\r\npublic abstract class AbstractSearchCriteriaC", "end": 2352, "score": 0.9652624726295471, "start": 2349, "tag": "NAME", "value": "Cha" } ]
null
[]
package aka.jmediainspector.controllers.tabs; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.SortedSet; import java.util.TreeSet; import java.util.logging.Level; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import aka.jmediainspector.JMediaInspector; import aka.jmediainspector.config.Configuration; import aka.jmediainspector.config.Criteria; import aka.jmediainspector.config.Paths; import aka.jmediainspector.config.Search; import aka.jmediainspector.config.helpers.JAXBHelper; import aka.jmediainspector.config.helpers.MetadataSearchConfigurationHelper; import aka.jmediainspector.config.helpers.MetadataSearchConfigurationHelper.Type; import aka.jmediainspector.config.helpers.PlexConfigurationHelper; import aka.jmediainspector.context.ApplicationContext; import aka.jmediainspector.helpers.dialogs.DialogsHelper; import aka.jmediainspector.helpers.search.SearchEventHandler; import aka.jmediainspector.helpers.search.SearchHelper; import aka.jmediainspector.helpers.search.interfaces.AbstractInterface; import aka.jmediainspector.helpers.search.interfaces.SearchInterface; import aka.jmediainspector.helpers.search.types.audio.SearchAudioEnum; import aka.jmediainspector.helpers.search.types.general.SearchGeneralEnum; import aka.jmediainspector.helpers.search.types.text.SearchTextEnum; import aka.jmediainspector.helpers.search.types.video.SearchVideoEnum; import aka.jmediainspector.listeners.ApplicationConfigurationsListener; import javafx.beans.value.ChangeListener; import javafx.concurrent.Service; import javafx.concurrent.Worker.State; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuItem; import javafx.scene.control.TextInputDialog; import javafx.scene.effect.BoxBlur; import javafx.scene.effect.Effect; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import javafx.stage.Window; /** * Abstract class for SearchCriteria Controllers. * * @author Cha */ public abstract class AbstractSearchCriteriaController extends AnchorPane implements ApplicationConfigurationsListener { private MetadataSearchConfigurationHelper metadataSearchCriteriaHelper; @FXML private AnchorPane leftPane; @FXML private AnchorPane rightPane; @FXML private Menu menuGeneral; @FXML private Menu menuVideo; @FXML private Menu menuAudio; @FXML private Menu menuText; @FXML private Button runButton; /** * SearchHelper. */ protected SearchHelper searchHelper; private PlexConfigurationHelper configurationHelper; @FXML private ListView<Search> existingSearchListView; private Type searchType; /** * Initialize component. * Internal use only. */ @FXML public void initialize() { this.configurationHelper = ApplicationContext.getInstance().getCurrentPlexConfigurationHelper(); // TODO link searchhelper with related search final AnchorPane currentLeftPane = this.leftPane; assert currentLeftPane != null; final AnchorPane currentRightPane = this.rightPane; assert currentRightPane != null; this.searchHelper = new SearchHelper(new Search(), currentLeftPane, currentRightPane); this.metadataSearchCriteriaHelper = ApplicationContext.getInstance().getCurrentMetadataSearchConfigurationHelper(); this.existingSearchListView.setCellFactory(p -> new SearchCellListView(this.existingSearchListView)); initMenuVideo(); initMenuGeneral(); initMenuAudio(); initMenuText(); // this.configurationsList.setButtonCell(new ConfigurationListCell()); // this.configurationsList.setCellFactory(p -> new ConfigurationListCell()); // // refreshConfigurationList(); // setSelectedConfiguration(); } private void initMenuVideo() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchVideoEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuVideo.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuVideo", e.getMessage(), e); } } private void initMenuGeneral() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchGeneralEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuGeneral.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuGeneral", e.getMessage(), e); } } @NonNull private Map<String, AbstractInterface<?>> getSearchItemMenuMap(final @NonNull SearchInterface @NonNull [] searchInterfaceArray) throws InstantiationException, IllegalAccessException { final Map<String, AbstractInterface<?>> map = new HashMap<>(); for (final @NonNull SearchInterface entry : searchInterfaceArray) { final AbstractInterface<?> newInstance = entry.getFiltersInterface().newInstance(); assert newInstance != null; final String fullName = newInstance.getFullName(); map.put(fullName, newInstance); } return map; } private void initMenuAudio() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchAudioEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuAudio.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuAudio", e.getMessage(), e); } } private void initMenuText() { try { // Sort by items full name final Map<String, AbstractInterface<?>> map = getSearchItemMenuMap(SearchTextEnum.values()); final SortedSet<String> keys = new TreeSet<>(map.keySet()); for (final String key : keys) { final AbstractInterface<?> newInstance = map.get(key); // do something assert newInstance != null; final MenuItem menuItem = new MenuItem(key); menuItem.setOnAction(new SearchEventHandler(this.searchHelper, newInstance, this)); this.menuText.getItems().add(menuItem); } } catch (InstantiationException | IllegalAccessException e) { ApplicationContext.getInstance().getLogger().logp(Level.SEVERE, "AbstractSearchCriteriaController", "initMenuText", e.getMessage(), e); } } /** * Init existing searches. * * @param type */ void initExistingSearches(@NonNull final Type type) { // FIXME this method and all relevant methods must be in a upper controler so each searchhelper correspond to a search and we just have to set visible true/false on left list view click this.searchType = type; this.existingSearchListView.getItems().clear(); final List<Search> list = this.metadataSearchCriteriaHelper.getSearchByType(type); for (final Search search : list) { this.existingSearchListView.getItems().add(search); } } private final class SearchCellListView extends ListCell<Search> { public SearchCellListView(final ListView<Search> listView) { setOnMouseClicked(event -> { if (event.getClickCount() == 2 && (listView.getItems().size() > 0)) { final Search rowData = listView.getSelectionModel().getSelectedItem(); System.out.println(rowData); } }); } @Override protected void updateItem(final Search item, final boolean empty) { super.updateItem(item, empty); if (item != null) { setText(item.getName()); } } } /** * Get new criteria. * * @return new criteria */ @NonNull public Criteria getNewCriteria() { final Criteria newCriteria = this.metadataSearchCriteriaHelper.getNewCriteria(); assert newCriteria != null; newCriteria.setSelected(true); return newCriteria; } @FXML private void runSearch() { // PUT IN SERVICE, disable run button final List<@NonNull AbstractInterface<?>> filterList = this.searchHelper.getFiltersList(); if (!filterList.isEmpty()) { @Nullable final Configuration selectedConfiguration = this.configurationHelper.getSelectedConfiguration(); if (selectedConfiguration == null) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "No configuration selected!"); alert.showAndWait(); } else { final Paths paths = selectedConfiguration.getPaths(); if (paths == null || paths.getPath().size() == 0) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "No path(s) in the selected configuration!"); alert.showAndWait(); } else { final List<@NonNull String> pathsList = new ArrayList<>(); for (final String path : paths.getPath()) { if (path != null && path.trim().length() > 0) { pathsList.add(path); } } callSearchService(selectedConfiguration, pathsList); } } } } /** * Get search service. * * @param selectedConfiguration current selected configuration * @param pathsList path list directories * @return Service */ @NonNull abstract Service<?> getSearchService(@Nullable Configuration selectedConfiguration, @NonNull final List<@NonNull String> pathsList); private void callSearchService(@Nullable final Configuration selectedConfiguration, @NonNull final List<@NonNull String> pathsList) { final Service<?> service = getSearchService(selectedConfiguration, pathsList); final Stage stage = (Stage) JMediaInspector.getPrimaryStage().getScene().getWindow(); assert stage != null; final Dialog<String> progressDialog = DialogsHelper.createProgressRunSearchServiceDialog(service, stage); final Effect parentEffect = new BoxBlur(); this.runButton.setDisable(true); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(parentEffect); service.stateProperty().addListener((ChangeListener<State>) (observable, oldValue, newValue) -> { if (newValue == State.CANCELLED || newValue == State.FAILED || newValue == State.SUCCEEDED) { final Window window = progressDialog.getDialogPane().getScene().getWindow(); window.hide(); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(null); } }); progressDialog.show(); service.reset(); service.setOnSucceeded(e -> { final Window window = progressDialog.getDialogPane().getScene().getWindow(); window.hide(); JMediaInspector.getPrimaryStage().getScene().getRoot().setEffect(null); handleSearchResult(service.getValue()); }); this.runButton.setDisable(false); service.start(); } /** * Handle the result. * * @param object result of the service */ abstract void handleSearchResult(Object object); @FXML private void saveSearch() { processSave(false); } @FXML private void saveAsSearch() { processSave(true); } private void processSave(final boolean saveAs) { boolean processSave = true; final Search currentSearch = this.existingSearchListView.getSelectionModel().getSelectedItem(); Search newSearch; if (currentSearch == null) { final TextInputDialog dialog = DialogsHelper.getSaveAsDialog(); final Optional<String> result = dialog.showAndWait(); if (result.isPresent()) { final String searchName = result.get(); newSearch = this.metadataSearchCriteriaHelper.addNewSearch(getSearchType()); newSearch.setName(searchName); this.metadataSearchCriteriaHelper.getSearchByType(getSearchType()).add(newSearch); } else { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.ERROR, "Cancel saving..."); alert.showAndWait(); processSave = false; } } else { if (!saveAs) { final Alert alert = DialogsHelper.getAlert(JMediaInspector.getPrimaryStage(), Alert.AlertType.CONFIRMATION, "Override current search ?"); final Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent()) { final ButtonType button = result.get(); if (button == ButtonType.CANCEL) { processSave = false; } else { newSearch = JAXBHelper.deepCopyJAXB(currentSearch); } } } } if (processSave) { this.metadataSearchCriteriaHelper.saveConfig(); // refresh table view initExistingSearches(getSearchType()); } } @NonNull private Type getSearchType() { final Type currentType = this.searchType; assert currentType != null; return currentType; } @Override public void onChanges() { // reload file } }
16,163
0.635092
0.634845
386
39.873058
35.454517
193
false
false
0
0
0
0
0
0
0.637306
false
false
9
83596fd2a13ad7c2356918a9796cf8db7e60e02e
2,413,771,665,941
ec64592e00eb4a189cddcd94e89ca5302f535150
/test/ywd/bean/BeanTest.java
c45724c26a8a9eaf0c7aa026b5ce5dbe28772b0d
[]
no_license
dreamingodd/spring_source_reading
https://github.com/dreamingodd/spring_source_reading
a3b4d904e5d5f6db7eb868d2dddd632ba247ed21
1cd53e6271e2fafab72c9fe225a5467ebbbffddb
refs/heads/master
2021-01-12T13:06:24.165000
2016-10-18T14:20:16
2016-10-18T14:20:16
69,407,019
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package ywd.bean; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import ywd.bean.aware.AwareTest; import ywd.bean.circularDependency.CircleTestA; import ywd.bean.constructorArg.ArgBean; import ywd.bean.custom.User; import ywd.bean.factoryBean.Car; /** * All the tests here merely require 2 source projects which are spring-core and spring-beans. * @author dreamingodd * */ @SuppressWarnings("deprecation") public class BeanTest { @Test public void testTestBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); TestBean bean = (TestBean) bf.getBean("testBean"); Assert.assertEquals("Hello Spring!", bean.getTestStr()); } @Test @SuppressWarnings("unused") public void testArgBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); ArgBean argBean = (ArgBean) bf.getBean("argBean"); } @Test public void testAlias() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); TestBean bean = (TestBean) bf.getBean("a1"); Assert.assertEquals("Hello Spring!", bean.getTestStr()); } @Test public void testCustom() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); User user = (User) bf.getBean("customBean"); System.out.println(user.getUserName() + " - " + user.getEmail()); } @Test public void testFactoryBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); Car c = (Car) bf.getBean("car"); System.out.println(c); } @Test @SuppressWarnings("unused") public void testConstructorCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("constructorCircleTestBeanA"); } @Test @SuppressWarnings("unused") public void testSetterCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("setterCircleTestBeanA"); } @Test @SuppressWarnings("unused") public void testPrototypeCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("prototypeCircleTestBeanA"); } @Test public void testAware() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); AwareTest at = (AwareTest) bf.getBean("awareTest"); at.testAware(); } }
UTF-8
Java
2,775
java
BeanTest.java
Java
[ { "context": "which are spring-core and spring-beans.\n * @author dreamingodd\n *\n */\n@SuppressWarnings(\"deprecation\")\npublic cl", "end": 542, "score": 0.9994120597839355, "start": 531, "tag": "USERNAME", "value": "dreamingodd" } ]
null
[]
package ywd.bean; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import ywd.bean.aware.AwareTest; import ywd.bean.circularDependency.CircleTestA; import ywd.bean.constructorArg.ArgBean; import ywd.bean.custom.User; import ywd.bean.factoryBean.Car; /** * All the tests here merely require 2 source projects which are spring-core and spring-beans. * @author dreamingodd * */ @SuppressWarnings("deprecation") public class BeanTest { @Test public void testTestBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); TestBean bean = (TestBean) bf.getBean("testBean"); Assert.assertEquals("Hello Spring!", bean.getTestStr()); } @Test @SuppressWarnings("unused") public void testArgBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); ArgBean argBean = (ArgBean) bf.getBean("argBean"); } @Test public void testAlias() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); TestBean bean = (TestBean) bf.getBean("a1"); Assert.assertEquals("Hello Spring!", bean.getTestStr()); } @Test public void testCustom() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); User user = (User) bf.getBean("customBean"); System.out.println(user.getUserName() + " - " + user.getEmail()); } @Test public void testFactoryBean() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); Car c = (Car) bf.getBean("car"); System.out.println(c); } @Test @SuppressWarnings("unused") public void testConstructorCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("constructorCircleTestBeanA"); } @Test @SuppressWarnings("unused") public void testSetterCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("setterCircleTestBeanA"); } @Test @SuppressWarnings("unused") public void testPrototypeCircularDependency() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); CircleTestA a = (CircleTestA) bf.getBean("prototypeCircleTestBeanA"); } @Test public void testAware() { BeanFactory bf = new XmlBeanFactory(new ClassPathResource("beans.xml")); AwareTest at = (AwareTest) bf.getBean("awareTest"); at.testAware(); } }
2,775
0.685045
0.684324
77
35.03896
27.729418
94
false
false
0
0
0
0
0
0
0.467532
false
false
9
0279e3860149bd6e785b9ade1903d5e9a0896ba7
8,014,409,007,184
bfd8ccf3634727169a967963fc75c0a68c01702e
/software/eyeball-2.3/src-test/com/hp/hpl/jena/eyeball/web/statistics/test/BaseTest.java
b63b97322cc52d85c4dfcb7e2c684c00a8cb9a79
[]
no_license
ycba-cia/RDFer
https://github.com/ycba-cia/RDFer
a6dd2de15936e80cb728541637a169fd6193b4c9
d0d74ad5084e908533b8bd5708240a3337410e48
refs/heads/master
2022-07-26T06:01:22.330000
2022-07-18T17:57:07
2022-07-18T17:57:07
19,811,571
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * BaseTest.java * JUnit based test * * Created on August 23, 2006, 2007, 2008, 8:55 AM */ package com.hp.hpl.jena.eyeball.web.statistics.test; import com.hp.hpl.jena.eyeball.Report; import com.hp.hpl.jena.eyeball.vocabulary.EYE; import com.hp.hpl.jena.eyeball.web.WebEyeballer; import com.hp.hpl.jena.eyeball.web.statistics.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.rdf.model.test.ModelTestBase; import java.io.*; import java.util.Set; /** @author peter */ public class BaseTest extends ModelTestBase { public BaseTest() { super( "BaseTest" ); } private Model expResult, result; private void prepareTest( WebEyeballer e, Statistician instance, String statName ) { expResult = ModelFactory.createDefaultModel().read( "file:testcases/" + statName + "result.n3", "N3" ); ByteArrayOutputStream s = stringForModel( statName ); e.setModelType( "N3" ); e.setRdfModel( s.toString() ); Report r = new Report(); String plainReport = e.getPlainReport(); // System.err.println( ">> " + plainReport ); r.setMitems( ModelFactory.createDefaultModel().read( new StringReader( plainReport ), EYE.getURI(), e.getReportFormat() ) ); Resource hook = ModelFactory.createDefaultModel().createResource(); result = instance.gather( e, r, hook ); } /** long-winded, but ensures that the model is valid. */ private ByteArrayOutputStream stringForModel( String statName ) { ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream out = new PrintStream( s ); ModelFactory.createDefaultModel() .read( "file:testcases/" + statName + "input.n3", "N3" ) .write( out, "N3" ); return s; } protected void runStatisticianTest( WebEyeballer e, Statistician instance, String statName ) { prepareTest( e, instance, statName ); // assertIsoModels( "Statistician did not deliver expected results for " + statName, expResult, result ); System.err.println( "(Note: statistician test disabled; don't worry about this.)" ); } protected void runStatisticianContainsPredicatesTest( WebEyeballer e, Statistician instance, String statName ) { prepareTest( e, instance, statName ); Set<Property> expectedPredicates = expResult.listStatements().mapWith( Statement.Util.getPredicate ).toSet(); Set<Property> actualPredicates = result.listStatements().mapWith( Statement.Util.getPredicate ).toSet(); if (!expectedPredicates.containsAll( actualPredicates ) ) { actualPredicates.removeAll( expectedPredicates ); fail( "statistics report contains unexpected predicates: " + actualPredicates ); } } } /* * (c) Copyright 2006, 2007, 2008 Hewlett-Packard Development Company, LP All rights (c) Copyright 2010 Epimorphics Limited. * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. 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. 3. The name of the author may not * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
UTF-8
Java
4,404
java
BaseTest.java
Java
[ { "context": "java.io.*;\n\nimport java.util.Set;\n\n/**\n @author peter\n*/\npublic class BaseTest extends ModelTestBas", "end": 486, "score": 0.8582353591918945, "start": 485, "tag": "NAME", "value": "p" }, { "context": "va.io.*;\n\nimport java.util.Set;\n\n/**\n @author peter\n*/\npublic class BaseTest extends ModelTestBase\n ", "end": 490, "score": 0.7900431752204895, "start": 486, "tag": "USERNAME", "value": "eter" } ]
null
[]
/* * BaseTest.java * JUnit based test * * Created on August 23, 2006, 2007, 2008, 8:55 AM */ package com.hp.hpl.jena.eyeball.web.statistics.test; import com.hp.hpl.jena.eyeball.Report; import com.hp.hpl.jena.eyeball.vocabulary.EYE; import com.hp.hpl.jena.eyeball.web.WebEyeballer; import com.hp.hpl.jena.eyeball.web.statistics.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.rdf.model.test.ModelTestBase; import java.io.*; import java.util.Set; /** @author peter */ public class BaseTest extends ModelTestBase { public BaseTest() { super( "BaseTest" ); } private Model expResult, result; private void prepareTest( WebEyeballer e, Statistician instance, String statName ) { expResult = ModelFactory.createDefaultModel().read( "file:testcases/" + statName + "result.n3", "N3" ); ByteArrayOutputStream s = stringForModel( statName ); e.setModelType( "N3" ); e.setRdfModel( s.toString() ); Report r = new Report(); String plainReport = e.getPlainReport(); // System.err.println( ">> " + plainReport ); r.setMitems( ModelFactory.createDefaultModel().read( new StringReader( plainReport ), EYE.getURI(), e.getReportFormat() ) ); Resource hook = ModelFactory.createDefaultModel().createResource(); result = instance.gather( e, r, hook ); } /** long-winded, but ensures that the model is valid. */ private ByteArrayOutputStream stringForModel( String statName ) { ByteArrayOutputStream s = new ByteArrayOutputStream(); PrintStream out = new PrintStream( s ); ModelFactory.createDefaultModel() .read( "file:testcases/" + statName + "input.n3", "N3" ) .write( out, "N3" ); return s; } protected void runStatisticianTest( WebEyeballer e, Statistician instance, String statName ) { prepareTest( e, instance, statName ); // assertIsoModels( "Statistician did not deliver expected results for " + statName, expResult, result ); System.err.println( "(Note: statistician test disabled; don't worry about this.)" ); } protected void runStatisticianContainsPredicatesTest( WebEyeballer e, Statistician instance, String statName ) { prepareTest( e, instance, statName ); Set<Property> expectedPredicates = expResult.listStatements().mapWith( Statement.Util.getPredicate ).toSet(); Set<Property> actualPredicates = result.listStatements().mapWith( Statement.Util.getPredicate ).toSet(); if (!expectedPredicates.containsAll( actualPredicates ) ) { actualPredicates.removeAll( expectedPredicates ); fail( "statistics report contains unexpected predicates: " + actualPredicates ); } } } /* * (c) Copyright 2006, 2007, 2008 Hewlett-Packard Development Company, LP All rights (c) Copyright 2010 Epimorphics Limited. * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. 2. 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. 3. The name of the author may not * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. */
4,404
0.696185
0.686648
103
41.766991
34.758865
132
false
false
0
0
0
0
0
0
0.815534
false
false
9
64abedca59f8c5eafd2a59fe090891af947518ac
22,978,075,069,261
0dea0b6a26a5b0ef5d4100490a6a370e1d625144
/api/src/main/java/me/gyanendrokh/meiteimayek/dictionary/api/service/AuthService.java
fbfd8c608e38212d5cf578705e8910e85f2d7204
[]
no_license
meiteimayek/Dictionary
https://github.com/meiteimayek/Dictionary
86a09d0e4c74e4ed02346df3456fb347eca27574
908b84089f77e456f97f0289d552c218c0c12911
refs/heads/master
2020-05-19T05:54:54.536000
2019-05-10T15:51:05
2019-05-10T15:51:05
184,860,405
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.gyanendrokh.meiteimayek.dictionary.api.service; import me.gyanendrokh.meiteimayek.dictionary.api.AuthApi; public class AuthService extends BaseService<AuthApi> { private static AuthService mSelf = null; public static AuthService getInstance() { if(mSelf == null) { mSelf = new AuthService(); } return mSelf; } private AuthApi mApi; private AuthService() { super(); mApi = createService(AuthApi.class); } @Override public String getBaseUrl() { return Endpoints.AUTH_API; } @Override public AuthApi getApi() { return mApi; } }
UTF-8
Java
604
java
AuthService.java
Java
[]
null
[]
package me.gyanendrokh.meiteimayek.dictionary.api.service; import me.gyanendrokh.meiteimayek.dictionary.api.AuthApi; public class AuthService extends BaseService<AuthApi> { private static AuthService mSelf = null; public static AuthService getInstance() { if(mSelf == null) { mSelf = new AuthService(); } return mSelf; } private AuthApi mApi; private AuthService() { super(); mApi = createService(AuthApi.class); } @Override public String getBaseUrl() { return Endpoints.AUTH_API; } @Override public AuthApi getApi() { return mApi; } }
604
0.687086
0.687086
34
16.764706
18.41045
58
false
false
0
0
0
0
0
0
0.294118
false
false
9
e1508b123703456ff818241d102ee4dbb4bde5ad
953,482,787,640
5ba4d8b040f3bcadfe212c7fcbb1e778ad1212b4
/src/application/RepairController.java
1266caeb80fe5ce4fd7d61670928a67a0e54d3db
[]
no_license
MarcinKula96/WINsetup
https://github.com/MarcinKula96/WINsetup
ea5d228fa929412379cdc91e1d7ce0fe22a3409a
a52a90f7a0fcfd229aba8bde65035086f1e52052
refs/heads/master
2020-03-31T05:27:01.822000
2018-10-07T14:06:21
2018-10-07T14:06:21
151,946,036
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package application; import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; public class RepairController { @FXML private TextArea repairResultTextArea; @FXML private AnchorPane ap1; @FXML private AnchorPane ap2; @FXML private Text waitText; @FXML private RadioButton repairRadioSfc; @FXML private RadioButton repairRadiochk; @FXML private void initialize() { ap1.setStyle("-fx-background-color: " + SampleController.color +";"); ap2.setStyle("-fx-background-color: " + SampleController.color +";"); } @FXML private void sfcScannowFunc() { StringBuilder bufor = new StringBuilder(); bufor.append("Polecenie sfc /scannow spowoduje przeskanowanie wszystkich chronionych plików " + System.getProperty("line.separator") + "systemowych i zastąpienie plików uszkodzonych kopią buforowaną, " + System.getProperty("line.separator") + "która znajduje się w folderze skompresowanym %WinDir%\\System32\\dllcache."); bufor.append(System.getProperty("line.separator")); bufor.append(System.getProperty("line.separator")); bufor.append("Po kliknięciu przycisku 'Wykonaj' zostanie uruchomiona konsola CMD. " + System.getProperty("line.separator") + "Operacja może potrwać kilkanaście minut. Nie zamykaj konsoli w czasie skanowania plików." + System.getProperty("line.separator") + "Kiedy naprawa zostanie zakończona zostaniesz o tym poinformowany w konsoli CMD, " + System.getProperty("line.separator") + "wtedy możesz ją zamknąć." ); repairResultTextArea.setText(bufor.toString()); } @FXML private void chkdskFunc() { StringBuilder bufor = new StringBuilder(); bufor.append("Polecenie chkdsk c:/f spowoduje przeskanowanie partycji systemowej " + System.getProperty("line.separator") + "przy następnym uruchomieniu komputera. "); bufor.append(System.getProperty("line.separator")); bufor.append(System.getProperty("line.separator")); bufor.append("Po kliknięciu przycisku 'Wykonaj' zostanie uruchomiona konsola CMD. " + System.getProperty("line.separator") + "Zostaniesz zapytany czy zgadzasz się na sprawdzenie dysku przy następnym uruchomieniu " + System.getProperty("line.separator") + "komputera. Wpisz 'Y' lub 'T' (w zależności od języka sytemu). Nastepnie zamknij " + System.getProperty("line.separator") + "konsolę CMD i uruchom komputer ponownie. " + System.getProperty("line.separator") + "Dysk zostanie sprawdzony i w razie potrzeby naprawiony." ); repairResultTextArea.setText(bufor.toString()); } @FXML void repair(ActionEvent event) throws IOException { if(repairRadioSfc.isSelected()) { Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"sfc /scannow\""); }else if (repairRadiochk.isSelected()) { Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"chkdsk c:/f\""); } } @FXML void setWaitInfo(MouseEvent event) { } }
WINDOWS-1250
Java
3,327
java
RepairController.java
Java
[]
null
[]
package application; import java.io.IOException; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.ProgressIndicator; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; public class RepairController { @FXML private TextArea repairResultTextArea; @FXML private AnchorPane ap1; @FXML private AnchorPane ap2; @FXML private Text waitText; @FXML private RadioButton repairRadioSfc; @FXML private RadioButton repairRadiochk; @FXML private void initialize() { ap1.setStyle("-fx-background-color: " + SampleController.color +";"); ap2.setStyle("-fx-background-color: " + SampleController.color +";"); } @FXML private void sfcScannowFunc() { StringBuilder bufor = new StringBuilder(); bufor.append("Polecenie sfc /scannow spowoduje przeskanowanie wszystkich chronionych plików " + System.getProperty("line.separator") + "systemowych i zastąpienie plików uszkodzonych kopią buforowaną, " + System.getProperty("line.separator") + "która znajduje się w folderze skompresowanym %WinDir%\\System32\\dllcache."); bufor.append(System.getProperty("line.separator")); bufor.append(System.getProperty("line.separator")); bufor.append("Po kliknięciu przycisku 'Wykonaj' zostanie uruchomiona konsola CMD. " + System.getProperty("line.separator") + "Operacja może potrwać kilkanaście minut. Nie zamykaj konsoli w czasie skanowania plików." + System.getProperty("line.separator") + "Kiedy naprawa zostanie zakończona zostaniesz o tym poinformowany w konsoli CMD, " + System.getProperty("line.separator") + "wtedy możesz ją zamknąć." ); repairResultTextArea.setText(bufor.toString()); } @FXML private void chkdskFunc() { StringBuilder bufor = new StringBuilder(); bufor.append("Polecenie chkdsk c:/f spowoduje przeskanowanie partycji systemowej " + System.getProperty("line.separator") + "przy następnym uruchomieniu komputera. "); bufor.append(System.getProperty("line.separator")); bufor.append(System.getProperty("line.separator")); bufor.append("Po kliknięciu przycisku 'Wykonaj' zostanie uruchomiona konsola CMD. " + System.getProperty("line.separator") + "Zostaniesz zapytany czy zgadzasz się na sprawdzenie dysku przy następnym uruchomieniu " + System.getProperty("line.separator") + "komputera. Wpisz 'Y' lub 'T' (w zależności od języka sytemu). Nastepnie zamknij " + System.getProperty("line.separator") + "konsolę CMD i uruchom komputer ponownie. " + System.getProperty("line.separator") + "Dysk zostanie sprawdzony i w razie potrzeby naprawiony." ); repairResultTextArea.setText(bufor.toString()); } @FXML void repair(ActionEvent event) throws IOException { if(repairRadioSfc.isSelected()) { Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"sfc /scannow\""); }else if (repairRadiochk.isSelected()) { Runtime.getRuntime().exec("cmd /c start cmd.exe /K \"chkdsk c:/f\""); } } @FXML void setWaitInfo(MouseEvent event) { } }
3,327
0.70533
0.703513
98
32.693878
37.407413
135
false
false
0
0
0
0
0
0
1.234694
false
false
9
d360693555fa9194b950ffab7c56e6877c13ba81
27,298,812,162,023
de79fbb88f31b3d3d2e6776d0598720405a13431
/src/headfirst/designpatterns/collections/iterator_builtin/Menu.java
80e0376664a9217e29395a2735fe42a949a56d14
[]
no_license
mingruyue/Head-First-Design-Patterns
https://github.com/mingruyue/Head-First-Design-Patterns
b621a830f01bb80c4220523a55df1fd7a28abd60
35c5bd5fb5d0cfaa842fe5debd5a2c45d90d3327
refs/heads/master
2020-05-15T20:20:35.880000
2019-05-25T09:40:25
2019-05-25T09:40:25
182,480,310
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package headfirst.designpatterns.collections.iterator_builtin; import java.util.Iterator; public interface Menu { Iterator<String> createIterator(); }
UTF-8
Java
157
java
Menu.java
Java
[]
null
[]
package headfirst.designpatterns.collections.iterator_builtin; import java.util.Iterator; public interface Menu { Iterator<String> createIterator(); }
157
0.796178
0.796178
7
21.428572
21.645569
62
false
false
0
0
0
0
0
0
0.428571
false
false
9
6a1190bdb4183760ca41ae3d6172d0d9dbf20094
14,388,140,481,725
2e49f23ef1e4a50da89d46eb45bc019d04087d2c
/src/FunkoStore.java
2b90753290e81b4f147920628029e4afc6631803
[]
no_license
Dynotum/FactoryMethod
https://github.com/Dynotum/FactoryMethod
fb203e64290c15863fade46a32900e77c9f2e8fa
932402092d08aae59999b36448ae9efb3457af34
refs/heads/master
2022-11-07T04:50:01.571000
2020-06-14T05:03:01
2020-06-14T05:03:01
272,136,005
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class FunkoStore extends FunkoFactory { @Override Funko createFunko(String name) { switch (name) { case "mewtwo": return new MewtwoFunko(); case "ghost": return new GhostKamikazeFunko(); case "failed_fusion": return new FailedFusion(); } return null; } }
UTF-8
Java
400
java
FunkoStore.java
Java
[]
null
[]
public class FunkoStore extends FunkoFactory { @Override Funko createFunko(String name) { switch (name) { case "mewtwo": return new MewtwoFunko(); case "ghost": return new GhostKamikazeFunko(); case "failed_fusion": return new FailedFusion(); } return null; } }
400
0.4925
0.4925
16
23
16.37834
48
false
false
0
0
0
0
0
0
0.25
false
false
9
ca7332cc2db151738a96e2ef18f4140938718171
3,195,455,705,808
acbf60a09ef118ab3ec8f20b5568384164bf7984
/Day29Demo/src/com/itheima/servlet/OnlineServlet.java
b30f3315cf9fe2ad6ea068d0a9c6d38aac4ec59f
[]
no_license
361292623/learnjava
https://github.com/361292623/learnjava
40574ef82dfe1f90c0427296868c2211b7c5196c
3beb0f7f287bd1089b226bbd8b08d24f8b73247a
refs/heads/master
2020-04-01T17:53:15.315000
2018-11-26T12:40:44
2018-11-26T12:40:44
153,456,768
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.itheima.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /* 需求:统计在线人数 步骤分析 1. 接收用户名和密码 2. 判断用户名是否为admin和密码是否为123 3. 如果是,则登录成功, * 先从上下文域中根据count获得当前在线人数 * 如果count为null,则表示第一个登录,往上下文域中存储一个键值对:count:1 * 如果count不为null,则获得count值加一,再存储到上下文域中:count:count+1 * 则跳转到另一个页面:显示在线人数 4. 如果不是,则登录失败,则提示用户名或密码错误,3秒都跳转登录页面 */ @WebServlet(urlPatterns = "/online") public class OnlineServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 接收用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); // 获得上下文域对象 ServletContext context = getServletContext(); // 2. 判断用户名是否为admin和密码是否为123 if("admin".equals(username) && "123".equals(password)){ // 3. 如果是,则登录成功, // 先从上下文域中根据count获得当前在线人数 Integer count = (Integer)context.getAttribute("count"); if (count == null) { // 如果count为null,则表示第一个登录 count = 1; } else { // 如果count不为null,则获得count值加一 count++; } // 存储count到上下文域中 context.setAttribute("count", count); // 则跳转到另一个页面:显示在线人数 request.getRequestDispatcher("count").forward(request, response); } else { // 4. 如果不是,则登录失败,则提示用户名或密码错误,3秒都跳转登录页面 response.sendRedirect(request.getContextPath()+"/fail"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
UTF-8
Java
2,626
java
OnlineServlet.java
Java
[ { "context": "\n\n 步骤分析\n 1. 接收用户名和密码\n 2. 判断用户名是否为admin和密码是否为123\n 3. 如果是,则登录成功,\n * 先从上下", "end": 411, "score": 0.9729032516479492, "start": 406, "tag": "USERNAME", "value": "admin" }, { "context": " 1. 接收用户名和密码\n 2. 判断用户名是否为admin和密码是否为123\n 3. 如果是,则登录成功,\n * 先从上下文域中根据coun", "end": 420, "score": 0.9518961310386658, "start": 417, "tag": "PASSWORD", "value": "123" }, { "context": "密码\n String username = request.getParameter(\"username\");\n String password = request.getParameter(", "end": 965, "score": 0.9088174700737, "start": 957, "tag": "USERNAME", "value": "username" }, { "context": "ntext = getServletContext();\n // 2. 判断用户名是否为admin和密码是否为123\n if(\"admin\".equals(username) && \"1", "end": 1126, "score": 0.8492624759674072, "start": 1121, "tag": "USERNAME", "value": "admin" }, { "context": "ServletContext();\n // 2. 判断用户名是否为admin和密码是否为123\n if(\"admin\".equals(username) && \"123\".equal", "end": 1135, "score": 0.9329462051391602, "start": 1132, "tag": "PASSWORD", "value": "123" }, { "context": ");\n // 2. 判断用户名是否为admin和密码是否为123\n if(\"admin\".equals(username) && \"123\".equals(password)){\n ", "end": 1152, "score": 0.9768539667129517, "start": 1147, "tag": "USERNAME", "value": "admin" }, { "context": "n和密码是否为123\n if(\"admin\".equals(username) && \"123\".equals(password)){\n // 3. 如果是,则登录成功,\n ", "end": 1178, "score": 0.9043867588043213, "start": 1175, "tag": "PASSWORD", "value": "123" } ]
null
[]
package com.itheima.servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /* 需求:统计在线人数 步骤分析 1. 接收用户名和密码 2. 判断用户名是否为admin和密码是否为123 3. 如果是,则登录成功, * 先从上下文域中根据count获得当前在线人数 * 如果count为null,则表示第一个登录,往上下文域中存储一个键值对:count:1 * 如果count不为null,则获得count值加一,再存储到上下文域中:count:count+1 * 则跳转到另一个页面:显示在线人数 4. 如果不是,则登录失败,则提示用户名或密码错误,3秒都跳转登录页面 */ @WebServlet(urlPatterns = "/online") public class OnlineServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 接收用户名和密码 String username = request.getParameter("username"); String password = request.getParameter("password"); // 获得上下文域对象 ServletContext context = getServletContext(); // 2. 判断用户名是否为admin和密码是否为123 if("admin".equals(username) && "123".equals(password)){ // 3. 如果是,则登录成功, // 先从上下文域中根据count获得当前在线人数 Integer count = (Integer)context.getAttribute("count"); if (count == null) { // 如果count为null,则表示第一个登录 count = 1; } else { // 如果count不为null,则获得count值加一 count++; } // 存储count到上下文域中 context.setAttribute("count", count); // 则跳转到另一个页面:显示在线人数 request.getRequestDispatcher("count").forward(request, response); } else { // 4. 如果不是,则登录失败,则提示用户名或密码错误,3秒都跳转登录页面 response.sendRedirect(request.getContextPath()+"/fail"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
2,626
0.649657
0.638862
59
33.542374
25.583576
121
false
false
0
0
0
0
0
0
0.440678
false
false
9
0bdb0752e13aed5ca1ed5a73a0ce1d3346792868
3,702,261,846,293
987a2554910aa0becf75e151b83472f9bc714236
/src/org/pushingpixels/onyx/utils/TracingEventQueueThreadJMX.java
d837c30c10a8a94d9b9974f489d9d55d6fb79c9c
[ "Apache-2.0" ]
permissive
carloamaglio/josk
https://github.com/carloamaglio/josk
9a96ce63c67503f50a72154bc693425d41361ead
bf134c512b0f963afe40e717d0eea8f7342b3052
refs/heads/master
2016-09-06T09:28:45.692000
2013-09-12T09:33:24
2013-09-12T09:33:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * * Copyright 2013 Dott. Ing. Carlo Amaglio - Via Emigli, 10 - 25081 Bedizzole (BS) - Italy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package org.pushingpixels.onyx.utils; import java.awt.AWTEvent; import java.lang.management.*; import java.util.*; import javax.management.MBeanServer; import javax.management.ObjectName; class TracingEventQueueThreadJMX extends Thread { private long thresholdDelay; private Map<AWTEvent, Long> eventTimeMap; private ThreadMXBean threadBean; public TracingEventQueueThreadJMX(long thresholdDelay) { this.thresholdDelay = thresholdDelay; this.eventTimeMap = new HashMap<AWTEvent, Long>(); try { MBeanServer mbeanServer = ManagementFactory .getPlatformMBeanServer(); ObjectName objName = new ObjectName( ManagementFactory.THREAD_MXBEAN_NAME); Set<ObjectName> mbeans = mbeanServer.queryNames(objName, null); for (ObjectName name : mbeans) { this.threadBean = ManagementFactory.newPlatformMXBeanProxy( mbeanServer, name.toString(), ThreadMXBean.class); } } catch (Exception e) { e.printStackTrace(); } } public synchronized void eventDispatched(AWTEvent event) { this.eventTimeMap.put(event, System.currentTimeMillis()); } public synchronized void eventProcessed(AWTEvent event) { this.checkEventTime(event, System.currentTimeMillis(), this.eventTimeMap.get(event)); this.eventTimeMap.put(event, null); } private void checkEventTime(AWTEvent event, long currTime, long startTime) { long currProcessingTime = currTime - startTime; if (currProcessingTime >= this.thresholdDelay) { System.out.println("Event [" + event.hashCode() + "] " + event.getClass().getName() + " is taking too much time on EDT (" + currProcessingTime + ")"); if (this.threadBean != null) { long threadIds[] = threadBean.getAllThreadIds(); for (long threadId : threadIds) { ThreadInfo threadInfo = threadBean.getThreadInfo(threadId, Integer.MAX_VALUE); if (threadInfo.getThreadName().startsWith("AWT-EventQueue")) { System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); StackTraceElement[] stack = threadInfo.getStackTrace(); for (StackTraceElement stackEntry : stack) { System.out.println("\t" + stackEntry.getClassName() + "." + stackEntry.getMethodName() + " [" + stackEntry.getLineNumber() + "]"); } } } long[] deadlockedThreads = threadBean.findDeadlockedThreads(); if ((deadlockedThreads != null) && (deadlockedThreads.length > 0)) { System.out.println("Deadlocked threads:"); for (long threadId : deadlockedThreads) { ThreadInfo threadInfo = threadBean.getThreadInfo( threadId, Integer.MAX_VALUE); System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); StackTraceElement[] stack = threadInfo.getStackTrace(); for (StackTraceElement stackEntry : stack) { System.out.println("\t" + stackEntry.getClassName() + "." + stackEntry.getMethodName() + " [" + stackEntry.getLineNumber() + "]"); } } } } } } @Override public void run() { while (true) { long currTime = System.currentTimeMillis(); synchronized (this) { for (Map.Entry<AWTEvent, Long> entry : this.eventTimeMap .entrySet()) { AWTEvent event = entry.getKey(); if (entry.getValue() == null) continue; long startTime = entry.getValue(); this.checkEventTime(event, currTime, startTime); } } try { Thread.sleep(100); } catch (InterruptedException ie) { } } } }
UTF-8
Java
4,323
java
TracingEventQueueThreadJMX.java
Java
[ { "context": "/**\r\n * \r\n * Copyright 2013 Dott. Ing. Carlo Amaglio - Via Emigli, 10 - 25081 Bedizzole (BS) - Italy\r\n", "end": 52, "score": 0.9998658299446106, "start": 39, "tag": "NAME", "value": "Carlo Amaglio" }, { "context": "\n * \r\n * Copyright 2013 Dott. Ing. Carlo Amaglio - Via Emigli, 10 - 25081 Bedizzole (BS) - Italy\r\n *\r\n * Licens", "end": 65, "score": 0.9998313188552856, "start": 55, "tag": "NAME", "value": "Via Emigli" } ]
null
[]
/** * * Copyright 2013 Dott. Ing. <NAME> - <NAME>, 10 - 25081 Bedizzole (BS) - Italy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package org.pushingpixels.onyx.utils; import java.awt.AWTEvent; import java.lang.management.*; import java.util.*; import javax.management.MBeanServer; import javax.management.ObjectName; class TracingEventQueueThreadJMX extends Thread { private long thresholdDelay; private Map<AWTEvent, Long> eventTimeMap; private ThreadMXBean threadBean; public TracingEventQueueThreadJMX(long thresholdDelay) { this.thresholdDelay = thresholdDelay; this.eventTimeMap = new HashMap<AWTEvent, Long>(); try { MBeanServer mbeanServer = ManagementFactory .getPlatformMBeanServer(); ObjectName objName = new ObjectName( ManagementFactory.THREAD_MXBEAN_NAME); Set<ObjectName> mbeans = mbeanServer.queryNames(objName, null); for (ObjectName name : mbeans) { this.threadBean = ManagementFactory.newPlatformMXBeanProxy( mbeanServer, name.toString(), ThreadMXBean.class); } } catch (Exception e) { e.printStackTrace(); } } public synchronized void eventDispatched(AWTEvent event) { this.eventTimeMap.put(event, System.currentTimeMillis()); } public synchronized void eventProcessed(AWTEvent event) { this.checkEventTime(event, System.currentTimeMillis(), this.eventTimeMap.get(event)); this.eventTimeMap.put(event, null); } private void checkEventTime(AWTEvent event, long currTime, long startTime) { long currProcessingTime = currTime - startTime; if (currProcessingTime >= this.thresholdDelay) { System.out.println("Event [" + event.hashCode() + "] " + event.getClass().getName() + " is taking too much time on EDT (" + currProcessingTime + ")"); if (this.threadBean != null) { long threadIds[] = threadBean.getAllThreadIds(); for (long threadId : threadIds) { ThreadInfo threadInfo = threadBean.getThreadInfo(threadId, Integer.MAX_VALUE); if (threadInfo.getThreadName().startsWith("AWT-EventQueue")) { System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); StackTraceElement[] stack = threadInfo.getStackTrace(); for (StackTraceElement stackEntry : stack) { System.out.println("\t" + stackEntry.getClassName() + "." + stackEntry.getMethodName() + " [" + stackEntry.getLineNumber() + "]"); } } } long[] deadlockedThreads = threadBean.findDeadlockedThreads(); if ((deadlockedThreads != null) && (deadlockedThreads.length > 0)) { System.out.println("Deadlocked threads:"); for (long threadId : deadlockedThreads) { ThreadInfo threadInfo = threadBean.getThreadInfo( threadId, Integer.MAX_VALUE); System.out.println(threadInfo.getThreadName() + " / " + threadInfo.getThreadState()); StackTraceElement[] stack = threadInfo.getStackTrace(); for (StackTraceElement stackEntry : stack) { System.out.println("\t" + stackEntry.getClassName() + "." + stackEntry.getMethodName() + " [" + stackEntry.getLineNumber() + "]"); } } } } } } @Override public void run() { while (true) { long currTime = System.currentTimeMillis(); synchronized (this) { for (Map.Entry<AWTEvent, Long> entry : this.eventTimeMap .entrySet()) { AWTEvent event = entry.getKey(); if (entry.getValue() == null) continue; long startTime = entry.getValue(); this.checkEventTime(event, currTime, startTime); } } try { Thread.sleep(100); } catch (InterruptedException ie) { } } } }
4,312
0.663197
0.658802
131
31.015266
24.243984
90
false
false
0
0
0
0
0
0
3.229008
false
false
9
27c28ff900344707042cf9aadc2db68ff694e282
21,036,749,844,926
db1a6c786d399c73e6e3430feda827c2b307a1aa
/bundles/org.rubis.oscar.oscarcore.model/src/oscar/OscarFactory.java
891f03b39f2c2a63cbc87fcb73a34ede8f97cff3
[]
no_license
rubis-lab/oscar-ide
https://github.com/rubis-lab/oscar-ide
3476b448bae9c9ec67ad0c6d975e25a88d2e84f3
99e7216cc71d48320296aadcf48c7776f8efd743
refs/heads/master
2020-03-28T15:25:42.013000
2019-05-20T05:58:01
2019-05-20T05:58:01
148,591,881
8
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** */ package oscar; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see oscar.OscarPackage * @generated */ public interface OscarFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ OscarFactory eINSTANCE = oscar.impl.OscarFactoryImpl.init(); /** * Returns a new object of class '<em>OSCAR Container</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Container</em>'. * @generated */ OSCARContainer createOSCARContainer(); /** * Returns a new object of class '<em>OSCAR Object Process Diagram</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Object Process Diagram</em>'. * @generated */ OSCARObjectProcessDiagram createOSCARObjectProcessDiagram(); /** * Returns a new object of class '<em>OSCAR Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Node</em>'. * @generated */ OSCARNode createOSCARNode(); /** * Returns a new object of class '<em>OSCAR Thing</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Thing</em>'. * @generated */ OSCARThing createOSCARThing(); /** * Returns a new object of class '<em>Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Node</em>'. * @generated */ Node createNode(); /** * Returns a new object of class '<em>Topic</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Topic</em>'. * @generated */ Topic createTopic(); /** * Returns a new object of class '<em>OSCAR Link</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Link</em>'. * @generated */ OSCARLink createOSCARLink(); /** * Returns a new object of class '<em>OSCAR Procedural Link</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Procedural Link</em>'. * @generated */ OSCARProceduralLink createOSCARProceduralLink(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ OscarPackage getOscarPackage(); } //OscarFactory
UTF-8
Java
2,627
java
OscarFactory.java
Java
[]
null
[]
/** */ package oscar; import org.eclipse.emf.ecore.EFactory; /** * <!-- begin-user-doc --> * The <b>Factory</b> for the model. * It provides a create method for each non-abstract class of the model. * <!-- end-user-doc --> * @see oscar.OscarPackage * @generated */ public interface OscarFactory extends EFactory { /** * The singleton instance of the factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ OscarFactory eINSTANCE = oscar.impl.OscarFactoryImpl.init(); /** * Returns a new object of class '<em>OSCAR Container</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Container</em>'. * @generated */ OSCARContainer createOSCARContainer(); /** * Returns a new object of class '<em>OSCAR Object Process Diagram</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Object Process Diagram</em>'. * @generated */ OSCARObjectProcessDiagram createOSCARObjectProcessDiagram(); /** * Returns a new object of class '<em>OSCAR Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Node</em>'. * @generated */ OSCARNode createOSCARNode(); /** * Returns a new object of class '<em>OSCAR Thing</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Thing</em>'. * @generated */ OSCARThing createOSCARThing(); /** * Returns a new object of class '<em>Node</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Node</em>'. * @generated */ Node createNode(); /** * Returns a new object of class '<em>Topic</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>Topic</em>'. * @generated */ Topic createTopic(); /** * Returns a new object of class '<em>OSCAR Link</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Link</em>'. * @generated */ OSCARLink createOSCARLink(); /** * Returns a new object of class '<em>OSCAR Procedural Link</em>'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return a new object of class '<em>OSCAR Procedural Link</em>'. * @generated */ OSCARProceduralLink createOSCARProceduralLink(); /** * Returns the package supported by this factory. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the package supported by this factory. * @generated */ OscarPackage getOscarPackage(); } //OscarFactory
2,627
0.606014
0.606014
105
24.019047
21.217684
74
false
false
0
0
0
0
0
0
0.866667
false
false
9
da71d5e1e756a2651d2f7e2b4617f0f6e0623a21
30,451,318,165,725
417750e578d52c082022ea115a6a5a8200e8676c
/Organism.java
59d90d0edb5462c2737871bbbf245a3df98c1913
[]
no_license
epaglier/BF-Genetic-Programmer
https://github.com/epaglier/BF-Genetic-Programmer
fc2b8c1e9eee003c78587d0ed9ba636fa762f19a
2031bf6f145c36e18b6e73d50ee86aec34e933be
refs/heads/master
2021-06-28T20:50:42.148000
2017-09-12T05:41:07
2017-09-12T05:41:07
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.*; //THIS FOR SOME REASON ONLY USES NEXT LETTER IN SEQUENCE EASY FIX public class Organism { public String brain; public int fitness; public ArrayList<Integer> target; public BFToCode b; public Map table; public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void main(String[] args) { ArrayList<Integer> target = new ArrayList<Integer>(); //Strings can be obtained from ascii target.add(71); Organism s = new Organism(target); s.printBrain(); s.printMap(); } public Organism(ArrayList<Integer> target) { b = new BFToCode(); this.target = target; fitness = 0; brain = ""; table = new HashMap(); formMap(); //forming brain in the wrong spot formBrain(); } //must be called first public void formMap() { formStatement(table, "A"); } //must be called second public void formBrain() { brain = formBrainHelper("A"); } public String formBrainHelper(String letter) { String s = ((String)table.get(letter)); String b = ""; for (int i = 0; i < s.length(); i++) { if (ALPHABET.contains(s.substring(i,i+1))) { b += formBrainHelper(s.substring(i,i+1)); } else { b += s.substring(i,i+1); } } return b; } public void formStatement(Map m, String letter) { String temp = ""; for (int i = 0; i < 5; i++) { int t = (int)(Math.random()*9) + 1; if (t == 1) { temp += "<"; } else if (t == 2) { temp += ">"; } else if (t == 3) { temp += "["; } else if (t == 4) { temp += "]"; } else if (t == 5) { temp += "+"; } else if (t == 6) { temp += "-"; } else if (t == 7) { temp += "."; } else if (t == 8) { //the letters that are not allowed to have more letters if (letter.equals("W") || letter.equals("X") || letter.equals("Y") || letter.equals("Z")) {} else { //add letter from the next String[] split = ALPHABET.split(letter); int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); //THIS NEEDS TO BE ANY LETTER formStatement(m, document); temp += document; } } else { temp += ","; } } m.put(letter, temp); } public Organism(ArrayList<Integer> target, HashMap table) { this.target = target; this.table = table; formBrain(); } //ONLY CALL THIS ONCE public int findFitness() { BFToCode b = new BFToCode(); b.translate(brain); ArrayList<Integer> console = b.getOutputs(); for (int i = 0; i < console.size(); i++) { if (i < target.size()) fitness += 256 - Math.abs(console.get(i) - target.get(i)); } if (b.failed()) { fitness = 0; } return fitness; } //call this after finding fitness public int getFitness() { return fitness; } public void resetFitness() { fitness = 0; } public Organism copy() { //edit table and pass it on ArrayList<String> toDo = new ArrayList<String>(); Set keyChainz = table.keySet(); HashMap temp = new HashMap(); for (Object k: keyChainz) { String letter = (String) k; String s = (String)table.get(k); String fin = ""; for(int i = 0; i < s.length(); i++) { if (Math.random() < 0.05) { //add char/letter if (Math.random() > 0.5) { String toAdd = ""; int t = (int)(Math.random()*9) + 1; if (t == 1) { toAdd += "<"; } else if (t == 2) { toAdd += ">"; } else if (t == 3) { toAdd += "["; } else if (t == 4) { toAdd += "]"; } else if (t == 5) { toAdd += "+"; } else if (t == 6) { toAdd += "-"; } else if (t == 7) { toAdd += "."; } else if (t == 8) { //the letters that are not allowed to have more letters if (s.substring(i,i+1).equals("W") || s.substring(i,i+1).equals("X") || s.substring(i,i+1).equals("Y") || s.substring(i,i+1).equals("Z")) { String[] split = ALPHABET.split(letter); int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); if (!table.containsKey(document)) { toDo.add(document); } toAdd += document; } else { //add letter from the next String[] split = ALPHABET.split(letter); if (split.length == 1) {} else { int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); if (!table.containsKey(document)) { toDo.add(document); } toAdd += document; } } } else { toAdd += ","; } fin = fin + s.substring(i,i+1) + toAdd; } //remove char/letter else { } } else { fin += s.substring(i,i+1); } } temp.put(k,fin); for (String w: toDo) { formStatement(temp,w); } } return new Organism(target, temp); } public Organism crossBreed(Organism other) { //need new crossbreeding throw new RuntimeException("IMPLEMENT THIS"); } public void printBrain() { System.out.println(brain); } public String getBrain() { return brain; } public void printMap() { System.out.println(table); } }
UTF-8
Java
6,523
java
Organism.java
Java
[]
null
[]
import java.util.*; //THIS FOR SOME REASON ONLY USES NEXT LETTER IN SEQUENCE EASY FIX public class Organism { public String brain; public int fitness; public ArrayList<Integer> target; public BFToCode b; public Map table; public static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; public static void main(String[] args) { ArrayList<Integer> target = new ArrayList<Integer>(); //Strings can be obtained from ascii target.add(71); Organism s = new Organism(target); s.printBrain(); s.printMap(); } public Organism(ArrayList<Integer> target) { b = new BFToCode(); this.target = target; fitness = 0; brain = ""; table = new HashMap(); formMap(); //forming brain in the wrong spot formBrain(); } //must be called first public void formMap() { formStatement(table, "A"); } //must be called second public void formBrain() { brain = formBrainHelper("A"); } public String formBrainHelper(String letter) { String s = ((String)table.get(letter)); String b = ""; for (int i = 0; i < s.length(); i++) { if (ALPHABET.contains(s.substring(i,i+1))) { b += formBrainHelper(s.substring(i,i+1)); } else { b += s.substring(i,i+1); } } return b; } public void formStatement(Map m, String letter) { String temp = ""; for (int i = 0; i < 5; i++) { int t = (int)(Math.random()*9) + 1; if (t == 1) { temp += "<"; } else if (t == 2) { temp += ">"; } else if (t == 3) { temp += "["; } else if (t == 4) { temp += "]"; } else if (t == 5) { temp += "+"; } else if (t == 6) { temp += "-"; } else if (t == 7) { temp += "."; } else if (t == 8) { //the letters that are not allowed to have more letters if (letter.equals("W") || letter.equals("X") || letter.equals("Y") || letter.equals("Z")) {} else { //add letter from the next String[] split = ALPHABET.split(letter); int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); //THIS NEEDS TO BE ANY LETTER formStatement(m, document); temp += document; } } else { temp += ","; } } m.put(letter, temp); } public Organism(ArrayList<Integer> target, HashMap table) { this.target = target; this.table = table; formBrain(); } //ONLY CALL THIS ONCE public int findFitness() { BFToCode b = new BFToCode(); b.translate(brain); ArrayList<Integer> console = b.getOutputs(); for (int i = 0; i < console.size(); i++) { if (i < target.size()) fitness += 256 - Math.abs(console.get(i) - target.get(i)); } if (b.failed()) { fitness = 0; } return fitness; } //call this after finding fitness public int getFitness() { return fitness; } public void resetFitness() { fitness = 0; } public Organism copy() { //edit table and pass it on ArrayList<String> toDo = new ArrayList<String>(); Set keyChainz = table.keySet(); HashMap temp = new HashMap(); for (Object k: keyChainz) { String letter = (String) k; String s = (String)table.get(k); String fin = ""; for(int i = 0; i < s.length(); i++) { if (Math.random() < 0.05) { //add char/letter if (Math.random() > 0.5) { String toAdd = ""; int t = (int)(Math.random()*9) + 1; if (t == 1) { toAdd += "<"; } else if (t == 2) { toAdd += ">"; } else if (t == 3) { toAdd += "["; } else if (t == 4) { toAdd += "]"; } else if (t == 5) { toAdd += "+"; } else if (t == 6) { toAdd += "-"; } else if (t == 7) { toAdd += "."; } else if (t == 8) { //the letters that are not allowed to have more letters if (s.substring(i,i+1).equals("W") || s.substring(i,i+1).equals("X") || s.substring(i,i+1).equals("Y") || s.substring(i,i+1).equals("Z")) { String[] split = ALPHABET.split(letter); int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); if (!table.containsKey(document)) { toDo.add(document); } toAdd += document; } else { //add letter from the next String[] split = ALPHABET.split(letter); if (split.length == 1) {} else { int rand = (int)(Math.random()*split[1].length()); String document = split[1].substring(rand,rand+1); if (!table.containsKey(document)) { toDo.add(document); } toAdd += document; } } } else { toAdd += ","; } fin = fin + s.substring(i,i+1) + toAdd; } //remove char/letter else { } } else { fin += s.substring(i,i+1); } } temp.put(k,fin); for (String w: toDo) { formStatement(temp,w); } } return new Organism(target, temp); } public Organism crossBreed(Organism other) { //need new crossbreeding throw new RuntimeException("IMPLEMENT THIS"); } public void printBrain() { System.out.println(brain); } public String getBrain() { return brain; } public void printMap() { System.out.println(table); } }
6,523
0.437682
0.428944
284
21.97183
19.104216
153
false
false
0
0
0
0
0
0
0.457746
false
false
9
0c41bf1eef3c0374527a7b873630440c2c3423f4
22,325,240,037,981
436a6f01f9547cac62048fc85c8cddb21000b124
/api_car/src/main/java/com/jk/model/Userrole.java
8d80c9f4bdb0dc03226a32f9b2b275480349accb
[]
no_license
wzh1071522191/guazi-car
https://github.com/wzh1071522191/guazi-car
b67991decff71b98706ab55fc82be87fa3ecd04e
7cfd44d6afc5a2b838a3005f8aaf9a5448556716
refs/heads/master
2022-12-26T19:29:36.069000
2020-06-11T05:06:02
2020-06-11T05:06:02
202,494,685
0
0
null
false
2022-12-10T05:44:41
2019-08-15T07:27:58
2020-06-11T05:06:05
2022-12-10T05:44:40
43,537
0
0
22
JavaScript
false
false
package com.jk.model; import java.io.Serializable; /** * @author : 张松光 * @date :Created in 2019/8/15 9:59 * @description:员工权限表 * @package :com.jk.model * @version: 1.0.0 */ public class Userrole implements Serializable { private Integer id; private Integer uid; private Integer rid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Integer getRid() { return rid; } public void setRid(Integer rid) { this.rid = rid; } }
UTF-8
Java
705
java
Userrole.java
Java
[ { "context": ";\n\nimport java.io.Serializable;\n\n/**\n * @author : 张松光\n * @date :Created in 2019/8/15 9:59\n * @descripti", "end": 73, "score": 0.9997986555099487, "start": 70, "tag": "NAME", "value": "张松光" } ]
null
[]
package com.jk.model; import java.io.Serializable; /** * @author : 张松光 * @date :Created in 2019/8/15 9:59 * @description:员工权限表 * @package :com.jk.model * @version: 1.0.0 */ public class Userrole implements Serializable { private Integer id; private Integer uid; private Integer rid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUid() { return uid; } public void setUid(Integer uid) { this.uid = uid; } public Integer getRid() { return rid; } public void setRid(Integer rid) { this.rid = rid; } }
705
0.577093
0.558003
44
14.477273
13.405374
47
false
false
0
0
0
0
0
0
0.25
false
false
9
a756f95b11e1346690ef189a9125ef5aa3234239
14,654,428,454,959
53b900c49d6774e6e53ef304d28e441f21e46cf5
/f1indi/src/ClubComparator.java
1b55e49bb4062e4c8c668141db8df52c42962480
[]
no_license
v1nt/vsol
https://github.com/v1nt/vsol
19c4443551fff3dea46c9c86b11c006439eac328
d96dbdd3c636250e297ef5d29c41cd6862286a05
refs/heads/master
2020-05-19T14:13:03.033000
2013-07-21T11:15:37
2013-07-21T11:15:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.util.Comparator; public class ClubComparator implements Comparator<Club> { public ClubComparator() { // TODO Auto-generated constructor stub } public int compare(Club club1, Club club2) { return club2.getPoints() - club1.getPoints(); } }
UTF-8
Java
264
java
ClubComparator.java
Java
[]
null
[]
import java.util.Comparator; public class ClubComparator implements Comparator<Club> { public ClubComparator() { // TODO Auto-generated constructor stub } public int compare(Club club1, Club club2) { return club2.getPoints() - club1.getPoints(); } }
264
0.731061
0.715909
14
17.857143
20.99271
57
false
false
0
0
0
0
0
0
0.857143
false
false
9
da3d5cf076013341a9128d15afe28989611a9d7f
240,518,205,601
200a207ed990bf2b427160f7e9a2b5690be65788
/src/main/java/org/bukkit/event/entity/EntityPickupItemEvent.java
20f2d538f895683caac5dd44bd79dca420796cbb
[ "WTFPL" ]
permissive
8MiYile/HomoCraftServer
https://github.com/8MiYile/HomoCraftServer
8fae0e35a82267dbac023531c63903a293861e71
06c52bccad746256a08f78bfc56ae9e4c847445c
refs/heads/master
2021-02-07T20:55:22.127000
2020-05-06T10:01:49
2020-05-06T10:01:49
244,075,912
13
8
WTFPL
false
2020-10-13T19:58:13
2020-03-01T02:49:30
2020-05-12T07:41:59
2020-10-13T19:58:12
16,170
12
4
4
Java
false
false
package org.bukkit.event.entity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; /** * Thrown when a entity picks an item up from the ground */ public class EntityPickupItemEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Item item; private boolean cancel = false; private final int remaining; public EntityPickupItemEvent(final LivingEntity entity, final Item item, final int remaining) { super(entity); this.item = item; this.remaining = remaining; } @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * Gets the Item picked up by the entity. * * @return Item */ public Item getItem() { return item; } /** * Gets the amount remaining on the ground, if any * * @return amount remaining on the ground */ public int getRemaining() { return remaining; } public boolean isCancelled() { return cancel; } public void setCancelled(boolean cancel) { this.cancel = cancel; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
UTF-8
Java
1,429
java
EntityPickupItemEvent.java
Java
[]
null
[]
package org.bukkit.event.entity; import org.bukkit.entity.Item; import org.bukkit.entity.LivingEntity; import org.bukkit.event.Cancellable; import org.bukkit.event.HandlerList; /** * Thrown when a entity picks an item up from the ground */ public class EntityPickupItemEvent extends EntityEvent implements Cancellable { private static final HandlerList handlers = new HandlerList(); private final Item item; private boolean cancel = false; private final int remaining; public EntityPickupItemEvent(final LivingEntity entity, final Item item, final int remaining) { super(entity); this.item = item; this.remaining = remaining; } @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * Gets the Item picked up by the entity. * * @return Item */ public Item getItem() { return item; } /** * Gets the amount remaining on the ground, if any * * @return amount remaining on the ground */ public int getRemaining() { return remaining; } public boolean isCancelled() { return cancel; } public void setCancelled(boolean cancel) { this.cancel = cancel; } @Override public HandlerList getHandlers() { return handlers; } public static HandlerList getHandlerList() { return handlers; } }
1,429
0.648006
0.648006
62
22.048388
21.183855
99
false
false
0
0
0
0
0
0
0.354839
false
false
9
ef484ee20ae07e96215d6f73e02dbd63e92b95ed
28,793,460,784,996
f7cd8c857f6814b2d53264cc69f20eacc119c34c
/src/main/java/com/jfxgraph/scanner/beans/AnnotatedBeanDefinition.java
922e2f80e5ed7e5df85624b6b7249204ca8c1db5
[]
no_license
atschx/jfxgraph-asm-ext
https://github.com/atschx/jfxgraph-asm-ext
c5f403bab07cf61263dea5fabe5a4dbe42651dae
068b729f30d44d5d58697707734aaf2e5fd1669c
refs/heads/master
2021-01-19T04:21:46.391000
2015-08-05T03:16:44
2015-08-05T03:16:44
17,163,078
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.jfxgraph.scanner.beans; import com.jfxgraph.scanner.type.AnnotationMetadata; /** * AnnotatedBeanDefinition * @author Albert * @version $Id: AnnotatedBeanDefinition.java,v0.5 2013年10月27日 下午9:44:53 Albert Exp . * @since 3.1 */ public interface AnnotatedBeanDefinition extends BeanDefinition { /** * Obtain the annotation metadata (as well as basic class metadata) * for this bean definition's bean class. * @return the annotation metadata object (never {@code null}) */ AnnotationMetadata getMetadata(); }
UTF-8
Java
568
java
AnnotatedBeanDefinition.java
Java
[ { "context": "ata;\n\n/**\n * AnnotatedBeanDefinition\n * @author Albert\n * @version $Id: AnnotatedBeanDefinition.java,v", "end": 142, "score": 0.9998258352279663, "start": 136, "tag": "NAME", "value": "Albert" } ]
null
[]
package com.jfxgraph.scanner.beans; import com.jfxgraph.scanner.type.AnnotationMetadata; /** * AnnotatedBeanDefinition * @author Albert * @version $Id: AnnotatedBeanDefinition.java,v0.5 2013年10月27日 下午9:44:53 Albert Exp . * @since 3.1 */ public interface AnnotatedBeanDefinition extends BeanDefinition { /** * Obtain the annotation metadata (as well as basic class metadata) * for this bean definition's bean class. * @return the annotation metadata object (never {@code null}) */ AnnotationMetadata getMetadata(); }
568
0.72043
0.689964
19
28.368422
27.516905
87
false
false
0
0
0
0
0
0
0.210526
false
false
9
8027796e1be24560bdd8ef51a560ce920ae2758c
23,493,471,149,312
a700dc6db8d194e535572cb3907b49c7d99731e0
/src/main/java/com/trusthub/cobranca/application/util/ApiConstantes.java
a7ab6c2fc0db1cdcfdc3d5385efe1068e9e9d8d7
[]
no_license
reinaldojun/cobranca-relatorios
https://github.com/reinaldojun/cobranca-relatorios
05b75b0dcec82551912397a29514b71f5e53a4f3
d285e6b133b28d09d5d59c9cbed8639508d86609
refs/heads/master
2022-07-09T19:41:24.440000
2019-07-23T12:17:57
2019-07-23T12:17:57
198,423,386
0
0
null
false
2022-06-29T17:31:52
2019-07-23T12:11:31
2019-07-23T12:18:10
2022-06-29T17:31:51
84,250
0
0
2
Java
false
false
package com.trusthub.cobranca.application.util; /** * Constantes utilizadas nos servicos chamados * @author alan.franco/jose.viana */ public interface ApiConstantes { public static final String API_BAR = "/"; public static final String API_VALIDAR_TOKEN = "validar/token"; public static final String API_ATENDIMENTO_CONSULTAR_COBRANCA = "atendimentos/cobranca"; public static final String API_ATENDIMENTO_CONSULTAR_JURIDICO = "atendimentos/juridico"; public static final String API_CEDENTE = "cedente"; public static final String API_SACADO = "sacado"; }
UTF-8
Java
571
java
ApiConstantes.java
Java
[ { "context": "antes utilizadas nos servicos chamados \n * @author alan.franco/jose.viana\n */\npublic interface ApiConstantes {\n\t", "end": 123, "score": 0.9677545428276062, "start": 112, "tag": "USERNAME", "value": "alan.franco" }, { "context": "das nos servicos chamados \n * @author alan.franco/jose.viana\n */\npublic interface ApiConstantes {\n\t\n\tpublic st", "end": 134, "score": 0.9891287684440613, "start": 124, "tag": "USERNAME", "value": "jose.viana" } ]
null
[]
package com.trusthub.cobranca.application.util; /** * Constantes utilizadas nos servicos chamados * @author alan.franco/jose.viana */ public interface ApiConstantes { public static final String API_BAR = "/"; public static final String API_VALIDAR_TOKEN = "validar/token"; public static final String API_ATENDIMENTO_CONSULTAR_COBRANCA = "atendimentos/cobranca"; public static final String API_ATENDIMENTO_CONSULTAR_JURIDICO = "atendimentos/juridico"; public static final String API_CEDENTE = "cedente"; public static final String API_SACADO = "sacado"; }
571
0.767075
0.767075
17
32.588234
30.101904
89
false
false
0
0
0
0
0
0
0.882353
false
false
9
4490dc3fe02c83c3d78a2d4ebfa50b19167996b9
23,493,471,148,219
06250ed4c59aea8deaf82e67a00a6875e7dd137f
/src/com/example/fragmenttest1/AnimationSurfaceView.java
dd6fe482cc36f051af3b1e42a207d2526e9de7b1
[]
no_license
qishiri/RoboBeat
https://github.com/qishiri/RoboBeat
fe91a3960624422484caad23c443f198ab4feaca
f81a3541e841eeb11e1e67eb297ee6e2cf0e21f1
refs/heads/master
2020-05-26T21:44:27.093000
2014-07-14T08:14:25
2014-07-14T08:14:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.fragmenttest1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class AnimationSurfaceView extends SurfaceView implements Runnable, SurfaceHolder.Callback { static final long FPS = 60; static final long FRAME_TIME = 1000 / FPS; static int RECT_SIDE; SurfaceHolder surfaceHolder; Thread thread; Rect[] panel = new Rect[9]; int[] isTouched = new int[9]; int screen_width, screen_height; MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.fsan1); Context myContext; Fragment myFragment; SoundPool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); int spid; long time, remaining, offset = -0; long score = 0, score_now = 0; int mPointerID1 = -1, mPointerID2 = -1; int pointerId; float x1 = 0.0f; float y1 = 0.0f; float x2 = 0.0f; float y2 = 0.0f; public AnimationSurfaceView(Context context, Fragment fragment) { super(context); myContext = context; myFragment = fragment; surfaceHolder = getHolder(); surfaceHolder.addCallback(this); } @Override public void run() { for (int i = 0; i < 9; i++) { isTouched[i] = -1; } Canvas canvas = null; Paint paint = new Paint(); Paint bgPaint = new Paint(); Paint rectPaint = new Paint(); Paint rectPaint2 = new Paint(); // Background bgPaint.setStyle(Style.FILL); bgPaint.setColor(Color.WHITE); // Rectangle rectPaint.setStyle(Style.STROKE); rectPaint.setColor(Color.RED); // Rectangle(Touched) rectPaint2.setStyle(Style.FILL); rectPaint2.setColor(Color.RED); long loopCount = 0; long waitTime = 0; long startTime = System.currentTimeMillis(); spid = sp.load(myContext, R.raw.button, 1); Resources res = this.getResources(); InputStream is = res.openRawResource(R.raw.fsan1_n); InputStreamReader isr = null; try { isr = new InputStreamReader(is, "SJIS"); } catch (UnsupportedEncodingException e2) { // TODO 自動生成された catch ブロック e2.printStackTrace(); } BufferedReader br = new BufferedReader(isr); ArrayList<long[]> notes = new ArrayList<long[]>(); String temp0; String[] temp1; long[] temp2 = new long[3]; try { while ((temp0 = br.readLine()) != null) { temp1 = temp0.split(" ", 0); temp2[0] = Long.valueOf(temp1[0]); System.out.println(temp2[0]); temp2[1] = Long.valueOf(temp1[1]); System.out.println(temp2[1]); temp2[2] = 0; notes.add(temp2.clone()); } } catch (IOException e1) { // TODO 自動生成された catch ブロック e1.printStackTrace(); } for (Iterator<long[]> itr = notes.iterator(); itr.hasNext();) { System.out.println(itr.next()[0]); } mp.start(); long start = System.currentTimeMillis(); while (thread != null) { try { loopCount++; canvas = surfaceHolder.lockCanvas(); canvas.drawRect(0, 0, screen_width, screen_height, bgPaint); RECT_SIDE = screen_width / 5; for (Iterator<long[]> itr = notes.iterator(); itr.hasNext();) { long[] temp = itr.next(); remaining = temp[0] - time + offset; int difficulty = 600; if (-200 < remaining && remaining < difficulty && temp[2] == 0) { for (int i = 0; i < 9; i++) { if (isTouched[i] >= 0) { if (i == temp[1]) { temp[2] = 1; score_now = (long) (1000 * (1 - Math.abs(remaining) / (double) difficulty)); score += score_now; break; } } } if (temp[2] == 1) continue; int x0 = (int) (screen_width / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * (temp[1] % 3) + remaining / (difficulty / (double) 45)); int x1 = (int) (x0 + RECT_SIDE - remaining / (difficulty / (double) 90)); int y0 = (int) (screen_height / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * (temp[1] / 3) + remaining / (difficulty / (double) 45)); int y1 = (int) (y0 + RECT_SIDE - remaining / (difficulty / (double) 90)); canvas.drawRect(new Rect(x0, y0, x1, y1), rectPaint); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = (int) (screen_width / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * j); int y = (int) (screen_height / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * i); panel[i * 3 + j] = new Rect(x, y, x + RECT_SIDE, y + RECT_SIDE); if (isTouched[i * 3 + j] >= 0) { canvas.drawRect(panel[i * 3 + j], rectPaint2); } else { canvas.drawRect(panel[i * 3 + j], rectPaint); } } } time = System.currentTimeMillis() - start; canvas.drawText(String.valueOf(time), 10, 10, paint); canvas.drawText(String.valueOf(score), 10, 30, paint); canvas.drawText(String.valueOf(score_now), 10, 50, paint); canvas.drawText(String.valueOf(pointerId), 10, 70, paint); canvas.drawText( String.valueOf(x1) + " " + String.valueOf(y1) + " " + String.valueOf(x2) + " " + String.valueOf(y2), 10, 90, paint); canvas.drawText(String.valueOf(mPointerID1) + " " + String.valueOf(mPointerID2), 10, 110, paint); surfaceHolder.unlockCanvasAndPost(canvas); if (System.currentTimeMillis() - start > mp.getDuration()) { thread = null; FragmentTransaction ft = myFragment.getFragmentManager().beginTransaction(); Fragment next = new Fragment2(); ft.replace(R.id.container, next); ft.commit(); } waitTime = (loopCount * FRAME_TIME) - (System.currentTimeMillis() - startTime); if (waitTime > 0) { Thread.sleep(waitTime); } } catch (Exception e) { } } } @Override public boolean onTouchEvent(MotionEvent event) { int eventAction = event.getActionMasked(); int pointerIndex = event.getActionIndex(); pointerId = event.getPointerId(pointerIndex); switch (eventAction) { case MotionEvent.ACTION_DOWN: mPointerID1 = pointerId; mPointerID2 = -1; for (int i = 0; i < 9; i++) { if (panel[i].left <= event.getX() && event.getX() <= panel[i].right && panel[i].top <= event.getY() && event.getY() <= panel[i].bottom) { isTouched[i] = pointerId; sp.play(spid, 1.0F, 1.0F, 0, 0, 1.0F); } } break; case MotionEvent.ACTION_POINTER_DOWN: if (mPointerID2 == -1) { mPointerID2 = pointerId; } else if (mPointerID1 == -1) { mPointerID1 = pointerId; } if (mPointerID1 >= 0) { int ptrIndex = event.findPointerIndex(mPointerID1); x1 = event.getX(ptrIndex); y1 = event.getY(ptrIndex); } if (mPointerID2 >= 0) { int ptrIndex = event.findPointerIndex(mPointerID2); x2 = event.getX(ptrIndex); y2 = event.getY(ptrIndex); } for (int i = 0; i < 9; i++) { if ((panel[i].left <= x1 && x1 <= panel[i].right && panel[i].top <= y1 && y1 <= panel[i].bottom) || (panel[i].left <= x2 && x2 <= panel[i].right && panel[i].top <= y2 && y2 <= panel[i].bottom)) { isTouched[i] = pointerId; sp.play(spid, 1.0F, 1.0F, 0, 0, 1.0F); } } break; case MotionEvent.ACTION_UP: mPointerID1 = -1; mPointerID2 = -1; for (int i = 0; i < 9; i++) { isTouched[i] = -1; } break; case MotionEvent.ACTION_POINTER_UP: if (mPointerID1 == pointerId) { mPointerID1 = -1; } else if (mPointerID2 == pointerId) { mPointerID2 = -1; } for (int i = 0; i < 9; i++) { if (isTouched[i] == pointerId) isTouched[i] = -1; } break; default: break; } return true; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { screen_width = width; screen_height = height; } @Override public void surfaceCreated(SurfaceHolder holder) { thread = new Thread(this); thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { thread = null; mp.stop(); sp.release(); } }
SHIFT_JIS
Java
8,394
java
AnimationSurfaceView.java
Java
[]
null
[]
package com.example.fragmenttest1; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; public class AnimationSurfaceView extends SurfaceView implements Runnable, SurfaceHolder.Callback { static final long FPS = 60; static final long FRAME_TIME = 1000 / FPS; static int RECT_SIDE; SurfaceHolder surfaceHolder; Thread thread; Rect[] panel = new Rect[9]; int[] isTouched = new int[9]; int screen_width, screen_height; MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.fsan1); Context myContext; Fragment myFragment; SoundPool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0); int spid; long time, remaining, offset = -0; long score = 0, score_now = 0; int mPointerID1 = -1, mPointerID2 = -1; int pointerId; float x1 = 0.0f; float y1 = 0.0f; float x2 = 0.0f; float y2 = 0.0f; public AnimationSurfaceView(Context context, Fragment fragment) { super(context); myContext = context; myFragment = fragment; surfaceHolder = getHolder(); surfaceHolder.addCallback(this); } @Override public void run() { for (int i = 0; i < 9; i++) { isTouched[i] = -1; } Canvas canvas = null; Paint paint = new Paint(); Paint bgPaint = new Paint(); Paint rectPaint = new Paint(); Paint rectPaint2 = new Paint(); // Background bgPaint.setStyle(Style.FILL); bgPaint.setColor(Color.WHITE); // Rectangle rectPaint.setStyle(Style.STROKE); rectPaint.setColor(Color.RED); // Rectangle(Touched) rectPaint2.setStyle(Style.FILL); rectPaint2.setColor(Color.RED); long loopCount = 0; long waitTime = 0; long startTime = System.currentTimeMillis(); spid = sp.load(myContext, R.raw.button, 1); Resources res = this.getResources(); InputStream is = res.openRawResource(R.raw.fsan1_n); InputStreamReader isr = null; try { isr = new InputStreamReader(is, "SJIS"); } catch (UnsupportedEncodingException e2) { // TODO 自動生成された catch ブロック e2.printStackTrace(); } BufferedReader br = new BufferedReader(isr); ArrayList<long[]> notes = new ArrayList<long[]>(); String temp0; String[] temp1; long[] temp2 = new long[3]; try { while ((temp0 = br.readLine()) != null) { temp1 = temp0.split(" ", 0); temp2[0] = Long.valueOf(temp1[0]); System.out.println(temp2[0]); temp2[1] = Long.valueOf(temp1[1]); System.out.println(temp2[1]); temp2[2] = 0; notes.add(temp2.clone()); } } catch (IOException e1) { // TODO 自動生成された catch ブロック e1.printStackTrace(); } for (Iterator<long[]> itr = notes.iterator(); itr.hasNext();) { System.out.println(itr.next()[0]); } mp.start(); long start = System.currentTimeMillis(); while (thread != null) { try { loopCount++; canvas = surfaceHolder.lockCanvas(); canvas.drawRect(0, 0, screen_width, screen_height, bgPaint); RECT_SIDE = screen_width / 5; for (Iterator<long[]> itr = notes.iterator(); itr.hasNext();) { long[] temp = itr.next(); remaining = temp[0] - time + offset; int difficulty = 600; if (-200 < remaining && remaining < difficulty && temp[2] == 0) { for (int i = 0; i < 9; i++) { if (isTouched[i] >= 0) { if (i == temp[1]) { temp[2] = 1; score_now = (long) (1000 * (1 - Math.abs(remaining) / (double) difficulty)); score += score_now; break; } } } if (temp[2] == 1) continue; int x0 = (int) (screen_width / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * (temp[1] % 3) + remaining / (difficulty / (double) 45)); int x1 = (int) (x0 + RECT_SIDE - remaining / (difficulty / (double) 90)); int y0 = (int) (screen_height / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * (temp[1] / 3) + remaining / (difficulty / (double) 45)); int y1 = (int) (y0 + RECT_SIDE - remaining / (difficulty / (double) 90)); canvas.drawRect(new Rect(x0, y0, x1, y1), rectPaint); } } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int x = (int) (screen_width / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * j); int y = (int) (screen_height / 2 - RECT_SIDE * 2 + RECT_SIDE * 1.5 * i); panel[i * 3 + j] = new Rect(x, y, x + RECT_SIDE, y + RECT_SIDE); if (isTouched[i * 3 + j] >= 0) { canvas.drawRect(panel[i * 3 + j], rectPaint2); } else { canvas.drawRect(panel[i * 3 + j], rectPaint); } } } time = System.currentTimeMillis() - start; canvas.drawText(String.valueOf(time), 10, 10, paint); canvas.drawText(String.valueOf(score), 10, 30, paint); canvas.drawText(String.valueOf(score_now), 10, 50, paint); canvas.drawText(String.valueOf(pointerId), 10, 70, paint); canvas.drawText( String.valueOf(x1) + " " + String.valueOf(y1) + " " + String.valueOf(x2) + " " + String.valueOf(y2), 10, 90, paint); canvas.drawText(String.valueOf(mPointerID1) + " " + String.valueOf(mPointerID2), 10, 110, paint); surfaceHolder.unlockCanvasAndPost(canvas); if (System.currentTimeMillis() - start > mp.getDuration()) { thread = null; FragmentTransaction ft = myFragment.getFragmentManager().beginTransaction(); Fragment next = new Fragment2(); ft.replace(R.id.container, next); ft.commit(); } waitTime = (loopCount * FRAME_TIME) - (System.currentTimeMillis() - startTime); if (waitTime > 0) { Thread.sleep(waitTime); } } catch (Exception e) { } } } @Override public boolean onTouchEvent(MotionEvent event) { int eventAction = event.getActionMasked(); int pointerIndex = event.getActionIndex(); pointerId = event.getPointerId(pointerIndex); switch (eventAction) { case MotionEvent.ACTION_DOWN: mPointerID1 = pointerId; mPointerID2 = -1; for (int i = 0; i < 9; i++) { if (panel[i].left <= event.getX() && event.getX() <= panel[i].right && panel[i].top <= event.getY() && event.getY() <= panel[i].bottom) { isTouched[i] = pointerId; sp.play(spid, 1.0F, 1.0F, 0, 0, 1.0F); } } break; case MotionEvent.ACTION_POINTER_DOWN: if (mPointerID2 == -1) { mPointerID2 = pointerId; } else if (mPointerID1 == -1) { mPointerID1 = pointerId; } if (mPointerID1 >= 0) { int ptrIndex = event.findPointerIndex(mPointerID1); x1 = event.getX(ptrIndex); y1 = event.getY(ptrIndex); } if (mPointerID2 >= 0) { int ptrIndex = event.findPointerIndex(mPointerID2); x2 = event.getX(ptrIndex); y2 = event.getY(ptrIndex); } for (int i = 0; i < 9; i++) { if ((panel[i].left <= x1 && x1 <= panel[i].right && panel[i].top <= y1 && y1 <= panel[i].bottom) || (panel[i].left <= x2 && x2 <= panel[i].right && panel[i].top <= y2 && y2 <= panel[i].bottom)) { isTouched[i] = pointerId; sp.play(spid, 1.0F, 1.0F, 0, 0, 1.0F); } } break; case MotionEvent.ACTION_UP: mPointerID1 = -1; mPointerID2 = -1; for (int i = 0; i < 9; i++) { isTouched[i] = -1; } break; case MotionEvent.ACTION_POINTER_UP: if (mPointerID1 == pointerId) { mPointerID1 = -1; } else if (mPointerID2 == pointerId) { mPointerID2 = -1; } for (int i = 0; i < 9; i++) { if (isTouched[i] == pointerId) isTouched[i] = -1; } break; default: break; } return true; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { screen_width = width; screen_height = height; } @Override public void surfaceCreated(SurfaceHolder holder) { thread = new Thread(this); thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { thread = null; mp.stop(); sp.release(); } }
8,394
0.628743
0.59988
289
27.896194
22.743864
104
false
false
0
0
0
0
0
0
3.460208
false
false
9
392cd499577371b287dad5f4382e5efb508642ef
17,042,430,269,393
4deae34ce9dd49aaa14386c50ab39159ca8c1ef7
/src/mainlibrary/LibrarianDao.java
7f359c56eccf632659948b8bdad5b822cccefabb
[ "MIT" ]
permissive
ncisectest/spad
https://github.com/ncisectest/spad
83835419d7aad2e644c519b484fa67839f7110cb
170cd5c1341b276635cf5cfd9cba84b7cf67e3b0
refs/heads/master
2022-05-30T02:27:29.373000
2020-05-01T21:24:35
2020-05-01T21:24:35
258,034,564
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package mainlibrary; import java.sql.*; public final class LibrarianDao { public static boolean validate(String name, String password) { boolean status = false; Connection Con = null; PreparedStatement ps = null; ResultSet rs = null; try { Con = DB.getConnection(); ps = Con.prepareStatement("select * from Librarian where UserName=? and Password=?"); ps.setString(1, name); ps.setString(2, password); rs = ps.executeQuery(); status = rs.next(); } catch (Exception e) { java.util.logging.Logger.getLogger(LibrarianDao.class.getName()).log(java.util.logging.Level.SEVERE, null, e); } finally { try { rs.close(); ps.close(); Con.close(); } catch (Exception e) { /* ignored */ } } return status; } }
UTF-8
Java
978
java
LibrarianDao.java
Java
[]
null
[]
package mainlibrary; import java.sql.*; public final class LibrarianDao { public static boolean validate(String name, String password) { boolean status = false; Connection Con = null; PreparedStatement ps = null; ResultSet rs = null; try { Con = DB.getConnection(); ps = Con.prepareStatement("select * from Librarian where UserName=? and Password=?"); ps.setString(1, name); ps.setString(2, password); rs = ps.executeQuery(); status = rs.next(); } catch (Exception e) { java.util.logging.Logger.getLogger(LibrarianDao.class.getName()).log(java.util.logging.Level.SEVERE, null, e); } finally { try { rs.close(); ps.close(); Con.close(); } catch (Exception e) { /* ignored */ } } return status; } }
978
0.51227
0.510225
35
26.942858
25.089489
122
false
false
0
0
0
0
0
0
0.628571
false
false
9
c95196594c89ede99c8b24e27628ab4d5d2be73d
19,481,971,696,170
bd353d736f0580b4e77336bff9fb5d91d2794ed7
/service/src/main/java/com/stackroute/moviecruiserserver/controller/MovieController.java
f5fde73e3d3bccc7bc67688871835326beff2355
[]
no_license
Ayushi-Shukla/movie-cruiser
https://github.com/Ayushi-Shukla/movie-cruiser
4ee5c647e104fd9e029ec99d716f5626859707f8
454fe90ed46b28ff83dd4367d930bfc792257c0c
refs/heads/master
2023-01-07T19:53:14.987000
2019-12-27T11:46:27
2019-12-27T11:46:27
230,433,772
0
0
null
false
2023-01-06T00:56:27
2019-12-27T11:42:08
2019-12-27T11:46:47
2023-01-06T00:56:24
822
0
0
29
TypeScript
false
false
package com.stackroute.moviecruiserserver.controller; import java.util.*; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; import com.stackroute.moviecruiserserver.domain.*; import com.stackroute.moviecruiserserver.exception.*; import com.stackroute.moviecruiserserver.service.*; import io.jsonwebtoken.Jwts; @CrossOrigin @RestController @RequestMapping("/api/v1/movieservice") public class MovieController { @Autowired private MovieService movieservice; //< - - Save Method - - > @PostMapping("/movie") public ResponseEntity<?> saveNewMovie(@RequestBody Movie movie, HttpServletRequest request,HttpServletRequest response){ System.out.println("Saving movie"); String authHeader=request.getHeader("authorization"); String token=authHeader.substring(7); String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject(); System.out.println("userId: "+userId); try{ System.out.println(movie.getMovieId()); movie.setUserId(userId); movie.setMovieId(movie.getMovieId()); movieservice.saveMovie(movie); } catch(MovieAlreadyExistsException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.CONFLICT); } return new ResponseEntity<Movie>(movie,HttpStatus.CREATED); } @PutMapping("/movie") public ResponseEntity<?> updateMovie(@RequestBody Movie movie){ Movie fetchedMovie; try{ fetchedMovie=movieservice.updateMovie( movie); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<Movie>(fetchedMovie,HttpStatus.OK); } @DeleteMapping("/movie/{id}") public ResponseEntity<?> deleteMovie(@PathVariable("id") int id){ try{ movieservice.deleteMovieById(id); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<String>("Movie deleted successfully",HttpStatus.OK); } @GetMapping("/movie/{id}") public ResponseEntity<?> getMovie(@PathVariable("id") int id){ Movie thisMovie; try{ thisMovie=movieservice.getMovieById(id); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<Movie>(thisMovie, HttpStatus.OK); } @GetMapping("/movies") public @ResponseBody ResponseEntity<List<Movie>> getMyMovies(ServletRequest req, ServletResponse res){ HttpServletRequest request=(HttpServletRequest) req; String authHeader=request.getHeader("authorization"); String token=authHeader.substring(7); String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject(); return new ResponseEntity<List<Movie>>(movieservice.getMyMovies(userId),HttpStatus.OK); } }
UTF-8
Java
3,016
java
MovieController.java
Java
[]
null
[]
package com.stackroute.moviecruiserserver.controller; import java.util.*; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; import com.stackroute.moviecruiserserver.domain.*; import com.stackroute.moviecruiserserver.exception.*; import com.stackroute.moviecruiserserver.service.*; import io.jsonwebtoken.Jwts; @CrossOrigin @RestController @RequestMapping("/api/v1/movieservice") public class MovieController { @Autowired private MovieService movieservice; //< - - Save Method - - > @PostMapping("/movie") public ResponseEntity<?> saveNewMovie(@RequestBody Movie movie, HttpServletRequest request,HttpServletRequest response){ System.out.println("Saving movie"); String authHeader=request.getHeader("authorization"); String token=authHeader.substring(7); String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject(); System.out.println("userId: "+userId); try{ System.out.println(movie.getMovieId()); movie.setUserId(userId); movie.setMovieId(movie.getMovieId()); movieservice.saveMovie(movie); } catch(MovieAlreadyExistsException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.CONFLICT); } return new ResponseEntity<Movie>(movie,HttpStatus.CREATED); } @PutMapping("/movie") public ResponseEntity<?> updateMovie(@RequestBody Movie movie){ Movie fetchedMovie; try{ fetchedMovie=movieservice.updateMovie( movie); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<Movie>(fetchedMovie,HttpStatus.OK); } @DeleteMapping("/movie/{id}") public ResponseEntity<?> deleteMovie(@PathVariable("id") int id){ try{ movieservice.deleteMovieById(id); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<String>("Movie deleted successfully",HttpStatus.OK); } @GetMapping("/movie/{id}") public ResponseEntity<?> getMovie(@PathVariable("id") int id){ Movie thisMovie; try{ thisMovie=movieservice.getMovieById(id); } catch(MovieNotFoundException e){ return new ResponseEntity<String>(e.getMessage(),HttpStatus.NOT_FOUND); } return new ResponseEntity<Movie>(thisMovie, HttpStatus.OK); } @GetMapping("/movies") public @ResponseBody ResponseEntity<List<Movie>> getMyMovies(ServletRequest req, ServletResponse res){ HttpServletRequest request=(HttpServletRequest) req; String authHeader=request.getHeader("authorization"); String token=authHeader.substring(7); String userId=Jwts.parser().setSigningKey("secretkey").parseClaimsJws(token).getBody().getSubject(); return new ResponseEntity<List<Movie>>(movieservice.getMyMovies(userId),HttpStatus.OK); } }
3,016
0.765584
0.764589
95
30.747368
27.673651
103
false
false
0
0
0
0
0
0
1.905263
false
false
9
a5308d8ca6b622a4715ad60cf5bbbc66944add8e
7,653,631,766,713
799456023524d45a7c759fe4f5110364b85e31fc
/src/main/java/nacgroup/monoservice/server/repositories/ActivityTypeRepository.java
a8cf43641b72d0e40630251a453f2aa60581d373
[ "MIT" ]
permissive
MHAN001/NACGroup
https://github.com/MHAN001/NACGroup
3eb60fd27002aaafda67bbaed2269ac5f6277bac
f925bc82a140afcd21acc30899eb3544da0d95d9
refs/heads/master
2022-11-15T10:26:40.551000
2020-07-01T03:44:21
2020-07-01T03:44:21
272,576,213
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package nacgroup.monoservice.server.repositories; import nacgroup.monoservice.server.objects.ActivityType; import org.springframework.data.repository.CrudRepository; public interface ActivityTypeRepository extends CrudRepository<ActivityType, Long> { }
UTF-8
Java
255
java
ActivityTypeRepository.java
Java
[]
null
[]
package nacgroup.monoservice.server.repositories; import nacgroup.monoservice.server.objects.ActivityType; import org.springframework.data.repository.CrudRepository; public interface ActivityTypeRepository extends CrudRepository<ActivityType, Long> { }
255
0.862745
0.862745
7
35.42857
32.008289
84
false
false
0
0
0
0
0
0
0.571429
false
false
9
b8c48273ef396204734bee0adfe8647f90f5f819
12,927,851,607,863
21f8ccf607fd6269af377baef6f4f00a862db817
/src/Blackjack2/Welcome.java
79a980af024861f9f43cb9d21de1d411fb5085f0
[]
no_license
sethurbach/Blackjack
https://github.com/sethurbach/Blackjack
dfe178064923a9bc8f863adf1104d95dc2665bcd
4a681538b01b7222f61e14ee59bb6f8ff762528d
refs/heads/master
2021-01-20T20:36:39.832000
2016-06-08T14:10:20
2016-06-08T14:10:20
60,702,970
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/* * 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 Blackjack2; import static Blackjack2.Data.*; /** * * @author sethurbach */ public class Welcome { public static void Welcome() { System.out.println("Welcome To Blackjack!"); System.out.println("\nDo You Know How To Play?"); input1 = user.next(); while (!input1.equalsIgnoreCase(n)) { if (input1.equalsIgnoreCase(no)) { break; } else if (input1.equalsIgnoreCase(y)) { break; } else if (input1.equalsIgnoreCase(yes)) { break; } else { System.out.println("\nPlease Type yes/no Or y/n"); input1 = user.next(); } } if (input1.equalsIgnoreCase(n) || input1.equalsIgnoreCase(no)) { System.out.println("\nHere Are The Rules:"); System.out.println("1. The Goal Of The Game Is To Have A Bigger Sum Of Cards Than The Dealer, Without Going Over 21."); System.out.println("2. You And The Dealer Both Start With Two Cards."); System.out.println("3. At All Times, You Can See One And Only One Of The Dealers Cards."); System.out.println("4. You Can Draw Cards To Try To Beat The Dealer And/Or Get Closer To 21."); System.out.println("5. Kings, Queens, And Jacks Are All 10."); System.out.println("6. Aces Can Be Either 1 Or 11 And You Can Change What You Want Later To Fit Your Needs"); System.out.println("7. When You're Done Drawing, The Dealer Will Draw Until He's Done (Hits 17 Or Over)."); System.out.println("\nType Anything To Continue:"); input1 = user.next(); } } }
UTF-8
Java
1,924
java
Welcome.java
Java
[ { "context": "t static Blackjack2.Data.*;\r\n\r\n/**\r\n *\r\n * @author sethurbach\r\n */\r\npublic class Welcome {\r\n public static v", "end": 279, "score": 0.993969738483429, "start": 269, "tag": "USERNAME", "value": "sethurbach" }, { "context": "ackjack2.Data.*;\r\n\r\n/**\r\n *\r\n * @author sethurbach\r\n */\r\npublic class Welcome {\r\n public static voi", "end": 279, "score": 0.556057870388031, "start": 279, "tag": "NAME", "value": "" } ]
null
[]
/* * 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 Blackjack2; import static Blackjack2.Data.*; /** * * @author sethurbach */ public class Welcome { public static void Welcome() { System.out.println("Welcome To Blackjack!"); System.out.println("\nDo You Know How To Play?"); input1 = user.next(); while (!input1.equalsIgnoreCase(n)) { if (input1.equalsIgnoreCase(no)) { break; } else if (input1.equalsIgnoreCase(y)) { break; } else if (input1.equalsIgnoreCase(yes)) { break; } else { System.out.println("\nPlease Type yes/no Or y/n"); input1 = user.next(); } } if (input1.equalsIgnoreCase(n) || input1.equalsIgnoreCase(no)) { System.out.println("\nHere Are The Rules:"); System.out.println("1. The Goal Of The Game Is To Have A Bigger Sum Of Cards Than The Dealer, Without Going Over 21."); System.out.println("2. You And The Dealer Both Start With Two Cards."); System.out.println("3. At All Times, You Can See One And Only One Of The Dealers Cards."); System.out.println("4. You Can Draw Cards To Try To Beat The Dealer And/Or Get Closer To 21."); System.out.println("5. Kings, Queens, And Jacks Are All 10."); System.out.println("6. Aces Can Be Either 1 Or 11 And You Can Change What You Want Later To Fit Your Needs"); System.out.println("7. When You're Done Drawing, The Dealer Will Draw Until He's Done (Hits 17 Or Over)."); System.out.println("\nType Anything To Continue:"); input1 = user.next(); } } }
1,924
0.581601
0.566528
44
41.772728
35.605709
131
false
false
0
0
0
0
0
0
0.681818
false
false
9
319d10a83d6c7c6d4a3053f4f8a9f505b7dc51f5
12,927,851,605,364
7df85c6c3477e52413ba7e1615c51a2bd5987827
/thread-practice/src/main/java/cn/chap8/HeaderTextProcessing.java
5303b58d88da9032ca604e0c353b9711a77cf17f
[]
no_license
hjy628/test
https://github.com/hjy628/test
17f949b28077d82b577096e465a23bffb7eacdde
89379c17a84aecadb1d44a6afb2766d26430d437
refs/heads/master
2022-06-23T06:17:54.031000
2019-12-03T07:29:15
2019-12-03T07:29:15
53,647,728
1
2
null
false
2022-06-21T00:47:02
2016-03-11T07:20:26
2020-10-29T02:56:24
2022-06-21T00:46:59
11,168
1
2
4
Java
false
false
package cn.chap8; /** * Created by hjy on 17-2-8. */ public class HeaderTextProcessing extends ProcessingObject<String>{ @Override protected String handleWork(String input) { return "From Raoul,Mario and ALan: "+input; } }
UTF-8
Java
246
java
HeaderTextProcessing.java
Java
[ { "context": "package cn.chap8;\n\n/**\n * Created by hjy on 17-2-8.\n */\npublic class HeaderTextProcessing ", "end": 40, "score": 0.9995718002319336, "start": 37, "tag": "USERNAME", "value": "hjy" }, { "context": "ng handleWork(String input) {\n return \"From Raoul,Mario and ALan: \"+input;\n }\n}\n", "end": 212, "score": 0.9818561673164368, "start": 207, "tag": "NAME", "value": "Raoul" }, { "context": "leWork(String input) {\n return \"From Raoul,Mario and ALan: \"+input;\n }\n}\n", "end": 218, "score": 0.9936041235923767, "start": 213, "tag": "NAME", "value": "Mario" }, { "context": "ring input) {\n return \"From Raoul,Mario and ALan: \"+input;\n }\n}\n", "end": 227, "score": 0.970339834690094, "start": 223, "tag": "NAME", "value": "ALan" } ]
null
[]
package cn.chap8; /** * Created by hjy on 17-2-8. */ public class HeaderTextProcessing extends ProcessingObject<String>{ @Override protected String handleWork(String input) { return "From Raoul,Mario and ALan: "+input; } }
246
0.682927
0.662602
11
21.363636
22.491505
67
false
false
0
0
0
0
0
0
0.272727
false
false
9
b66232d805c86d0abef9c8d6a2ae8069afab22d7
541,165,946,443
49048765d3c7c7228a8c0089735e155e982f699f
/src/main/java/com/telrikk/elasticnotes/actions/AbstractNoResultAction.java
b6a30be71e6c4481321f198dc15619f674901e36
[]
no_license
telrikk/elastic-notes
https://github.com/telrikk/elastic-notes
eb6a7abaa094cfd289aa3d00275a82cb366b63fe
67788312605b7f8cf8c6a55a97831a2893b9a69e
refs/heads/master
2017-12-02T13:34:10.828000
2013-12-30T06:37:23
2013-12-30T06:37:23
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.telrikk.elasticnotes.actions; public abstract class AbstractNoResultAction { }
UTF-8
Java
93
java
AbstractNoResultAction.java
Java
[]
null
[]
package com.telrikk.elasticnotes.actions; public abstract class AbstractNoResultAction { }
93
0.827957
0.827957
5
17.6
21.209433
46
false
false
0
0
0
0
0
0
0.2
false
false
9
dd9a518f4f44f9f15acba1ba3097298f275bcb44
18,219,251,303,953
3a660a6557c03d1ca44d83d7558196fd5ae995b6
/src/bank/customer/PrivateCustomer.java
2a761daf14689e7b9aa1630870712cb86a32619b
[]
no_license
leonidkiritschenko/Bank
https://github.com/leonidkiritschenko/Bank
6426a63a819e04941a3248e6a311104148af0477
07a372fb758d3d61499afbf6d97a6c61d0f4c815
refs/heads/master
2020-08-30T12:16:14.117000
2019-11-08T11:07:05
2019-11-08T11:07:05
218,377,911
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package bank.customer; import bank.address.Address; import java.time.LocalDate; /** * PrivateCustomer is a value class. * Customer number will be assigned automatically, starts with "F" and is unique. */ public class PrivateCustomer extends Customer { private static int customerNumberCounter = 1001; private String customerNumber; private String firstName; private String lastName; private LocalDate birthday; public PrivateCustomer(String firstName, String lastName, String telefon, String email, LocalDate birthday, Address address) { super(telefon, email, address); this.customerNumber = "P" + customerNumberCounter++; this.firstName = firstName; this.lastName = lastName; this.birthday = birthday; } public PrivateCustomer(PrivateCustomer privateCustomer) { super(privateCustomer.getPhone(), privateCustomer.getEmail(), privateCustomer.getAddress()); this.customerNumber = privateCustomer.customerNumber; this.firstName = privateCustomer.firstName; this.lastName = privateCustomer.lastName; this.birthday = privateCustomer.birthday; } public String getCustomernumber() { return customerNumber; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public LocalDate getBirthday() { return birthday; } }
UTF-8
Java
1,381
java
PrivateCustomer.java
Java
[ { "context": "calDate birthday;\n\n public PrivateCustomer(String firstName, String lastName, String telefon, String email, L", "end": 468, "score": 0.7088603377342224, "start": 459, "tag": "NAME", "value": "firstName" }, { "context": "\n public PrivateCustomer(String firstName, String lastName, String telefon, String email, LocalDate birthday", "end": 485, "score": 0.6745234131813049, "start": 477, "tag": "NAME", "value": "lastName" }, { "context": "P\" + customerNumberCounter++;\n this.firstName = firstName;\n this.lastName = lastName;\n this.birthday ", "end": 704, "score": 0.9981217980384827, "start": 695, "tag": "NAME", "value": "firstName" }, { "context": " this.firstName = firstName;\n this.lastName = lastName;\n this.birthday = birthday;\n }\n\n public Priv", "end": 734, "score": 0.998415470123291, "start": 726, "tag": "NAME", "value": "lastName" }, { "context": ";\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public String getLastName() {\n return ", "end": 1254, "score": 0.7582417726516724, "start": 1245, "tag": "NAME", "value": "firstName" }, { "context": "e;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public LocalDate getBirthday() {\n retu", "end": 1312, "score": 0.5512639880180359, "start": 1304, "tag": "NAME", "value": "lastName" } ]
null
[]
package bank.customer; import bank.address.Address; import java.time.LocalDate; /** * PrivateCustomer is a value class. * Customer number will be assigned automatically, starts with "F" and is unique. */ public class PrivateCustomer extends Customer { private static int customerNumberCounter = 1001; private String customerNumber; private String firstName; private String lastName; private LocalDate birthday; public PrivateCustomer(String firstName, String lastName, String telefon, String email, LocalDate birthday, Address address) { super(telefon, email, address); this.customerNumber = "P" + customerNumberCounter++; this.firstName = firstName; this.lastName = lastName; this.birthday = birthday; } public PrivateCustomer(PrivateCustomer privateCustomer) { super(privateCustomer.getPhone(), privateCustomer.getEmail(), privateCustomer.getAddress()); this.customerNumber = privateCustomer.customerNumber; this.firstName = privateCustomer.firstName; this.lastName = privateCustomer.lastName; this.birthday = privateCustomer.birthday; } public String getCustomernumber() { return customerNumber; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public LocalDate getBirthday() { return birthday; } }
1,381
0.731354
0.728458
49
27.183674
25.178282
109
false
false
0
0
0
0
0
0
0.653061
false
false
9
4c28098ca5f7db02e53a995b47a879e97cdba04e
31,748,398,271,489
3657b6f5b30ac061e2ab1db7cd745e2ca8183af3
/homeProject/src/com/house/framework/web/controller/KindeditorController.java
b2b4d1c6b012aafc084de4736fa0adbef0599fd2
[]
no_license
Lxt000806/eclipse_workspace
https://github.com/Lxt000806/eclipse_workspace
b25f4f81bd0aa6f8d55fc834dd09cdb473af1f3f
04376681ec91c3f8dbde2908d35612c4842a868c
refs/heads/main
2023-05-23T12:05:26.989000
2021-06-13T05:49:26
2021-06-13T05:49:26
376,452,726
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.house.framework.web.controller; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import com.house.framework.commons.cache.DictCacheUtil; import com.house.framework.commons.conf.DictConstant; @Controller @RequestMapping("/admin/kindeditor") public class KindeditorController { private static final Logger logger = LoggerFactory.getLogger(KindeditorController.class); private static final String PARAM_DIR = "dir"; private HashMap<String, String> extMap = new HashMap<String, String>(); public KindeditorController(){ extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); } @RequestMapping("/kindeditor_demo") public ModelAndView kindeditorDemo(HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("widget/kindeditor_demo"); } @RequestMapping("/upload_json") public void uploadJson(HttpServletRequest request, HttpServletResponse response) { String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL); //文件保存目录路径 String savePath = request.getSession().getServletContext().getRealPath("/") + uploadRoot; savePath = savePath.replaceAll("\\\\", "/").replaceAll("//", "/"); //文件保存目录URL String saveUrl = request.getContextPath() + File.separator + uploadRoot; if(!ServletFileUpload.isMultipartContent(request)){ flushResult(request, response, getError("请选择文件。") ); return; } //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ flushResult(request, response, getError("上传目录不存在。") ); return; } //检查目录写权限 if(!uploadDir.canWrite()){ flushResult(request, response, getError("上传目录没有写权限。") ); return; } //取得上传文件类型, 即构造四种类型 String dirName = request.getParameter(PARAM_DIR); if(!extMap.containsKey(dirName)){ flushResult(request, response, getError("文件类型不正确。") ); return; } // //创建文件夹 // savePath += dirName + File.separator; // saveUrl += dirName + File.separator; uploadFile(request, response, savePath, saveUrl); } @RequestMapping("/file_manager_json") @SuppressWarnings("unchecked") public void fileManagerJson(HttpServletRequest request, HttpServletResponse response){ String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL ); //文件保存目录路径 String rootPath = request.getSession().getServletContext().getRealPath("/") + uploadRoot; rootPath = rootPath.replaceAll("\\\\", "/").replaceAll("//", "/"); //文件保存目录URL String rootUrl = request.getContextPath() + "/" + uploadRoot; rootUrl = rootUrl.replaceAll("//", "/"); //图片扩展名 String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"}; //上传文件类型 String dirName = request.getParameter(PARAM_DIR); if (dirName != null) { if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){ flushResult(request, response, "Invalid Directory name."); return; } rootPath += dirName + "/"; rootUrl += dirName + "/"; File saveDirFile = new File(rootPath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } } //根据path参数,设置各路径和URL String path = request.getParameter("path") != null ? request.getParameter("path") : ""; String currentPath = rootPath + path; String currentUrl = rootUrl + path; String currentDirPath = path; String moveupDirPath = "";//上一级路径 if (!"".equals(path)) { String str = currentDirPath.substring(0, currentDirPath.length() - 1); moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : ""; } //排序形式,name or size or type String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name"; //不允许使用..移动到上一级目录 if (path.indexOf("..") >= 0) { flushResult(request, response, "Access is not allowed."); return; } //最后一个字符不是/ if (!"".equals(path) && !path.endsWith("/")) { flushResult(request, response, "Parameter is not valid."); return; } //目录不存在或不是目录 File currentPathFile = new File(currentPath); if(!currentPathFile.isDirectory()){ flushResult(request, response, "Directory does not exist."); return; } //遍历目录取的文件信息 List<Hashtable<String, ?>> fileList = new ArrayList<Hashtable<String, ?>>(); if(currentPathFile.listFiles() != null) { for (File file : currentPathFile.listFiles()) { Hashtable<String, Object> hash = new Hashtable<String, Object>(); String fileName = file.getName(); if(file.isDirectory()) { hash.put("is_dir", true); hash.put("has_file", (file.listFiles() != null)); hash.put("filesize", 0L); hash.put("is_photo", false); hash.put("filetype", ""); } else if(file.isFile()){ String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.length()); hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt)); hash.put("filetype", fileExt); } hash.put("filename", fileName); hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified())); fileList.add(hash); } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator()); } else { Collections.sort(fileList, new NameComparator()); } JSONObject result = new JSONObject(); result.put("moveup_dir_path", moveupDirPath); result.put("current_dir_path", currentDirPath); result.put("current_url", currentUrl); result.put("total_count", fileList.size()); result.put("file_list", fileList); response.setContentType("application/json; charset=UTF-8"); flushResult(request, response, result.toJSONString()); } /** * 上传文件 * @param request * @param response * @param savePath * @param saveUrl */ private void uploadFile(HttpServletRequest request, HttpServletResponse response, String savePath, String saveUrl) { // 转型为MultipartHttpRequest: MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 遍历所有文件域,获得上传的文件, 针对kindeditor 上传附件, 只支持上传一个,因此for循环一次 for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) { String key = (String) it.next(); MultipartFile file = multipartRequest.getFile(key); saveFile(request, response, file, savePath, saveUrl); } } @SuppressWarnings("unused") private void saveFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file, String savePath, String saveUrl) { if (file == null || file.isEmpty())return; String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL); //创建上传当天文件夹 String ymd = DateFormatUtils.format(new Date(), "yyyyMMdd"); savePath += ymd + File.separator; saveUrl += ymd + File.separator; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //获取上传文件类型 String dirName = request.getParameter(PARAM_DIR); if (dirName == null) { dirName = "image"; } //检查扩展名 String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){ flushResult(request, response, getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。") ); return; } //创建文件 String newFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_" + new Random().nextInt(1000) + "." + fileExt; saveUrl = saveUrl.replaceAll("\\\\", "/").replaceAll("//", "/"); try{ File uploadedFile = new File(savePath, newFileName); file.transferTo(uploadedFile); flushResult(request, response, getSuccess(saveUrl, newFileName)); }catch(Exception e){ e.printStackTrace(); flushResult(request, response, getError("上传文件失败。") ); } } /** * 将用户数据返回给相应的客服端请求ajax页面 * @param response * @param str */ private void flushResult(HttpServletRequest request, HttpServletResponse response, String str){ setDisableCacheHeader(response); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); logger.debug("用户数据返回: [ {} ]", str); out.print(str); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ if(null != out){ out.close(); } } } /** * 设置禁止客户端缓存的Header. */ private void setDisableCacheHeader(HttpServletResponse response) { //Http 1.0 header response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); //Http 1.1 header response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); } /** * 失败返回错误信息 * @param message * @return */ private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } /** * 成功后返回信息 * @param saveUrl * @param newFileName * @return */ private String getSuccess(String saveUrl, String newFileName) { JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url",saveUrl+newFileName); return obj.toJSONString(); } } @SuppressWarnings("rawtypes") class NameComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename")); } } } @SuppressWarnings({ "rawtypes" }) class SizeComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) { return 1; } else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) { return -1; } else { return 0; } } } } @SuppressWarnings("rawtypes") class TypeComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype")); } } }
UTF-8
Java
12,654
java
KindeditorController.java
Java
[ { "context": "es(); it.hasNext();) {\n\t\t\tString key = (String) it.next();\n\t\t\tMultipartFile file = multipartRequest.getFi", "end": 7498, "score": 0.6410726308822632, "start": 7494, "tag": "KEY", "value": "next" } ]
null
[]
package com.house.framework.web.controller; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.time.DateFormatUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.alibaba.fastjson.JSONObject; import com.house.framework.commons.cache.DictCacheUtil; import com.house.framework.commons.conf.DictConstant; @Controller @RequestMapping("/admin/kindeditor") public class KindeditorController { private static final Logger logger = LoggerFactory.getLogger(KindeditorController.class); private static final String PARAM_DIR = "dir"; private HashMap<String, String> extMap = new HashMap<String, String>(); public KindeditorController(){ extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); } @RequestMapping("/kindeditor_demo") public ModelAndView kindeditorDemo(HttpServletRequest request, HttpServletResponse response){ return new ModelAndView("widget/kindeditor_demo"); } @RequestMapping("/upload_json") public void uploadJson(HttpServletRequest request, HttpServletResponse response) { String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL); //文件保存目录路径 String savePath = request.getSession().getServletContext().getRealPath("/") + uploadRoot; savePath = savePath.replaceAll("\\\\", "/").replaceAll("//", "/"); //文件保存目录URL String saveUrl = request.getContextPath() + File.separator + uploadRoot; if(!ServletFileUpload.isMultipartContent(request)){ flushResult(request, response, getError("请选择文件。") ); return; } //检查目录 File uploadDir = new File(savePath); if(!uploadDir.isDirectory()){ flushResult(request, response, getError("上传目录不存在。") ); return; } //检查目录写权限 if(!uploadDir.canWrite()){ flushResult(request, response, getError("上传目录没有写权限。") ); return; } //取得上传文件类型, 即构造四种类型 String dirName = request.getParameter(PARAM_DIR); if(!extMap.containsKey(dirName)){ flushResult(request, response, getError("文件类型不正确。") ); return; } // //创建文件夹 // savePath += dirName + File.separator; // saveUrl += dirName + File.separator; uploadFile(request, response, savePath, saveUrl); } @RequestMapping("/file_manager_json") @SuppressWarnings("unchecked") public void fileManagerJson(HttpServletRequest request, HttpServletResponse response){ String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL ); //文件保存目录路径 String rootPath = request.getSession().getServletContext().getRealPath("/") + uploadRoot; rootPath = rootPath.replaceAll("\\\\", "/").replaceAll("//", "/"); //文件保存目录URL String rootUrl = request.getContextPath() + "/" + uploadRoot; rootUrl = rootUrl.replaceAll("//", "/"); //图片扩展名 String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp"}; //上传文件类型 String dirName = request.getParameter(PARAM_DIR); if (dirName != null) { if(!Arrays.<String>asList(new String[]{"image", "flash", "media", "file"}).contains(dirName)){ flushResult(request, response, "Invalid Directory name."); return; } rootPath += dirName + "/"; rootUrl += dirName + "/"; File saveDirFile = new File(rootPath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } } //根据path参数,设置各路径和URL String path = request.getParameter("path") != null ? request.getParameter("path") : ""; String currentPath = rootPath + path; String currentUrl = rootUrl + path; String currentDirPath = path; String moveupDirPath = "";//上一级路径 if (!"".equals(path)) { String str = currentDirPath.substring(0, currentDirPath.length() - 1); moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : ""; } //排序形式,name or size or type String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name"; //不允许使用..移动到上一级目录 if (path.indexOf("..") >= 0) { flushResult(request, response, "Access is not allowed."); return; } //最后一个字符不是/ if (!"".equals(path) && !path.endsWith("/")) { flushResult(request, response, "Parameter is not valid."); return; } //目录不存在或不是目录 File currentPathFile = new File(currentPath); if(!currentPathFile.isDirectory()){ flushResult(request, response, "Directory does not exist."); return; } //遍历目录取的文件信息 List<Hashtable<String, ?>> fileList = new ArrayList<Hashtable<String, ?>>(); if(currentPathFile.listFiles() != null) { for (File file : currentPathFile.listFiles()) { Hashtable<String, Object> hash = new Hashtable<String, Object>(); String fileName = file.getName(); if(file.isDirectory()) { hash.put("is_dir", true); hash.put("has_file", (file.listFiles() != null)); hash.put("filesize", 0L); hash.put("is_photo", false); hash.put("filetype", ""); } else if(file.isFile()){ String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); hash.put("is_dir", false); hash.put("has_file", false); hash.put("filesize", file.length()); hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt)); hash.put("filetype", fileExt); } hash.put("filename", fileName); hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified())); fileList.add(hash); } } if ("size".equals(order)) { Collections.sort(fileList, new SizeComparator()); } else if ("type".equals(order)) { Collections.sort(fileList, new TypeComparator()); } else { Collections.sort(fileList, new NameComparator()); } JSONObject result = new JSONObject(); result.put("moveup_dir_path", moveupDirPath); result.put("current_dir_path", currentDirPath); result.put("current_url", currentUrl); result.put("total_count", fileList.size()); result.put("file_list", fileList); response.setContentType("application/json; charset=UTF-8"); flushResult(request, response, result.toJSONString()); } /** * 上传文件 * @param request * @param response * @param savePath * @param saveUrl */ private void uploadFile(HttpServletRequest request, HttpServletResponse response, String savePath, String saveUrl) { // 转型为MultipartHttpRequest: MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 遍历所有文件域,获得上传的文件, 针对kindeditor 上传附件, 只支持上传一个,因此for循环一次 for (Iterator<String> it = multipartRequest.getFileNames(); it.hasNext();) { String key = (String) it.next(); MultipartFile file = multipartRequest.getFile(key); saveFile(request, response, file, savePath, saveUrl); } } @SuppressWarnings("unused") private void saveFile(HttpServletRequest request, HttpServletResponse response, MultipartFile file, String savePath, String saveUrl) { if (file == null || file.isEmpty())return; String uploadRoot = DictCacheUtil.getItemValue(DictConstant.ABSTRACT_DICT_UPLOAD_URL, DictConstant.DICT_KINDEDITOR_UPLOAD_URL); //创建上传当天文件夹 String ymd = DateFormatUtils.format(new Date(), "yyyyMMdd"); savePath += ymd + File.separator; saveUrl += ymd + File.separator; File dirFile = new File(savePath); if (!dirFile.exists()) { dirFile.mkdirs(); } //获取上传文件类型 String dirName = request.getParameter(PARAM_DIR); if (dirName == null) { dirName = "image"; } //检查扩展名 String fileName = file.getOriginalFilename(); String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); if(!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)){ flushResult(request, response, getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。") ); return; } //创建文件 String newFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_" + new Random().nextInt(1000) + "." + fileExt; saveUrl = saveUrl.replaceAll("\\\\", "/").replaceAll("//", "/"); try{ File uploadedFile = new File(savePath, newFileName); file.transferTo(uploadedFile); flushResult(request, response, getSuccess(saveUrl, newFileName)); }catch(Exception e){ e.printStackTrace(); flushResult(request, response, getError("上传文件失败。") ); } } /** * 将用户数据返回给相应的客服端请求ajax页面 * @param response * @param str */ private void flushResult(HttpServletRequest request, HttpServletResponse response, String str){ setDisableCacheHeader(response); response.setContentType("text/html; charset=UTF-8"); PrintWriter out = null; try { out = response.getWriter(); logger.debug("用户数据返回: [ {} ]", str); out.print(str); out.flush(); } catch (IOException e) { e.printStackTrace(); }finally{ if(null != out){ out.close(); } } } /** * 设置禁止客户端缓存的Header. */ private void setDisableCacheHeader(HttpServletResponse response) { //Http 1.0 header response.setDateHeader("Expires", 1L); response.addHeader("Pragma", "no-cache"); //Http 1.1 header response.setHeader("Cache-Control", "no-cache, no-store, max-age=0"); } /** * 失败返回错误信息 * @param message * @return */ private String getError(String message) { JSONObject obj = new JSONObject(); obj.put("error", 1); obj.put("message", message); return obj.toJSONString(); } /** * 成功后返回信息 * @param saveUrl * @param newFileName * @return */ private String getSuccess(String saveUrl, String newFileName) { JSONObject obj = new JSONObject(); obj.put("error", 0); obj.put("url",saveUrl+newFileName); return obj.toJSONString(); } } @SuppressWarnings("rawtypes") class NameComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename")); } } } @SuppressWarnings({ "rawtypes" }) class SizeComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) { return 1; } else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) { return -1; } else { return 0; } } } } @SuppressWarnings("rawtypes") class TypeComparator implements Comparator { public int compare(Object a, Object b) { Hashtable hashA = (Hashtable)a; Hashtable hashB = (Hashtable)b; if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) { return -1; } else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) { return 1; } else { return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype")); } } }
12,654
0.687053
0.683979
383
30.420366
28.520769
135
false
false
0
0
0
0
0
0
2.689295
false
false
9
74aa473311e05123db58e290664ebeb6596858c6
29,901,562,317,532
0b6aa5586caf78dad8a00b4ca8c30b1a429031f6
/java9/src/com/myLibrary/test/testDBS.java
666b554aaff7f02e36238f2de1b14a6427af3f5c
[]
no_license
weiye-Lee/myUniverse
https://github.com/weiye-Lee/myUniverse
d1e2e253fbd7abb8a4e2ffcd89d5fc24d664ef6a
bff9bb69a4a73a9a22ed25fd5377b6572c65181d
refs/heads/master
2022-12-19T11:57:20.004000
2020-09-20T10:34:00
2020-09-20T10:34:00
268,029,041
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.myLibrary.test; import com.myLibrary.database.Database; /* * 测试Database * */ public class testDBS { public static void main(String[] args) { Database.getLibraryBooks().get(0).setBorrowPerson("lalala"); Database.getLibraryBooks() .forEach(a -> System.out.println(a.getBorrowPerson())); } }
UTF-8
Java
359
java
testDBS.java
Java
[]
null
[]
package com.myLibrary.test; import com.myLibrary.database.Database; /* * 测试Database * */ public class testDBS { public static void main(String[] args) { Database.getLibraryBooks().get(0).setBorrowPerson("lalala"); Database.getLibraryBooks() .forEach(a -> System.out.println(a.getBorrowPerson())); } }
359
0.63662
0.633803
13
25.307692
23.78553
71
false
false
0
0
0
0
0
0
0.307692
false
false
9
8c4e142c4d333bba519dd48e1953db47204284d9
14,147,622,295,307
1f745c04f437f90a7dbc84ce9c44d1e008fa3124
/src/bsh/ClassGeneratorUtil.java
ea41dfb3390100c9c93c64dcbbaa5a1ea885205f
[ "Apache-2.0", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "SPL-1.0" ]
permissive
jessepav/beanshell
https://github.com/jessepav/beanshell
70ddfecc38bd2594385db80e3f976ba6de8aa117
22ae11c05a59edff7bc7edb1b77283cdc652a775
refs/heads/v2
2022-05-20T00:25:26.968000
2022-04-09T16:51:24
2022-04-09T16:51:24
334,516,617
0
0
Apache-2.0
true
2021-04-23T22:28:39
2021-01-30T21:37:34
2021-01-30T21:37:36
2021-04-23T22:28:37
6,227
0
0
0
null
false
false
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * 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 file is part of the BeanShell Java Scripting distribution. * * Documentation and updates may be found at http://www.beanshell.org/ * * Patrick Niemeyer (pat@pat.net) * * Author of Learning Java, O'Reilly & Associates * * * *****************************************************************************/ package bsh; import bsh.org.objectweb.asm.*; import bsh.org.objectweb.asm.Type; import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; /** * ClassGeneratorUtil utilizes the ASM (www.objectweb.org) bytecode generator * by Eric Bruneton in order to generate class "stubs" for BeanShell at * runtime. * <p/> * <p/> * Stub classes contain all of the fields of a BeanShell scripted class * as well as two "callback" references to BeanShell namespaces: one for * static methods and one for instance methods. Methods of the class are * delegators which invoke corresponding methods on either the static or * instance bsh object and then unpack and return the results. The static * namespace utilizes a static import to delegate variable access to the * class' static fields. The instance namespace utilizes a dynamic import * (i.e. mixin) to delegate variable access to the class' instance variables. * <p/> * <p/> * Constructors for the class delegate to the static initInstance() method of * ClassGeneratorUtil to initialize new instances of the object. initInstance() * invokes the instance intializer code (init vars and instance blocks) and * then delegates to the corresponding scripted constructor method in the * instance namespace. Constructors contain special switch logic which allows * the BeanShell to control the calling of alternate constructors (this() or * super() references) at runtime. * <p/> * <p/> * Specially named superclass delegator methods are also generated in order to * allow BeanShell to access overridden methods of the superclass (which * reflection does not normally allow). * <p/> * * @author Pat Niemeyer */ /* Notes: It would not be hard to eliminate the use of org.objectweb.asm.Type from this class, making the distribution a tiny bit smaller. */ public class ClassGeneratorUtil implements Constants { /** * The name of the static field holding the reference to the bsh * static This (the callback namespace for static methods) */ static final String BSHSTATIC = "_bshStatic"; /** * The name of the instance field holding the reference to the bsh * instance This (the callback namespace for instance methods) */ private static final String BSHTHIS = "_bshThis"; /** * The prefix for the name of the super delegate methods. e.g. * _bshSuperfoo() is equivalent to super.foo() */ static final String BSHSUPER = "_bshSuper"; /** * The bsh static namespace variable name of the instance initializer */ static final String BSHINIT = "_bshInstanceInitializer"; /** * The bsh static namespace variable that holds the constructor methods */ private static final String BSHCONSTRUCTORS = "_bshConstructors"; /** * The switch branch number for the default constructor. * The value -1 will cause the default branch to be taken. */ private static final int DEFAULTCONSTRUCTOR = -1; private static final String OBJECT = "Ljava/lang/Object;"; private final String className; /** * fully qualified class name (with package) e.g. foo/bar/Blah */ private final String fqClassName; private final Class superClass; private final String superClassName; private final Class[] interfaces; private final Variable[] vars; private final Constructor[] superConstructors; private final DelayedEvalBshMethod[] constructors; private final DelayedEvalBshMethod[] methods; private final NameSpace classStaticNameSpace; private final Modifiers classModifiers; private boolean isInterface; /** * @param packageName e.g. "com.foo.bar" */ public ClassGeneratorUtil(Modifiers classModifiers, String className, String packageName, Class superClass, Class[] interfaces, Variable[] vars, DelayedEvalBshMethod[] bshmethods, NameSpace classStaticNameSpace, boolean isInterface) { this.classModifiers = classModifiers; this.className = className; if (packageName != null) { this.fqClassName = packageName.replace('.', '/') + "/" + className; } else { this.fqClassName = className; } if (superClass == null) { superClass = Object.class; } this.superClass = superClass; this.superClassName = Type.getInternalName(superClass); if (interfaces == null) { interfaces = new Class[0]; } this.interfaces = interfaces; this.vars = vars; this.classStaticNameSpace = classStaticNameSpace; this.superConstructors = superClass.getDeclaredConstructors(); // Split the methods into constructors and regular method lists List consl = new ArrayList(); List methodsl = new ArrayList(); String classBaseName = getBaseName(className); // for inner classes for (DelayedEvalBshMethod bshmethod : bshmethods) { if (bshmethod.getName().equals(classBaseName)) { consl.add(bshmethod); if ((packageName == null) && !Capabilities.haveAccessibility()) { bshmethod.makePublic(); } } else { methodsl.add(bshmethod); } } this.constructors = (DelayedEvalBshMethod[]) consl.toArray(new DelayedEvalBshMethod[consl.size()]); this.methods = (DelayedEvalBshMethod[]) methodsl.toArray(new DelayedEvalBshMethod[methodsl.size()]); try { classStaticNameSpace.setLocalVariable(BSHCONSTRUCTORS, constructors, false/*strict*/); } catch (UtilEvalError e) { throw new InterpreterError("can't set cons var"); } this.isInterface = isInterface; } /** * Generate the class bytecode for this class. */ public byte[] generateClass() { // Force the class public for now... int classMods = getASMModifiers(classModifiers) | ACC_PUBLIC; if (isInterface) { classMods |= ACC_INTERFACE; } String[] interfaceNames = new String[interfaces.length + (isInterface ? 0 : 1)]; // one more interface for instance init callback for (int i = 0; i < interfaces.length; i++) { interfaceNames[i] = Type.getInternalName(interfaces[i]); } if ( ! isInterface) { interfaceNames[interfaces.length] = Type.getInternalName(GeneratedClass.class); } String sourceFile = "BeanShell Generated via ASM (www.objectweb.org)"; ClassWriter cw = new ClassWriter(false); cw.visit(classMods, fqClassName, superClassName, interfaceNames, sourceFile); if ( ! isInterface) { // Generate the bsh instance 'This' reference holder field generateField(BSHTHIS + className, "Lbsh/This;", ACC_PUBLIC, cw); // Generate the static bsh static reference holder field generateField(BSHSTATIC + className, "Lbsh/This;", ACC_PUBLIC + ACC_STATIC, cw); } // Generate the fields for (Variable var : vars) { String type = var.getTypeDescriptor(); // Don't generate private or loosely typed fields // Note: loose types aren't currently parsed anyway... if (var.hasModifier("private") || type == null) { continue; } int modifiers; if (isInterface) { modifiers = ACC_PUBLIC | ACC_STATIC | ACC_FINAL; } else { modifiers = getASMModifiers(var.getModifiers()); } generateField(var.getName(), type, modifiers, cw); } // Generate the constructors boolean hasConstructor = false; for (int i = 0; i < constructors.length; i++) { // Don't generate private constructors if (constructors[i].hasModifier("private")) { continue; } int modifiers = getASMModifiers(constructors[i].getModifiers()); generateConstructor(i, constructors[i].getParamTypeDescriptors(), modifiers, cw); hasConstructor = true; } // If no other constructors, generate a default constructor if ( ! isInterface && ! hasConstructor) { generateConstructor(DEFAULTCONSTRUCTOR/*index*/, new String[0], ACC_PUBLIC, cw); } // Generate the delegate methods for (DelayedEvalBshMethod method : methods) { String returnType = method.getReturnTypeDescriptor(); // Don't generate private /*or loosely return typed */ methods if (method.hasModifier("private") /*|| returnType == null*/) { continue; } int modifiers = getASMModifiers(method.getModifiers()); if (isInterface) { modifiers |= (ACC_PUBLIC | ACC_ABSTRACT); } generateMethod(className, fqClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw); boolean isStatic = (modifiers & ACC_STATIC) > 0; boolean overridden = classContainsMethod(superClass, method.getName(), method.getParamTypeDescriptors()); if (!isStatic && overridden) { generateSuperDelegateMethod(superClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw); } } return cw.toByteArray(); } /** * Translate bsh.Modifiers into ASM modifier bitflags. */ private static int getASMModifiers(Modifiers modifiers) { int mods = 0; if (modifiers == null) { return mods; } if (modifiers.hasModifier("public")) { mods += ACC_PUBLIC; } if (modifiers.hasModifier("protected")) { mods += ACC_PROTECTED; } if (modifiers.hasModifier("static")) { mods += ACC_STATIC; } if (modifiers.hasModifier("synchronized")) { mods += ACC_SYNCHRONIZED; } if (modifiers.hasModifier("abstract")) { mods += ACC_ABSTRACT; } return mods; } /** * Generate a field - static or instance. */ private static void generateField(String fieldName, String type, int modifiers, ClassWriter cw) { cw.visitField(modifiers, fieldName, type, null/*value*/); } /** * Generate a delegate method - static or instance. * The generated code packs the method arguments into an object array * (wrapping primitive types in bsh.Primitive), invokes the static or * instance namespace invokeMethod() method, and then unwraps / returns * the result. */ private static void generateMethod(String className, String fqClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) { String[] exceptions = null; boolean isStatic = (modifiers & ACC_STATIC) != 0; if (returnType == null) // map loose return type to Object { returnType = OBJECT; } String methodDescriptor = getMethodDescriptor(returnType, paramTypes); // Generate method body CodeVisitor cv = cw.visitMethod(modifiers, methodName, methodDescriptor, exceptions); if ((modifiers & ACC_ABSTRACT) != 0) { return; } // Generate code to push the BSHTHIS or BSHSTATIC field if (isStatic) { cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;"); } else { // Push 'this' cv.visitVarInsn(ALOAD, 0); // Get the instance field cv.visitFieldInsn(GETFIELD, fqClassName, BSHTHIS + className, "Lbsh/This;"); } // Push the name of the method as a constant cv.visitLdcInsn(methodName); // Generate code to push arguments as an object array generateParameterReifierCode(paramTypes, isStatic, cv); // Push nulls for various args of invokeMethod cv.visitInsn(ACONST_NULL); // interpreter cv.visitInsn(ACONST_NULL); // callstack cv.visitInsn(ACONST_NULL); // callerinfo // Push the boolean constant 'true' (for declaredOnly) cv.visitInsn(ICONST_1); // Invoke the method This.invokeMethod( name, Class [] sig, boolean ) cv.visitMethodInsn(INVOKEVIRTUAL, "bsh/This", "invokeMethod", Type.getMethodDescriptor(Type.getType(Object.class), new Type[]{Type.getType(String.class), Type.getType(Object[].class), Type.getType(Interpreter.class), Type.getType(CallStack.class), Type.getType(SimpleNode.class), Type.getType(Boolean.TYPE)})); // Generate code to unwrap bsh Primitive types cv.visitMethodInsn(INVOKESTATIC, "bsh/Primitive", "unwrap", "(Ljava/lang/Object;)Ljava/lang/Object;"); // Generate code to return the value generateReturnCode(returnType, cv); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } /** * Generate a constructor. */ void generateConstructor(int index, String[] paramTypes, int modifiers, ClassWriter cw) { /** offset after params of the args object [] var */ final int argsVar = paramTypes.length + 1; /** offset after params of the ConstructorArgs var */ final int consArgsVar = paramTypes.length + 2; String[] exceptions = null; String methodDescriptor = getMethodDescriptor("V", paramTypes); // Create this constructor method CodeVisitor cv = cw.visitMethod(modifiers, "<init>", methodDescriptor, exceptions); // Generate code to push arguments as an object array generateParameterReifierCode(paramTypes, false/*isStatic*/, cv); cv.visitVarInsn(ASTORE, argsVar); // Generate the code implementing the alternate constructor switch generateConstructorSwitch(index, argsVar, consArgsVar, cv); // Generate code to invoke the ClassGeneratorUtil initInstance() method // push 'this' cv.visitVarInsn(ALOAD, 0); // Push the class/constructor name as a constant cv.visitLdcInsn(className); // Push arguments as an object array cv.visitVarInsn(ALOAD, argsVar); // invoke the initInstance() method cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "initInstance", "(L" + GeneratedClass.class.getName().replace('.', '/') + ";Ljava/lang/String;[Ljava/lang/Object;)V"); cv.visitInsn(RETURN); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } /** * Generate a switch with a branch for each possible alternate * constructor. This includes all superclass constructors and all * constructors of this class. The default branch of this switch is the * default superclass constructor. * <p/> * This method also generates the code to call the static * ClassGeneratorUtil * getConstructorArgs() method which inspects the scripted constructor to * find the alternate constructor signature (if any) and evalute the * arguments at runtime. The getConstructorArgs() method returns the * actual arguments as well as the index of the constructor to call. */ void generateConstructorSwitch(int consIndex, int argsVar, int consArgsVar, CodeVisitor cv) { Label defaultLabel = new Label(); Label endLabel = new Label(); int cases = superConstructors.length + constructors.length; Label[] labels = new Label[cases]; for (int i = 0; i < cases; i++) { labels[i] = new Label(); } // Generate code to call ClassGeneratorUtil to get our switch index // and give us args... // push super class name cv.visitLdcInsn(superClass.getName()); // use superClassName var? // push class static This object cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;"); // push args cv.visitVarInsn(ALOAD, argsVar); // push this constructor index number onto stack cv.visitIntInsn(BIPUSH, consIndex); // invoke the ClassGeneratorUtil getConstructorsArgs() method cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "getConstructorArgs", "(Ljava/lang/String;Lbsh/This;[Ljava/lang/Object;I)" + "Lbsh/ClassGeneratorUtil$ConstructorArgs;"); // store ConstructorArgs in consArgsVar cv.visitVarInsn(ASTORE, consArgsVar); // Get the ConstructorArgs selector field from ConstructorArgs // push ConstructorArgs cv.visitVarInsn(ALOAD, consArgsVar); cv.visitFieldInsn(GETFIELD, "bsh/ClassGeneratorUtil$ConstructorArgs", "selector", "I"); // start switch cv.visitTableSwitchInsn(0/*min*/, cases - 1/*max*/, defaultLabel, labels); // generate switch body int index = 0; for (int i = 0; i < superConstructors.length; i++, index++) { doSwitchBranch(index, superClassName, getTypeDescriptors(superConstructors[i].getParameterTypes()), endLabel, labels, consArgsVar, cv); } for (int i = 0; i < constructors.length; i++, index++) { doSwitchBranch(index, fqClassName, constructors[i].getParamTypeDescriptors(), endLabel, labels, consArgsVar, cv); } // generate the default branch of switch cv.visitLabel(defaultLabel); // default branch always invokes no args super cv.visitVarInsn(ALOAD, 0); // push 'this' cv.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", "()V"); // done with switch cv.visitLabel(endLabel); } /* Generate a branch of the constructor switch. This method is called by generateConstructorSwitch. The code generated by this method assumes that the argument array is on the stack. */ private static void doSwitchBranch(int index, String targetClassName, String[] paramTypes, Label endLabel, Label[] labels, int consArgsVar, CodeVisitor cv) { cv.visitLabel(labels[index]); //cv.visitLineNumber( index, labels[index] ); cv.visitVarInsn(ALOAD, 0); // push this before args // Unload the arguments from the ConstructorArgs object for (String type : paramTypes) { final String method; if (type.equals("Z")) { method = "getBoolean"; } else if (type.equals("B")) { method = "getByte"; } else if (type.equals("C")) { method = "getChar"; } else if (type.equals("S")) { method = "getShort"; } else if (type.equals("I")) { method = "getInt"; } else if (type.equals("J")) { method = "getLong"; } else if (type.equals("D")) { method = "getDouble"; } else if (type.equals("F")) { method = "getFloat"; } else { method = "getObject"; } // invoke the iterator method on the ConstructorArgs cv.visitVarInsn(ALOAD, consArgsVar); // push the ConstructorArgs String className = "bsh/ClassGeneratorUtil$ConstructorArgs"; String retType; if (method.equals("getObject")) { retType = OBJECT; } else { retType = type; } cv.visitMethodInsn(INVOKEVIRTUAL, className, method, "()" + retType); // if it's an object type we must do a check cast if (method.equals("getObject")) { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(type)); } } // invoke the constructor for this branch String descriptor = getMethodDescriptor("V", paramTypes); cv.visitMethodInsn(INVOKESPECIAL, targetClassName, "<init>", descriptor); cv.visitJumpInsn(GOTO, endLabel); } private static String getMethodDescriptor(String returnType, String[] paramTypes) { StringBuilder sb = new StringBuilder("("); for (String paramType : paramTypes) { sb.append(paramType); } sb.append(')').append(returnType); return sb.toString(); } /** * Generate a superclass method delegate accessor method. * These methods are specially named methods which allow access to * overridden methods of the superclass (which the Java reflection API * normally does not allow). */ // Maybe combine this with generateMethod() private static void generateSuperDelegateMethod(String superClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) { String[] exceptions = null; if (returnType == null) // map loose return to Object { returnType = OBJECT; } String methodDescriptor = getMethodDescriptor(returnType, paramTypes); // Add method body CodeVisitor cv = cw.visitMethod(modifiers, "_bshSuper" + methodName, methodDescriptor, exceptions); cv.visitVarInsn(ALOAD, 0); // Push vars int localVarIndex = 1; for (String paramType : paramTypes) { if (isPrimitive(paramType)) { cv.visitVarInsn(ILOAD, localVarIndex); } else { cv.visitVarInsn(ALOAD, localVarIndex); } localVarIndex += ((paramType.equals("D") || paramType.equals("J")) ? 2 : 1); } cv.visitMethodInsn(INVOKESPECIAL, superClassName, methodName, methodDescriptor); generatePlainReturnCode(returnType, cv); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } boolean classContainsMethod(Class clas, String methodName, String[] paramTypes) { while (clas != null) { Method[] methods = clas.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { String[] methodParamTypes = getTypeDescriptors(method.getParameterTypes()); boolean found = true; for (int j = 0; j < methodParamTypes.length; j++) { if (!paramTypes[j].equals(methodParamTypes[j])) { found = false; break; } } if (found) { return true; } } } clas = clas.getSuperclass(); } return false; } /** * Generate return code for a normal bytecode */ private static void generatePlainReturnCode(String returnType, CodeVisitor cv) { if (returnType.equals("V")) { cv.visitInsn(RETURN); } else if (isPrimitive(returnType)) { int opcode = IRETURN; if (returnType.equals("D")) { opcode = DRETURN; } else if (returnType.equals("F")) { opcode = FRETURN; } else if (returnType.equals("J")) //long { opcode = LRETURN; } cv.visitInsn(opcode); } else { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType)); cv.visitInsn(ARETURN); } } /** * Generates the code to reify the arguments of the given method. * For a method "int m (int i, String s)", this code is the bytecode * corresponding to the "new Object[] { new bsh.Primitive(i), s }" * expression. * * @param cv the code visitor to be used to generate the bytecode. * @param isStatic the enclosing methods is static * @author Eric Bruneton * @author Pat Niemeyer */ private static void generateParameterReifierCode(String[] paramTypes, boolean isStatic, final CodeVisitor cv) { cv.visitIntInsn(SIPUSH, paramTypes.length); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int localVarIndex = isStatic ? 0 : 1; for (int i = 0; i < paramTypes.length; ++i) { String param = paramTypes[i]; cv.visitInsn(DUP); cv.visitIntInsn(SIPUSH, i); if (isPrimitive(param)) { int opcode; if (param.equals("F")) { opcode = FLOAD; } else if (param.equals("D")) { opcode = DLOAD; } else if (param.equals("J")) { opcode = LLOAD; } else { opcode = ILOAD; } String type = "bsh/Primitive"; cv.visitTypeInsn(NEW, type); cv.visitInsn(DUP); cv.visitVarInsn(opcode, localVarIndex); String desc = param; // ok? cv.visitMethodInsn(INVOKESPECIAL, type, "<init>", "(" + desc + ")V"); } else { // Technically incorrect here - we need to wrap null values // as bsh.Primitive.NULL. However the This.invokeMethod() // will do that much for us. // We need to generate a conditional here to test for null // and return Primitive.NULL cv.visitVarInsn(ALOAD, localVarIndex); } cv.visitInsn(AASTORE); localVarIndex += ((param.equals("D") || param.equals("J")) ? 2 : 1); } } /** * Generates the code to unreify the result of the given method. For a * method "int m (int i, String s)", this code is the bytecode * corresponding to the "((Integer)...).intValue()" expression. * * @param cv the code visitor to be used to generate the bytecode. * @author Eric Bruneton * @author Pat Niemeyer */ private static void generateReturnCode(String returnType, CodeVisitor cv) { if (returnType.equals("V")) { cv.visitInsn(POP); cv.visitInsn(RETURN); } else if (isPrimitive(returnType)) { int opcode = IRETURN; String type; String meth; if (returnType.equals("B")) { type = "java/lang/Byte"; meth = "byteValue"; } else if (returnType.equals("I")) { type = "java/lang/Integer"; meth = "intValue"; } else if (returnType.equals("Z")) { type = "java/lang/Boolean"; meth = "booleanValue"; } else if (returnType.equals("D")) { opcode = DRETURN; type = "java/lang/Double"; meth = "doubleValue"; } else if (returnType.equals("F")) { opcode = FRETURN; type = "java/lang/Float"; meth = "floatValue"; } else if (returnType.equals("J")) { opcode = LRETURN; type = "java/lang/Long"; meth = "longValue"; } else if (returnType.equals("C")) { type = "java/lang/Character"; meth = "charValue"; } else /*if (returnType.equals("S") )*/ { type = "java/lang/Short"; meth = "shortValue"; } String desc = returnType; cv.visitTypeInsn(CHECKCAST, type); // type is correct here cv.visitMethodInsn(INVOKEVIRTUAL, type, meth, "()" + desc); cv.visitInsn(opcode); } else { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType)); cv.visitInsn(ARETURN); } } /** * Evaluate the arguments (if any) for the constructor specified by * the constructor index. Return the ConstructorArgs object which * contains the actual arguments to the alternate constructor and also the * index of that constructor for the constructor switch. * * @param consArgs the arguments to the constructor. These are necessary in * the evaluation of the alt constructor args. e.g. Foo(a) { super(a); } * @return the ConstructorArgs object containing a constructor selector * and evaluated arguments for the alternate constructor */ public static ConstructorArgs getConstructorArgs(String superClassName, This classStaticThis, Object[] consArgs, int index) { DelayedEvalBshMethod[] constructors; try { constructors = (DelayedEvalBshMethod[]) classStaticThis.getNameSpace().getVariable(BSHCONSTRUCTORS); } catch (Exception e) { throw new InterpreterError("unable to get instance initializer: " + e); } if (index == DEFAULTCONSTRUCTOR) // auto-gen default constructor { return ConstructorArgs.DEFAULT; } // use default super constructor DelayedEvalBshMethod constructor = constructors[index]; if (constructor.methodBody.jjtGetNumChildren() == 0) { return ConstructorArgs.DEFAULT; } // use default super constructor // Determine if the constructor calls this() or super() String altConstructor = null; BSHArguments argsNode = null; SimpleNode firstStatement = (SimpleNode) constructor.methodBody.jjtGetChild(0); if (firstStatement instanceof BSHPrimaryExpression) { firstStatement = (SimpleNode) firstStatement.jjtGetChild(0); } if (firstStatement instanceof BSHMethodInvocation) { BSHMethodInvocation methodNode = (BSHMethodInvocation) firstStatement; BSHAmbiguousName methodName = methodNode.getNameNode(); if (methodName.text.equals("super") || methodName.text.equals("this")) { altConstructor = methodName.text; argsNode = methodNode.getArgsNode(); } } if (altConstructor == null) { return ConstructorArgs.DEFAULT; } // use default super constructor // Make a tmp namespace to hold the original constructor args for // use in eval of the parameters node NameSpace consArgsNameSpace = new NameSpace(classStaticThis.getNameSpace(), "consArgs"); String[] consArgNames = constructor.getParameterNames(); Class[] consArgTypes = constructor.getParameterTypes(); for (int i = 0; i < consArgs.length; i++) { try { consArgsNameSpace.setTypedVariable(consArgNames[i], consArgTypes[i], consArgs[i], null/*modifiers*/); } catch (UtilEvalError e) { throw new InterpreterError("err setting local cons arg:" + e); } } // evaluate the args CallStack callstack = new CallStack(); callstack.push(consArgsNameSpace); Object[] args; Interpreter interpreter = classStaticThis.declaringInterpreter; try { args = argsNode.getArguments(callstack, interpreter); } catch (EvalError e) { throw new InterpreterError("Error evaluating constructor args: " + e); } Class[] argTypes = Types.getTypes(args); args = Primitive.unwrap(args); Class superClass = interpreter.getClassManager().classForName(superClassName); if (superClass == null) { throw new InterpreterError("can't find superclass: " + superClassName); } Constructor[] superCons = superClass.getDeclaredConstructors(); // find the matching super() constructor for the args if (altConstructor.equals("super")) { int i = Reflect.findMostSpecificConstructorIndex(argTypes, superCons); if (i == -1) { throw new InterpreterError("can't find constructor for args!"); } return new ConstructorArgs(i, args); } // find the matching this() constructor for the args Class[][] candidates = new Class[constructors.length][]; for (int i = 0; i < candidates.length; i++) { candidates[i] = constructors[i].getParameterTypes(); } int i = Reflect.findMostSpecificSignature(argTypes, candidates); if (i == -1) { throw new InterpreterError("can't find constructor for args 2!"); } // this() constructors come after super constructors in the table int selector = i + superCons.length; int ourSelector = index + superCons.length; // Are we choosing ourselves recursively through a this() reference? if (selector == ourSelector) { throw new InterpreterError("Recusive constructor call."); } return new ConstructorArgs(selector, args); } private static final ThreadLocal<NameSpace> CONTEXT_NAMESPACE = new ThreadLocal<NameSpace>(); private static final ThreadLocal<Interpreter> CONTEXT_INTERPRETER = new ThreadLocal<Interpreter>(); /** * Register actual context, used by generated class constructor, which calls * {@link #initInstance(GeneratedClass, String, Object[])}. */ static void registerConstructorContext(CallStack callstack, Interpreter interpreter) { if (callstack != null) { CONTEXT_NAMESPACE.set(callstack.top()); } else { CONTEXT_NAMESPACE.remove(); } if (interpreter != null) { CONTEXT_INTERPRETER.set(interpreter); } else { CONTEXT_INTERPRETER.remove(); } } /** * Initialize an instance of the class. * This method is called from the generated class constructor to evaluate * the instance initializer and scripted constructor in the instance * namespace. */ public static void initInstance(GeneratedClass instance, String className, Object[] args) { Class[] sig = Types.getTypes(args); CallStack callstack = new CallStack(); Interpreter interpreter; NameSpace instanceNameSpace; // check to see if the instance has already been initialized // (the case if using a this() alternate constuctor) // todo PeJoBo70 write test for this This instanceThis = getClassInstanceThis(instance, className); // XXX clean up this conditional if (instanceThis == null) { // Create the instance 'This' namespace, set it on the object // instance and invoke the instance initializer // Get the static This reference from the proto-instance This classStaticThis = getClassStaticThis(instance.getClass(), className); interpreter = CONTEXT_INTERPRETER.get(); if (interpreter == null) { interpreter = classStaticThis.declaringInterpreter; } // Get the instance initializer block from the static This BSHBlock instanceInitBlock; try { instanceInitBlock = (BSHBlock) classStaticThis.getNameSpace().getVariable(BSHINIT); } catch (Exception e) { throw new InterpreterError("unable to get instance initializer: " + e); } // Create the instance namespace if (CONTEXT_NAMESPACE.get() != null) { instanceNameSpace = classStaticThis.getNameSpace().copy(); instanceNameSpace.setParent(CONTEXT_NAMESPACE.get()); } else { instanceNameSpace = new NameSpace(classStaticThis.getNameSpace(), className); // todo: old code } instanceNameSpace.isClass = true; // Set the instance This reference on the instance instanceThis = instanceNameSpace.getThis(interpreter); try { LHS lhs = Reflect.getLHSObjectField(instance, BSHTHIS + className); lhs.assign(instanceThis, false/*strict*/); } catch (Exception e) { throw new InterpreterError("Error in class gen setup: " + e); } // Give the instance space its object import instanceNameSpace.setClassInstance(instance); // should use try/finally here to pop ns callstack.push(instanceNameSpace); // evaluate the instance portion of the block in it try { // Evaluate the initializer block instanceInitBlock.evalBlock(callstack, interpreter, true/*override*/, ClassGenerator.ClassNodeFilter.CLASSINSTANCE); } catch (Exception e) { throw new InterpreterError("Error in class initialization: " + e, e); } callstack.pop(); } else { // The object instance has already been initialzed by another // constructor. Fall through to invoke the constructor body below. interpreter = instanceThis.declaringInterpreter; instanceNameSpace = instanceThis.getNameSpace(); } // invoke the constructor method from the instanceThis String constructorName = getBaseName(className); try { // Find the constructor (now in the instance namespace) BshMethod constructor = instanceNameSpace.getMethod(constructorName, sig, true/*declaredOnly*/); // if args, we must have constructor if (args.length > 0 && constructor == null) { throw new InterpreterError("Can't find constructor: " + className); } // Evaluate the constructor if (constructor != null) { constructor.invoke(args, interpreter, callstack, null/*callerInfo*/, false/*overrideNameSpace*/); } } catch (Exception e) { if (e instanceof TargetError) { e = (Exception) ((TargetError) e).getTarget(); } if (e instanceof InvocationTargetException) { e = (Exception) ((InvocationTargetException) e).getTargetException(); } throw new InterpreterError("Error in class initialization: " + e, e); } } /** * Get the static bsh namespace field from the class. * * @param className may be the name of clas itself or a superclass of clas. */ private static This getClassStaticThis(Class clas, String className) { try { return (This) Reflect.getStaticFieldValue(clas, BSHSTATIC + className); } catch (Exception e) { throw new InterpreterError("Unable to get class static space: " + e); } } /** * Get the instance bsh namespace field from the object instance. * * @return the class instance This object or null if the object has not * been initialized. */ static This getClassInstanceThis(Object instance, String className) { try { Object o = Reflect.getObjectFieldValue(instance, BSHTHIS + className); return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null } catch (Exception e) { throw new InterpreterError("Generated class: Error getting This" + e); } } /** * Does the type descriptor string describe a primitive type? */ private static boolean isPrimitive(String typeDescriptor) { return typeDescriptor.length() == 1; // right? } private static String[] getTypeDescriptors(Class[] cparams) { String[] sa = new String[cparams.length]; for (int i = 0; i < sa.length; i++) { sa[i] = BSHType.getTypeDescriptor(cparams[i]); } return sa; } /** * If a non-array object type, remove the prefix "L" and suffix ";". */ // Can this be factored out...? // Should be be adding the L...; here instead? private static String descriptorToClassName(String s) { if (s.startsWith("[") || !s.startsWith("L")) { return s; } return s.substring(1, s.length() - 1); } private static String getBaseName(String className) { int i = className.indexOf("$"); if (i == -1) { return className; } return className.substring(i + 1); } /** * A ConstructorArgs object holds evaluated arguments for a constructor * call as well as the index of a possible alternate selector to invoke. * This object is used by the constructor switch. * * @see bsh.ClassGeneratorUtil#generateConstructor(int, String[], int, bsh.org.objectweb.asm.ClassWriter) */ public static class ConstructorArgs { /** * A ConstructorArgs which calls the default constructor */ public static final ConstructorArgs DEFAULT = new ConstructorArgs(); public int selector = DEFAULTCONSTRUCTOR; Object[] args; int arg; /** * The index of the constructor to call. */ ConstructorArgs() { } ConstructorArgs(int selector, Object[] args) { this.selector = selector; this.args = args; } Object next() { return args[arg++]; } public boolean getBoolean() { return (Boolean) next(); } public byte getByte() { return (Byte) next(); } public char getChar() { return (Character) next(); } public short getShort() { return (Short) next(); } public int getInt() { return (Integer) next(); } public long getLong() { return (Long) next(); } public double getDouble() { return (Double) next(); } public float getFloat() { return (Float) next(); } public Object getObject() { return next(); } } }
UTF-8
Java
38,053
java
ClassGeneratorUtil.java
Java
[ { "context": "y be found at http://www.beanshell.org/ *\n * Patrick Niemeyer (pat@pat.net) ", "end": 1599, "score": 0.9998928904533386, "start": 1583, "tag": "NAME", "value": "Patrick Niemeyer" }, { "context": "//www.beanshell.org/ *\n * Patrick Niemeyer (pat@pat.net) *\n * ", "end": 1612, "score": 0.9999252557754517, "start": 1601, "tag": "EMAIL", "value": "pat@pat.net" }, { "context": "e ASM (www.objectweb.org) bytecode generator\n * by Eric Bruneton in order to generate class \"stubs\" for BeanShell ", "end": 2161, "score": 0.997719943523407, "start": 2148, "tag": "NAME", "value": "Eric Bruneton" }, { "context": "on does not normally allow).\n * <p/>\n *\n * @author Pat Niemeyer\n */\n/*\n\tNotes:\n\tIt would not be hard to eliminate", "end": 3593, "score": 0.9998413920402527, "start": 3581, "tag": "NAME", "value": "Pat Niemeyer" }, { "context": "Static the enclosing methods is static\n\t * @author Eric Bruneton\n\t * @author Pat Niemeyer\n\t */\n\tprivate static voi", "end": 22877, "score": 0.9998782873153687, "start": 22864, "tag": "NAME", "value": "Eric Bruneton" }, { "context": "ds is static\n\t * @author Eric Bruneton\n\t * @author Pat Niemeyer\n\t */\n\tprivate static void generateParameterReifie", "end": 22902, "score": 0.9998663067817688, "start": 22890, "tag": "NAME", "value": "Pat Niemeyer" }, { "context": "r to be used to generate the bytecode.\n\t * @author Eric Bruneton\n\t * @author Pat Niemeyer\n\t */\n\tprivate static voi", "end": 24510, "score": 0.9998797178268433, "start": 24497, "tag": "NAME", "value": "Eric Bruneton" }, { "context": "he bytecode.\n\t * @author Eric Bruneton\n\t * @author Pat Niemeyer\n\t */\n\tprivate static void generateReturnCode(Stri", "end": 24535, "score": 0.9998835325241089, "start": 24523, "tag": "NAME", "value": "Pat Niemeyer" }, { "context": " if using a this() alternate constuctor)\n\t\t// todo PeJoBo70 write test for this\n\t\tThis instanceThis = getClas", "end": 31603, "score": 0.9484611749649048, "start": 31595, "tag": "USERNAME", "value": "PeJoBo70" } ]
null
[]
/***************************************************************************** * Licensed to the Apache Software Foundation (ASF) under one * * or more contributor license agreements. See the NOTICE file * * distributed with this work for additional information * * regarding copyright ownership. The ASF licenses this file * * to you under the Apache License, Version 2.0 (the * * "License"); you may not use this file except in compliance * * with the License. You may obtain a copy of the License at * * * * 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 file is part of the BeanShell Java Scripting distribution. * * Documentation and updates may be found at http://www.beanshell.org/ * * <NAME> (<EMAIL>) * * Author of Learning Java, O'Reilly & Associates * * * *****************************************************************************/ package bsh; import bsh.org.objectweb.asm.*; import bsh.org.objectweb.asm.Type; import java.lang.reflect.*; import java.util.ArrayList; import java.util.List; /** * ClassGeneratorUtil utilizes the ASM (www.objectweb.org) bytecode generator * by <NAME> in order to generate class "stubs" for BeanShell at * runtime. * <p/> * <p/> * Stub classes contain all of the fields of a BeanShell scripted class * as well as two "callback" references to BeanShell namespaces: one for * static methods and one for instance methods. Methods of the class are * delegators which invoke corresponding methods on either the static or * instance bsh object and then unpack and return the results. The static * namespace utilizes a static import to delegate variable access to the * class' static fields. The instance namespace utilizes a dynamic import * (i.e. mixin) to delegate variable access to the class' instance variables. * <p/> * <p/> * Constructors for the class delegate to the static initInstance() method of * ClassGeneratorUtil to initialize new instances of the object. initInstance() * invokes the instance intializer code (init vars and instance blocks) and * then delegates to the corresponding scripted constructor method in the * instance namespace. Constructors contain special switch logic which allows * the BeanShell to control the calling of alternate constructors (this() or * super() references) at runtime. * <p/> * <p/> * Specially named superclass delegator methods are also generated in order to * allow BeanShell to access overridden methods of the superclass (which * reflection does not normally allow). * <p/> * * @author <NAME> */ /* Notes: It would not be hard to eliminate the use of org.objectweb.asm.Type from this class, making the distribution a tiny bit smaller. */ public class ClassGeneratorUtil implements Constants { /** * The name of the static field holding the reference to the bsh * static This (the callback namespace for static methods) */ static final String BSHSTATIC = "_bshStatic"; /** * The name of the instance field holding the reference to the bsh * instance This (the callback namespace for instance methods) */ private static final String BSHTHIS = "_bshThis"; /** * The prefix for the name of the super delegate methods. e.g. * _bshSuperfoo() is equivalent to super.foo() */ static final String BSHSUPER = "_bshSuper"; /** * The bsh static namespace variable name of the instance initializer */ static final String BSHINIT = "_bshInstanceInitializer"; /** * The bsh static namespace variable that holds the constructor methods */ private static final String BSHCONSTRUCTORS = "_bshConstructors"; /** * The switch branch number for the default constructor. * The value -1 will cause the default branch to be taken. */ private static final int DEFAULTCONSTRUCTOR = -1; private static final String OBJECT = "Ljava/lang/Object;"; private final String className; /** * fully qualified class name (with package) e.g. foo/bar/Blah */ private final String fqClassName; private final Class superClass; private final String superClassName; private final Class[] interfaces; private final Variable[] vars; private final Constructor[] superConstructors; private final DelayedEvalBshMethod[] constructors; private final DelayedEvalBshMethod[] methods; private final NameSpace classStaticNameSpace; private final Modifiers classModifiers; private boolean isInterface; /** * @param packageName e.g. "com.foo.bar" */ public ClassGeneratorUtil(Modifiers classModifiers, String className, String packageName, Class superClass, Class[] interfaces, Variable[] vars, DelayedEvalBshMethod[] bshmethods, NameSpace classStaticNameSpace, boolean isInterface) { this.classModifiers = classModifiers; this.className = className; if (packageName != null) { this.fqClassName = packageName.replace('.', '/') + "/" + className; } else { this.fqClassName = className; } if (superClass == null) { superClass = Object.class; } this.superClass = superClass; this.superClassName = Type.getInternalName(superClass); if (interfaces == null) { interfaces = new Class[0]; } this.interfaces = interfaces; this.vars = vars; this.classStaticNameSpace = classStaticNameSpace; this.superConstructors = superClass.getDeclaredConstructors(); // Split the methods into constructors and regular method lists List consl = new ArrayList(); List methodsl = new ArrayList(); String classBaseName = getBaseName(className); // for inner classes for (DelayedEvalBshMethod bshmethod : bshmethods) { if (bshmethod.getName().equals(classBaseName)) { consl.add(bshmethod); if ((packageName == null) && !Capabilities.haveAccessibility()) { bshmethod.makePublic(); } } else { methodsl.add(bshmethod); } } this.constructors = (DelayedEvalBshMethod[]) consl.toArray(new DelayedEvalBshMethod[consl.size()]); this.methods = (DelayedEvalBshMethod[]) methodsl.toArray(new DelayedEvalBshMethod[methodsl.size()]); try { classStaticNameSpace.setLocalVariable(BSHCONSTRUCTORS, constructors, false/*strict*/); } catch (UtilEvalError e) { throw new InterpreterError("can't set cons var"); } this.isInterface = isInterface; } /** * Generate the class bytecode for this class. */ public byte[] generateClass() { // Force the class public for now... int classMods = getASMModifiers(classModifiers) | ACC_PUBLIC; if (isInterface) { classMods |= ACC_INTERFACE; } String[] interfaceNames = new String[interfaces.length + (isInterface ? 0 : 1)]; // one more interface for instance init callback for (int i = 0; i < interfaces.length; i++) { interfaceNames[i] = Type.getInternalName(interfaces[i]); } if ( ! isInterface) { interfaceNames[interfaces.length] = Type.getInternalName(GeneratedClass.class); } String sourceFile = "BeanShell Generated via ASM (www.objectweb.org)"; ClassWriter cw = new ClassWriter(false); cw.visit(classMods, fqClassName, superClassName, interfaceNames, sourceFile); if ( ! isInterface) { // Generate the bsh instance 'This' reference holder field generateField(BSHTHIS + className, "Lbsh/This;", ACC_PUBLIC, cw); // Generate the static bsh static reference holder field generateField(BSHSTATIC + className, "Lbsh/This;", ACC_PUBLIC + ACC_STATIC, cw); } // Generate the fields for (Variable var : vars) { String type = var.getTypeDescriptor(); // Don't generate private or loosely typed fields // Note: loose types aren't currently parsed anyway... if (var.hasModifier("private") || type == null) { continue; } int modifiers; if (isInterface) { modifiers = ACC_PUBLIC | ACC_STATIC | ACC_FINAL; } else { modifiers = getASMModifiers(var.getModifiers()); } generateField(var.getName(), type, modifiers, cw); } // Generate the constructors boolean hasConstructor = false; for (int i = 0; i < constructors.length; i++) { // Don't generate private constructors if (constructors[i].hasModifier("private")) { continue; } int modifiers = getASMModifiers(constructors[i].getModifiers()); generateConstructor(i, constructors[i].getParamTypeDescriptors(), modifiers, cw); hasConstructor = true; } // If no other constructors, generate a default constructor if ( ! isInterface && ! hasConstructor) { generateConstructor(DEFAULTCONSTRUCTOR/*index*/, new String[0], ACC_PUBLIC, cw); } // Generate the delegate methods for (DelayedEvalBshMethod method : methods) { String returnType = method.getReturnTypeDescriptor(); // Don't generate private /*or loosely return typed */ methods if (method.hasModifier("private") /*|| returnType == null*/) { continue; } int modifiers = getASMModifiers(method.getModifiers()); if (isInterface) { modifiers |= (ACC_PUBLIC | ACC_ABSTRACT); } generateMethod(className, fqClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw); boolean isStatic = (modifiers & ACC_STATIC) > 0; boolean overridden = classContainsMethod(superClass, method.getName(), method.getParamTypeDescriptors()); if (!isStatic && overridden) { generateSuperDelegateMethod(superClassName, method.getName(), returnType, method.getParamTypeDescriptors(), modifiers, cw); } } return cw.toByteArray(); } /** * Translate bsh.Modifiers into ASM modifier bitflags. */ private static int getASMModifiers(Modifiers modifiers) { int mods = 0; if (modifiers == null) { return mods; } if (modifiers.hasModifier("public")) { mods += ACC_PUBLIC; } if (modifiers.hasModifier("protected")) { mods += ACC_PROTECTED; } if (modifiers.hasModifier("static")) { mods += ACC_STATIC; } if (modifiers.hasModifier("synchronized")) { mods += ACC_SYNCHRONIZED; } if (modifiers.hasModifier("abstract")) { mods += ACC_ABSTRACT; } return mods; } /** * Generate a field - static or instance. */ private static void generateField(String fieldName, String type, int modifiers, ClassWriter cw) { cw.visitField(modifiers, fieldName, type, null/*value*/); } /** * Generate a delegate method - static or instance. * The generated code packs the method arguments into an object array * (wrapping primitive types in bsh.Primitive), invokes the static or * instance namespace invokeMethod() method, and then unwraps / returns * the result. */ private static void generateMethod(String className, String fqClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) { String[] exceptions = null; boolean isStatic = (modifiers & ACC_STATIC) != 0; if (returnType == null) // map loose return type to Object { returnType = OBJECT; } String methodDescriptor = getMethodDescriptor(returnType, paramTypes); // Generate method body CodeVisitor cv = cw.visitMethod(modifiers, methodName, methodDescriptor, exceptions); if ((modifiers & ACC_ABSTRACT) != 0) { return; } // Generate code to push the BSHTHIS or BSHSTATIC field if (isStatic) { cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;"); } else { // Push 'this' cv.visitVarInsn(ALOAD, 0); // Get the instance field cv.visitFieldInsn(GETFIELD, fqClassName, BSHTHIS + className, "Lbsh/This;"); } // Push the name of the method as a constant cv.visitLdcInsn(methodName); // Generate code to push arguments as an object array generateParameterReifierCode(paramTypes, isStatic, cv); // Push nulls for various args of invokeMethod cv.visitInsn(ACONST_NULL); // interpreter cv.visitInsn(ACONST_NULL); // callstack cv.visitInsn(ACONST_NULL); // callerinfo // Push the boolean constant 'true' (for declaredOnly) cv.visitInsn(ICONST_1); // Invoke the method This.invokeMethod( name, Class [] sig, boolean ) cv.visitMethodInsn(INVOKEVIRTUAL, "bsh/This", "invokeMethod", Type.getMethodDescriptor(Type.getType(Object.class), new Type[]{Type.getType(String.class), Type.getType(Object[].class), Type.getType(Interpreter.class), Type.getType(CallStack.class), Type.getType(SimpleNode.class), Type.getType(Boolean.TYPE)})); // Generate code to unwrap bsh Primitive types cv.visitMethodInsn(INVOKESTATIC, "bsh/Primitive", "unwrap", "(Ljava/lang/Object;)Ljava/lang/Object;"); // Generate code to return the value generateReturnCode(returnType, cv); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } /** * Generate a constructor. */ void generateConstructor(int index, String[] paramTypes, int modifiers, ClassWriter cw) { /** offset after params of the args object [] var */ final int argsVar = paramTypes.length + 1; /** offset after params of the ConstructorArgs var */ final int consArgsVar = paramTypes.length + 2; String[] exceptions = null; String methodDescriptor = getMethodDescriptor("V", paramTypes); // Create this constructor method CodeVisitor cv = cw.visitMethod(modifiers, "<init>", methodDescriptor, exceptions); // Generate code to push arguments as an object array generateParameterReifierCode(paramTypes, false/*isStatic*/, cv); cv.visitVarInsn(ASTORE, argsVar); // Generate the code implementing the alternate constructor switch generateConstructorSwitch(index, argsVar, consArgsVar, cv); // Generate code to invoke the ClassGeneratorUtil initInstance() method // push 'this' cv.visitVarInsn(ALOAD, 0); // Push the class/constructor name as a constant cv.visitLdcInsn(className); // Push arguments as an object array cv.visitVarInsn(ALOAD, argsVar); // invoke the initInstance() method cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "initInstance", "(L" + GeneratedClass.class.getName().replace('.', '/') + ";Ljava/lang/String;[Ljava/lang/Object;)V"); cv.visitInsn(RETURN); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } /** * Generate a switch with a branch for each possible alternate * constructor. This includes all superclass constructors and all * constructors of this class. The default branch of this switch is the * default superclass constructor. * <p/> * This method also generates the code to call the static * ClassGeneratorUtil * getConstructorArgs() method which inspects the scripted constructor to * find the alternate constructor signature (if any) and evalute the * arguments at runtime. The getConstructorArgs() method returns the * actual arguments as well as the index of the constructor to call. */ void generateConstructorSwitch(int consIndex, int argsVar, int consArgsVar, CodeVisitor cv) { Label defaultLabel = new Label(); Label endLabel = new Label(); int cases = superConstructors.length + constructors.length; Label[] labels = new Label[cases]; for (int i = 0; i < cases; i++) { labels[i] = new Label(); } // Generate code to call ClassGeneratorUtil to get our switch index // and give us args... // push super class name cv.visitLdcInsn(superClass.getName()); // use superClassName var? // push class static This object cv.visitFieldInsn(GETSTATIC, fqClassName, BSHSTATIC + className, "Lbsh/This;"); // push args cv.visitVarInsn(ALOAD, argsVar); // push this constructor index number onto stack cv.visitIntInsn(BIPUSH, consIndex); // invoke the ClassGeneratorUtil getConstructorsArgs() method cv.visitMethodInsn(INVOKESTATIC, "bsh/ClassGeneratorUtil", "getConstructorArgs", "(Ljava/lang/String;Lbsh/This;[Ljava/lang/Object;I)" + "Lbsh/ClassGeneratorUtil$ConstructorArgs;"); // store ConstructorArgs in consArgsVar cv.visitVarInsn(ASTORE, consArgsVar); // Get the ConstructorArgs selector field from ConstructorArgs // push ConstructorArgs cv.visitVarInsn(ALOAD, consArgsVar); cv.visitFieldInsn(GETFIELD, "bsh/ClassGeneratorUtil$ConstructorArgs", "selector", "I"); // start switch cv.visitTableSwitchInsn(0/*min*/, cases - 1/*max*/, defaultLabel, labels); // generate switch body int index = 0; for (int i = 0; i < superConstructors.length; i++, index++) { doSwitchBranch(index, superClassName, getTypeDescriptors(superConstructors[i].getParameterTypes()), endLabel, labels, consArgsVar, cv); } for (int i = 0; i < constructors.length; i++, index++) { doSwitchBranch(index, fqClassName, constructors[i].getParamTypeDescriptors(), endLabel, labels, consArgsVar, cv); } // generate the default branch of switch cv.visitLabel(defaultLabel); // default branch always invokes no args super cv.visitVarInsn(ALOAD, 0); // push 'this' cv.visitMethodInsn(INVOKESPECIAL, superClassName, "<init>", "()V"); // done with switch cv.visitLabel(endLabel); } /* Generate a branch of the constructor switch. This method is called by generateConstructorSwitch. The code generated by this method assumes that the argument array is on the stack. */ private static void doSwitchBranch(int index, String targetClassName, String[] paramTypes, Label endLabel, Label[] labels, int consArgsVar, CodeVisitor cv) { cv.visitLabel(labels[index]); //cv.visitLineNumber( index, labels[index] ); cv.visitVarInsn(ALOAD, 0); // push this before args // Unload the arguments from the ConstructorArgs object for (String type : paramTypes) { final String method; if (type.equals("Z")) { method = "getBoolean"; } else if (type.equals("B")) { method = "getByte"; } else if (type.equals("C")) { method = "getChar"; } else if (type.equals("S")) { method = "getShort"; } else if (type.equals("I")) { method = "getInt"; } else if (type.equals("J")) { method = "getLong"; } else if (type.equals("D")) { method = "getDouble"; } else if (type.equals("F")) { method = "getFloat"; } else { method = "getObject"; } // invoke the iterator method on the ConstructorArgs cv.visitVarInsn(ALOAD, consArgsVar); // push the ConstructorArgs String className = "bsh/ClassGeneratorUtil$ConstructorArgs"; String retType; if (method.equals("getObject")) { retType = OBJECT; } else { retType = type; } cv.visitMethodInsn(INVOKEVIRTUAL, className, method, "()" + retType); // if it's an object type we must do a check cast if (method.equals("getObject")) { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(type)); } } // invoke the constructor for this branch String descriptor = getMethodDescriptor("V", paramTypes); cv.visitMethodInsn(INVOKESPECIAL, targetClassName, "<init>", descriptor); cv.visitJumpInsn(GOTO, endLabel); } private static String getMethodDescriptor(String returnType, String[] paramTypes) { StringBuilder sb = new StringBuilder("("); for (String paramType : paramTypes) { sb.append(paramType); } sb.append(')').append(returnType); return sb.toString(); } /** * Generate a superclass method delegate accessor method. * These methods are specially named methods which allow access to * overridden methods of the superclass (which the Java reflection API * normally does not allow). */ // Maybe combine this with generateMethod() private static void generateSuperDelegateMethod(String superClassName, String methodName, String returnType, String[] paramTypes, int modifiers, ClassWriter cw) { String[] exceptions = null; if (returnType == null) // map loose return to Object { returnType = OBJECT; } String methodDescriptor = getMethodDescriptor(returnType, paramTypes); // Add method body CodeVisitor cv = cw.visitMethod(modifiers, "_bshSuper" + methodName, methodDescriptor, exceptions); cv.visitVarInsn(ALOAD, 0); // Push vars int localVarIndex = 1; for (String paramType : paramTypes) { if (isPrimitive(paramType)) { cv.visitVarInsn(ILOAD, localVarIndex); } else { cv.visitVarInsn(ALOAD, localVarIndex); } localVarIndex += ((paramType.equals("D") || paramType.equals("J")) ? 2 : 1); } cv.visitMethodInsn(INVOKESPECIAL, superClassName, methodName, methodDescriptor); generatePlainReturnCode(returnType, cv); // Need to calculate this... just fudging here for now. cv.visitMaxs(20, 20); } boolean classContainsMethod(Class clas, String methodName, String[] paramTypes) { while (clas != null) { Method[] methods = clas.getDeclaredMethods(); for (Method method : methods) { if (method.getName().equals(methodName)) { String[] methodParamTypes = getTypeDescriptors(method.getParameterTypes()); boolean found = true; for (int j = 0; j < methodParamTypes.length; j++) { if (!paramTypes[j].equals(methodParamTypes[j])) { found = false; break; } } if (found) { return true; } } } clas = clas.getSuperclass(); } return false; } /** * Generate return code for a normal bytecode */ private static void generatePlainReturnCode(String returnType, CodeVisitor cv) { if (returnType.equals("V")) { cv.visitInsn(RETURN); } else if (isPrimitive(returnType)) { int opcode = IRETURN; if (returnType.equals("D")) { opcode = DRETURN; } else if (returnType.equals("F")) { opcode = FRETURN; } else if (returnType.equals("J")) //long { opcode = LRETURN; } cv.visitInsn(opcode); } else { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType)); cv.visitInsn(ARETURN); } } /** * Generates the code to reify the arguments of the given method. * For a method "int m (int i, String s)", this code is the bytecode * corresponding to the "new Object[] { new bsh.Primitive(i), s }" * expression. * * @param cv the code visitor to be used to generate the bytecode. * @param isStatic the enclosing methods is static * @author <NAME> * @author <NAME> */ private static void generateParameterReifierCode(String[] paramTypes, boolean isStatic, final CodeVisitor cv) { cv.visitIntInsn(SIPUSH, paramTypes.length); cv.visitTypeInsn(ANEWARRAY, "java/lang/Object"); int localVarIndex = isStatic ? 0 : 1; for (int i = 0; i < paramTypes.length; ++i) { String param = paramTypes[i]; cv.visitInsn(DUP); cv.visitIntInsn(SIPUSH, i); if (isPrimitive(param)) { int opcode; if (param.equals("F")) { opcode = FLOAD; } else if (param.equals("D")) { opcode = DLOAD; } else if (param.equals("J")) { opcode = LLOAD; } else { opcode = ILOAD; } String type = "bsh/Primitive"; cv.visitTypeInsn(NEW, type); cv.visitInsn(DUP); cv.visitVarInsn(opcode, localVarIndex); String desc = param; // ok? cv.visitMethodInsn(INVOKESPECIAL, type, "<init>", "(" + desc + ")V"); } else { // Technically incorrect here - we need to wrap null values // as bsh.Primitive.NULL. However the This.invokeMethod() // will do that much for us. // We need to generate a conditional here to test for null // and return Primitive.NULL cv.visitVarInsn(ALOAD, localVarIndex); } cv.visitInsn(AASTORE); localVarIndex += ((param.equals("D") || param.equals("J")) ? 2 : 1); } } /** * Generates the code to unreify the result of the given method. For a * method "int m (int i, String s)", this code is the bytecode * corresponding to the "((Integer)...).intValue()" expression. * * @param cv the code visitor to be used to generate the bytecode. * @author <NAME> * @author <NAME> */ private static void generateReturnCode(String returnType, CodeVisitor cv) { if (returnType.equals("V")) { cv.visitInsn(POP); cv.visitInsn(RETURN); } else if (isPrimitive(returnType)) { int opcode = IRETURN; String type; String meth; if (returnType.equals("B")) { type = "java/lang/Byte"; meth = "byteValue"; } else if (returnType.equals("I")) { type = "java/lang/Integer"; meth = "intValue"; } else if (returnType.equals("Z")) { type = "java/lang/Boolean"; meth = "booleanValue"; } else if (returnType.equals("D")) { opcode = DRETURN; type = "java/lang/Double"; meth = "doubleValue"; } else if (returnType.equals("F")) { opcode = FRETURN; type = "java/lang/Float"; meth = "floatValue"; } else if (returnType.equals("J")) { opcode = LRETURN; type = "java/lang/Long"; meth = "longValue"; } else if (returnType.equals("C")) { type = "java/lang/Character"; meth = "charValue"; } else /*if (returnType.equals("S") )*/ { type = "java/lang/Short"; meth = "shortValue"; } String desc = returnType; cv.visitTypeInsn(CHECKCAST, type); // type is correct here cv.visitMethodInsn(INVOKEVIRTUAL, type, meth, "()" + desc); cv.visitInsn(opcode); } else { cv.visitTypeInsn(CHECKCAST, descriptorToClassName(returnType)); cv.visitInsn(ARETURN); } } /** * Evaluate the arguments (if any) for the constructor specified by * the constructor index. Return the ConstructorArgs object which * contains the actual arguments to the alternate constructor and also the * index of that constructor for the constructor switch. * * @param consArgs the arguments to the constructor. These are necessary in * the evaluation of the alt constructor args. e.g. Foo(a) { super(a); } * @return the ConstructorArgs object containing a constructor selector * and evaluated arguments for the alternate constructor */ public static ConstructorArgs getConstructorArgs(String superClassName, This classStaticThis, Object[] consArgs, int index) { DelayedEvalBshMethod[] constructors; try { constructors = (DelayedEvalBshMethod[]) classStaticThis.getNameSpace().getVariable(BSHCONSTRUCTORS); } catch (Exception e) { throw new InterpreterError("unable to get instance initializer: " + e); } if (index == DEFAULTCONSTRUCTOR) // auto-gen default constructor { return ConstructorArgs.DEFAULT; } // use default super constructor DelayedEvalBshMethod constructor = constructors[index]; if (constructor.methodBody.jjtGetNumChildren() == 0) { return ConstructorArgs.DEFAULT; } // use default super constructor // Determine if the constructor calls this() or super() String altConstructor = null; BSHArguments argsNode = null; SimpleNode firstStatement = (SimpleNode) constructor.methodBody.jjtGetChild(0); if (firstStatement instanceof BSHPrimaryExpression) { firstStatement = (SimpleNode) firstStatement.jjtGetChild(0); } if (firstStatement instanceof BSHMethodInvocation) { BSHMethodInvocation methodNode = (BSHMethodInvocation) firstStatement; BSHAmbiguousName methodName = methodNode.getNameNode(); if (methodName.text.equals("super") || methodName.text.equals("this")) { altConstructor = methodName.text; argsNode = methodNode.getArgsNode(); } } if (altConstructor == null) { return ConstructorArgs.DEFAULT; } // use default super constructor // Make a tmp namespace to hold the original constructor args for // use in eval of the parameters node NameSpace consArgsNameSpace = new NameSpace(classStaticThis.getNameSpace(), "consArgs"); String[] consArgNames = constructor.getParameterNames(); Class[] consArgTypes = constructor.getParameterTypes(); for (int i = 0; i < consArgs.length; i++) { try { consArgsNameSpace.setTypedVariable(consArgNames[i], consArgTypes[i], consArgs[i], null/*modifiers*/); } catch (UtilEvalError e) { throw new InterpreterError("err setting local cons arg:" + e); } } // evaluate the args CallStack callstack = new CallStack(); callstack.push(consArgsNameSpace); Object[] args; Interpreter interpreter = classStaticThis.declaringInterpreter; try { args = argsNode.getArguments(callstack, interpreter); } catch (EvalError e) { throw new InterpreterError("Error evaluating constructor args: " + e); } Class[] argTypes = Types.getTypes(args); args = Primitive.unwrap(args); Class superClass = interpreter.getClassManager().classForName(superClassName); if (superClass == null) { throw new InterpreterError("can't find superclass: " + superClassName); } Constructor[] superCons = superClass.getDeclaredConstructors(); // find the matching super() constructor for the args if (altConstructor.equals("super")) { int i = Reflect.findMostSpecificConstructorIndex(argTypes, superCons); if (i == -1) { throw new InterpreterError("can't find constructor for args!"); } return new ConstructorArgs(i, args); } // find the matching this() constructor for the args Class[][] candidates = new Class[constructors.length][]; for (int i = 0; i < candidates.length; i++) { candidates[i] = constructors[i].getParameterTypes(); } int i = Reflect.findMostSpecificSignature(argTypes, candidates); if (i == -1) { throw new InterpreterError("can't find constructor for args 2!"); } // this() constructors come after super constructors in the table int selector = i + superCons.length; int ourSelector = index + superCons.length; // Are we choosing ourselves recursively through a this() reference? if (selector == ourSelector) { throw new InterpreterError("Recusive constructor call."); } return new ConstructorArgs(selector, args); } private static final ThreadLocal<NameSpace> CONTEXT_NAMESPACE = new ThreadLocal<NameSpace>(); private static final ThreadLocal<Interpreter> CONTEXT_INTERPRETER = new ThreadLocal<Interpreter>(); /** * Register actual context, used by generated class constructor, which calls * {@link #initInstance(GeneratedClass, String, Object[])}. */ static void registerConstructorContext(CallStack callstack, Interpreter interpreter) { if (callstack != null) { CONTEXT_NAMESPACE.set(callstack.top()); } else { CONTEXT_NAMESPACE.remove(); } if (interpreter != null) { CONTEXT_INTERPRETER.set(interpreter); } else { CONTEXT_INTERPRETER.remove(); } } /** * Initialize an instance of the class. * This method is called from the generated class constructor to evaluate * the instance initializer and scripted constructor in the instance * namespace. */ public static void initInstance(GeneratedClass instance, String className, Object[] args) { Class[] sig = Types.getTypes(args); CallStack callstack = new CallStack(); Interpreter interpreter; NameSpace instanceNameSpace; // check to see if the instance has already been initialized // (the case if using a this() alternate constuctor) // todo PeJoBo70 write test for this This instanceThis = getClassInstanceThis(instance, className); // XXX clean up this conditional if (instanceThis == null) { // Create the instance 'This' namespace, set it on the object // instance and invoke the instance initializer // Get the static This reference from the proto-instance This classStaticThis = getClassStaticThis(instance.getClass(), className); interpreter = CONTEXT_INTERPRETER.get(); if (interpreter == null) { interpreter = classStaticThis.declaringInterpreter; } // Get the instance initializer block from the static This BSHBlock instanceInitBlock; try { instanceInitBlock = (BSHBlock) classStaticThis.getNameSpace().getVariable(BSHINIT); } catch (Exception e) { throw new InterpreterError("unable to get instance initializer: " + e); } // Create the instance namespace if (CONTEXT_NAMESPACE.get() != null) { instanceNameSpace = classStaticThis.getNameSpace().copy(); instanceNameSpace.setParent(CONTEXT_NAMESPACE.get()); } else { instanceNameSpace = new NameSpace(classStaticThis.getNameSpace(), className); // todo: old code } instanceNameSpace.isClass = true; // Set the instance This reference on the instance instanceThis = instanceNameSpace.getThis(interpreter); try { LHS lhs = Reflect.getLHSObjectField(instance, BSHTHIS + className); lhs.assign(instanceThis, false/*strict*/); } catch (Exception e) { throw new InterpreterError("Error in class gen setup: " + e); } // Give the instance space its object import instanceNameSpace.setClassInstance(instance); // should use try/finally here to pop ns callstack.push(instanceNameSpace); // evaluate the instance portion of the block in it try { // Evaluate the initializer block instanceInitBlock.evalBlock(callstack, interpreter, true/*override*/, ClassGenerator.ClassNodeFilter.CLASSINSTANCE); } catch (Exception e) { throw new InterpreterError("Error in class initialization: " + e, e); } callstack.pop(); } else { // The object instance has already been initialzed by another // constructor. Fall through to invoke the constructor body below. interpreter = instanceThis.declaringInterpreter; instanceNameSpace = instanceThis.getNameSpace(); } // invoke the constructor method from the instanceThis String constructorName = getBaseName(className); try { // Find the constructor (now in the instance namespace) BshMethod constructor = instanceNameSpace.getMethod(constructorName, sig, true/*declaredOnly*/); // if args, we must have constructor if (args.length > 0 && constructor == null) { throw new InterpreterError("Can't find constructor: " + className); } // Evaluate the constructor if (constructor != null) { constructor.invoke(args, interpreter, callstack, null/*callerInfo*/, false/*overrideNameSpace*/); } } catch (Exception e) { if (e instanceof TargetError) { e = (Exception) ((TargetError) e).getTarget(); } if (e instanceof InvocationTargetException) { e = (Exception) ((InvocationTargetException) e).getTargetException(); } throw new InterpreterError("Error in class initialization: " + e, e); } } /** * Get the static bsh namespace field from the class. * * @param className may be the name of clas itself or a superclass of clas. */ private static This getClassStaticThis(Class clas, String className) { try { return (This) Reflect.getStaticFieldValue(clas, BSHSTATIC + className); } catch (Exception e) { throw new InterpreterError("Unable to get class static space: " + e); } } /** * Get the instance bsh namespace field from the object instance. * * @return the class instance This object or null if the object has not * been initialized. */ static This getClassInstanceThis(Object instance, String className) { try { Object o = Reflect.getObjectFieldValue(instance, BSHTHIS + className); return (This) Primitive.unwrap(o); // unwrap Primitive.Null to null } catch (Exception e) { throw new InterpreterError("Generated class: Error getting This" + e); } } /** * Does the type descriptor string describe a primitive type? */ private static boolean isPrimitive(String typeDescriptor) { return typeDescriptor.length() == 1; // right? } private static String[] getTypeDescriptors(Class[] cparams) { String[] sa = new String[cparams.length]; for (int i = 0; i < sa.length; i++) { sa[i] = BSHType.getTypeDescriptor(cparams[i]); } return sa; } /** * If a non-array object type, remove the prefix "L" and suffix ";". */ // Can this be factored out...? // Should be be adding the L...; here instead? private static String descriptorToClassName(String s) { if (s.startsWith("[") || !s.startsWith("L")) { return s; } return s.substring(1, s.length() - 1); } private static String getBaseName(String className) { int i = className.indexOf("$"); if (i == -1) { return className; } return className.substring(i + 1); } /** * A ConstructorArgs object holds evaluated arguments for a constructor * call as well as the index of a possible alternate selector to invoke. * This object is used by the constructor switch. * * @see bsh.ClassGeneratorUtil#generateConstructor(int, String[], int, bsh.org.objectweb.asm.ClassWriter) */ public static class ConstructorArgs { /** * A ConstructorArgs which calls the default constructor */ public static final ConstructorArgs DEFAULT = new ConstructorArgs(); public int selector = DEFAULTCONSTRUCTOR; Object[] args; int arg; /** * The index of the constructor to call. */ ConstructorArgs() { } ConstructorArgs(int selector, Object[] args) { this.selector = selector; this.args = args; } Object next() { return args[arg++]; } public boolean getBoolean() { return (Boolean) next(); } public byte getByte() { return (Byte) next(); } public char getChar() { return (Character) next(); } public short getShort() { return (Short) next(); } public int getInt() { return (Integer) next(); } public long getLong() { return (Long) next(); } public double getDouble() { return (Double) next(); } public float getFloat() { return (Float) next(); } public Object getObject() { return next(); } } }
38,000
0.686385
0.684598
1,157
31.88937
31.612167
312
false
false
0
0
0
0
0
0
2.325843
false
false
9
f669af4be33691fb72bb25f1ea96b99eb585e0ec
25,855,703,146,533
64d3ecff33658b2b0c1c8241c8d1a465d450c9ba
/src/main/java/com/thousandeyes/dao/UserDAO.java
c5aca90350e24d28786c80091e489da32d25aae7
[]
no_license
vineetbhatkoti/Twitter-backend
https://github.com/vineetbhatkoti/Twitter-backend
0fe7a216477ef708a6639f7be89f690fe4418e8a
f357cc094195f553a6f2dd2524d69195bb4a300e
refs/heads/master
2020-05-23T20:50:00.664000
2017-03-15T22:56:34
2017-03-15T22:56:34
84,788,679
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.thousandeyes.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.thousandeyes.exception.DAOException; import com.thousandeyes.model.PopularUser; import com.thousandeyes.model.User; /* * @desc: This is the DAO interface for the user requests * @author: Vineet Bhatkoti */ @Repository public interface UserDAO { public List<User> getFollowersOfUser(User usr) throws DAOException; public List<User> getUserFollows(User user) throws DAOException; public String startFollowing(User firstUser, User secondUser) throws DAOException; public String unfollow(User firstUser, User secondUser) throws DAOException; public List<PopularUser> mostPopularFollower() throws DAOException; }
UTF-8
Java
744
java
UserDAO.java
Java
[ { "context": "he DAO interface for the user requests\n * @author: Vineet Bhatkoti\n */\n\n@Repository\npublic interface UserDAO {\n\tpubl", "end": 322, "score": 0.9998914003372192, "start": 307, "tag": "NAME", "value": "Vineet Bhatkoti" } ]
null
[]
package com.thousandeyes.dao; import java.util.List; import org.springframework.stereotype.Repository; import com.thousandeyes.exception.DAOException; import com.thousandeyes.model.PopularUser; import com.thousandeyes.model.User; /* * @desc: This is the DAO interface for the user requests * @author: <NAME> */ @Repository public interface UserDAO { public List<User> getFollowersOfUser(User usr) throws DAOException; public List<User> getUserFollows(User user) throws DAOException; public String startFollowing(User firstUser, User secondUser) throws DAOException; public String unfollow(User firstUser, User secondUser) throws DAOException; public List<PopularUser> mostPopularFollower() throws DAOException; }
735
0.801075
0.801075
27
26.555555
27.970001
83
false
false
0
0
0
0
0
0
0.814815
false
false
9
e48a6409671f267b2f7185b2318be446eddbd363
25,855,703,146,227
745d255706d6e41994dfe4b6a6a6c073959431ff
/src/test/java/com/eclecticlogic/stepper/antlr/TestGrammar.java
5feceffaa33380401c0b6285c2a38a230c379691
[ "Apache-2.0" ]
permissive
JulianoCristian/stepper
https://github.com/JulianoCristian/stepper
ece0ad08cd1ac400fde64a533428e8f8289ed46f
eb3f6cfbf23cabe4efa49fb30ec1427e798c02e2
refs/heads/master
2020-05-04T17:10:17.234000
2019-03-26T01:05:09
2019-03-26T01:05:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eclecticlogic.stepper.antlr; import org.antlr.v4.runtime.ParserRuleContext; import org.junit.Test; import java.util.function.Function; /** * Tests parsing rules. Simply tests that parsing doesn't fail with exceptions. */ public class TestGrammar extends AbstractGrammarTester { void testScalarTypeUse(Function<StepperParser, ParserRuleContext> parserFunction) { parse("\"hello\"", parserFunction); parse("\"he\"llo\"", parserFunction); parse("\"he\"\"llo\"", parserFunction); parse("123", parserFunction); parse("123.23", parserFunction); parse("123.23e+10", parserFunction); parse("123.23e-10", parserFunction); parse("-123.23e-10", parserFunction); parse("true", parserFunction); parse("false", parserFunction); } @Test public void testScalar() { testScalarTypeUse(p -> p.scalar()); } @Test public void testValue() { Function<StepperParser, ParserRuleContext> fn = p -> p.value(); testScalarTypeUse(fn); parse("{}", fn); parse("[]", fn); parse("[1, 2, true, false]", fn); parse("[\"a\", \"b\"]", fn); parse("{\"attrib\": 123}", fn); parse("[{\"attrib\": 123}]", fn); parse("[{\"attrib\": 123, \"c\": [\"a\", true]}]", fn); parse("grammar.stg", "testValueNested", fn); } @Test public void testJsonObject() { parse("grammar.stg", "testValueNested", p -> p.jsonObject()); } @Test public void testTask() { parse("grammar.stg", "testTask", p -> p.task()); parse("grammar.stg", "testStatementTask1", p -> p.statement()); parse("grammar.stg", "testStatementTask2", p -> p.statement()); parse("grammar.stg", "testStatementTask3", p -> p.statement()); parse("grammar.stg", "testStatementTask4", p -> p.statement()); } @Test public void testDereference() { Function<StepperParser, ParserRuleContext> fn = p -> p.dereference(); parse("abc.def", fn); parse("abc", fn); parse("abc.d.e.f", fn); } @Test public void testExpr() { Function<StepperParser, ParserRuleContext> fn = p -> p.expr(); testScalarTypeUse(fn); parse("null", fn); parse("12 * 3", fn); parse("12 / 3", fn); parse("12 + 3", fn); parse("12 - 3", fn); parse("a * b", fn); parse("a / b", fn); parse("a + b", fn); parse("a - b", fn); parse("(a - b)", fn); parse("c + (a - b)", fn); parse("c && (a || !b)", fn); parse("c == (a + b) * c", fn); parse("c < (a + b) * c", fn); parse("c <= (a + b) * c", fn); parse("c > (a + b) * c", fn); parse("c >= (a + b) * c", fn); parse("c.d.e", fn); parse("c.d.e[3].f", fn); parse("c.d.e[3].f().g", fn); parse("c().d().e[0][1]", fn); parse("c(a+b).d(r && f).e[0][w-q(4)]", fn); parse("c(a+b, r(z).d && f)", fn); parse("c++", fn); parse("++c", fn); parse("--c", fn); parse("c--", fn); parse("c()--", fn); parse("--c()", fn); parse("++c()", fn); parse("c()++", fn); } @Test public void testAssignment() { Function<StepperParser, ParserRuleContext> fn = p -> p.assignment(); parse("grammar.stg", "testAssignmentTask1", fn); parse("grammar.stg", "testAssignmentTask2", fn); parse("@Label(\"xyz\") a.b.c = d - g();", fn); parse("a.b.c += d - g()--;", fn); parse("a.b.c -= d - g();", fn); parse("@Label(\"xyz\") a.b.c *= d - ++g();", fn); parse("a.b.c /= d - g();", fn); parse("grammar.stg", "testAssignmentJson", fn); parse("@Label(\"xyz\") ab.cd = [1, 2, 3]", fn); } @Test public void testFor() { Function<StepperParser, ParserRuleContext> fn = p -> p.forStatement(); parse("grammar.stg", "testForLoop1", fn); parse("grammar.stg", "testForLoop2", fn); parse("grammar.stg", "testForLoop3", fn); parse("grammar.stg", "testForIteration", fn); } @Test public void testIf() { Function<StepperParser, ParserRuleContext> fn = p -> p.ifStatement(); parse("grammar.stg", "testIf1", fn); parse("grammar.stg", "testIf2", fn); parse("grammar.stg", "testIf3", fn); } @Test public void testWhile() { Function<StepperParser, ParserRuleContext> fn = p -> p.whileStatement(); parse("grammar.stg", "testWhile", fn); } @Test public void testWhen() { Function<StepperParser, ParserRuleContext> fn = p -> p.whenStatement(); parse("grammar.stg", "testWhen1", fn); parse("grammar.stg", "testWhen2", fn); parse("grammar.stg", "testWhen3", fn); } }
UTF-8
Java
4,899
java
TestGrammar.java
Java
[]
null
[]
package com.eclecticlogic.stepper.antlr; import org.antlr.v4.runtime.ParserRuleContext; import org.junit.Test; import java.util.function.Function; /** * Tests parsing rules. Simply tests that parsing doesn't fail with exceptions. */ public class TestGrammar extends AbstractGrammarTester { void testScalarTypeUse(Function<StepperParser, ParserRuleContext> parserFunction) { parse("\"hello\"", parserFunction); parse("\"he\"llo\"", parserFunction); parse("\"he\"\"llo\"", parserFunction); parse("123", parserFunction); parse("123.23", parserFunction); parse("123.23e+10", parserFunction); parse("123.23e-10", parserFunction); parse("-123.23e-10", parserFunction); parse("true", parserFunction); parse("false", parserFunction); } @Test public void testScalar() { testScalarTypeUse(p -> p.scalar()); } @Test public void testValue() { Function<StepperParser, ParserRuleContext> fn = p -> p.value(); testScalarTypeUse(fn); parse("{}", fn); parse("[]", fn); parse("[1, 2, true, false]", fn); parse("[\"a\", \"b\"]", fn); parse("{\"attrib\": 123}", fn); parse("[{\"attrib\": 123}]", fn); parse("[{\"attrib\": 123, \"c\": [\"a\", true]}]", fn); parse("grammar.stg", "testValueNested", fn); } @Test public void testJsonObject() { parse("grammar.stg", "testValueNested", p -> p.jsonObject()); } @Test public void testTask() { parse("grammar.stg", "testTask", p -> p.task()); parse("grammar.stg", "testStatementTask1", p -> p.statement()); parse("grammar.stg", "testStatementTask2", p -> p.statement()); parse("grammar.stg", "testStatementTask3", p -> p.statement()); parse("grammar.stg", "testStatementTask4", p -> p.statement()); } @Test public void testDereference() { Function<StepperParser, ParserRuleContext> fn = p -> p.dereference(); parse("abc.def", fn); parse("abc", fn); parse("abc.d.e.f", fn); } @Test public void testExpr() { Function<StepperParser, ParserRuleContext> fn = p -> p.expr(); testScalarTypeUse(fn); parse("null", fn); parse("12 * 3", fn); parse("12 / 3", fn); parse("12 + 3", fn); parse("12 - 3", fn); parse("a * b", fn); parse("a / b", fn); parse("a + b", fn); parse("a - b", fn); parse("(a - b)", fn); parse("c + (a - b)", fn); parse("c && (a || !b)", fn); parse("c == (a + b) * c", fn); parse("c < (a + b) * c", fn); parse("c <= (a + b) * c", fn); parse("c > (a + b) * c", fn); parse("c >= (a + b) * c", fn); parse("c.d.e", fn); parse("c.d.e[3].f", fn); parse("c.d.e[3].f().g", fn); parse("c().d().e[0][1]", fn); parse("c(a+b).d(r && f).e[0][w-q(4)]", fn); parse("c(a+b, r(z).d && f)", fn); parse("c++", fn); parse("++c", fn); parse("--c", fn); parse("c--", fn); parse("c()--", fn); parse("--c()", fn); parse("++c()", fn); parse("c()++", fn); } @Test public void testAssignment() { Function<StepperParser, ParserRuleContext> fn = p -> p.assignment(); parse("grammar.stg", "testAssignmentTask1", fn); parse("grammar.stg", "testAssignmentTask2", fn); parse("@Label(\"xyz\") a.b.c = d - g();", fn); parse("a.b.c += d - g()--;", fn); parse("a.b.c -= d - g();", fn); parse("@Label(\"xyz\") a.b.c *= d - ++g();", fn); parse("a.b.c /= d - g();", fn); parse("grammar.stg", "testAssignmentJson", fn); parse("@Label(\"xyz\") ab.cd = [1, 2, 3]", fn); } @Test public void testFor() { Function<StepperParser, ParserRuleContext> fn = p -> p.forStatement(); parse("grammar.stg", "testForLoop1", fn); parse("grammar.stg", "testForLoop2", fn); parse("grammar.stg", "testForLoop3", fn); parse("grammar.stg", "testForIteration", fn); } @Test public void testIf() { Function<StepperParser, ParserRuleContext> fn = p -> p.ifStatement(); parse("grammar.stg", "testIf1", fn); parse("grammar.stg", "testIf2", fn); parse("grammar.stg", "testIf3", fn); } @Test public void testWhile() { Function<StepperParser, ParserRuleContext> fn = p -> p.whileStatement(); parse("grammar.stg", "testWhile", fn); } @Test public void testWhen() { Function<StepperParser, ParserRuleContext> fn = p -> p.whenStatement(); parse("grammar.stg", "testWhen1", fn); parse("grammar.stg", "testWhen2", fn); parse("grammar.stg", "testWhen3", fn); } }
4,899
0.514595
0.498877
161
29.428572
22.978985
87
false
false
0
0
0
0
0
0
1.347826
false
false
9
63c6fdde9102ddb1e9ec68ad38b4c478bf2b25b0
31,516,470,056,447
f124eec14975c5f9bdc5a64de9b3e80e518b9891
/src/main/java/com/cts/codeassignment/formsubmission/service/UserService.java
ca46a3a9c4a06f10f4c43983fbbe37f3084cd410
[]
no_license
sudheerrachuri/RaboCodeAssignment
https://github.com/sudheerrachuri/RaboCodeAssignment
aa2de6ac771fafae21b17ce55a3bece6b218bbcd
d5ba93c89c85655af16b398ea166e0f452911da4
refs/heads/master
2022-01-26T04:29:57.868000
2020-01-17T14:26:58
2020-01-17T14:26:58
233,062,992
0
0
null
false
2022-01-21T23:36:14
2020-01-10T14:22:38
2020-01-17T14:27:07
2022-01-21T23:36:14
79
0
0
2
Java
false
false
package com.cts.codeassignment.formsubmission.service; import com.cts.codeassignment.formsubmission.beans.User; import java.util.List; public interface UserService { User saveUser(User user); List<User> getUsers(); User updateUser(User updateUser); boolean deleteUserById(int id); }
UTF-8
Java
303
java
UserService.java
Java
[]
null
[]
package com.cts.codeassignment.formsubmission.service; import com.cts.codeassignment.formsubmission.beans.User; import java.util.List; public interface UserService { User saveUser(User user); List<User> getUsers(); User updateUser(User updateUser); boolean deleteUserById(int id); }
303
0.762376
0.762376
13
22.307692
19.76549
56
false
false
0
0
0
0
0
0
0.538462
false
false
9
c1863532b87265556934703f9d00daabf670198a
20,478,404,098,228
da1d67376ba55e1726ef5266a9389e5b2f122ea0
/JavaWork/Exceptions/src/com/cognizant/Examples/MyException.java
3aabc5137d930f743a751a6c5d6aec4508a32d7b
[]
no_license
Zak-Roberts/JavaWork
https://github.com/Zak-Roberts/JavaWork
4a9761e02e9581013228e3d09c6d836796608f53
d90090c7189572d7b6cd2b8238d6c521bf4093a8
refs/heads/master
2020-04-07T21:49:23.915000
2018-11-23T16:23:59
2018-11-23T16:23:59
158,742,235
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
// showcasing creating my own exception in another class to throw here (linked class is 'ThrowException') package com.cognizant.Examples; import java.util.Scanner; public class MyException { public static void main(String[] args) { MyException e = new MyException(); try { System.out.println(e.method1()); } catch(ThrowException e1) { System.out.println(e1.toString()); } } public String method1() throws ThrowException { Scanner sc = new Scanner(System.in); System.out.println("Enter a number: "); float input = sc.nextFloat(); sc.close(); if(input == 0) { throw new ThrowException(); } else { return "5 divided by your number is " + 5/input; } } }
UTF-8
Java
706
java
MyException.java
Java
[]
null
[]
// showcasing creating my own exception in another class to throw here (linked class is 'ThrowException') package com.cognizant.Examples; import java.util.Scanner; public class MyException { public static void main(String[] args) { MyException e = new MyException(); try { System.out.println(e.method1()); } catch(ThrowException e1) { System.out.println(e1.toString()); } } public String method1() throws ThrowException { Scanner sc = new Scanner(System.in); System.out.println("Enter a number: "); float input = sc.nextFloat(); sc.close(); if(input == 0) { throw new ThrowException(); } else { return "5 divided by your number is " + 5/input; } } }
706
0.671388
0.661473
34
19.705883
22.353483
105
false
false
0
0
0
0
0
0
1.676471
false
false
9
361e5cffc09216f3fc295f70bf1cc9d04f106dfd
15,221,364,103,342
0a15ac66636ffcb77ed5605cb04222c178f22525
/src/main/java/in/com/firstchoice/reservation/controller/ReservationController.java
dc35c91d99d9c3928372e1d72db76f4033cc71bd
[]
no_license
shahnahidmahmud/reservation
https://github.com/shahnahidmahmud/reservation
86a6c5b81fa6ea441362c7ba957ff4aeca4baf27
bf8fa56a28e23b78e3c8f2a82613cf27348faf34
refs/heads/master
2023-04-05T16:10:53.479000
2020-02-05T01:24:24
2020-02-05T01:24:24
238,342,825
0
0
null
false
2023-03-23T20:38:49
2020-02-05T01:24:07
2020-02-05T01:24:27
2023-03-23T20:38:45
21
0
0
2
Java
false
false
package in.com.firstchoice.reservation.controller; import in.com.firstchoice.reservation.common.DateCalculation; import in.com.firstchoice.reservation.common.Price; import in.com.firstchoice.reservation.common.ResponseDetails; import in.com.firstchoice.reservation.common.Schedule; import in.com.firstchoice.reservation.model.ReservationBookingMaster; import in.com.firstchoice.reservation.model.ReservationMaster; import in.com.firstchoice.reservation.request.CancelBooking; import in.com.firstchoice.reservation.request.DateRangeDto; import in.com.firstchoice.reservation.request.ReservationReq; import in.com.firstchoice.reservation.request.UpdateReservationReq; import in.com.firstchoice.reservation.response.AvailabilityRes; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.joda.time.DateTime; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.time.temporal.ChronoUnit; @RestController @RequestMapping("/reservation") @Slf4j public class ReservationController { @Autowired private static ReservationMaster reservationMaster; @Autowired private static List<ReservationBookingMaster> reservationBookingMasterList = new ArrayList<>(); @Autowired private ModelMapper modelMapper; @GetMapping("/getAvailability") public ResponseEntity fetchReservationAvailability(HttpServletRequest request, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) { try { log.debug("Get Reservation Availability For the Date {}", DateTime.now()); DateCalculation dateCalculation = new DateCalculation(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDate), DateTime.parse(endDate), new ArrayList<>()); List<AvailabilityRes> availabilityResList = new ArrayList<>(); detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { AvailabilityRes availabilityRes = new AvailabilityRes(); reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { availabilityRes.setMonth(reservationSchedule.getMonth()); dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { Schedule schedule1 = new Schedule(); schedule1.setAvailability(schedule.getAvailability()); schedule1.setDate(schedule.getDate()); schedule1.setPriceList(schedule.getPriceList()); schedule1.setTotalInventory(schedule.getTotalInventory()); availabilityRes.getSchedules().add(schedule1); } }); }); } }); availabilityResList.add(availabilityRes); }); return ResponseEntity.ok(availabilityResList); } catch (NullPointerException e) { return ResponseDetails.pleaseTryagainResponse(); } catch (Exception e) { return ResponseDetails.pleaseTryagainResponse(); } } @PostMapping("/savereservation") public ResponseEntity saveReservation(HttpServletRequest request, @RequestBody ReservationReq reservationReq) { log.debug("Save Reservation Details"); try { if(null==reservationMaster) { loadData(); } long daysBetween = ChronoUnit.DAYS.between(reservationReq.getStartDate(), reservationReq.getEndDate()); if (daysBetween > 3) { return ResponseDetails.unsucessfullResponse("Max allowed stay is 3 days"); } long bookingDate = ChronoUnit.DAYS.between(LocalDate.now(), reservationReq.getStartDate()); if (bookingDate < 1) { return ResponseDetails.unsucessfullResponse("Booking cannot be done on the Departure Date"); } else if (bookingDate > 30) { return ResponseDetails.unsucessfullResponse("Booking is allowed within 30 days only"); } else { DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationReq.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationReq.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationReq.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { if (schedule.getAvailability() >= Integer.valueOf(paxDetails.getNumberOfPax())) { schedule.setAvailability(schedule.getAvailability() - Integer.valueOf(paxDetails.getNumberOfPax())); } else if (schedule.getAvailability() < Integer.valueOf(paxDetails.getNumberOfPax())) { inventoryAvailable[0] = Boolean.TRUE; } } }); }); } }); }); }); if (inventoryAvailable[0]) { return ResponseDetails.unsucessfullResponse("Inventory unavailable"); } else { ModelMapper modelMapper=new ModelMapper(); ReservationBookingMaster reservationBookingMaster = modelMapper.map(reservationReq, ReservationBookingMaster.class); reservationBookingMaster.setStatus("Confirmed"); String randomAlphabetic = RandomStringUtils.randomAlphabetic(6); reservationBookingMaster.setBookingId(randomAlphabetic); reservationBookingMasterList.add(reservationBookingMaster); return ResponseDetails.successResponse("Booking is successfull ,Booking Id - "+randomAlphabetic); } } } catch (NullPointerException e) { return ResponseDetails.pleaseTryagainResponse(); } catch (Exception e) { return ResponseDetails.pleaseTryagainResponse(); } } @PostMapping("/cancelBooking") public ResponseEntity cancelBooking(HttpServletRequest request, @RequestBody CancelBooking cancelBooking) { DateCalculation dateCalculation = new DateCalculation(); reservationBookingMasterList.stream().forEach(reservationBookingMaster -> { if (reservationBookingMaster.getBookingId().equals(cancelBooking.getBookingId())) { reservationBookingMaster.setStatus("Cancelled"); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationBookingMaster.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { schedule.setAvailability(schedule.getAvailability() + Integer.valueOf(paxDetails.getNumberOfPax())); } }); }); } }); }); }); } }); return ResponseDetails.successResponse("Booking has been cancelled for booking id " + cancelBooking.getBookingId()); } @PostMapping("/modifyreservation") public ResponseEntity modifyReservation(HttpServletRequest request, @RequestBody UpdateReservationReq reservationReq) { final ReservationBookingMaster[] toRemove = {new ReservationBookingMaster()}; reservationBookingMasterList.stream().forEach(reservationBookingMaster -> { if (reservationBookingMaster.getBookingId().equals(reservationReq.getBookingId())) { toRemove[0] = reservationBookingMaster; DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); //Add Inventory Back detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationBookingMaster.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { schedule.setAvailability(schedule.getAvailability() + Integer.valueOf(paxDetails.getNumberOfPax())); } }); }); } }); }); }); } }); reservationBookingMasterList.remove(toRemove[0]); // Remove From inventory DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationReq.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationReq.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationReq.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { if (schedule.getAvailability() >= Integer.valueOf(paxDetails.getNumberOfPax())) { schedule.setAvailability(schedule.getAvailability() - Integer.valueOf(paxDetails.getNumberOfPax())); } else if (schedule.getAvailability() < Integer.valueOf(paxDetails.getNumberOfPax())) { inventoryAvailable[0] = Boolean.TRUE; } } }); }); } }); }); }); if (inventoryAvailable[0]) { return ResponseDetails.unsucessfullResponse("Inventory unavailable"); } else { ModelMapper modelMapper=new ModelMapper(); ReservationBookingMaster bookingMaster = modelMapper.map(reservationReq, ReservationBookingMaster.class); bookingMaster.setStatus("Confirmed"); reservationBookingMasterList.add(bookingMaster); return ResponseDetails.successResponse("Modified booking successfully for booking id - " + bookingMaster.getBookingId()); } } @GetMapping("/loadData") public static void loadData() { reservationMaster = new ReservationMaster(); // Cancelltion Policy reservationMaster.getCancellationPolicy().add("Till 72 hours before departure time: 10% of basic fare"); reservationMaster.getCancellationPolicy().add("Between 72 hours and up to 24 hours before departure time: 25% of basic fare."); reservationMaster.getCancellationPolicy().add("Between 24 hours and up to 30 minutes from departure time: 50% of basic fare"); // Exclusion reservationMaster.getExclusion().add("Package price does not include Gala dinner charges applicable on Christmas and New Year's Eve"); // Polices reservationMaster.getPolicies().add("\n" + "Please note that these packages are customizable, which means that you will be able to make changes to the itinerary/activity " + "if you so desire. The final payment will be calculated as per the activities reflecting on the website which will be outlined in the " + "confirmatory e-mail sent to you"); DateCalculation dateCalculation = new DateCalculation(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.now(), DateTime.now().plusDays(90), new ArrayList<>()); detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { ReservationMaster.ReservationSchedule reservationSchedule = new ReservationMaster.ReservationSchedule(); reservationSchedule.setMonth(dateRangeDto.getMonthOfYear()); dateRangeDto.getDatesOfMonths().stream().forEach(date -> { Schedule schedule = new Schedule(); schedule.setAvailability(30); schedule.setDate(date); schedule.setTotalInventory(30); Price price = new Price(); price.setLabel("Adult"); price.setPrice("1000"); Price price1 = new Price(); price1.setLabel("Child"); price1.setPrice("500"); schedule.getPriceList().add(price); schedule.getPriceList().add(price1); reservationSchedule.getSchedules().add(schedule); }); reservationMaster.getReservationSchedules().add(reservationSchedule); }); } }
UTF-8
Java
17,782
java
ReservationController.java
Java
[]
null
[]
package in.com.firstchoice.reservation.controller; import in.com.firstchoice.reservation.common.DateCalculation; import in.com.firstchoice.reservation.common.Price; import in.com.firstchoice.reservation.common.ResponseDetails; import in.com.firstchoice.reservation.common.Schedule; import in.com.firstchoice.reservation.model.ReservationBookingMaster; import in.com.firstchoice.reservation.model.ReservationMaster; import in.com.firstchoice.reservation.request.CancelBooking; import in.com.firstchoice.reservation.request.DateRangeDto; import in.com.firstchoice.reservation.request.ReservationReq; import in.com.firstchoice.reservation.request.UpdateReservationReq; import in.com.firstchoice.reservation.response.AvailabilityRes; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.RandomStringUtils; import org.joda.time.DateTime; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.time.temporal.ChronoUnit; @RestController @RequestMapping("/reservation") @Slf4j public class ReservationController { @Autowired private static ReservationMaster reservationMaster; @Autowired private static List<ReservationBookingMaster> reservationBookingMasterList = new ArrayList<>(); @Autowired private ModelMapper modelMapper; @GetMapping("/getAvailability") public ResponseEntity fetchReservationAvailability(HttpServletRequest request, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) { try { log.debug("Get Reservation Availability For the Date {}", DateTime.now()); DateCalculation dateCalculation = new DateCalculation(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDate), DateTime.parse(endDate), new ArrayList<>()); List<AvailabilityRes> availabilityResList = new ArrayList<>(); detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { AvailabilityRes availabilityRes = new AvailabilityRes(); reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { availabilityRes.setMonth(reservationSchedule.getMonth()); dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { Schedule schedule1 = new Schedule(); schedule1.setAvailability(schedule.getAvailability()); schedule1.setDate(schedule.getDate()); schedule1.setPriceList(schedule.getPriceList()); schedule1.setTotalInventory(schedule.getTotalInventory()); availabilityRes.getSchedules().add(schedule1); } }); }); } }); availabilityResList.add(availabilityRes); }); return ResponseEntity.ok(availabilityResList); } catch (NullPointerException e) { return ResponseDetails.pleaseTryagainResponse(); } catch (Exception e) { return ResponseDetails.pleaseTryagainResponse(); } } @PostMapping("/savereservation") public ResponseEntity saveReservation(HttpServletRequest request, @RequestBody ReservationReq reservationReq) { log.debug("Save Reservation Details"); try { if(null==reservationMaster) { loadData(); } long daysBetween = ChronoUnit.DAYS.between(reservationReq.getStartDate(), reservationReq.getEndDate()); if (daysBetween > 3) { return ResponseDetails.unsucessfullResponse("Max allowed stay is 3 days"); } long bookingDate = ChronoUnit.DAYS.between(LocalDate.now(), reservationReq.getStartDate()); if (bookingDate < 1) { return ResponseDetails.unsucessfullResponse("Booking cannot be done on the Departure Date"); } else if (bookingDate > 30) { return ResponseDetails.unsucessfullResponse("Booking is allowed within 30 days only"); } else { DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationReq.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationReq.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationReq.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { if (schedule.getAvailability() >= Integer.valueOf(paxDetails.getNumberOfPax())) { schedule.setAvailability(schedule.getAvailability() - Integer.valueOf(paxDetails.getNumberOfPax())); } else if (schedule.getAvailability() < Integer.valueOf(paxDetails.getNumberOfPax())) { inventoryAvailable[0] = Boolean.TRUE; } } }); }); } }); }); }); if (inventoryAvailable[0]) { return ResponseDetails.unsucessfullResponse("Inventory unavailable"); } else { ModelMapper modelMapper=new ModelMapper(); ReservationBookingMaster reservationBookingMaster = modelMapper.map(reservationReq, ReservationBookingMaster.class); reservationBookingMaster.setStatus("Confirmed"); String randomAlphabetic = RandomStringUtils.randomAlphabetic(6); reservationBookingMaster.setBookingId(randomAlphabetic); reservationBookingMasterList.add(reservationBookingMaster); return ResponseDetails.successResponse("Booking is successfull ,Booking Id - "+randomAlphabetic); } } } catch (NullPointerException e) { return ResponseDetails.pleaseTryagainResponse(); } catch (Exception e) { return ResponseDetails.pleaseTryagainResponse(); } } @PostMapping("/cancelBooking") public ResponseEntity cancelBooking(HttpServletRequest request, @RequestBody CancelBooking cancelBooking) { DateCalculation dateCalculation = new DateCalculation(); reservationBookingMasterList.stream().forEach(reservationBookingMaster -> { if (reservationBookingMaster.getBookingId().equals(cancelBooking.getBookingId())) { reservationBookingMaster.setStatus("Cancelled"); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationBookingMaster.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { schedule.setAvailability(schedule.getAvailability() + Integer.valueOf(paxDetails.getNumberOfPax())); } }); }); } }); }); }); } }); return ResponseDetails.successResponse("Booking has been cancelled for booking id " + cancelBooking.getBookingId()); } @PostMapping("/modifyreservation") public ResponseEntity modifyReservation(HttpServletRequest request, @RequestBody UpdateReservationReq reservationReq) { final ReservationBookingMaster[] toRemove = {new ReservationBookingMaster()}; reservationBookingMasterList.stream().forEach(reservationBookingMaster -> { if (reservationBookingMaster.getBookingId().equals(reservationReq.getBookingId())) { toRemove[0] = reservationBookingMaster; DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationBookingMaster.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); //Add Inventory Back detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationBookingMaster.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { schedule.setAvailability(schedule.getAvailability() + Integer.valueOf(paxDetails.getNumberOfPax())); } }); }); } }); }); }); } }); reservationBookingMasterList.remove(toRemove[0]); // Remove From inventory DateCalculation dateCalculation = new DateCalculation(); SimpleDateFormat startDateString = new SimpleDateFormat("yyyy-MM-dd"); ZoneId defaultZoneId = ZoneId.systemDefault(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.parse(startDateString.format(Date.from(reservationReq.getStartDate().atStartOfDay(defaultZoneId).toInstant()))), DateTime.parse(startDateString.format(Date.from(reservationReq.getEndDate().atStartOfDay(defaultZoneId).toInstant()))), new ArrayList<>()); final Boolean[] inventoryAvailable = {Boolean.FALSE}; detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { reservationReq.getPaxDetails().stream().forEach(paxDetails -> { reservationMaster.getReservationSchedules().stream().forEach(reservationSchedule -> { if (dateRangeDto.getMonthOfYear().equals(reservationSchedule.getMonth())) { dateRangeDto.getDatesOfMonths().stream().forEach(date -> { reservationSchedule.getSchedules().stream().forEach(schedule -> { if (schedule.getDate() == Integer.valueOf(date).intValue()) { if (schedule.getAvailability() >= Integer.valueOf(paxDetails.getNumberOfPax())) { schedule.setAvailability(schedule.getAvailability() - Integer.valueOf(paxDetails.getNumberOfPax())); } else if (schedule.getAvailability() < Integer.valueOf(paxDetails.getNumberOfPax())) { inventoryAvailable[0] = Boolean.TRUE; } } }); }); } }); }); }); if (inventoryAvailable[0]) { return ResponseDetails.unsucessfullResponse("Inventory unavailable"); } else { ModelMapper modelMapper=new ModelMapper(); ReservationBookingMaster bookingMaster = modelMapper.map(reservationReq, ReservationBookingMaster.class); bookingMaster.setStatus("Confirmed"); reservationBookingMasterList.add(bookingMaster); return ResponseDetails.successResponse("Modified booking successfully for booking id - " + bookingMaster.getBookingId()); } } @GetMapping("/loadData") public static void loadData() { reservationMaster = new ReservationMaster(); // Cancelltion Policy reservationMaster.getCancellationPolicy().add("Till 72 hours before departure time: 10% of basic fare"); reservationMaster.getCancellationPolicy().add("Between 72 hours and up to 24 hours before departure time: 25% of basic fare."); reservationMaster.getCancellationPolicy().add("Between 24 hours and up to 30 minutes from departure time: 50% of basic fare"); // Exclusion reservationMaster.getExclusion().add("Package price does not include Gala dinner charges applicable on Christmas and New Year's Eve"); // Polices reservationMaster.getPolicies().add("\n" + "Please note that these packages are customizable, which means that you will be able to make changes to the itinerary/activity " + "if you so desire. The final payment will be calculated as per the activities reflecting on the website which will be outlined in the " + "confirmatory e-mail sent to you"); DateCalculation dateCalculation = new DateCalculation(); List<DateRangeDto> detailsBetweenTwoDates = dateCalculation.getMonthDetailsBetweenTwoDates(DateTime.now(), DateTime.now().plusDays(90), new ArrayList<>()); detailsBetweenTwoDates.stream().forEach(dateRangeDto -> { ReservationMaster.ReservationSchedule reservationSchedule = new ReservationMaster.ReservationSchedule(); reservationSchedule.setMonth(dateRangeDto.getMonthOfYear()); dateRangeDto.getDatesOfMonths().stream().forEach(date -> { Schedule schedule = new Schedule(); schedule.setAvailability(30); schedule.setDate(date); schedule.setTotalInventory(30); Price price = new Price(); price.setLabel("Adult"); price.setPrice("1000"); Price price1 = new Price(); price1.setLabel("Child"); price1.setPrice("500"); schedule.getPriceList().add(price); schedule.getPriceList().add(price1); reservationSchedule.getSchedules().add(schedule); }); reservationMaster.getReservationSchedules().add(reservationSchedule); }); } }
17,782
0.607862
0.604656
316
55.272152
44.615326
202
false
false
0
0
0
0
0
0
0.553797
false
false
9
47165b6586d44fcb699aa83d1a34c2a0c506d8f7
17,815,524,357,540
a337f9db7322ce90440284580ea8abd655f88d51
/esclient/src/main/java/com/qyou/es/query/Pagination.java
238c3d9c0b7626f889f26e89039601507d175ddf
[]
no_license
QunarYou/TTF_Things
https://github.com/QunarYou/TTF_Things
ae05d7dc3fc3f50ef87e19e0d7f24bd8afe491e6
7a95b94e65f91c79e21e6a1079fc4ad9ac36f948
refs/heads/master
2015-09-25T14:05:56.950000
2015-08-18T12:19:29
2015-08-18T12:19:29
40,519,068
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.qyou.es.query; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created: 5:25 PM 03/03/2014 * * @author <a href="mailto:guo.song@qunar.com">guo.song</a> */ public class Pagination implements Serializable { public final static int DEFAULT_PAGE_SIZE = 20; public final static int DEFAULT_PAGE_NUMBER = 1; public final static int DEFAULT_VISIBLE_PAGE_LENGTH = 10; private int count = 0; private int pageSize = DEFAULT_PAGE_SIZE; private int curPage = DEFAULT_PAGE_NUMBER; /** * 绑定的实体list */ private List data; public int getFirstPage() { return 1; } public int getLastPage() { if(count > 0) { return getPageCount(); } else { return 0; } } public int getPrevios() { if(curPage <= 1) { return 1; } return curPage - 1; } public int getNext() { if(getPageCount() <= 0) { return 0; } if(curPage >= getPageCount()) { return getPageCount(); } return curPage + 1; } public List<Integer> getVisiblePage() { ArrayList<Integer> pages = new ArrayList<Integer>(); if(getPageCount() == 0) { return pages; } int last = getLastPage(); int length = DEFAULT_VISIBLE_PAGE_LENGTH; int mid = DEFAULT_VISIBLE_PAGE_LENGTH / 2; int start = curPage - mid <= 0 ? 1 : curPage - mid; int end = (start + length) > last ? last : start + length; start = (end - length) <= 0 ? 1 : (end - length); if(start > 0) { pages.add(null); } for(int i = start; i <= end; i++) { pages.add(i); } if(end < last) { pages.add(null); } return pages; } public int getPageCount() { return count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1; } /** * @return the pageSize */ public int getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * @return the curPage */ public int getCurPage() { return curPage; } /** * @param curPage the curPage to set */ public void setCurPage(int curPage) { this.curPage = curPage; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } public int getStartIndex() { return pageSize * (curPage - 1); } public int getStartIndexShow() { if(count == 0) return 0; return getStartIndex() + 1; } public int getEndIndex() { int endIndex = getStartIndex() + pageSize; if(endIndex > count - 1) return count; else return endIndex; } public int getEndIndexShow() { return getEndIndex(); } public List getData() { return data; } public void setData(List data) { this.data = data; } }
UTF-8
Java
3,298
java
Pagination.java
Java
[ { "context": " 5:25 PM 03/03/2014\n *\n * @author <a href=\"mailto:guo.song@qunar.com\">guo.song</a>\n */\npublic class Pagination impleme", "end": 192, "score": 0.9999297261238098, "start": 174, "tag": "EMAIL", "value": "guo.song@qunar.com" }, { "context": " *\n * @author <a href=\"mailto:guo.song@qunar.com\">guo.song</a>\n */\npublic class Pagination implements Serial", "end": 202, "score": 0.961104154586792, "start": 194, "tag": "USERNAME", "value": "guo.song" } ]
null
[]
package com.qyou.es.query; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Created: 5:25 PM 03/03/2014 * * @author <a href="mailto:<EMAIL>">guo.song</a> */ public class Pagination implements Serializable { public final static int DEFAULT_PAGE_SIZE = 20; public final static int DEFAULT_PAGE_NUMBER = 1; public final static int DEFAULT_VISIBLE_PAGE_LENGTH = 10; private int count = 0; private int pageSize = DEFAULT_PAGE_SIZE; private int curPage = DEFAULT_PAGE_NUMBER; /** * 绑定的实体list */ private List data; public int getFirstPage() { return 1; } public int getLastPage() { if(count > 0) { return getPageCount(); } else { return 0; } } public int getPrevios() { if(curPage <= 1) { return 1; } return curPage - 1; } public int getNext() { if(getPageCount() <= 0) { return 0; } if(curPage >= getPageCount()) { return getPageCount(); } return curPage + 1; } public List<Integer> getVisiblePage() { ArrayList<Integer> pages = new ArrayList<Integer>(); if(getPageCount() == 0) { return pages; } int last = getLastPage(); int length = DEFAULT_VISIBLE_PAGE_LENGTH; int mid = DEFAULT_VISIBLE_PAGE_LENGTH / 2; int start = curPage - mid <= 0 ? 1 : curPage - mid; int end = (start + length) > last ? last : start + length; start = (end - length) <= 0 ? 1 : (end - length); if(start > 0) { pages.add(null); } for(int i = start; i <= end; i++) { pages.add(i); } if(end < last) { pages.add(null); } return pages; } public int getPageCount() { return count % pageSize == 0 ? count / pageSize : (count / pageSize) + 1; } /** * @return the pageSize */ public int getPageSize() { return pageSize; } /** * @param pageSize the pageSize to set */ public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * @return the curPage */ public int getCurPage() { return curPage; } /** * @param curPage the curPage to set */ public void setCurPage(int curPage) { this.curPage = curPage; } /** * @return the count */ public int getCount() { return count; } /** * @param count the count to set */ public void setCount(int count) { this.count = count; } public int getStartIndex() { return pageSize * (curPage - 1); } public int getStartIndexShow() { if(count == 0) return 0; return getStartIndex() + 1; } public int getEndIndex() { int endIndex = getStartIndex() + pageSize; if(endIndex > count - 1) return count; else return endIndex; } public int getEndIndexShow() { return getEndIndex(); } public List getData() { return data; } public void setData(List data) { this.data = data; } }
3,287
0.524939
0.512774
157
19.949045
17.751575
81
false
false
0
0
0
0
0
0
0.312102
false
false
9
4d215f7c614650a1f966751c8d85ee9a4f544b4c
3,728,031,684,405
7b82d70ba5fef677d83879dfeab859d17f4809aa
/_part2/gray/gray/gray-manager/src/main/java/com/xlz/gray/service/StrategyService.java
d8447ca66c9064efbfda7f2a6b616687937ce315
[]
no_license
apollowesley/jun_test
https://github.com/apollowesley/jun_test
fb962a28b6384c4097c7a8087a53878188db2ebc
c7a4600c3f0e1b045280eaf3464b64e908d2f0a2
refs/heads/main
2022-12-30T20:47:36.637000
2020-10-13T18:10:46
2020-10-13T18:10:46
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.xlz.gray.service; import java.util.List; import com.xlz.commons.base.service.BaseService; import com.xlz.engine.common.config.Level; import com.xlz.gray.model.Strategy; public interface StrategyService extends BaseService<Strategy> { List<Strategy> findStrategyByLink(Long id, String engineType,Level level); }
UTF-8
Java
332
java
StrategyService.java
Java
[]
null
[]
package com.xlz.gray.service; import java.util.List; import com.xlz.commons.base.service.BaseService; import com.xlz.engine.common.config.Level; import com.xlz.gray.model.Strategy; public interface StrategyService extends BaseService<Strategy> { List<Strategy> findStrategyByLink(Long id, String engineType,Level level); }
332
0.798193
0.798193
13
24.461538
25.665348
75
false
false
0
0
0
0
0
0
0.846154
false
false
9