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
16126364c5aa2c989c64747e4800f536825ffbf5
13,099,650,317,872
c165cd61c1ee65d8c7249fd538f361544a1d0a6a
/ASEN/src/main/java/es/uji/ei1027/asen/dao/VigilanciaDao.java
b3e9f302e0babe5836d39b1af71bdc944549b39d
[]
no_license
ATNAislove/ASEN
https://github.com/ATNAislove/ASEN
e9ae43128590be33a571117e54382579dfb04514
f8726ec252a14d2b67279643c7b8058c065019c1
refs/heads/master
2023-06-13T00:04:52.199000
2021-07-05T16:16:16
2021-07-05T16:16:16
352,984,674
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package es.uji.ei1027.asen.dao; import es.uji.ei1027.asen.model.Vigilancia; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.util.ArrayList; import java.util.List; @Repository public class VigilanciaDao { private JdbcTemplate jdbcTemplate; // Obté el jdbcTemplate a partir del Data Source @Autowired public void setDataSource(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); } /* Afegeix el vigilancia a la base de dades */ public void addVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("INSERT INTO Vigilancia VALUES(?, ?)", vigilancia.getDni(), vigilancia.getIdArea()); } /* Esborra el vigilancia de la base de dades */ public void deleteVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("DELETE FROM vigilancia WHERE dni=?",vigilancia.getDni()); } /* Esborra el vigilancia de la base de dades */ public void deleteVigilancia(String dni) { jdbcTemplate.update("DELETE FROM vigilancia WHERE dni=?", dni); } /* Actualitza els atributs del vigilancia (excepte el nom, que és la clau primària) */ public void updateVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("UPDATE vigilancia SET dni=?, idArea=?", vigilancia.getDni(),vigilancia.getIdArea()); } /* Obté el vigilancia amb el nom donat. Torna null si no existeix. */ public Vigilancia getVigilancia(String dni) { try { return jdbcTemplate.queryForObject("SELECT * FROM Vigilancia WHERE dni = '"+ dni + "'", new VigilanciaRowMapper()); } catch(EmptyResultDataAccessException e) { return null; } } /* Obté tots els vigilancia. Torna una llista buida si no n'hi ha cap. */ public List<Vigilancia> getVigilancias() { try { return jdbcTemplate.query("SELECT * FROM Vigilancia", new VigilanciaRowMapper()); } catch(EmptyResultDataAccessException e) { return new ArrayList<Vigilancia>(); } } }
UTF-8
Java
2,265
java
VigilanciaDao.java
Java
[]
null
[]
package es.uji.ei1027.asen.dao; import es.uji.ei1027.asen.model.Vigilancia; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import javax.sql.DataSource; import java.util.ArrayList; import java.util.List; @Repository public class VigilanciaDao { private JdbcTemplate jdbcTemplate; // Obté el jdbcTemplate a partir del Data Source @Autowired public void setDataSource(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); } /* Afegeix el vigilancia a la base de dades */ public void addVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("INSERT INTO Vigilancia VALUES(?, ?)", vigilancia.getDni(), vigilancia.getIdArea()); } /* Esborra el vigilancia de la base de dades */ public void deleteVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("DELETE FROM vigilancia WHERE dni=?",vigilancia.getDni()); } /* Esborra el vigilancia de la base de dades */ public void deleteVigilancia(String dni) { jdbcTemplate.update("DELETE FROM vigilancia WHERE dni=?", dni); } /* Actualitza els atributs del vigilancia (excepte el nom, que és la clau primària) */ public void updateVigilancia(Vigilancia vigilancia) { jdbcTemplate.update("UPDATE vigilancia SET dni=?, idArea=?", vigilancia.getDni(),vigilancia.getIdArea()); } /* Obté el vigilancia amb el nom donat. Torna null si no existeix. */ public Vigilancia getVigilancia(String dni) { try { return jdbcTemplate.queryForObject("SELECT * FROM Vigilancia WHERE dni = '"+ dni + "'", new VigilanciaRowMapper()); } catch(EmptyResultDataAccessException e) { return null; } } /* Obté tots els vigilancia. Torna una llista buida si no n'hi ha cap. */ public List<Vigilancia> getVigilancias() { try { return jdbcTemplate.query("SELECT * FROM Vigilancia", new VigilanciaRowMapper()); } catch(EmptyResultDataAccessException e) { return new ArrayList<Vigilancia>(); } } }
2,265
0.692478
0.688938
61
36.049179
31.252239
127
false
false
0
0
0
0
0
0
0.491803
false
false
0
36bb79f550ef12bcf06115e06c84f585cab9e06e
32,487,132,678,756
727881821436c1a5c6d894b47e7964ba043b312c
/src/com/shaunz/designpattern/mediatorpattern/MediatorPatternDemo.java
9cffac9b0ef2614c389ef9e8867cde8561b23425
[]
no_license
ShaunzWorks/DesignPattern
https://github.com/ShaunzWorks/DesignPattern
9fab2707a6287af9ab5a39f2b161d4babf6f379a
cbd1d5b1c0cdee4f58cd53214cb324da03879212
refs/heads/master
2020-06-14T23:51:25.165000
2019-07-04T02:50:01
2019-07-04T02:50:01
195,157,818
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.shaunz.designpattern.mediatorpattern; /** * Mediator pattern is used to reduce communication complexity between multiple objects or classes. * This pattern provides a mediator class which normally handles all the communications between different classes and supports easy * maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category. * <b>Implementation</b> * We are demonstrating mediator pattern by example of a chat room where multiple users can send message to chat room and it is the responsibility * of chat room to show the messages to all users. We have created two classes ChatRoom and User. User objects will use ChatRoom method * to share their messages.MediatorPatternDemo, our demo class, will use User objects to show communication between them. * @author dengxiong90@foxmail.com */ public class MediatorPatternDemo { public static void main(String[] args) { User robert = new User("Robert"); User john = new User("John"); robert.sendMessage("Hi! John!"); john.sendMessage("Hello! Robert!"); } }
UTF-8
Java
1,088
java
MediatorPatternDemo.java
Java
[ { "context": "cts to show communication between them.\n * @author dengxiong90@foxmail.com\n */\npublic class MediatorPatternDemo {\n\tpublic st", "end": 860, "score": 0.9999186396598816, "start": 837, "tag": "EMAIL", "value": "dengxiong90@foxmail.com" }, { "context": "{\n\tpublic static void main(String[] args) {\n\t\tUser robert = new User(\"Robert\");\n\t\tUser john = new User(\"Joh", "end": 955, "score": 0.9152296781539917, "start": 949, "tag": "NAME", "value": "robert" }, { "context": "d main(String[] args) {\n\t\tUser robert = new User(\"Robert\");\n\t\tUser john = new User(\"John\");\n\t\trobert.sendM", "end": 974, "score": 0.9996734857559204, "start": 968, "tag": "NAME", "value": "Robert" }, { "context": "ert = new User(\"Robert\");\n\t\tUser john = new User(\"John\");\n\t\trobert.sendMessage(\"Hi! John!\");\n\t\tjohn.send", "end": 1006, "score": 0.9959394931793213, "start": 1002, "tag": "NAME", "value": "John" }, { "context": "john = new User(\"John\");\n\t\trobert.sendMessage(\"Hi! John!\");\n\t\tjohn.sendMessage(\"Hello! Robert!\");\n\t}\n}\n", "end": 1040, "score": 0.9997809529304504, "start": 1036, "tag": "NAME", "value": "John" }, { "context": "ndMessage(\"Hi! John!\");\n\t\tjohn.sendMessage(\"Hello! Robert!\");\n\t}\n}\n", "end": 1078, "score": 0.9998152852058411, "start": 1072, "tag": "NAME", "value": "Robert" } ]
null
[]
package com.shaunz.designpattern.mediatorpattern; /** * Mediator pattern is used to reduce communication complexity between multiple objects or classes. * This pattern provides a mediator class which normally handles all the communications between different classes and supports easy * maintenance of the code by loose coupling. Mediator pattern falls under behavioral pattern category. * <b>Implementation</b> * We are demonstrating mediator pattern by example of a chat room where multiple users can send message to chat room and it is the responsibility * of chat room to show the messages to all users. We have created two classes ChatRoom and User. User objects will use ChatRoom method * to share their messages.MediatorPatternDemo, our demo class, will use User objects to show communication between them. * @author <EMAIL> */ public class MediatorPatternDemo { public static void main(String[] args) { User robert = new User("Robert"); User john = new User("John"); robert.sendMessage("Hi! John!"); john.sendMessage("Hello! Robert!"); } }
1,072
0.773897
0.772059
20
53.400002
48.823559
146
false
false
0
0
0
0
0
0
0.85
false
false
0
d83346acb71dd1749922064bbca2c27a40480518
3,143,916,069,262
a8602d22c89afff28e77b996b74c89eb9f62fd8d
/src/main/java/com/sasconsul/restcoding/config/liquibase/package-info.java
8bb645f80d33aa79266467edc2d2e3e948c590db
[]
no_license
sasconsul/jhipster_restcoding
https://github.com/sasconsul/jhipster_restcoding
255e422195384c2c9587fa5c5e9c8d2f073a4c26
3c9c1da291df7163cb022532f1d7ba1ebf595aff
refs/heads/master
2021-01-12T18:05:44.697000
2016-10-31T06:47:36
2016-10-31T06:47:36
71,322,561
0
0
null
false
2019-02-14T00:13:18
2016-10-19T05:36:52
2016-10-19T05:48:18
2019-02-14T00:13:17
4,208
0
0
1
Java
false
null
/** * Liquibase specific code. */ package com.sasconsul.restcoding.config.liquibase;
UTF-8
Java
87
java
package-info.java
Java
[]
null
[]
/** * Liquibase specific code. */ package com.sasconsul.restcoding.config.liquibase;
87
0.747126
0.747126
4
20.75
19.524023
50
false
false
0
0
0
0
0
0
0.25
false
false
0
a196628b19ec49e15f00ce350908b315ec1a6568
13,615,046,355,400
c35375da635311117dcc939fc0bd9416999f7046
/changefontsize/src/main/java/com/example/changefontsize/MainActivity.java
ae268a6da2acdab4e168e380bcae4c84aafed1f8
[]
no_license
hohyon/androidView2
https://github.com/hohyon/androidView2
bca99a0e2c0a7f9c1411fccdc790d768cb8bd924
1e17a29914a1129d6a431bd87f7f87c53b143272
refs/heads/master
2020-03-23T12:03:18.833000
2018-07-19T06:41:29
2018-07-19T06:41:29
141,534,205
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.changefontsize; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView t1; Button b1; Button b2; Button b3; Button b4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); t1 = findViewById(R.id.txt); b1 = findViewById(R.id.big); b2 = findViewById(R.id.reset); b3 = findViewById(R.id.small); b4 = findViewById(R.id.color); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setText("감사합니다"); t1.setTextSize(60); Toast.makeText(MainActivity.this, "확대되었습니다.", Toast.LENGTH_SHORT).show(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setText("경범선생"); t1.setTextSize(30); Toast.makeText(MainActivity.this, "초기화되었습니다.", Toast.LENGTH_SHORT).show(); } }); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setTextSize(20); Toast.makeText(MainActivity.this, "축소되었습니다.", Toast.LENGTH_SHORT).show(); } }); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setTextSize(30); t1.setTextColor(Color.BLUE); Toast.makeText(MainActivity.this, "변경되었습니다.", Toast.LENGTH_SHORT).show(); } }); } }
UTF-8
Java
2,075
java
MainActivity.java
Java
[]
null
[]
package com.example.changefontsize; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView t1; Button b1; Button b2; Button b3; Button b4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); t1 = findViewById(R.id.txt); b1 = findViewById(R.id.big); b2 = findViewById(R.id.reset); b3 = findViewById(R.id.small); b4 = findViewById(R.id.color); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setText("감사합니다"); t1.setTextSize(60); Toast.makeText(MainActivity.this, "확대되었습니다.", Toast.LENGTH_SHORT).show(); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setText("경범선생"); t1.setTextSize(30); Toast.makeText(MainActivity.this, "초기화되었습니다.", Toast.LENGTH_SHORT).show(); } }); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setTextSize(20); Toast.makeText(MainActivity.this, "축소되었습니다.", Toast.LENGTH_SHORT).show(); } }); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { t1.setTextSize(30); t1.setTextColor(Color.BLUE); Toast.makeText(MainActivity.this, "변경되었습니다.", Toast.LENGTH_SHORT).show(); } }); } }
2,075
0.582291
0.567284
72
26.763889
23.628193
90
false
false
0
0
0
0
0
0
0.597222
false
false
0
928f34cdb78e0eb127a4b833217be657105264d6
11,175,504,932,921
a58c698682a6067dab6d71965fa9b5872c44dbfb
/src/main/java/com/mar/zur/util/DecryptionUtils.java
9aa3c5ea89cefd549131f8b5687e7bb3ded2adfd
[]
no_license
Marciokas/DragonsOfMugloar
https://github.com/Marciokas/DragonsOfMugloar
bfb103f4fba8dff58d4d0483b74368e4a3368897
cb1eb5fec75c7945026bdf357414b91d1a16206f
refs/heads/master
2020-04-26T06:26:01.095000
2019-03-03T17:33:59
2019-03-03T17:33:59
172,147,966
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.mar.zur.util; import java.io.UnsupportedEncodingException; import java.util.Base64; public class DecryptionUtils { private DecryptionUtils() { } public static String decryptStringBase64(String value) { try { return new String(Base64.getDecoder().decode(value), "utf-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unable to decrypt given message: " + value); } } public static String decryptStringROT13(String value) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c >= 'a' && c <= 'm') c += 13; else if (c >= 'A' && c <= 'M') c += 13; else if (c >= 'n' && c <= 'z') c -= 13; else if (c >= 'N' && c <= 'Z') c -= 13; sb.append(c); } return sb.toString(); } }
UTF-8
Java
952
java
DecryptionUtils.java
Java
[]
null
[]
package com.mar.zur.util; import java.io.UnsupportedEncodingException; import java.util.Base64; public class DecryptionUtils { private DecryptionUtils() { } public static String decryptStringBase64(String value) { try { return new String(Base64.getDecoder().decode(value), "utf-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Unable to decrypt given message: " + value); } } public static String decryptStringROT13(String value) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c >= 'a' && c <= 'm') c += 13; else if (c >= 'A' && c <= 'M') c += 13; else if (c >= 'n' && c <= 'z') c -= 13; else if (c >= 'N' && c <= 'Z') c -= 13; sb.append(c); } return sb.toString(); } }
952
0.534664
0.515756
32
28.75
24.619606
89
false
false
0
0
0
0
0
0
0.5
false
false
0
2c5f6bd5b044629e1cec7d29a7377bd5c13d38c3
32,040,456,062,342
49b57339d939ea3f498249d3aacca1dec543163b
/jadx-snap-new/sources/com/snap/ui/view/multisnap/MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2.java
baa51c145946c50a958e415233e16a435f4de89e
[]
no_license
8secz-johndpope/snapchat-re
https://github.com/8secz-johndpope/snapchat-re
1655036c41518c3a2aaa0c2543dc49f4acb93eaf
04f5c5bb627d21f620088525fffcf5c99abd7ce5
refs/heads/master
2020-08-24T09:14:38.209000
2019-06-14T05:13:44
2019-06-14T05:13:44
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.snap.ui.view.multisnap; import defpackage.akbk; import defpackage.akcs; final class MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2 extends akcs implements akbk<Integer> { final /* synthetic */ MultiSnapThumbnailViewFactoryProvider this$0; MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2(MultiSnapThumbnailViewFactoryProvider multiSnapThumbnailViewFactoryProvider) { this.this$0 = multiSnapThumbnailViewFactoryProvider; super(0); } public final int invoke() { MultiSnapThumbnailViewFactoryProvider multiSnapThumbnailViewFactoryProvider = this.this$0; return multiSnapThumbnailViewFactoryProvider.calculateThumbnailWidth(multiSnapThumbnailViewFactoryProvider.context, this.this$0.getThumbnailHeight()); } }
UTF-8
Java
788
java
MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2.java
Java
[]
null
[]
package com.snap.ui.view.multisnap; import defpackage.akbk; import defpackage.akcs; final class MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2 extends akcs implements akbk<Integer> { final /* synthetic */ MultiSnapThumbnailViewFactoryProvider this$0; MultiSnapThumbnailViewFactoryProvider$thumbnailWidth$2(MultiSnapThumbnailViewFactoryProvider multiSnapThumbnailViewFactoryProvider) { this.this$0 = multiSnapThumbnailViewFactoryProvider; super(0); } public final int invoke() { MultiSnapThumbnailViewFactoryProvider multiSnapThumbnailViewFactoryProvider = this.this$0; return multiSnapThumbnailViewFactoryProvider.calculateThumbnailWidth(multiSnapThumbnailViewFactoryProvider.context, this.this$0.getThumbnailHeight()); } }
788
0.808376
0.799492
18
42.777779
49.362103
158
false
false
0
0
0
0
0
0
0.5
false
false
0
62bb9440b05878121832ae930267d52953d76311
32,040,456,063,369
6314615a2d603be7f9abefdbfb027251290fd8ef
/simipay-app/src/main/java/com/xyz/simipay/app/modular/system/service/LogService.java
1362aa4680537f59a1648daeb6c97057b27f56c6
[]
no_license
SimbaBlock/simipay
https://github.com/SimbaBlock/simipay
88d5045d9b77320e2e2489cf5a42dc6b13e310f2
448440ac565e86c174834a77bdcad9b40ed1fe2f
refs/heads/master
2022-10-21T11:37:33.136000
2020-04-28T10:54:39
2020-04-28T10:54:39
248,151,422
0
0
null
false
2022-10-12T20:37:46
2020-03-18T06:03:21
2020-04-28T10:55:47
2022-10-12T20:37:44
117
0
0
5
Java
false
false
package com.xyz.simipay.app.modular.system.service; import com.baomidou.mybatisplus.service.IService; import com.xyz.simipay.app.modular.system.model.Log; public interface LogService extends IService<Log> { int insertLog(Log log); }
UTF-8
Java
241
java
LogService.java
Java
[]
null
[]
package com.xyz.simipay.app.modular.system.service; import com.baomidou.mybatisplus.service.IService; import com.xyz.simipay.app.modular.system.model.Log; public interface LogService extends IService<Log> { int insertLog(Log log); }
241
0.788382
0.788382
10
23.1
23.876558
52
false
false
0
0
0
0
0
0
0.4
false
false
0
7a58d4dcc9bb88b532d5c0f44e42e83e8f35531d
29,566,554,887,004
f11e1484e2b9950860640a5517eddf52ffa421b3
/src/Views/StaffViewBookings.java
2f1a07d9c6cb73dbb14ade7f5732f69566e9b147
[]
no_license
paulk909/DroversLodge2
https://github.com/paulk909/DroversLodge2
e718dd8676dee63570d6063e91dee025d4d764d6
92780451fde752c5ed65b83436cedb378a09cc7c
refs/heads/master
2020-03-17T22:48:32.387000
2018-06-04T10:53:17
2018-06-04T10:53:17
134,018,905
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 Views; import Models.Booking; import Models.CardType; import Models.Customer; import Models.DBManager; import Models.ExcelWriter; import Models.LoggedInUser; import Models.Payment; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; /** * * @author Paul */ public class StaffViewBookings extends javax.swing.JFrame { //pass user details //initialise variables for payments and refunds private LoggedInUser loggedInUser = new LoggedInUser(); private double refundDue = 0; private int refundBookingID = 0; private double amountDue = 0; private int paymentBookingID = 0; /** * allows staff to view all bookings and delete/ edit/ take payments and make refunds * @param loggedInUser */ public StaffViewBookings(LoggedInUser loggedInUser) { this.loggedInUser = loggedInUser; loadFrame(); } //initialise componenets in frame public void loadFrame() { initComponents(); this.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); Font ttfBase = null; Font ttfReal = null; try { InputStream myStream = new BufferedInputStream(new FileInputStream("src/fonts/Dillanda Caligraphy Script Demo.ttf")); ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream); ttfReal = ttfBase.deriveFont(Font.BOLD, 50); lblTitle.setFont(ttfReal); lblTitle.setForeground(new Color(102, 0, 0)); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Custom font not loaded."); } btnSignIn.setText("Logged in as " + loggedInUser.getUsername()); btnSignIn.setEnabled(false); btnRegister.setText("Logout"); loadBookingTable(); btnPayBooking.setVisible(false); btnEditBooking.setVisible(false); btnDeleteBooking.setVisible(false); btnStaffExportBookingReport.setVisible(false); } //load booking details into table public void loadBookingTable() { tblBookings.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); DefaultTableModel model = (DefaultTableModel)tblBookings.getModel(); HashMap<Integer, Booking> bookings = new HashMap<Integer, Booking>(); DBManager db = new DBManager(); bookings = db.getBookings(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); for(Map.Entry<Integer, Booking> bookingEntry : bookings.entrySet()) { Booking currentBooking = bookingEntry.getValue(); model.addRow(new Object[]{currentBooking.getBookingID(), currentBooking.getCustomerID(), currentBooking.getIsPaid(), String.format("%.02f",currentBooking.getOutstandingBalance()), String.format("%.02f",currentBooking.getTotalCost()), dateFormat.format(currentBooking.getDateBooked()) }); } } //add card types to drop down public void populateCardTypeDropDown() { comboCardType.removeAllItems(); DBManager db = new DBManager(); HashMap<Integer, CardType> cardTypes = new HashMap<Integer, CardType>(); cardTypes = db.getCardTypes(); comboCardType.addItem("--Please Select--"); for (Map.Entry<Integer, CardType> cardTypeEntry : cardTypes.entrySet()) { comboCardType.addItem(cardTypeEntry.getValue().getCardType()); } } //add card types to drop down public void populateRefundCardTypeDropDown() { comboRefundCardType.removeAllItems(); DBManager db = new DBManager(); HashMap<Integer, CardType> cardTypes = new HashMap<Integer, CardType>(); cardTypes = db.getCardTypes(); comboRefundCardType.addItem("--Please Select--"); for (Map.Entry<Integer, CardType> cardTypeEntry : cardTypes.entrySet()) { comboRefundCardType.addItem(cardTypeEntry.getValue().getCardType()); } } /** * 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() { jframePayment = new javax.swing.JFrame(); btnPaymentSubmit = new javax.swing.JButton(); btnPaymentClear = new javax.swing.JButton(); btnPaymentClose = new javax.swing.JButton(); jLabel18 = new javax.swing.JLabel(); txtPayeeName = new javax.swing.JTextField(); jLabel19 = new javax.swing.JLabel(); txtCardNo = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); txtSecurityNo = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); comboCardType = new javax.swing.JComboBox<>(); txtPaymentTotalCost = new javax.swing.JTextField(); lblPaymentTotalCost = new javax.swing.JLabel(); lblPaymentTitle = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel24 = new javax.swing.JLabel(); jMonthExpiry = new com.toedter.calendar.JMonthChooser(); jYearExpiry = new com.toedter.calendar.JYearChooser(); jPanel5 = new javax.swing.JPanel(); jLabel30 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); txtPaymentHouse = new javax.swing.JTextField(); txtPaymentStreet = new javax.swing.JTextField(); txtPaymentTown = new javax.swing.JTextField(); txtPaymentPostcode = new javax.swing.JTextField(); checkSameAddress = new javax.swing.JCheckBox(); jframeRefund = new javax.swing.JFrame(); btnRefundSubmit = new javax.swing.JButton(); btnRefundClear = new javax.swing.JButton(); btnRefundClose = new javax.swing.JButton(); jLabel22 = new javax.swing.JLabel(); txtRefundPayeeName = new javax.swing.JTextField(); jLabel23 = new javax.swing.JLabel(); txtRefundCardNo = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); txtRefundSecurityNo = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); comboRefundCardType = new javax.swing.JComboBox<>(); txtRefundTotalRefund = new javax.swing.JTextField(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel29 = new javax.swing.JLabel(); jMonthRefundExpiry = new com.toedter.calendar.JMonthChooser(); jYearRefundExpiry = new com.toedter.calendar.JYearChooser(); jPanel6 = new javax.swing.JPanel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jLabel36 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); txtPaymentHouse1 = new javax.swing.JTextField(); txtPaymentStreet1 = new javax.swing.JTextField(); txtPaymentTown1 = new javax.swing.JTextField(); txtPaymentPostcode1 = new javax.swing.JTextField(); checkSameAddress1 = new javax.swing.JCheckBox(); btnEditBooking = new javax.swing.JButton(); btnDeleteBooking = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); btnAbout = new javax.swing.JButton(); btnRegister = new javax.swing.JButton(); btnSignIn = new javax.swing.JButton(); btnCart = new javax.swing.JButton(); btnControlPanel = new javax.swing.JButton(); btnPayBooking = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); lblTitle = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tblBookings = new javax.swing.JTable(); lblStaff = new javax.swing.JLabel(); btnStaffExportBookingReport = new javax.swing.JButton(); btnPaymentSubmit.setText("Submit"); btnPaymentSubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentSubmitActionPerformed(evt); } }); btnPaymentClear.setText("Clear"); btnPaymentClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentClearActionPerformed(evt); } }); btnPaymentClose.setText("Close"); btnPaymentClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentCloseActionPerformed(evt); } }); jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel18.setText("Card Holder's Name"); jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel19.setText("Card No"); jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel20.setText("Security No"); jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel21.setText("Card Type"); txtPaymentTotalCost.setEditable(false); lblPaymentTotalCost.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); lblPaymentTotalCost.setText("Total Cost"); lblPaymentTitle.setBackground(new java.awt.Color(255, 255, 255)); lblPaymentTitle.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N lblPaymentTitle.setForeground(new java.awt.Color(51, 0, 0)); lblPaymentTitle.setText("Payment Details"); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel24.setText("Expiry Date"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jMonthExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jYearExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel24) .addGap(70, 70, 70)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jLabel24) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMonthExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jYearExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23)) ); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Payee's Address")); jLabel30.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel30.setText("Address 1"); jLabel31.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel31.setText("Address 2"); jLabel32.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel32.setText("Town"); jLabel33.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel33.setText("Postcode"); checkSameAddress.setText("Same as account address"); checkSameAddress.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkSameAddressActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentHouse, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentTown, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel33, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentPostcode, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentStreet, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(26, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkSameAddress) .addGap(54, 54, 54)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel30) .addComponent(txtPaymentHouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel31) .addComponent(txtPaymentStreet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel32) .addComponent(txtPaymentTown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel33) .addComponent(txtPaymentPostcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(checkSameAddress) .addGap(23, 23, 23)) ); javax.swing.GroupLayout jframePaymentLayout = new javax.swing.GroupLayout(jframePayment.getContentPane()); jframePayment.getContentPane().setLayout(jframePaymentLayout); jframePaymentLayout.setHorizontalGroup( jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(lblPaymentTitle) .addContainerGap(482, Short.MAX_VALUE)) .addGroup(jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel20) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel19) .addComponent(jLabel18))) .addGap(32, 32, 32) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframePaymentLayout.createSequentialGroup() .addComponent(btnPaymentSubmit) .addGap(54, 54, 54) .addComponent(btnPaymentClear) .addGap(61, 61, 61) .addComponent(btnPaymentClose)) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel21) .addComponent(lblPaymentTotalCost)) .addGap(32, 32, 32) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtPaymentTotalCost, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboCardType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(59, 59, 59)))) ); jframePaymentLayout.setVerticalGroup( jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(lblPaymentTitle) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(txtPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel19)) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(comboCardType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPaymentTotalCost) .addComponent(txtPaymentTotalCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(44, 44, 44)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jframePaymentLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26))) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnPaymentSubmit) .addComponent(btnPaymentClear) .addComponent(btnPaymentClose)) .addContainerGap(46, Short.MAX_VALUE)) ); btnRefundSubmit.setText("Submit"); btnRefundSubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundSubmitActionPerformed(evt); } }); btnRefundClear.setText("Clear"); btnRefundClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundClearActionPerformed(evt); } }); btnRefundClose.setText("Close"); btnRefundClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundCloseActionPerformed(evt); } }); jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel22.setText("Card Holder's Name"); jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel23.setText("Card No"); jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel25.setText("Security No"); jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel26.setText("Card Type"); txtRefundTotalRefund.setEditable(false); jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel27.setText("Total Refund"); jLabel28.setBackground(new java.awt.Color(255, 255, 255)); jLabel28.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel28.setForeground(new java.awt.Color(51, 0, 0)); jLabel28.setText("Refund Details"); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel29.setText("Expiry Date"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jMonthRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jYearRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel29) .addGap(70, 70, 70)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jLabel29) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMonthRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jYearRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23)) ); jPanel6.setBackground(new java.awt.Color(255, 255, 255)); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Payee's Address")); jLabel34.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel34.setText("Address 1"); jLabel35.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel35.setText("Address 2"); jLabel36.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel36.setText("Town"); jLabel37.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel37.setText("Postcode"); checkSameAddress1.setText("Same as account address"); checkSameAddress1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkSameAddress1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel34, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentHouse1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentTown1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel37, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentPostcode1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel35, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentStreet1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(26, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkSameAddress1) .addGap(54, 54, 54)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel34) .addComponent(txtPaymentHouse1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel35) .addComponent(txtPaymentStreet1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel36) .addComponent(txtPaymentTown1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel37) .addComponent(txtPaymentPostcode1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(checkSameAddress1) .addGap(23, 23, 23)) ); javax.swing.GroupLayout jframeRefundLayout = new javax.swing.GroupLayout(jframeRefund.getContentPane()); jframeRefund.getContentPane().setLayout(jframeRefundLayout); jframeRefundLayout.setHorizontalGroup( jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(jLabel28) .addContainerGap(609, Short.MAX_VALUE)) .addGroup(jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel25) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtRefundSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel23) .addComponent(jLabel22))) .addGap(32, 32, 32) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtRefundPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtRefundCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframeRefundLayout.createSequentialGroup() .addComponent(btnRefundSubmit) .addGap(54, 54, 54) .addComponent(btnRefundClear) .addGap(61, 61, 61) .addComponent(btnRefundClose)) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel26) .addComponent(jLabel27)) .addGap(32, 32, 32) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtRefundTotalRefund, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboRefundCardType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(125, 125, 125)))) ); jframeRefundLayout.setVerticalGroup( jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jLabel28) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(txtRefundPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtRefundCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel23)) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel25) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtRefundSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel26) .addComponent(comboRefundCardType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel27) .addComponent(txtRefundTotalRefund, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(28, 28, 28) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnRefundSubmit) .addComponent(btnRefundClear) .addComponent(btnRefundClose)) .addContainerGap(46, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnEditBooking.setText("View Booking"); btnEditBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditBookingActionPerformed(evt); } }); btnDeleteBooking.setText("Delete Booking"); btnDeleteBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteBookingActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(224, 224, 224)); jPanel2.setToolTipText(""); btnAbout.setText("About Drovers Lodge"); btnAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAboutActionPerformed(evt); } }); btnRegister.setText("Register"); btnRegister.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegisterActionPerformed(evt); } }); btnSignIn.setText("Sign In"); btnSignIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSignInActionPerformed(evt); } }); btnCart.setBackground(new java.awt.Color(51, 0, 0)); btnCart.setForeground(new java.awt.Color(255, 255, 255)); btnCart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/basket.png"))); // NOI18N btnCart.setText("Cart"); btnCart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCartActionPerformed(evt); } }); btnControlPanel.setBackground(new java.awt.Color(51, 0, 0)); btnControlPanel.setForeground(new java.awt.Color(255, 255, 255)); btnControlPanel.setText("Control Panel"); btnControlPanel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnControlPanelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(btnAbout) .addGap(18, 18, 18) .addComponent(btnControlPanel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSignIn) .addGap(18, 18, 18) .addComponent(btnRegister) .addGap(18, 18, 18) .addComponent(btnCart) .addGap(15, 15, 15)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAbout) .addComponent(btnSignIn) .addComponent(btnRegister) .addComponent(btnCart) .addComponent(btnControlPanel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); btnPayBooking.setText("Pay For Booking"); btnPayBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPayBookingActionPerformed(evt); } }); jLabel1.setText("All Bookings"); lblTitle.setBackground(new java.awt.Color(255, 255, 255)); lblTitle.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N lblTitle.setForeground(new java.awt.Color(102, 0, 0)); lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTitle.setText("Drovers Lodge"); tblBookings.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Booking ID", "Customer ID", "Is Paid", "Outstanding Balance", "Total Cost", "Date Booked" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Integer.class, java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, true, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tblBookings.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblBookingsMouseClicked(evt); } }); jScrollPane1.setViewportView(tblBookings); lblStaff.setBackground(new java.awt.Color(255, 255, 51)); lblStaff.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N lblStaff.setForeground(new java.awt.Color(51, 51, 51)); lblStaff.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblStaff.setText("STAFF"); lblStaff.setOpaque(true); btnStaffExportBookingReport.setText("Export Booking Report"); btnStaffExportBookingReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStaffExportBookingReportActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(165, 165, 165) .addComponent(lblTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE) .addComponent(lblStaff, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(btnStaffExportBookingReport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPayBooking) .addGap(45, 45, 45) .addComponent(btnDeleteBooking) .addGap(34, 34, 34) .addComponent(btnEditBooking))) .addGap(32, 32, 32)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblStaff)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addGap(11, 11, 11) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnDeleteBooking) .addComponent(btnEditBooking) .addComponent(btnPayBooking) .addComponent(btnStaffExportBookingReport)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnEditBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditBookingActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); EditBooking rForm = new EditBooking(bookingID, loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnEditBookingActionPerformed private void btnDeleteBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteBookingActionPerformed //delete booking and make refund if due int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); if(selectedBooking.getIsPaid()) { refundDue = selectedBooking.getTotalCost() - selectedBooking.getOutstandingBalance(); refundBookingID = selectedBooking.getBookingID(); db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); //make refund panel visible jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else { double totalCost = selectedBooking.getTotalCost(); double outstandingBalance = selectedBooking.getOutstandingBalance(); //check if refund is due if((totalCost - outstandingBalance) > 0) { refundDue = totalCost - outstandingBalance; refundBookingID = selectedBooking.getBookingID(); db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else { db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); } } }//GEN-LAST:event_btnDeleteBookingActionPerformed private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed loggedInUser = new LoggedInUser(); loggedInUser.setIsLoggedIn(false); btnSignIn.setText("Sign In"); btnSignIn.setEnabled(true); btnRegister.setText("Register"); MainMenu rForm = new MainMenu(); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnRegisterActionPerformed private void btnSignInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSignInActionPerformed }//GEN-LAST:event_btnSignInActionPerformed private void btnCartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCartActionPerformed Cart rForm = new Cart(loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnCartActionPerformed private void btnPayBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPayBookingActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); if(selectedBooking.getOutstandingBalance() < 0) { refundDue = selectedBooking.getTotalCost() - selectedBooking.getOutstandingBalance(); refundBookingID = selectedBooking.getBookingID(); //make payment panel visible jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else if(selectedBooking.getOutstandingBalance() > 0) { amountDue = selectedBooking.getOutstandingBalance(); paymentBookingID = selectedBooking.getBookingID(); jframePayment.setVisible(true); jframePayment.setSize(840,600); jframePayment.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframePayment.setLocation(dim.width/2-jframePayment.getSize().width/2, dim.height/2-jframePayment.getSize().height/2); jframePayment.setVisible(true); populateCardTypeDropDown(); txtPaymentTotalCost.setText("£" + String.format("%.02f",(amountDue))); } }//GEN-LAST:event_btnPayBookingActionPerformed private void btnPaymentSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentSubmitActionPerformed //check payment details have been filled in if(txtPayeeName.getText().isEmpty() || txtCardNo.getText().isEmpty() || txtSecurityNo.getText().isEmpty() || comboCardType.getSelectedIndex()==0 || txtPaymentHouse.getText().isEmpty() || txtPaymentTown.getText().isEmpty() || txtPaymentPostcode.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Please fill in all payment fields"); } else { int length = txtCardNo.getText().length(); if(length < 10) { JOptionPane.showMessageDialog(null, "Card number must be at least 10 digits"); } else { DBManager db = new DBManager(); String payeeName = txtPayeeName.getText(); String cardNo = txtCardNo.getText(); String securityNo = txtSecurityNo.getText(); int expiryMonth = jMonthExpiry.getMonth(); String monthString; switch (expiryMonth) { case 0: monthString = "Jan"; break; case 1: monthString = "Feb"; break; case 2: monthString = "Mar"; break; case 3: monthString = "Apr"; break; case 4: monthString = "May"; break; case 5: monthString = "Jun"; break; case 6: monthString = "Jul"; break; case 7: monthString = "Aug"; break; case 8: monthString = "Sep"; break; case 9: monthString = "Oct"; break; case 10: monthString = "Nov"; break; case 11: monthString = "Dec"; break; default: monthString = "Invalid month"; break; } int expiryYear = jYearExpiry.getYear(); Date expiryDate = new Date(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); expiryDate = dateFormat.parse(expiryYear + "-" + monthString + "-01 00:00:00"); } catch (ParseException ex) { Logger.getLogger(Cart.class.getName()).log(Level.SEVERE, null, ex); } int cardTypeID = db.getCardTypeIDFromCardType(String.valueOf(comboCardType.getSelectedItem())); String paymentHouse = txtPaymentHouse.getText(); String paymentStreet = txtPaymentStreet.getText(); String paymentTown = txtPaymentTown.getText(); String paymentPostcode = txtPaymentPostcode.getText(); Payment payment = new Payment(payeeName, cardNo, securityNo, expiryDate, cardTypeID, amountDue, paymentBookingID, paymentHouse, paymentStreet, paymentTown, paymentPostcode); db.takePayment(payment); db.setOutstandingPaymentZeroIsPaidTrue(paymentBookingID); amountDue = 0; paymentBookingID = 0; txtPayeeName.setText(""); txtCardNo.setText(""); txtSecurityNo.setText(""); comboCardType.setSelectedIndex(0); checkSameAddress.setSelected(false); txtPaymentHouse.setText(""); txtPaymentStreet.setText(""); txtPaymentTown.setText(""); txtPaymentPostcode.setText(""); jframePayment.dispose(); JOptionPane.showMessageDialog(null, "Payment successful"); clearBookingTable(); loadBookingTable(); } } }//GEN-LAST:event_btnPaymentSubmitActionPerformed private void btnPaymentClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentClearActionPerformed txtPayeeName.setText(""); txtCardNo.setText(""); txtSecurityNo.setText(""); comboCardType.setSelectedIndex(0); checkSameAddress.setSelected(false); txtPaymentHouse.setText(""); txtPaymentStreet.setText(""); txtPaymentTown.setText(""); txtPaymentPostcode.setText(""); }//GEN-LAST:event_btnPaymentClearActionPerformed private void btnPaymentCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentCloseActionPerformed jframePayment.dispose(); }//GEN-LAST:event_btnPaymentCloseActionPerformed private void btnRefundSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundSubmitActionPerformed //check all refund details are filled in if(txtRefundPayeeName.getText().isEmpty() || txtRefundCardNo.getText().isEmpty() || txtRefundSecurityNo.getText().isEmpty() || comboRefundCardType.getSelectedIndex()==0 || txtPaymentHouse1.getText().isEmpty() || txtPaymentTown1.getText().isEmpty() || txtPaymentPostcode1.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Please fill in all payment fields"); } else { int length = txtRefundCardNo.getText().length(); if(length < 10) { JOptionPane.showMessageDialog(null, "Card number must be at least 10 digits"); } else { DBManager db = new DBManager(); String refundPayeeName = txtRefundPayeeName.getText(); String refundCardNo = txtRefundCardNo.getText(); String refundSecurityNo = txtRefundSecurityNo.getText(); int refundExpiryMonth = jMonthRefundExpiry.getMonth(); String refundMonthString; switch (refundExpiryMonth) { case 0: refundMonthString = "Jan"; break; case 1: refundMonthString = "Feb"; break; case 2: refundMonthString = "Mar"; break; case 3: refundMonthString = "Apr"; break; case 4: refundMonthString = "May"; break; case 5: refundMonthString = "Jun"; break; case 6: refundMonthString = "Jul"; break; case 7: refundMonthString = "Aug"; break; case 8: refundMonthString = "Sep"; break; case 9: refundMonthString = "Oct"; break; case 10: refundMonthString = "Nov"; break; case 11: refundMonthString = "Dec"; break; default: refundMonthString = "Invalid month"; break; } int refundExpiryYear = jYearRefundExpiry.getYear(); Date refundExpiryDate = new Date(); try { SimpleDateFormat refundDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); refundExpiryDate = refundDateFormat.parse(refundExpiryYear + "-" + refundMonthString + "-01 00:00:00"); } catch (ParseException ex) { Logger.getLogger(Cart.class.getName()).log(Level.SEVERE, null, ex); } int cardTypeID = db.getCardTypeIDFromCardType(String.valueOf(comboCardType.getSelectedItem())); double totalRefund = refundDue; Payment refund = new Payment(refundPayeeName, refundCardNo, refundSecurityNo, refundExpiryDate, cardTypeID, totalRefund, refundBookingID); db.takePayment(refund); db.setOutstandingPaymentZeroIsPaidTrue(refundBookingID); refundDue = 0; refundBookingID = 0; txtRefundPayeeName.setText(""); txtRefundCardNo.setText(""); txtRefundSecurityNo.setText(""); comboRefundCardType.setSelectedIndex(0); checkSameAddress1.setSelected(false); txtPaymentHouse1.setText(""); txtPaymentStreet1.setText(""); txtPaymentTown1.setText(""); txtPaymentPostcode1.setText(""); jframeRefund.dispose(); JOptionPane.showMessageDialog(null, "Refund successful"); clearBookingTable(); loadBookingTable(); } } }//GEN-LAST:event_btnRefundSubmitActionPerformed //remove old rows from booking table public void clearBookingTable() { DefaultTableModel model = (DefaultTableModel)tblBookings.getModel(); int rows = model.getRowCount(); for(int i = rows - 1; i >=0; i--) { model.removeRow(i); } } private void btnRefundClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundClearActionPerformed txtRefundPayeeName.setText(""); txtRefundCardNo.setText(""); txtRefundSecurityNo.setText(""); comboRefundCardType.setSelectedIndex(0); checkSameAddress1.setSelected(false); txtPaymentHouse1.setText(""); txtPaymentStreet1.setText(""); txtPaymentTown1.setText(""); txtPaymentPostcode1.setText(""); }//GEN-LAST:event_btnRefundClearActionPerformed private void btnRefundCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundCloseActionPerformed jframePayment.dispose(); }//GEN-LAST:event_btnRefundCloseActionPerformed private void btnControlPanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnControlPanelActionPerformed if(loggedInUser.getUserTypeID() == 2) { CustomerHome rForm = new CustomerHome(loggedInUser); this.dispose(); rForm.setVisible(true); } else if(loggedInUser.getUserTypeID() == 3) { StaffHome rForm = new StaffHome(loggedInUser); this.dispose(); rForm.setVisible(true); } }//GEN-LAST:event_btnControlPanelActionPerformed private void btnStaffExportBookingReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStaffExportBookingReportActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); Customer bookingCustomer = db.getCustomerFromCustomerID(selectedBooking.getCustomerID()); String strBookingID = String.valueOf(selectedBooking.getBookingID()); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat fileFormat = new SimpleDateFormat("dd_MM_yyyy"); String dateBooked = dateFormat.format(selectedBooking.getDateBooked()); String outstandingBalance = String.valueOf(selectedBooking.getOutstandingBalance()); String totalCost = String.valueOf(selectedBooking.getTotalCost()); String customerName = bookingCustomer.getFirstName() + " " + bookingCustomer.getLastName(); Date today = new Date(); String todaysDate = fileFormat.format(today); //create pdf of booking details try { String fileName = strBookingID + "_" + todaysDate; Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("src\\reports\\Booking\\staff\\Booking_Report_Booking_ID_" +fileName +".pdf")); doc.open(); //load booking details into pdf Paragraph heading1 = new Paragraph(); heading1.add("Booking Report"); heading1.setAlignment(Element.ALIGN_CENTER); Paragraph heading2 = new Paragraph(); heading2.add("Booking ID " + bookingID); heading2.setAlignment(Element.ALIGN_CENTER); Paragraph heading3 = new Paragraph(); heading3.add("Date Booked " + dateBooked ); heading3.setAlignment(Element.ALIGN_CENTER); Paragraph heading4 = new Paragraph(); heading4.add("Outstanding Balance " + outstandingBalance ); heading4.setAlignment(Element.ALIGN_CENTER); Paragraph heading5 = new Paragraph(); heading5.add("Total Cost " + totalCost ); heading5.setAlignment(Element.ALIGN_CENTER); Paragraph heading6 = new Paragraph(); heading6.add("Customer Name " + customerName ); heading6.setAlignment(Element.ALIGN_CENTER); doc.add(heading1); doc.add(heading2); doc.add(heading3); doc.add(heading4); doc.add(heading5); doc.add(heading6); doc.close(); JOptionPane.showMessageDialog(null, "Successfully Exported"); } catch (DocumentException ex) { Logger.getLogger(StaffViewRooms.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(StaffViewRooms.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnStaffExportBookingReportActionPerformed private void btnAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAboutActionPerformed About rForm = new About(loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnAboutActionPerformed private void checkSameAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSameAddressActionPerformed DBManager db = new DBManager(); Customer paymentCustomer = new Customer(); int customerID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 1); paymentCustomer = db.getCustomerFromCustomerID(customerID);; txtPaymentHouse.setText(paymentCustomer.getHouse()); txtPaymentStreet.setText(paymentCustomer.getStreet()); txtPaymentTown.setText(paymentCustomer.getTown()); txtPaymentPostcode.setText(paymentCustomer.getPostcode()); }//GEN-LAST:event_checkSameAddressActionPerformed private void checkSameAddress1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSameAddress1ActionPerformed DBManager db = new DBManager(); Customer paymentCustomer = new Customer(); int customerID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 1); paymentCustomer = db.getCustomerFromCustomerID(customerID); txtPaymentHouse1.setText(paymentCustomer.getHouse()); txtPaymentStreet1.setText(paymentCustomer.getStreet()); txtPaymentTown1.setText(paymentCustomer.getTown()); txtPaymentPostcode1.setText(paymentCustomer.getPostcode()); }//GEN-LAST:event_checkSameAddress1ActionPerformed private void tblBookingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblBookingsMouseClicked if(tblBookings.getSelectedRow() != -1) { int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); Date today = new Date(); Date dateBooked = selectedBooking.getDateBooked(); Calendar cal = Calendar.getInstance(); cal.setTime(dateBooked); cal.add(Calendar.DATE, 1); Date bookingPlus24hr = cal.getTime(); btnEditBooking.setVisible(true); btnStaffExportBookingReport.setVisible(true); if(selectedBooking.getOutstandingBalance() > 0) { btnPayBooking.setText("Pay For Booking"); btnPayBooking.setVisible(true); } else if(selectedBooking.getOutstandingBalance() < 0) { btnPayBooking.setText("Refund Balance"); btnPayBooking.setVisible(true); } else if(!(selectedBooking.getOutstandingBalance() < 0) && !(selectedBooking.getOutstandingBalance() > 0)) { btnPayBooking.setVisible(false); } if(!today.after(bookingPlus24hr)) { btnDeleteBooking.setVisible(true); } else { btnDeleteBooking.setVisible(false); } } }//GEN-LAST:event_tblBookingsMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //new StaffViewBookings().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAbout; private javax.swing.JButton btnCart; private javax.swing.JButton btnControlPanel; private javax.swing.JButton btnDeleteBooking; private javax.swing.JButton btnEditBooking; private javax.swing.JButton btnPayBooking; private javax.swing.JButton btnPaymentClear; private javax.swing.JButton btnPaymentClose; private javax.swing.JButton btnPaymentSubmit; private javax.swing.JButton btnRefundClear; private javax.swing.JButton btnRefundClose; private javax.swing.JButton btnRefundSubmit; private javax.swing.JButton btnRegister; private javax.swing.JButton btnSignIn; private javax.swing.JButton btnStaffExportBookingReport; private javax.swing.JCheckBox checkSameAddress; private javax.swing.JCheckBox checkSameAddress1; private javax.swing.JComboBox<String> comboCardType; private javax.swing.JComboBox<String> comboRefundCardType; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private com.toedter.calendar.JMonthChooser jMonthExpiry; private com.toedter.calendar.JMonthChooser jMonthRefundExpiry; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private com.toedter.calendar.JYearChooser jYearExpiry; private com.toedter.calendar.JYearChooser jYearRefundExpiry; private javax.swing.JFrame jframePayment; private javax.swing.JFrame jframeRefund; private javax.swing.JLabel lblPaymentTitle; private javax.swing.JLabel lblPaymentTotalCost; private javax.swing.JLabel lblStaff; private javax.swing.JLabel lblTitle; private javax.swing.JTable tblBookings; private javax.swing.JTextField txtCardNo; private javax.swing.JTextField txtPayeeName; private javax.swing.JTextField txtPaymentHouse; private javax.swing.JTextField txtPaymentHouse1; private javax.swing.JTextField txtPaymentPostcode; private javax.swing.JTextField txtPaymentPostcode1; private javax.swing.JTextField txtPaymentStreet; private javax.swing.JTextField txtPaymentStreet1; private javax.swing.JTextField txtPaymentTotalCost; private javax.swing.JTextField txtPaymentTown; private javax.swing.JTextField txtPaymentTown1; private javax.swing.JTextField txtRefundCardNo; private javax.swing.JTextField txtRefundPayeeName; private javax.swing.JTextField txtRefundSecurityNo; private javax.swing.JTextField txtRefundTotalRefund; private javax.swing.JTextField txtSecurityNo; // End of variables declaration//GEN-END:variables }
UTF-8
Java
82,363
java
StaffViewBookings.java
Java
[ { "context": ".swing.table.DefaultTableModel;\n\n/**\n *\n * @author Paul\n */\npublic class StaffViewBookings extends javax.", "end": 1346, "score": 0.9974834322929382, "start": 1342, "tag": "NAME", "value": "Paul" }, { "context": ");\n heading6.add(\"Customer Name \" + customerName );\n heading6.setAlignment(Elem", "end": 72832, "score": 0.9740074276924133, "start": 72824, "tag": "NAME", "value": "customer" } ]
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 Views; import Models.Booking; import Models.CardType; import Models.Customer; import Models.DBManager; import Models.ExcelWriter; import Models.LoggedInUser; import Models.Payment; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableModel; /** * * @author Paul */ public class StaffViewBookings extends javax.swing.JFrame { //pass user details //initialise variables for payments and refunds private LoggedInUser loggedInUser = new LoggedInUser(); private double refundDue = 0; private int refundBookingID = 0; private double amountDue = 0; private int paymentBookingID = 0; /** * allows staff to view all bookings and delete/ edit/ take payments and make refunds * @param loggedInUser */ public StaffViewBookings(LoggedInUser loggedInUser) { this.loggedInUser = loggedInUser; loadFrame(); } //initialise componenets in frame public void loadFrame() { initComponents(); this.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2); Font ttfBase = null; Font ttfReal = null; try { InputStream myStream = new BufferedInputStream(new FileInputStream("src/fonts/Dillanda Caligraphy Script Demo.ttf")); ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream); ttfReal = ttfBase.deriveFont(Font.BOLD, 50); lblTitle.setFont(ttfReal); lblTitle.setForeground(new Color(102, 0, 0)); } catch (Exception ex) { ex.printStackTrace(); System.err.println("Custom font not loaded."); } btnSignIn.setText("Logged in as " + loggedInUser.getUsername()); btnSignIn.setEnabled(false); btnRegister.setText("Logout"); loadBookingTable(); btnPayBooking.setVisible(false); btnEditBooking.setVisible(false); btnDeleteBooking.setVisible(false); btnStaffExportBookingReport.setVisible(false); } //load booking details into table public void loadBookingTable() { tblBookings.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); DefaultTableModel model = (DefaultTableModel)tblBookings.getModel(); HashMap<Integer, Booking> bookings = new HashMap<Integer, Booking>(); DBManager db = new DBManager(); bookings = db.getBookings(); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); for(Map.Entry<Integer, Booking> bookingEntry : bookings.entrySet()) { Booking currentBooking = bookingEntry.getValue(); model.addRow(new Object[]{currentBooking.getBookingID(), currentBooking.getCustomerID(), currentBooking.getIsPaid(), String.format("%.02f",currentBooking.getOutstandingBalance()), String.format("%.02f",currentBooking.getTotalCost()), dateFormat.format(currentBooking.getDateBooked()) }); } } //add card types to drop down public void populateCardTypeDropDown() { comboCardType.removeAllItems(); DBManager db = new DBManager(); HashMap<Integer, CardType> cardTypes = new HashMap<Integer, CardType>(); cardTypes = db.getCardTypes(); comboCardType.addItem("--Please Select--"); for (Map.Entry<Integer, CardType> cardTypeEntry : cardTypes.entrySet()) { comboCardType.addItem(cardTypeEntry.getValue().getCardType()); } } //add card types to drop down public void populateRefundCardTypeDropDown() { comboRefundCardType.removeAllItems(); DBManager db = new DBManager(); HashMap<Integer, CardType> cardTypes = new HashMap<Integer, CardType>(); cardTypes = db.getCardTypes(); comboRefundCardType.addItem("--Please Select--"); for (Map.Entry<Integer, CardType> cardTypeEntry : cardTypes.entrySet()) { comboRefundCardType.addItem(cardTypeEntry.getValue().getCardType()); } } /** * 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() { jframePayment = new javax.swing.JFrame(); btnPaymentSubmit = new javax.swing.JButton(); btnPaymentClear = new javax.swing.JButton(); btnPaymentClose = new javax.swing.JButton(); jLabel18 = new javax.swing.JLabel(); txtPayeeName = new javax.swing.JTextField(); jLabel19 = new javax.swing.JLabel(); txtCardNo = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); txtSecurityNo = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); comboCardType = new javax.swing.JComboBox<>(); txtPaymentTotalCost = new javax.swing.JTextField(); lblPaymentTotalCost = new javax.swing.JLabel(); lblPaymentTitle = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel24 = new javax.swing.JLabel(); jMonthExpiry = new com.toedter.calendar.JMonthChooser(); jYearExpiry = new com.toedter.calendar.JYearChooser(); jPanel5 = new javax.swing.JPanel(); jLabel30 = new javax.swing.JLabel(); jLabel31 = new javax.swing.JLabel(); jLabel32 = new javax.swing.JLabel(); jLabel33 = new javax.swing.JLabel(); txtPaymentHouse = new javax.swing.JTextField(); txtPaymentStreet = new javax.swing.JTextField(); txtPaymentTown = new javax.swing.JTextField(); txtPaymentPostcode = new javax.swing.JTextField(); checkSameAddress = new javax.swing.JCheckBox(); jframeRefund = new javax.swing.JFrame(); btnRefundSubmit = new javax.swing.JButton(); btnRefundClear = new javax.swing.JButton(); btnRefundClose = new javax.swing.JButton(); jLabel22 = new javax.swing.JLabel(); txtRefundPayeeName = new javax.swing.JTextField(); jLabel23 = new javax.swing.JLabel(); txtRefundCardNo = new javax.swing.JTextField(); jLabel25 = new javax.swing.JLabel(); txtRefundSecurityNo = new javax.swing.JTextField(); jLabel26 = new javax.swing.JLabel(); comboRefundCardType = new javax.swing.JComboBox<>(); txtRefundTotalRefund = new javax.swing.JTextField(); jLabel27 = new javax.swing.JLabel(); jLabel28 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel29 = new javax.swing.JLabel(); jMonthRefundExpiry = new com.toedter.calendar.JMonthChooser(); jYearRefundExpiry = new com.toedter.calendar.JYearChooser(); jPanel6 = new javax.swing.JPanel(); jLabel34 = new javax.swing.JLabel(); jLabel35 = new javax.swing.JLabel(); jLabel36 = new javax.swing.JLabel(); jLabel37 = new javax.swing.JLabel(); txtPaymentHouse1 = new javax.swing.JTextField(); txtPaymentStreet1 = new javax.swing.JTextField(); txtPaymentTown1 = new javax.swing.JTextField(); txtPaymentPostcode1 = new javax.swing.JTextField(); checkSameAddress1 = new javax.swing.JCheckBox(); btnEditBooking = new javax.swing.JButton(); btnDeleteBooking = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); btnAbout = new javax.swing.JButton(); btnRegister = new javax.swing.JButton(); btnSignIn = new javax.swing.JButton(); btnCart = new javax.swing.JButton(); btnControlPanel = new javax.swing.JButton(); btnPayBooking = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); lblTitle = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); tblBookings = new javax.swing.JTable(); lblStaff = new javax.swing.JLabel(); btnStaffExportBookingReport = new javax.swing.JButton(); btnPaymentSubmit.setText("Submit"); btnPaymentSubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentSubmitActionPerformed(evt); } }); btnPaymentClear.setText("Clear"); btnPaymentClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentClearActionPerformed(evt); } }); btnPaymentClose.setText("Close"); btnPaymentClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPaymentCloseActionPerformed(evt); } }); jLabel18.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel18.setText("Card Holder's Name"); jLabel19.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel19.setText("Card No"); jLabel20.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel20.setText("Security No"); jLabel21.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel21.setText("Card Type"); txtPaymentTotalCost.setEditable(false); lblPaymentTotalCost.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); lblPaymentTotalCost.setText("Total Cost"); lblPaymentTitle.setBackground(new java.awt.Color(255, 255, 255)); lblPaymentTitle.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N lblPaymentTitle.setForeground(new java.awt.Color(51, 0, 0)); lblPaymentTitle.setText("Payment Details"); jPanel3.setBackground(new java.awt.Color(255, 255, 255)); jLabel24.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel24.setText("Expiry Date"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jMonthExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jYearExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel24) .addGap(70, 70, 70)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jLabel24) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMonthExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jYearExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23)) ); jPanel5.setBackground(new java.awt.Color(255, 255, 255)); jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Payee's Address")); jLabel30.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel30.setText("Address 1"); jLabel31.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel31.setText("Address 2"); jLabel32.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel32.setText("Town"); jLabel33.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel33.setText("Postcode"); checkSameAddress.setText("Same as account address"); checkSameAddress.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkSameAddressActionPerformed(evt); } }); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel30, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentHouse, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel32, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentTown, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel33, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentPostcode, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel31, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentStreet, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(26, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkSameAddress) .addGap(54, 54, 54)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel30) .addComponent(txtPaymentHouse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel31) .addComponent(txtPaymentStreet, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel32) .addComponent(txtPaymentTown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel33) .addComponent(txtPaymentPostcode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(checkSameAddress) .addGap(23, 23, 23)) ); javax.swing.GroupLayout jframePaymentLayout = new javax.swing.GroupLayout(jframePayment.getContentPane()); jframePayment.getContentPane().setLayout(jframePaymentLayout); jframePaymentLayout.setHorizontalGroup( jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(lblPaymentTitle) .addContainerGap(482, Short.MAX_VALUE)) .addGroup(jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel20) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel19) .addComponent(jLabel18))) .addGap(32, 32, 32) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframePaymentLayout.createSequentialGroup() .addComponent(btnPaymentSubmit) .addGap(54, 54, 54) .addComponent(btnPaymentClear) .addGap(61, 61, 61) .addComponent(btnPaymentClose)) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jframePaymentLayout.createSequentialGroup() .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel21) .addComponent(lblPaymentTotalCost)) .addGap(32, 32, 32) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtPaymentTotalCost, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboCardType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(59, 59, 59)))) ); jframePaymentLayout.setVerticalGroup( jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(lblPaymentTitle) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(txtPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel19)) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframePaymentLayout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel20) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(comboCardType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPaymentTotalCost) .addComponent(txtPaymentTotalCost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(44, 44, 44)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jframePaymentLayout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26))) .addGroup(jframePaymentLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnPaymentSubmit) .addComponent(btnPaymentClear) .addComponent(btnPaymentClose)) .addContainerGap(46, Short.MAX_VALUE)) ); btnRefundSubmit.setText("Submit"); btnRefundSubmit.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundSubmitActionPerformed(evt); } }); btnRefundClear.setText("Clear"); btnRefundClear.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundClearActionPerformed(evt); } }); btnRefundClose.setText("Close"); btnRefundClose.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRefundCloseActionPerformed(evt); } }); jLabel22.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel22.setText("Card Holder's Name"); jLabel23.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel23.setText("Card No"); jLabel25.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel25.setText("Security No"); jLabel26.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel26.setText("Card Type"); txtRefundTotalRefund.setEditable(false); jLabel27.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel27.setText("Total Refund"); jLabel28.setBackground(new java.awt.Color(255, 255, 255)); jLabel28.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel28.setForeground(new java.awt.Color(51, 0, 0)); jLabel28.setText("Refund Details"); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jLabel29.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel29.setText("Expiry Date"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addGap(23, 23, 23) .addComponent(jMonthRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jYearRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 11, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel29) .addGap(70, 70, 70)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap(20, Short.MAX_VALUE) .addComponent(jLabel29) .addGap(18, 18, 18) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jMonthRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jYearRefundExpiry, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23)) ); jPanel6.setBackground(new java.awt.Color(255, 255, 255)); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Payee's Address")); jLabel34.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel34.setText("Address 1"); jLabel35.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel35.setText("Address 2"); jLabel36.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel36.setText("Town"); jLabel37.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); jLabel37.setText("Postcode"); checkSameAddress1.setText("Same as account address"); checkSameAddress1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkSameAddress1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel34, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentHouse1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel36, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentTown1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel37, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentPostcode1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jLabel35, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPaymentStreet1, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(26, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel6Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(checkSameAddress1) .addGap(54, 54, 54)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(31, 31, 31) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel34) .addComponent(txtPaymentHouse1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel35) .addComponent(txtPaymentStreet1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel36) .addComponent(txtPaymentTown1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(23, 23, 23) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel37) .addComponent(txtPaymentPostcode1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE) .addComponent(checkSameAddress1) .addGap(23, 23, 23)) ); javax.swing.GroupLayout jframeRefundLayout = new javax.swing.GroupLayout(jframeRefund.getContentPane()); jframeRefund.getContentPane().setLayout(jframeRefundLayout); jframeRefundLayout.setHorizontalGroup( jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(75, 75, 75) .addComponent(jLabel28) .addContainerGap(609, Short.MAX_VALUE)) .addGroup(jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel25) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(txtRefundSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel23) .addComponent(jLabel22))) .addGap(32, 32, 32) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtRefundPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtRefundCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jframeRefundLayout.createSequentialGroup() .addComponent(btnRefundSubmit) .addGap(54, 54, 54) .addComponent(btnRefundClear) .addGap(61, 61, 61) .addComponent(btnRefundClose)) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jframeRefundLayout.createSequentialGroup() .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel26) .addComponent(jLabel27)) .addGap(32, 32, 32) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtRefundTotalRefund, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboRefundCardType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(125, 125, 125)))) ); jframeRefundLayout.setVerticalGroup( jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jLabel28) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(49, 49, 49) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(txtRefundPayeeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtRefundCardNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel23)) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(45, 45, 45) .addComponent(jLabel25) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtRefundSecurityNo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel26) .addComponent(comboRefundCardType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel27) .addComponent(txtRefundTotalRefund, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jframeRefundLayout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jPanel6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(28, 28, 28) .addGroup(jframeRefundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnRefundSubmit) .addComponent(btnRefundClear) .addComponent(btnRefundClose)) .addContainerGap(46, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); btnEditBooking.setText("View Booking"); btnEditBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEditBookingActionPerformed(evt); } }); btnDeleteBooking.setText("Delete Booking"); btnDeleteBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnDeleteBookingActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(224, 224, 224)); jPanel2.setToolTipText(""); btnAbout.setText("About Drovers Lodge"); btnAbout.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnAboutActionPerformed(evt); } }); btnRegister.setText("Register"); btnRegister.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRegisterActionPerformed(evt); } }); btnSignIn.setText("Sign In"); btnSignIn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSignInActionPerformed(evt); } }); btnCart.setBackground(new java.awt.Color(51, 0, 0)); btnCart.setForeground(new java.awt.Color(255, 255, 255)); btnCart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/basket.png"))); // NOI18N btnCart.setText("Cart"); btnCart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCartActionPerformed(evt); } }); btnControlPanel.setBackground(new java.awt.Color(51, 0, 0)); btnControlPanel.setForeground(new java.awt.Color(255, 255, 255)); btnControlPanel.setText("Control Panel"); btnControlPanel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnControlPanelActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(btnAbout) .addGap(18, 18, 18) .addComponent(btnControlPanel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnSignIn) .addGap(18, 18, 18) .addComponent(btnRegister) .addGap(18, 18, 18) .addComponent(btnCart) .addGap(15, 15, 15)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnAbout) .addComponent(btnSignIn) .addComponent(btnRegister) .addComponent(btnCart) .addComponent(btnControlPanel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); btnPayBooking.setText("Pay For Booking"); btnPayBooking.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnPayBookingActionPerformed(evt); } }); jLabel1.setText("All Bookings"); lblTitle.setBackground(new java.awt.Color(255, 255, 255)); lblTitle.setFont(new java.awt.Font("Arial", 1, 48)); // NOI18N lblTitle.setForeground(new java.awt.Color(102, 0, 0)); lblTitle.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTitle.setText("Drovers Lodge"); tblBookings.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Booking ID", "Customer ID", "Is Paid", "Outstanding Balance", "Total Cost", "Date Booked" } ) { Class[] types = new Class [] { java.lang.Integer.class, java.lang.Integer.class, java.lang.Boolean.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, true, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); tblBookings.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tblBookingsMouseClicked(evt); } }); jScrollPane1.setViewportView(tblBookings); lblStaff.setBackground(new java.awt.Color(255, 255, 51)); lblStaff.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N lblStaff.setForeground(new java.awt.Color(51, 51, 51)); lblStaff.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblStaff.setText("STAFF"); lblStaff.setOpaque(true); btnStaffExportBookingReport.setText("Export Booking Report"); btnStaffExportBookingReport.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnStaffExportBookingReportActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGap(165, 165, 165) .addComponent(lblTitle) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 132, Short.MAX_VALUE) .addComponent(lblStaff, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(btnStaffExportBookingReport) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPayBooking) .addGap(45, 45, 45) .addComponent(btnDeleteBooking) .addGap(34, 34, 34) .addComponent(btnEditBooking))) .addGap(32, 32, 32)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblTitle, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblStaff)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel1) .addGap(11, 11, 11) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 168, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 37, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnDeleteBooking) .addComponent(btnEditBooking) .addComponent(btnPayBooking) .addComponent(btnStaffExportBookingReport)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnEditBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditBookingActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); EditBooking rForm = new EditBooking(bookingID, loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnEditBookingActionPerformed private void btnDeleteBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteBookingActionPerformed //delete booking and make refund if due int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); if(selectedBooking.getIsPaid()) { refundDue = selectedBooking.getTotalCost() - selectedBooking.getOutstandingBalance(); refundBookingID = selectedBooking.getBookingID(); db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); //make refund panel visible jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else { double totalCost = selectedBooking.getTotalCost(); double outstandingBalance = selectedBooking.getOutstandingBalance(); //check if refund is due if((totalCost - outstandingBalance) > 0) { refundDue = totalCost - outstandingBalance; refundBookingID = selectedBooking.getBookingID(); db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else { db.removeBooking(bookingID); JOptionPane.showMessageDialog(null, "Booking deleted"); } } }//GEN-LAST:event_btnDeleteBookingActionPerformed private void btnRegisterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegisterActionPerformed loggedInUser = new LoggedInUser(); loggedInUser.setIsLoggedIn(false); btnSignIn.setText("Sign In"); btnSignIn.setEnabled(true); btnRegister.setText("Register"); MainMenu rForm = new MainMenu(); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnRegisterActionPerformed private void btnSignInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSignInActionPerformed }//GEN-LAST:event_btnSignInActionPerformed private void btnCartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCartActionPerformed Cart rForm = new Cart(loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnCartActionPerformed private void btnPayBookingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPayBookingActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); if(selectedBooking.getOutstandingBalance() < 0) { refundDue = selectedBooking.getTotalCost() - selectedBooking.getOutstandingBalance(); refundBookingID = selectedBooking.getBookingID(); //make payment panel visible jframeRefund.setVisible(true); jframeRefund.setSize(840,600); jframeRefund.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframeRefund.setLocation(dim.width/2-jframeRefund.getSize().width/2, dim.height/2-jframeRefund.getSize().height/2); jframeRefund.setVisible(true); populateRefundCardTypeDropDown(); txtRefundTotalRefund.setText("£" + String.format("%.02f",(refundDue))); } else if(selectedBooking.getOutstandingBalance() > 0) { amountDue = selectedBooking.getOutstandingBalance(); paymentBookingID = selectedBooking.getBookingID(); jframePayment.setVisible(true); jframePayment.setSize(840,600); jframePayment.getContentPane().setBackground(Color.white); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); jframePayment.setLocation(dim.width/2-jframePayment.getSize().width/2, dim.height/2-jframePayment.getSize().height/2); jframePayment.setVisible(true); populateCardTypeDropDown(); txtPaymentTotalCost.setText("£" + String.format("%.02f",(amountDue))); } }//GEN-LAST:event_btnPayBookingActionPerformed private void btnPaymentSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentSubmitActionPerformed //check payment details have been filled in if(txtPayeeName.getText().isEmpty() || txtCardNo.getText().isEmpty() || txtSecurityNo.getText().isEmpty() || comboCardType.getSelectedIndex()==0 || txtPaymentHouse.getText().isEmpty() || txtPaymentTown.getText().isEmpty() || txtPaymentPostcode.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Please fill in all payment fields"); } else { int length = txtCardNo.getText().length(); if(length < 10) { JOptionPane.showMessageDialog(null, "Card number must be at least 10 digits"); } else { DBManager db = new DBManager(); String payeeName = txtPayeeName.getText(); String cardNo = txtCardNo.getText(); String securityNo = txtSecurityNo.getText(); int expiryMonth = jMonthExpiry.getMonth(); String monthString; switch (expiryMonth) { case 0: monthString = "Jan"; break; case 1: monthString = "Feb"; break; case 2: monthString = "Mar"; break; case 3: monthString = "Apr"; break; case 4: monthString = "May"; break; case 5: monthString = "Jun"; break; case 6: monthString = "Jul"; break; case 7: monthString = "Aug"; break; case 8: monthString = "Sep"; break; case 9: monthString = "Oct"; break; case 10: monthString = "Nov"; break; case 11: monthString = "Dec"; break; default: monthString = "Invalid month"; break; } int expiryYear = jYearExpiry.getYear(); Date expiryDate = new Date(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); expiryDate = dateFormat.parse(expiryYear + "-" + monthString + "-01 00:00:00"); } catch (ParseException ex) { Logger.getLogger(Cart.class.getName()).log(Level.SEVERE, null, ex); } int cardTypeID = db.getCardTypeIDFromCardType(String.valueOf(comboCardType.getSelectedItem())); String paymentHouse = txtPaymentHouse.getText(); String paymentStreet = txtPaymentStreet.getText(); String paymentTown = txtPaymentTown.getText(); String paymentPostcode = txtPaymentPostcode.getText(); Payment payment = new Payment(payeeName, cardNo, securityNo, expiryDate, cardTypeID, amountDue, paymentBookingID, paymentHouse, paymentStreet, paymentTown, paymentPostcode); db.takePayment(payment); db.setOutstandingPaymentZeroIsPaidTrue(paymentBookingID); amountDue = 0; paymentBookingID = 0; txtPayeeName.setText(""); txtCardNo.setText(""); txtSecurityNo.setText(""); comboCardType.setSelectedIndex(0); checkSameAddress.setSelected(false); txtPaymentHouse.setText(""); txtPaymentStreet.setText(""); txtPaymentTown.setText(""); txtPaymentPostcode.setText(""); jframePayment.dispose(); JOptionPane.showMessageDialog(null, "Payment successful"); clearBookingTable(); loadBookingTable(); } } }//GEN-LAST:event_btnPaymentSubmitActionPerformed private void btnPaymentClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentClearActionPerformed txtPayeeName.setText(""); txtCardNo.setText(""); txtSecurityNo.setText(""); comboCardType.setSelectedIndex(0); checkSameAddress.setSelected(false); txtPaymentHouse.setText(""); txtPaymentStreet.setText(""); txtPaymentTown.setText(""); txtPaymentPostcode.setText(""); }//GEN-LAST:event_btnPaymentClearActionPerformed private void btnPaymentCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPaymentCloseActionPerformed jframePayment.dispose(); }//GEN-LAST:event_btnPaymentCloseActionPerformed private void btnRefundSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundSubmitActionPerformed //check all refund details are filled in if(txtRefundPayeeName.getText().isEmpty() || txtRefundCardNo.getText().isEmpty() || txtRefundSecurityNo.getText().isEmpty() || comboRefundCardType.getSelectedIndex()==0 || txtPaymentHouse1.getText().isEmpty() || txtPaymentTown1.getText().isEmpty() || txtPaymentPostcode1.getText().isEmpty()) { JOptionPane.showMessageDialog(null, "Please fill in all payment fields"); } else { int length = txtRefundCardNo.getText().length(); if(length < 10) { JOptionPane.showMessageDialog(null, "Card number must be at least 10 digits"); } else { DBManager db = new DBManager(); String refundPayeeName = txtRefundPayeeName.getText(); String refundCardNo = txtRefundCardNo.getText(); String refundSecurityNo = txtRefundSecurityNo.getText(); int refundExpiryMonth = jMonthRefundExpiry.getMonth(); String refundMonthString; switch (refundExpiryMonth) { case 0: refundMonthString = "Jan"; break; case 1: refundMonthString = "Feb"; break; case 2: refundMonthString = "Mar"; break; case 3: refundMonthString = "Apr"; break; case 4: refundMonthString = "May"; break; case 5: refundMonthString = "Jun"; break; case 6: refundMonthString = "Jul"; break; case 7: refundMonthString = "Aug"; break; case 8: refundMonthString = "Sep"; break; case 9: refundMonthString = "Oct"; break; case 10: refundMonthString = "Nov"; break; case 11: refundMonthString = "Dec"; break; default: refundMonthString = "Invalid month"; break; } int refundExpiryYear = jYearRefundExpiry.getYear(); Date refundExpiryDate = new Date(); try { SimpleDateFormat refundDateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); refundExpiryDate = refundDateFormat.parse(refundExpiryYear + "-" + refundMonthString + "-01 00:00:00"); } catch (ParseException ex) { Logger.getLogger(Cart.class.getName()).log(Level.SEVERE, null, ex); } int cardTypeID = db.getCardTypeIDFromCardType(String.valueOf(comboCardType.getSelectedItem())); double totalRefund = refundDue; Payment refund = new Payment(refundPayeeName, refundCardNo, refundSecurityNo, refundExpiryDate, cardTypeID, totalRefund, refundBookingID); db.takePayment(refund); db.setOutstandingPaymentZeroIsPaidTrue(refundBookingID); refundDue = 0; refundBookingID = 0; txtRefundPayeeName.setText(""); txtRefundCardNo.setText(""); txtRefundSecurityNo.setText(""); comboRefundCardType.setSelectedIndex(0); checkSameAddress1.setSelected(false); txtPaymentHouse1.setText(""); txtPaymentStreet1.setText(""); txtPaymentTown1.setText(""); txtPaymentPostcode1.setText(""); jframeRefund.dispose(); JOptionPane.showMessageDialog(null, "Refund successful"); clearBookingTable(); loadBookingTable(); } } }//GEN-LAST:event_btnRefundSubmitActionPerformed //remove old rows from booking table public void clearBookingTable() { DefaultTableModel model = (DefaultTableModel)tblBookings.getModel(); int rows = model.getRowCount(); for(int i = rows - 1; i >=0; i--) { model.removeRow(i); } } private void btnRefundClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundClearActionPerformed txtRefundPayeeName.setText(""); txtRefundCardNo.setText(""); txtRefundSecurityNo.setText(""); comboRefundCardType.setSelectedIndex(0); checkSameAddress1.setSelected(false); txtPaymentHouse1.setText(""); txtPaymentStreet1.setText(""); txtPaymentTown1.setText(""); txtPaymentPostcode1.setText(""); }//GEN-LAST:event_btnRefundClearActionPerformed private void btnRefundCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefundCloseActionPerformed jframePayment.dispose(); }//GEN-LAST:event_btnRefundCloseActionPerformed private void btnControlPanelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnControlPanelActionPerformed if(loggedInUser.getUserTypeID() == 2) { CustomerHome rForm = new CustomerHome(loggedInUser); this.dispose(); rForm.setVisible(true); } else if(loggedInUser.getUserTypeID() == 3) { StaffHome rForm = new StaffHome(loggedInUser); this.dispose(); rForm.setVisible(true); } }//GEN-LAST:event_btnControlPanelActionPerformed private void btnStaffExportBookingReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnStaffExportBookingReportActionPerformed int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); Customer bookingCustomer = db.getCustomerFromCustomerID(selectedBooking.getCustomerID()); String strBookingID = String.valueOf(selectedBooking.getBookingID()); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); SimpleDateFormat fileFormat = new SimpleDateFormat("dd_MM_yyyy"); String dateBooked = dateFormat.format(selectedBooking.getDateBooked()); String outstandingBalance = String.valueOf(selectedBooking.getOutstandingBalance()); String totalCost = String.valueOf(selectedBooking.getTotalCost()); String customerName = bookingCustomer.getFirstName() + " " + bookingCustomer.getLastName(); Date today = new Date(); String todaysDate = fileFormat.format(today); //create pdf of booking details try { String fileName = strBookingID + "_" + todaysDate; Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("src\\reports\\Booking\\staff\\Booking_Report_Booking_ID_" +fileName +".pdf")); doc.open(); //load booking details into pdf Paragraph heading1 = new Paragraph(); heading1.add("Booking Report"); heading1.setAlignment(Element.ALIGN_CENTER); Paragraph heading2 = new Paragraph(); heading2.add("Booking ID " + bookingID); heading2.setAlignment(Element.ALIGN_CENTER); Paragraph heading3 = new Paragraph(); heading3.add("Date Booked " + dateBooked ); heading3.setAlignment(Element.ALIGN_CENTER); Paragraph heading4 = new Paragraph(); heading4.add("Outstanding Balance " + outstandingBalance ); heading4.setAlignment(Element.ALIGN_CENTER); Paragraph heading5 = new Paragraph(); heading5.add("Total Cost " + totalCost ); heading5.setAlignment(Element.ALIGN_CENTER); Paragraph heading6 = new Paragraph(); heading6.add("Customer Name " + customerName ); heading6.setAlignment(Element.ALIGN_CENTER); doc.add(heading1); doc.add(heading2); doc.add(heading3); doc.add(heading4); doc.add(heading5); doc.add(heading6); doc.close(); JOptionPane.showMessageDialog(null, "Successfully Exported"); } catch (DocumentException ex) { Logger.getLogger(StaffViewRooms.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(StaffViewRooms.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_btnStaffExportBookingReportActionPerformed private void btnAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAboutActionPerformed About rForm = new About(loggedInUser); this.dispose(); rForm.setVisible(true); }//GEN-LAST:event_btnAboutActionPerformed private void checkSameAddressActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSameAddressActionPerformed DBManager db = new DBManager(); Customer paymentCustomer = new Customer(); int customerID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 1); paymentCustomer = db.getCustomerFromCustomerID(customerID);; txtPaymentHouse.setText(paymentCustomer.getHouse()); txtPaymentStreet.setText(paymentCustomer.getStreet()); txtPaymentTown.setText(paymentCustomer.getTown()); txtPaymentPostcode.setText(paymentCustomer.getPostcode()); }//GEN-LAST:event_checkSameAddressActionPerformed private void checkSameAddress1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkSameAddress1ActionPerformed DBManager db = new DBManager(); Customer paymentCustomer = new Customer(); int customerID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 1); paymentCustomer = db.getCustomerFromCustomerID(customerID); txtPaymentHouse1.setText(paymentCustomer.getHouse()); txtPaymentStreet1.setText(paymentCustomer.getStreet()); txtPaymentTown1.setText(paymentCustomer.getTown()); txtPaymentPostcode1.setText(paymentCustomer.getPostcode()); }//GEN-LAST:event_checkSameAddress1ActionPerformed private void tblBookingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblBookingsMouseClicked if(tblBookings.getSelectedRow() != -1) { int bookingID = (Integer)tblBookings.getValueAt(tblBookings.getSelectedRow(), 0); DBManager db = new DBManager(); Booking selectedBooking = db.getBookingFromBookingID(bookingID); Date today = new Date(); Date dateBooked = selectedBooking.getDateBooked(); Calendar cal = Calendar.getInstance(); cal.setTime(dateBooked); cal.add(Calendar.DATE, 1); Date bookingPlus24hr = cal.getTime(); btnEditBooking.setVisible(true); btnStaffExportBookingReport.setVisible(true); if(selectedBooking.getOutstandingBalance() > 0) { btnPayBooking.setText("Pay For Booking"); btnPayBooking.setVisible(true); } else if(selectedBooking.getOutstandingBalance() < 0) { btnPayBooking.setText("Refund Balance"); btnPayBooking.setVisible(true); } else if(!(selectedBooking.getOutstandingBalance() < 0) && !(selectedBooking.getOutstandingBalance() > 0)) { btnPayBooking.setVisible(false); } if(!today.after(bookingPlus24hr)) { btnDeleteBooking.setVisible(true); } else { btnDeleteBooking.setVisible(false); } } }//GEN-LAST:event_tblBookingsMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(StaffViewBookings.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { //new StaffViewBookings().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAbout; private javax.swing.JButton btnCart; private javax.swing.JButton btnControlPanel; private javax.swing.JButton btnDeleteBooking; private javax.swing.JButton btnEditBooking; private javax.swing.JButton btnPayBooking; private javax.swing.JButton btnPaymentClear; private javax.swing.JButton btnPaymentClose; private javax.swing.JButton btnPaymentSubmit; private javax.swing.JButton btnRefundClear; private javax.swing.JButton btnRefundClose; private javax.swing.JButton btnRefundSubmit; private javax.swing.JButton btnRegister; private javax.swing.JButton btnSignIn; private javax.swing.JButton btnStaffExportBookingReport; private javax.swing.JCheckBox checkSameAddress; private javax.swing.JCheckBox checkSameAddress1; private javax.swing.JComboBox<String> comboCardType; private javax.swing.JComboBox<String> comboRefundCardType; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JLabel jLabel23; private javax.swing.JLabel jLabel24; private javax.swing.JLabel jLabel25; private javax.swing.JLabel jLabel26; private javax.swing.JLabel jLabel27; private javax.swing.JLabel jLabel28; private javax.swing.JLabel jLabel29; private javax.swing.JLabel jLabel30; private javax.swing.JLabel jLabel31; private javax.swing.JLabel jLabel32; private javax.swing.JLabel jLabel33; private javax.swing.JLabel jLabel34; private javax.swing.JLabel jLabel35; private javax.swing.JLabel jLabel36; private javax.swing.JLabel jLabel37; private com.toedter.calendar.JMonthChooser jMonthExpiry; private com.toedter.calendar.JMonthChooser jMonthRefundExpiry; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private com.toedter.calendar.JYearChooser jYearExpiry; private com.toedter.calendar.JYearChooser jYearRefundExpiry; private javax.swing.JFrame jframePayment; private javax.swing.JFrame jframeRefund; private javax.swing.JLabel lblPaymentTitle; private javax.swing.JLabel lblPaymentTotalCost; private javax.swing.JLabel lblStaff; private javax.swing.JLabel lblTitle; private javax.swing.JTable tblBookings; private javax.swing.JTextField txtCardNo; private javax.swing.JTextField txtPayeeName; private javax.swing.JTextField txtPaymentHouse; private javax.swing.JTextField txtPaymentHouse1; private javax.swing.JTextField txtPaymentPostcode; private javax.swing.JTextField txtPaymentPostcode1; private javax.swing.JTextField txtPaymentStreet; private javax.swing.JTextField txtPaymentStreet1; private javax.swing.JTextField txtPaymentTotalCost; private javax.swing.JTextField txtPaymentTown; private javax.swing.JTextField txtPaymentTown1; private javax.swing.JTextField txtRefundCardNo; private javax.swing.JTextField txtRefundPayeeName; private javax.swing.JTextField txtRefundSecurityNo; private javax.swing.JTextField txtRefundTotalRefund; private javax.swing.JTextField txtSecurityNo; // End of variables declaration//GEN-END:variables }
82,363
0.635146
0.620127
1,503
53.796406
38.250687
201
false
false
0
0
0
0
0
0
0.842315
false
false
0
6826e6d548e92500a1685517ef70f98a9a971e8c
32,074,815,802,648
d2a93dfbcdffde5dc64f3a1a66150df87dd3dfea
/main-src/com/eleven/client/core/CoreSet.java
11cf4c5a07e0aabce8a50ae4768d927bc42d80df
[]
no_license
gnl/Janus
https://github.com/gnl/Janus
aacf9ae5c14cb083af4682582c695be17f215b99
773864c37986aa4151991e47724c11c3ac59ee86
refs/heads/master
2015-08-12T16:52:08.605000
2014-07-28T20:11:24
2014-07-28T20:11:24
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.eleven.client.core; import com.eleven.client.core.fn.Function; import org.jetbrains.annotations.NotNull; /** * CoreObject must know about the Core* collection classes in * order to be able to create collection copies - allowing custom * CoreCollection class implementations would break this. This is * also why CoreArray and CoreSet are declared final. */ // this must be declared final public class CoreSet<T> extends CoreArray<T> implements CoreCollection { public CoreSet() { super(); } protected CoreSet(final boolean synthesized) { super(synthesized); } @Override public void add(@NotNull final T element) { if (!contains(element)) super.add(element); } @Override public void add(final int index, @NotNull final T element) { if (!contains(element)) super.add(index, element); } @Override public T set(final int index, @NotNull final T element) { if (!contains(element)) return super.set(index, element); return null; } @Override public boolean remove(@NotNull final T element) { return contains(element) && super.remove(element); } @Override public void check_add(@NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) super.check_add(element, checkSynthesized); } @Override public void check_add(final int index, @NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) super.check_add(index, element, checkSynthesized); } @Override public boolean check_remove(@NotNull final T element, final boolean checkSynthesized) { return contains(element) && super.check_remove(element, checkSynthesized); } @Override public T check_set(final int index, @NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) return super.check_set(index, element, checkSynthesized); return null; } @Override protected <V> CoreArray<V> foreach_kvc(@NotNull final Function<KVCObject, V> function) { CoreSet<V> array = new CoreSet<V>(); V value; for (Object element : this) { if (element instanceof KVCObject) { value = function.apply((KVCObject) element); if (value != null) array.check_add(value, false); } } return array; } }
UTF-8
Java
2,232
java
CoreSet.java
Java
[]
null
[]
package com.eleven.client.core; import com.eleven.client.core.fn.Function; import org.jetbrains.annotations.NotNull; /** * CoreObject must know about the Core* collection classes in * order to be able to create collection copies - allowing custom * CoreCollection class implementations would break this. This is * also why CoreArray and CoreSet are declared final. */ // this must be declared final public class CoreSet<T> extends CoreArray<T> implements CoreCollection { public CoreSet() { super(); } protected CoreSet(final boolean synthesized) { super(synthesized); } @Override public void add(@NotNull final T element) { if (!contains(element)) super.add(element); } @Override public void add(final int index, @NotNull final T element) { if (!contains(element)) super.add(index, element); } @Override public T set(final int index, @NotNull final T element) { if (!contains(element)) return super.set(index, element); return null; } @Override public boolean remove(@NotNull final T element) { return contains(element) && super.remove(element); } @Override public void check_add(@NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) super.check_add(element, checkSynthesized); } @Override public void check_add(final int index, @NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) super.check_add(index, element, checkSynthesized); } @Override public boolean check_remove(@NotNull final T element, final boolean checkSynthesized) { return contains(element) && super.check_remove(element, checkSynthesized); } @Override public T check_set(final int index, @NotNull final T element, final boolean checkSynthesized) { if (!contains(element)) return super.check_set(index, element, checkSynthesized); return null; } @Override protected <V> CoreArray<V> foreach_kvc(@NotNull final Function<KVCObject, V> function) { CoreSet<V> array = new CoreSet<V>(); V value; for (Object element : this) { if (element instanceof KVCObject) { value = function.apply((KVCObject) element); if (value != null) array.check_add(value, false); } } return array; } }
2,232
0.719534
0.719534
90
23.799999
26.570744
99
false
false
0
0
0
0
0
0
1.611111
false
false
0
2c536b56c6876703935824da921e0f957b9adee5
4,260,607,609,821
aae446f7bbc953c3280c95a3fdb1b0e69b56000a
/02-JavaBasic/src/Ternary.java
a6a73d9296e3c6a585b1b502aef339cb1004c705
[]
no_license
Ryu-kwonhee/javabasic
https://github.com/Ryu-kwonhee/javabasic
499ee2c0c4e86099ee0ce2c5cd48167c0c3b151e
48645def241fdb7bd5a4510872edfd14b308d3e6
refs/heads/master
2023-07-13T04:24:39.518000
2021-08-15T00:59:16
2021-08-15T00:59:16
380,178,606
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Ternary { public static void main(String[] args) { /* * 삼항 연산자는 (조건시 ? 결과1 : 결과2) * 로 작성합니다. * 조건식의 결과가 true라면 결과1이 * 조건식의 결과가 false라면 결과2가 출력됩니다. */ System.out.println((3 > 5 ? "참" : "거짓")); } }
UTF-8
Java
335
java
Ternary.java
Java
[]
null
[]
public class Ternary { public static void main(String[] args) { /* * 삼항 연산자는 (조건시 ? 결과1 : 결과2) * 로 작성합니다. * 조건식의 결과가 true라면 결과1이 * 조건식의 결과가 false라면 결과2가 출력됩니다. */ System.out.println((3 > 5 ? "참" : "거짓")); } }
335
0.55794
0.532189
12
18.333334
15.326085
43
false
false
0
0
0
0
0
0
1.416667
false
false
0
5991c3e88d566447e0f21a1ae16b7ad906e05df9
1,666,447,312,274
084f900c36b289331e886e312a26ca697e86d3c5
/src/main/java/frc/robot/autos/CenterFarRocketHatch.java
723cbf926dd773a813e6e9a280531d353ac1fc01
[]
no_license
TF-185/FRC-5254---2019
https://github.com/TF-185/FRC-5254---2019
8bb12df95c479a1bc8ff95e3592e19eeefa9ac82
9ebd9c768ab7184e534715783f9fb811273772b8
refs/heads/master
2023-04-30T09:01:27.184000
2020-01-20T13:38:51
2020-01-20T13:38:51
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.autos; import edu.wpi.first.wpilibj.command.CommandGroup; import frc.robot.commands.DrivetrainLineUp2; import frc.robot.commands.HatchMechSetFinState; import frc.robot.commands.HatchMechSetKickerState; import frc.robot.commands.HatchMechSetSliderState; import frc.robot.easypath.FollowPath; import frc.robot.easypath.Path; import frc.robot.subsystems.HatchMech.SliderState; import frc.robot.subsystems.HatchMech.FinState; import frc.robot.subsystems.HatchMech.KickerState; public class CenterFarRocketHatch extends CommandGroup { /** * Add your docs here. */ public CenterFarRocketHatch(Path path) { addSequential(new FollowPath(path, 0.25)); addSequential(new DrivetrainLineUp2()); addSequential(new HatchMechSetSliderState(SliderState.OUT)); // TODO setMechState? or place command? addSequential(new HatchMechSetFinState(FinState.UNCLAMPED)); addSequential(new HatchMechSetKickerState(KickerState.OUT)); } }
UTF-8
Java
1,449
java
CenterFarRocketHatch.java
Java
[]
null
[]
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.autos; import edu.wpi.first.wpilibj.command.CommandGroup; import frc.robot.commands.DrivetrainLineUp2; import frc.robot.commands.HatchMechSetFinState; import frc.robot.commands.HatchMechSetKickerState; import frc.robot.commands.HatchMechSetSliderState; import frc.robot.easypath.FollowPath; import frc.robot.easypath.Path; import frc.robot.subsystems.HatchMech.SliderState; import frc.robot.subsystems.HatchMech.FinState; import frc.robot.subsystems.HatchMech.KickerState; public class CenterFarRocketHatch extends CommandGroup { /** * Add your docs here. */ public CenterFarRocketHatch(Path path) { addSequential(new FollowPath(path, 0.25)); addSequential(new DrivetrainLineUp2()); addSequential(new HatchMechSetSliderState(SliderState.OUT)); // TODO setMechState? or place command? addSequential(new HatchMechSetFinState(FinState.UNCLAMPED)); addSequential(new HatchMechSetKickerState(KickerState.OUT)); } }
1,449
0.648033
0.641822
32
44.28125
28.461855
104
false
false
0
0
0
0
0
0
0.53125
false
false
0
f20f75870e28ea4627cb87fc121e86c7368eb30c
14,491,219,670,371
814fd0bea5bc063a4e34ebdd0a5597c9ff67532b
/net/android/java/src/org/chromium/net/NetworkChangeNotifierAutoDetect.java
aea674adb4d5be5e83f5b1b49ab8451797695562
[ "BSD-3-Clause" ]
permissive
rzr/chromium-crosswalk
https://github.com/rzr/chromium-crosswalk
1b22208ff556d69c009ad292bc17dca3fe15c493
d391344809adf7b4f39764ac0e15c378169b805f
refs/heads/master
2021-01-21T09:11:07.316000
2015-02-16T11:52:21
2015-02-16T11:52:21
38,887,985
0
0
NOASSERTION
true
2019-08-07T21:59:20
2015-07-10T15:35:50
2015-07-10T15:39:32
2019-08-07T21:59:16
2,560,080
0
0
1
C++
false
false
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.net; import android.Manifest.permission; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import android.util.Log; import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; /** * Used by the NetworkChangeNotifier to listens to platform changes in connectivity. * Note that use of this class requires that the app have the platform * ACCESS_NETWORK_STATE permission. */ public class NetworkChangeNotifierAutoDetect extends BroadcastReceiver implements ApplicationStatus.ApplicationStateListener { static class NetworkState { private final boolean mConnected; private final int mType; private final int mSubtype; public NetworkState(boolean connected, int type, int subtype) { mConnected = connected; mType = type; mSubtype = subtype; } public boolean isConnected() { return mConnected; } public int getNetworkType() { return mType; } public int getNetworkSubType() { return mSubtype; } } /** Queries the ConnectivityManager for information about the current connection. */ static class ConnectivityManagerDelegate { private final ConnectivityManager mConnectivityManager; ConnectivityManagerDelegate(Context context) { mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } // For testing. ConnectivityManagerDelegate() { // All the methods below should be overridden. mConnectivityManager = null; } NetworkState getNetworkState() { final NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { return new NetworkState(false, -1, -1); } return new NetworkState(true, networkInfo.getType(), networkInfo.getSubtype()); } } /** Queries the WifiManager for SSID of the current Wifi connection. */ static class WifiManagerDelegate { private final Context mContext; private final WifiManager mWifiManager; private final boolean mHasWifiPermission; WifiManagerDelegate(Context context) { mContext = context; // TODO(jkarlin): If the embedder doesn't have ACCESS_WIFI_STATE permission then inform // native code and fail if native NetworkChangeNotifierAndroid::GetMaxBandwidth() is // called. mHasWifiPermission = mContext.getPackageManager().checkPermission( permission.ACCESS_WIFI_STATE, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED; mWifiManager = mHasWifiPermission ? (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE) : null; } // For testing. WifiManagerDelegate() { // All the methods below should be overridden. mContext = null; mWifiManager = null; mHasWifiPermission = false; } String getWifiSSID() { final Intent intent = mContext.registerReceiver(null, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); if (intent != null) { final WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); if (wifiInfo != null) { final String ssid = wifiInfo.getSSID(); if (ssid != null) { return ssid; } } } return ""; } /* * Requires ACCESS_WIFI_STATE permission to get the real link speed, else returns * UNKNOWN_LINK_SPEED. */ int getLinkSpeedInMbps() { if (!mHasWifiPermission || mWifiManager == null) return UNKNOWN_LINK_SPEED; final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); if (wifiInfo == null) return UNKNOWN_LINK_SPEED; // wifiInfo.getLinkSpeed returns the current wifi linkspeed, which can change even // though the connection type hasn't changed. return wifiInfo.getLinkSpeed(); } boolean getHasWifiPermission() { return mHasWifiPermission; } } private static final String TAG = "NetworkChangeNotifierAutoDetect"; private static final int UNKNOWN_LINK_SPEED = -1; private final NetworkConnectivityIntentFilter mIntentFilter; private final Observer mObserver; private final Context mContext; private ConnectivityManagerDelegate mConnectivityManagerDelegate; private WifiManagerDelegate mWifiManagerDelegate; private boolean mRegistered; private int mConnectionType; private String mWifiSSID; private double mMaxBandwidthMbps; /** * Observer notified on the UI thread whenever a new connection type was detected or max * bandwidth is changed. */ public static interface Observer { public void onConnectionTypeChanged(int newConnectionType); public void onMaxBandwidthChanged(double maxBandwidthMbps); } /** * Constructs a NetworkChangeNotifierAutoDetect. * @param alwaysWatchForChanges If true, always watch for network changes. * Otherwise, only watch if app is in foreground. */ public NetworkChangeNotifierAutoDetect(Observer observer, Context context, boolean alwaysWatchForChanges) { mObserver = observer; mContext = context.getApplicationContext(); mConnectivityManagerDelegate = new ConnectivityManagerDelegate(context); mWifiManagerDelegate = new WifiManagerDelegate(context); final NetworkState networkState = mConnectivityManagerDelegate.getNetworkState(); mConnectionType = getCurrentConnectionType(networkState); mWifiSSID = getCurrentWifiSSID(networkState); mMaxBandwidthMbps = getCurrentMaxBandwidthInMbps(networkState); mIntentFilter = new NetworkConnectivityIntentFilter(mWifiManagerDelegate.getHasWifiPermission()); if (alwaysWatchForChanges) { registerReceiver(); } else { ApplicationStatus.registerApplicationStateListener(this); } } /** * Allows overriding the ConnectivityManagerDelegate for tests. */ void setConnectivityManagerDelegateForTests(ConnectivityManagerDelegate delegate) { mConnectivityManagerDelegate = delegate; } /** * Allows overriding the WifiManagerDelegate for tests. */ void setWifiManagerDelegateForTests(WifiManagerDelegate delegate) { mWifiManagerDelegate = delegate; } public void destroy() { unregisterReceiver(); } /** * Register a BroadcastReceiver in the given context. */ private void registerReceiver() { if (!mRegistered) { mRegistered = true; mContext.registerReceiver(this, mIntentFilter); } } /** * Unregister the BroadcastReceiver in the given context. */ private void unregisterReceiver() { if (mRegistered) { mRegistered = false; mContext.unregisterReceiver(this); } } public NetworkState getCurrentNetworkState() { return mConnectivityManagerDelegate.getNetworkState(); } public int getCurrentConnectionType(NetworkState networkState) { if (!networkState.isConnected()) { return ConnectionType.CONNECTION_NONE; } switch (networkState.getNetworkType()) { case ConnectivityManager.TYPE_ETHERNET: return ConnectionType.CONNECTION_ETHERNET; case ConnectivityManager.TYPE_WIFI: return ConnectionType.CONNECTION_WIFI; case ConnectivityManager.TYPE_WIMAX: return ConnectionType.CONNECTION_4G; case ConnectivityManager.TYPE_BLUETOOTH: return ConnectionType.CONNECTION_BLUETOOTH; case ConnectivityManager.TYPE_MOBILE: // Use information from TelephonyManager to classify the connection. switch (networkState.getNetworkSubType()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: return ConnectionType.CONNECTION_2G; case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: return ConnectionType.CONNECTION_3G; case TelephonyManager.NETWORK_TYPE_LTE: return ConnectionType.CONNECTION_4G; default: return ConnectionType.CONNECTION_UNKNOWN; } default: return ConnectionType.CONNECTION_UNKNOWN; } } /* * Returns the bandwidth of the current connection in Mbps. The result is * derived from the NetInfo v3 specification's mapping from network type to * max link speed. In cases where more information is available, such as wifi, * that is used instead. For more on NetInfo, see http://w3c.github.io/netinfo/. */ public double getCurrentMaxBandwidthInMbps(NetworkState networkState) { if (getCurrentConnectionType(networkState) == ConnectionType.CONNECTION_WIFI) { final int link_speed = mWifiManagerDelegate.getLinkSpeedInMbps(); if (link_speed != UNKNOWN_LINK_SPEED) { return link_speed; } } return NetworkChangeNotifier.getMaxBandwidthForConnectionSubtype( getCurrentConnectionSubtype(networkState)); } private int getCurrentConnectionSubtype(NetworkState networkState) { if (!networkState.isConnected()) { return ConnectionSubtype.SUBTYPE_NONE; } switch (networkState.getNetworkType()) { case ConnectivityManager.TYPE_ETHERNET: case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_BLUETOOTH: return ConnectionSubtype.SUBTYPE_UNKNOWN; case ConnectivityManager.TYPE_MOBILE: // Use information from TelephonyManager to classify the connection. switch (networkState.getNetworkSubType()) { case TelephonyManager.NETWORK_TYPE_GPRS: return ConnectionSubtype.SUBTYPE_GPRS; case TelephonyManager.NETWORK_TYPE_EDGE: return ConnectionSubtype.SUBTYPE_EDGE; case TelephonyManager.NETWORK_TYPE_CDMA: return ConnectionSubtype.SUBTYPE_CDMA; case TelephonyManager.NETWORK_TYPE_1xRTT: return ConnectionSubtype.SUBTYPE_1XRTT; case TelephonyManager.NETWORK_TYPE_IDEN: return ConnectionSubtype.SUBTYPE_IDEN; case TelephonyManager.NETWORK_TYPE_UMTS: return ConnectionSubtype.SUBTYPE_UMTS; case TelephonyManager.NETWORK_TYPE_EVDO_0: return ConnectionSubtype.SUBTYPE_EVDO_REV_0; case TelephonyManager.NETWORK_TYPE_EVDO_A: return ConnectionSubtype.SUBTYPE_EVDO_REV_A; case TelephonyManager.NETWORK_TYPE_HSDPA: return ConnectionSubtype.SUBTYPE_HSDPA; case TelephonyManager.NETWORK_TYPE_HSUPA: return ConnectionSubtype.SUBTYPE_HSUPA; case TelephonyManager.NETWORK_TYPE_HSPA: return ConnectionSubtype.SUBTYPE_HSPA; case TelephonyManager.NETWORK_TYPE_EVDO_B: return ConnectionSubtype.SUBTYPE_EVDO_REV_B; case TelephonyManager.NETWORK_TYPE_EHRPD: return ConnectionSubtype.SUBTYPE_EHRPD; case TelephonyManager.NETWORK_TYPE_HSPAP: return ConnectionSubtype.SUBTYPE_HSPAP; case TelephonyManager.NETWORK_TYPE_LTE: return ConnectionSubtype.SUBTYPE_LTE; default: return ConnectionSubtype.SUBTYPE_UNKNOWN; } default: return ConnectionSubtype.SUBTYPE_UNKNOWN; } } private String getCurrentWifiSSID(NetworkState networkState) { if (getCurrentConnectionType(networkState) != ConnectionType.CONNECTION_WIFI) return ""; return mWifiManagerDelegate.getWifiSSID(); } // BroadcastReceiver @Override public void onReceive(Context context, Intent intent) { final NetworkState networkState = getCurrentNetworkState(); if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { connectionTypeChanged(networkState); maxBandwidthChanged(networkState); } else if (WifiManager.RSSI_CHANGED_ACTION.equals(intent.getAction())) { maxBandwidthChanged(networkState); } } // ApplicationStatus.ApplicationStateListener @Override public void onApplicationStateChange(int newState) { final NetworkState networkState = getCurrentNetworkState(); if (newState == ApplicationState.HAS_RUNNING_ACTIVITIES) { connectionTypeChanged(networkState); maxBandwidthChanged(networkState); registerReceiver(); } else if (newState == ApplicationState.HAS_PAUSED_ACTIVITIES) { unregisterReceiver(); } } private void connectionTypeChanged(NetworkState networkState) { int newConnectionType = getCurrentConnectionType(networkState); String newWifiSSID = getCurrentWifiSSID(networkState); if (newConnectionType == mConnectionType && newWifiSSID.equals(mWifiSSID)) return; mConnectionType = newConnectionType; mWifiSSID = newWifiSSID; Log.d(TAG, "Network connectivity changed, type is: " + mConnectionType); mObserver.onConnectionTypeChanged(newConnectionType); } private void maxBandwidthChanged(NetworkState networkState) { double newMaxBandwidthMbps = getCurrentMaxBandwidthInMbps(networkState); if (newMaxBandwidthMbps == mMaxBandwidthMbps) return; mMaxBandwidthMbps = newMaxBandwidthMbps; mObserver.onMaxBandwidthChanged(newMaxBandwidthMbps); } private static class NetworkConnectivityIntentFilter extends IntentFilter { NetworkConnectivityIntentFilter(boolean monitorRSSI) { addAction(ConnectivityManager.CONNECTIVITY_ACTION); if (monitorRSSI) addAction(WifiManager.RSSI_CHANGED_ACTION); } } }
UTF-8
Java
16,226
java
NetworkChangeNotifierAutoDetect.java
Java
[ { "context": " mContext = context;\n // TODO(jkarlin): If the embedder doesn't have ACCESS_WIFI_STATE ", "end": 2926, "score": 0.9994123578071594, "start": 2919, "tag": "USERNAME", "value": "jkarlin" } ]
null
[]
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.net; import android.Manifest.permission; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.telephony.TelephonyManager; import android.util.Log; import org.chromium.base.ApplicationState; import org.chromium.base.ApplicationStatus; /** * Used by the NetworkChangeNotifier to listens to platform changes in connectivity. * Note that use of this class requires that the app have the platform * ACCESS_NETWORK_STATE permission. */ public class NetworkChangeNotifierAutoDetect extends BroadcastReceiver implements ApplicationStatus.ApplicationStateListener { static class NetworkState { private final boolean mConnected; private final int mType; private final int mSubtype; public NetworkState(boolean connected, int type, int subtype) { mConnected = connected; mType = type; mSubtype = subtype; } public boolean isConnected() { return mConnected; } public int getNetworkType() { return mType; } public int getNetworkSubType() { return mSubtype; } } /** Queries the ConnectivityManager for information about the current connection. */ static class ConnectivityManagerDelegate { private final ConnectivityManager mConnectivityManager; ConnectivityManagerDelegate(Context context) { mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); } // For testing. ConnectivityManagerDelegate() { // All the methods below should be overridden. mConnectivityManager = null; } NetworkState getNetworkState() { final NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected()) { return new NetworkState(false, -1, -1); } return new NetworkState(true, networkInfo.getType(), networkInfo.getSubtype()); } } /** Queries the WifiManager for SSID of the current Wifi connection. */ static class WifiManagerDelegate { private final Context mContext; private final WifiManager mWifiManager; private final boolean mHasWifiPermission; WifiManagerDelegate(Context context) { mContext = context; // TODO(jkarlin): If the embedder doesn't have ACCESS_WIFI_STATE permission then inform // native code and fail if native NetworkChangeNotifierAndroid::GetMaxBandwidth() is // called. mHasWifiPermission = mContext.getPackageManager().checkPermission( permission.ACCESS_WIFI_STATE, mContext.getPackageName()) == PackageManager.PERMISSION_GRANTED; mWifiManager = mHasWifiPermission ? (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE) : null; } // For testing. WifiManagerDelegate() { // All the methods below should be overridden. mContext = null; mWifiManager = null; mHasWifiPermission = false; } String getWifiSSID() { final Intent intent = mContext.registerReceiver(null, new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION)); if (intent != null) { final WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO); if (wifiInfo != null) { final String ssid = wifiInfo.getSSID(); if (ssid != null) { return ssid; } } } return ""; } /* * Requires ACCESS_WIFI_STATE permission to get the real link speed, else returns * UNKNOWN_LINK_SPEED. */ int getLinkSpeedInMbps() { if (!mHasWifiPermission || mWifiManager == null) return UNKNOWN_LINK_SPEED; final WifiInfo wifiInfo = mWifiManager.getConnectionInfo(); if (wifiInfo == null) return UNKNOWN_LINK_SPEED; // wifiInfo.getLinkSpeed returns the current wifi linkspeed, which can change even // though the connection type hasn't changed. return wifiInfo.getLinkSpeed(); } boolean getHasWifiPermission() { return mHasWifiPermission; } } private static final String TAG = "NetworkChangeNotifierAutoDetect"; private static final int UNKNOWN_LINK_SPEED = -1; private final NetworkConnectivityIntentFilter mIntentFilter; private final Observer mObserver; private final Context mContext; private ConnectivityManagerDelegate mConnectivityManagerDelegate; private WifiManagerDelegate mWifiManagerDelegate; private boolean mRegistered; private int mConnectionType; private String mWifiSSID; private double mMaxBandwidthMbps; /** * Observer notified on the UI thread whenever a new connection type was detected or max * bandwidth is changed. */ public static interface Observer { public void onConnectionTypeChanged(int newConnectionType); public void onMaxBandwidthChanged(double maxBandwidthMbps); } /** * Constructs a NetworkChangeNotifierAutoDetect. * @param alwaysWatchForChanges If true, always watch for network changes. * Otherwise, only watch if app is in foreground. */ public NetworkChangeNotifierAutoDetect(Observer observer, Context context, boolean alwaysWatchForChanges) { mObserver = observer; mContext = context.getApplicationContext(); mConnectivityManagerDelegate = new ConnectivityManagerDelegate(context); mWifiManagerDelegate = new WifiManagerDelegate(context); final NetworkState networkState = mConnectivityManagerDelegate.getNetworkState(); mConnectionType = getCurrentConnectionType(networkState); mWifiSSID = getCurrentWifiSSID(networkState); mMaxBandwidthMbps = getCurrentMaxBandwidthInMbps(networkState); mIntentFilter = new NetworkConnectivityIntentFilter(mWifiManagerDelegate.getHasWifiPermission()); if (alwaysWatchForChanges) { registerReceiver(); } else { ApplicationStatus.registerApplicationStateListener(this); } } /** * Allows overriding the ConnectivityManagerDelegate for tests. */ void setConnectivityManagerDelegateForTests(ConnectivityManagerDelegate delegate) { mConnectivityManagerDelegate = delegate; } /** * Allows overriding the WifiManagerDelegate for tests. */ void setWifiManagerDelegateForTests(WifiManagerDelegate delegate) { mWifiManagerDelegate = delegate; } public void destroy() { unregisterReceiver(); } /** * Register a BroadcastReceiver in the given context. */ private void registerReceiver() { if (!mRegistered) { mRegistered = true; mContext.registerReceiver(this, mIntentFilter); } } /** * Unregister the BroadcastReceiver in the given context. */ private void unregisterReceiver() { if (mRegistered) { mRegistered = false; mContext.unregisterReceiver(this); } } public NetworkState getCurrentNetworkState() { return mConnectivityManagerDelegate.getNetworkState(); } public int getCurrentConnectionType(NetworkState networkState) { if (!networkState.isConnected()) { return ConnectionType.CONNECTION_NONE; } switch (networkState.getNetworkType()) { case ConnectivityManager.TYPE_ETHERNET: return ConnectionType.CONNECTION_ETHERNET; case ConnectivityManager.TYPE_WIFI: return ConnectionType.CONNECTION_WIFI; case ConnectivityManager.TYPE_WIMAX: return ConnectionType.CONNECTION_4G; case ConnectivityManager.TYPE_BLUETOOTH: return ConnectionType.CONNECTION_BLUETOOTH; case ConnectivityManager.TYPE_MOBILE: // Use information from TelephonyManager to classify the connection. switch (networkState.getNetworkSubType()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: return ConnectionType.CONNECTION_2G; case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: return ConnectionType.CONNECTION_3G; case TelephonyManager.NETWORK_TYPE_LTE: return ConnectionType.CONNECTION_4G; default: return ConnectionType.CONNECTION_UNKNOWN; } default: return ConnectionType.CONNECTION_UNKNOWN; } } /* * Returns the bandwidth of the current connection in Mbps. The result is * derived from the NetInfo v3 specification's mapping from network type to * max link speed. In cases where more information is available, such as wifi, * that is used instead. For more on NetInfo, see http://w3c.github.io/netinfo/. */ public double getCurrentMaxBandwidthInMbps(NetworkState networkState) { if (getCurrentConnectionType(networkState) == ConnectionType.CONNECTION_WIFI) { final int link_speed = mWifiManagerDelegate.getLinkSpeedInMbps(); if (link_speed != UNKNOWN_LINK_SPEED) { return link_speed; } } return NetworkChangeNotifier.getMaxBandwidthForConnectionSubtype( getCurrentConnectionSubtype(networkState)); } private int getCurrentConnectionSubtype(NetworkState networkState) { if (!networkState.isConnected()) { return ConnectionSubtype.SUBTYPE_NONE; } switch (networkState.getNetworkType()) { case ConnectivityManager.TYPE_ETHERNET: case ConnectivityManager.TYPE_WIFI: case ConnectivityManager.TYPE_WIMAX: case ConnectivityManager.TYPE_BLUETOOTH: return ConnectionSubtype.SUBTYPE_UNKNOWN; case ConnectivityManager.TYPE_MOBILE: // Use information from TelephonyManager to classify the connection. switch (networkState.getNetworkSubType()) { case TelephonyManager.NETWORK_TYPE_GPRS: return ConnectionSubtype.SUBTYPE_GPRS; case TelephonyManager.NETWORK_TYPE_EDGE: return ConnectionSubtype.SUBTYPE_EDGE; case TelephonyManager.NETWORK_TYPE_CDMA: return ConnectionSubtype.SUBTYPE_CDMA; case TelephonyManager.NETWORK_TYPE_1xRTT: return ConnectionSubtype.SUBTYPE_1XRTT; case TelephonyManager.NETWORK_TYPE_IDEN: return ConnectionSubtype.SUBTYPE_IDEN; case TelephonyManager.NETWORK_TYPE_UMTS: return ConnectionSubtype.SUBTYPE_UMTS; case TelephonyManager.NETWORK_TYPE_EVDO_0: return ConnectionSubtype.SUBTYPE_EVDO_REV_0; case TelephonyManager.NETWORK_TYPE_EVDO_A: return ConnectionSubtype.SUBTYPE_EVDO_REV_A; case TelephonyManager.NETWORK_TYPE_HSDPA: return ConnectionSubtype.SUBTYPE_HSDPA; case TelephonyManager.NETWORK_TYPE_HSUPA: return ConnectionSubtype.SUBTYPE_HSUPA; case TelephonyManager.NETWORK_TYPE_HSPA: return ConnectionSubtype.SUBTYPE_HSPA; case TelephonyManager.NETWORK_TYPE_EVDO_B: return ConnectionSubtype.SUBTYPE_EVDO_REV_B; case TelephonyManager.NETWORK_TYPE_EHRPD: return ConnectionSubtype.SUBTYPE_EHRPD; case TelephonyManager.NETWORK_TYPE_HSPAP: return ConnectionSubtype.SUBTYPE_HSPAP; case TelephonyManager.NETWORK_TYPE_LTE: return ConnectionSubtype.SUBTYPE_LTE; default: return ConnectionSubtype.SUBTYPE_UNKNOWN; } default: return ConnectionSubtype.SUBTYPE_UNKNOWN; } } private String getCurrentWifiSSID(NetworkState networkState) { if (getCurrentConnectionType(networkState) != ConnectionType.CONNECTION_WIFI) return ""; return mWifiManagerDelegate.getWifiSSID(); } // BroadcastReceiver @Override public void onReceive(Context context, Intent intent) { final NetworkState networkState = getCurrentNetworkState(); if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { connectionTypeChanged(networkState); maxBandwidthChanged(networkState); } else if (WifiManager.RSSI_CHANGED_ACTION.equals(intent.getAction())) { maxBandwidthChanged(networkState); } } // ApplicationStatus.ApplicationStateListener @Override public void onApplicationStateChange(int newState) { final NetworkState networkState = getCurrentNetworkState(); if (newState == ApplicationState.HAS_RUNNING_ACTIVITIES) { connectionTypeChanged(networkState); maxBandwidthChanged(networkState); registerReceiver(); } else if (newState == ApplicationState.HAS_PAUSED_ACTIVITIES) { unregisterReceiver(); } } private void connectionTypeChanged(NetworkState networkState) { int newConnectionType = getCurrentConnectionType(networkState); String newWifiSSID = getCurrentWifiSSID(networkState); if (newConnectionType == mConnectionType && newWifiSSID.equals(mWifiSSID)) return; mConnectionType = newConnectionType; mWifiSSID = newWifiSSID; Log.d(TAG, "Network connectivity changed, type is: " + mConnectionType); mObserver.onConnectionTypeChanged(newConnectionType); } private void maxBandwidthChanged(NetworkState networkState) { double newMaxBandwidthMbps = getCurrentMaxBandwidthInMbps(networkState); if (newMaxBandwidthMbps == mMaxBandwidthMbps) return; mMaxBandwidthMbps = newMaxBandwidthMbps; mObserver.onMaxBandwidthChanged(newMaxBandwidthMbps); } private static class NetworkConnectivityIntentFilter extends IntentFilter { NetworkConnectivityIntentFilter(boolean monitorRSSI) { addAction(ConnectivityManager.CONNECTIVITY_ACTION); if (monitorRSSI) addAction(WifiManager.RSSI_CHANGED_ACTION); } } }
16,226
0.642118
0.640947
396
39.974747
27.497372
99
false
false
0
0
0
0
0
0
0.409091
false
false
0
cd8d5788a1898fd1cfe886b262de04f6d0cd6a80
22,213,570,909,902
cc76595d6c4a2481e701fe5bf501e1086a3d3880
/multi-matcher-core/src/main/java/io/github/richardstartin/multimatcher/core/matchers/DoubleMatcher.java
67a247f23c684d5ecf916cbd83d436febf4f5605
[ "Apache-2.0" ]
permissive
andy-wagner/multi-matcher
https://github.com/andy-wagner/multi-matcher
84b8b29e3aab018658b7b1f76346ecb10d2ff9ad
a9fdc099c1f96a41e0becc76b74170a0c3ff34f9
refs/heads/master
2022-04-17T15:12:30.690000
2020-04-16T17:51:55
2020-04-16T17:51:55
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package io.github.richardstartin.multimatcher.core.matchers; import io.github.richardstartin.multimatcher.core.*; import io.github.richardstartin.multimatcher.core.masks.MaskStore; import io.github.richardstartin.multimatcher.core.matchers.nodes.DoubleNode; import java.util.function.ToDoubleFunction; import static io.github.richardstartin.multimatcher.core.Utils.newArray; import static io.github.richardstartin.multimatcher.core.Utils.nullCount; import static io.github.richardstartin.multimatcher.core.matchers.SelectivityHeuristics.avgCardinality; public class DoubleMatcher<T, MaskType extends Mask<MaskType>> implements ConstraintAccumulator<T, MaskType>, Matcher<T, MaskType> { private final ToDoubleFunction<T> accessor; private final MaskStore<MaskType> store; private final int wildcards; private DoubleNode<MaskType>[] children; @SuppressWarnings("unchecked") public DoubleMatcher(ToDoubleFunction<T> accessor, MaskStore<MaskType> maskStore, int max) { this.accessor = accessor; this.wildcards = maskStore.newContiguousMaskId(max); this.store = maskStore; this.children = (DoubleNode<MaskType>[]) newArray(DoubleNode.class, Operation.SIZE); } @Override public void match(T value, MaskType context) { MaskType temp = store.getTemp(wildcards); double attributeValue = accessor.applyAsDouble(value); for (var component : children) { store.orInto(temp, component.match(attributeValue, 0)); } context.inPlaceAnd(temp); } @Override public boolean addConstraint(Constraint constraint, int priority) { Number number = constraint.getValue(); double value = number.doubleValue(); add(constraint.getOperation(), value, priority); store.remove(wildcards, priority); return true; } @Override public Matcher<T, MaskType> toMatcher() { optimise(); store.optimise(wildcards); return this; } private void add(Operation relation, double threshold, int priority) { var existing = children[relation.ordinal()]; if (null == existing) { existing = children[relation.ordinal()] = new DoubleNode<>(store, relation); } existing.add(threshold, priority); } @SuppressWarnings("unchecked") private void optimise() { int nullCount = nullCount(children); if (nullCount > 0) { var newChildren = (DoubleNode<MaskType>[]) newArray(DoubleNode.class, children.length - nullCount); int i = 0; for (var child : children) { if (null != child) { newChildren[i++] = child.optimise(); } } children = newChildren; } } @Override public float averageSelectivity() { return avgCardinality(children, DoubleNode::averageSelectivity); } }
UTF-8
Java
2,976
java
DoubleMatcher.java
Java
[ { "context": "package io.github.richardstartin.multimatcher.core.matchers;\n\nimport io.github.ric", "end": 32, "score": 0.9946197867393494, "start": 18, "tag": "USERNAME", "value": "richardstartin" }, { "context": "tin.multimatcher.core.matchers;\n\nimport io.github.richardstartin.multimatcher.core.*;\nimport io.github.richardstar", "end": 93, "score": 0.9971634745597839, "start": 79, "tag": "USERNAME", "value": "richardstartin" }, { "context": "hardstartin.multimatcher.core.*;\nimport io.github.richardstartin.multimatcher.core.masks.MaskStore;\nimport io.gith", "end": 146, "score": 0.993047297000885, "start": 132, "tag": "USERNAME", "value": "richardstartin" }, { "context": "ltimatcher.core.masks.MaskStore;\nimport io.github.richardstartin.multimatcher.core.matchers.nodes.DoubleNode;\n\nimp", "end": 213, "score": 0.990437388420105, "start": 199, "tag": "USERNAME", "value": "richardstartin" }, { "context": "nction.ToDoubleFunction;\n\nimport static io.github.richardstartin.multimatcher.core.Utils.newArray;\nimport static i", "end": 343, "score": 0.98631352186203, "start": 329, "tag": "USERNAME", "value": "richardstartin" }, { "context": "cher.core.Utils.newArray;\nimport static io.github.richardstartin.multimatcher.core.Utils.nullCount;\nimport static ", "end": 416, "score": 0.952568769454956, "start": 402, "tag": "USERNAME", "value": "richardstartin" }, { "context": "her.core.Utils.nullCount;\nimport static io.github.richardstartin.multimatcher.core.matchers.SelectivityHeuristics.", "end": 490, "score": 0.8139623999595642, "start": 476, "tag": "USERNAME", "value": "richardstartin" } ]
null
[]
package io.github.richardstartin.multimatcher.core.matchers; import io.github.richardstartin.multimatcher.core.*; import io.github.richardstartin.multimatcher.core.masks.MaskStore; import io.github.richardstartin.multimatcher.core.matchers.nodes.DoubleNode; import java.util.function.ToDoubleFunction; import static io.github.richardstartin.multimatcher.core.Utils.newArray; import static io.github.richardstartin.multimatcher.core.Utils.nullCount; import static io.github.richardstartin.multimatcher.core.matchers.SelectivityHeuristics.avgCardinality; public class DoubleMatcher<T, MaskType extends Mask<MaskType>> implements ConstraintAccumulator<T, MaskType>, Matcher<T, MaskType> { private final ToDoubleFunction<T> accessor; private final MaskStore<MaskType> store; private final int wildcards; private DoubleNode<MaskType>[] children; @SuppressWarnings("unchecked") public DoubleMatcher(ToDoubleFunction<T> accessor, MaskStore<MaskType> maskStore, int max) { this.accessor = accessor; this.wildcards = maskStore.newContiguousMaskId(max); this.store = maskStore; this.children = (DoubleNode<MaskType>[]) newArray(DoubleNode.class, Operation.SIZE); } @Override public void match(T value, MaskType context) { MaskType temp = store.getTemp(wildcards); double attributeValue = accessor.applyAsDouble(value); for (var component : children) { store.orInto(temp, component.match(attributeValue, 0)); } context.inPlaceAnd(temp); } @Override public boolean addConstraint(Constraint constraint, int priority) { Number number = constraint.getValue(); double value = number.doubleValue(); add(constraint.getOperation(), value, priority); store.remove(wildcards, priority); return true; } @Override public Matcher<T, MaskType> toMatcher() { optimise(); store.optimise(wildcards); return this; } private void add(Operation relation, double threshold, int priority) { var existing = children[relation.ordinal()]; if (null == existing) { existing = children[relation.ordinal()] = new DoubleNode<>(store, relation); } existing.add(threshold, priority); } @SuppressWarnings("unchecked") private void optimise() { int nullCount = nullCount(children); if (nullCount > 0) { var newChildren = (DoubleNode<MaskType>[]) newArray(DoubleNode.class, children.length - nullCount); int i = 0; for (var child : children) { if (null != child) { newChildren[i++] = child.optimise(); } } children = newChildren; } } @Override public float averageSelectivity() { return avgCardinality(children, DoubleNode::averageSelectivity); } }
2,976
0.664987
0.663979
84
34.42857
28.483196
111
false
false
0
0
0
0
0
0
0.690476
false
false
0
10aa4d484126be02adb40937b56b2e0fdcb7d101
16,647,293,255,042
32c53f88fc0467629760fbef80fc706ddbeb20e2
/infrastructure/src/main/java/org/corfudb/infrastructure/RemoteMonitoringService.java
76df9fc0266e90f7a14fb178b911d8d5b0ab3e86
[ "Apache-2.0" ]
permissive
CorfuDB/CorfuDB
https://github.com/CorfuDB/CorfuDB
1e6dfe0f1e51a6184c61ccb9010f930e9f75bf04
778930f92f37cedb3ab59c242ed070b6ca9aceda
refs/heads/master
2023-09-04T03:30:10.854000
2023-09-01T18:53:29
2023-09-01T18:53:29
12,960,439
651
171
NOASSERTION
false
2023-09-12T21:02:06
2013-09-19T22:02:36
2023-09-08T16:42:13
2023-09-12T21:02:04
526,935
611
123
137
Java
false
false
package org.corfudb.infrastructure; import com.google.common.util.concurrent.ThreadFactoryBuilder; import lombok.Getter; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.corfudb.infrastructure.health.Component; import org.corfudb.infrastructure.health.HealthMonitor; import org.corfudb.infrastructure.health.Issue; import org.corfudb.infrastructure.log.FileSystemAgent; import org.corfudb.infrastructure.log.FileSystemAgent.PartitionAgent.PartitionAttribute; import org.corfudb.infrastructure.management.ClusterAdvisor; import org.corfudb.infrastructure.management.ClusterAdvisorFactory; import org.corfudb.infrastructure.management.ClusterStateContext; import org.corfudb.infrastructure.management.ClusterType; import org.corfudb.infrastructure.management.FailureDetector; import org.corfudb.infrastructure.management.FileSystemAdvisor; import org.corfudb.infrastructure.management.PollReport; import org.corfudb.infrastructure.management.failuredetector.EpochHandler; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorDataStore; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorException; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorHelper; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorService; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorService.SequencerBootstrapper; import org.corfudb.infrastructure.management.failuredetector.FailuresAgent; import org.corfudb.infrastructure.management.failuredetector.HealingAgent; import org.corfudb.protocols.wireprotocol.ClusterState; import org.corfudb.protocols.wireprotocol.SequencerMetrics; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats.BatchProcessorStats; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats.PartitionAttributeStats; import org.corfudb.runtime.CorfuRuntime; import org.corfudb.runtime.view.Layout; import org.corfudb.util.LambdaUtils; import org.corfudb.util.concurrent.SingletonResource; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static org.corfudb.infrastructure.health.Issue.IssueId.SOME_NODES_ARE_UNRESPONSIVE; /** * Remote Monitoring Service constitutes of failure and healing monitoring and handling. * This service is responsible for heartbeat and aggregating the cluster view. This is * updated in the shared context with the management server which serves the heartbeat responses. * The failure detector updates the unreachable nodes in the layout. * The healing detector heals nodes which were previously marked unresponsive but have now healed. * Created by zlokhandwala on 11/2/18. */ @Slf4j public class RemoteMonitoringService implements ManagementService { private static final CompletableFuture<DetectorTask> DETECTOR_TASK_NOT_COMPLETED = CompletableFuture.completedFuture(DetectorTask.NOT_COMPLETED); /** * Detectors to be used to detect failures and healing. */ @Getter private final FailureDetector failureDetector; /** * Detection Task Scheduler Service * This service schedules the following tasks every POLICY_EXECUTE_INTERVAL (1 sec): * - Detection of failed nodes. * - Detection of healed nodes. */ @Getter private final ScheduledExecutorService detectionTasksScheduler; /** * To dispatch tasks for failure or healed nodes detection. */ @Getter private final ExecutorService failureDetectorWorker; private final ServerContext serverContext; private final SingletonResource<CorfuRuntime> runtimeSingletonResource; private final ClusterStateContext clusterContext; private final LocalMonitoringService localMonitoringService; /** * Future for periodic failure and healed nodes detection task. */ private CompletableFuture<DetectorTask> failureDetectorFuture = DETECTOR_TASK_NOT_COMPLETED; private final FailureDetectorService fdService; /** * Number of workers for failure detector. Three workers used by default: * - failure/healing detection * - bootstrap sequencer * - merge segments */ private final int detectionWorkersCount = 3; RemoteMonitoringService(@NonNull ServerContext serverContext, @NonNull SingletonResource<CorfuRuntime> runtimeSingletonResource, @NonNull ClusterStateContext clusterContext, @NonNull FailureDetector failureDetector, @NonNull LocalMonitoringService localMonitoringService) { this.serverContext = serverContext; this.runtimeSingletonResource = runtimeSingletonResource; this.clusterContext = clusterContext; this.failureDetector = failureDetector; this.localMonitoringService = localMonitoringService; ClusterAdvisor advisor = ClusterAdvisorFactory.createForStrategy( ClusterType.COMPLETE_GRAPH ); this.detectionTasksScheduler = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(serverContext.getThreadPrefix() + "RemoteMonitoringService") .build()); // Creating the detection worker thread pool. // This thread pool is utilized to dispatch detection tasks at regular intervals in the // detectorTaskScheduler. ThreadFactory fdThreadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(serverContext.getThreadPrefix() + "DetectionWorker-%d") .build(); this.failureDetectorWorker = Executors.newFixedThreadPool(detectionWorkersCount, fdThreadFactory); FailureDetectorDataStore fdDataStore = FailureDetectorDataStore.builder() .localEndpoint(serverContext.getLocalEndpoint()) .dataStore(serverContext.getDataStore()) .build(); FileSystemAdvisor fsAdvisor = new FileSystemAdvisor(); EpochHandler epochHandler = EpochHandler.builder() .runtimeSingletonResource(runtimeSingletonResource) .serverContext(serverContext) .failureDetectorWorker(failureDetectorWorker) .build(); HealingAgent healingAgent = HealingAgent.builder() .advisor(advisor) .fsAdvisor(fsAdvisor) .runtimeSingleton(runtimeSingletonResource) .failureDetectorWorker(failureDetectorWorker) .dataStore(fdDataStore) .build(); FailuresAgent failuresAgent = FailuresAgent.builder() .fdDataStore(fdDataStore) .advisor(advisor) .fsAdvisor(fsAdvisor) .runtimeSingleton(runtimeSingletonResource) .build(); SequencerBootstrapper sequencerBootstrapper = SequencerBootstrapper.builder() .runtimeSingletonResource(runtimeSingletonResource) .clusterContext(clusterContext) .failureDetectorWorker(failureDetectorWorker) .build(); this.fdService = FailureDetectorService.builder() .epochHandler(epochHandler) .failuresAgent(failuresAgent) .healingAgent(healingAgent) .sequencerBootstrapper(sequencerBootstrapper) .failureDetectorWorker(failureDetectorWorker) .build(); } private CorfuRuntime getCorfuRuntime() { return runtimeSingletonResource.get(); } /** * Executes task to run failure and healing detection every poll interval. (Default: 1 sec) * <p> * During the initialization step, the method: * - triggers sequencer bootstrap * - starts failure and healing detection mechanism, by running <code>runDetectionTasks</code> * every second (by default). Next iteration of detection task can be run only if current iteration is completed. */ @Override public void start(Duration monitoringInterval) { // Trigger sequencer bootstrap on startup. sequencerBootstrap(serverContext); Runnable task = () -> { if (!failureDetectorFuture.isDone()) { return; } failureDetectorFuture = runDetectionTasks(); }; detectionTasksScheduler.scheduleAtFixedRate( () -> LambdaUtils.runSansThrow(task), 0, monitoringInterval.toMillis(), TimeUnit.MILLISECONDS ); HealthMonitor.resolveIssue(Issue.createInitIssue(Component.FAILURE_DETECTOR)); } /** * Trigger sequencer bootstrap mechanism. Get current layout management view and execute async bootstrap * * @param serverContext server context */ private CompletableFuture<DetectorTask> sequencerBootstrap(ServerContext serverContext) { log.info("Trigger sequencer bootstrap on startup"); return getCorfuRuntime() .getLayoutManagementView() .asyncSequencerBootstrap(serverContext.copyManagementLayout(), failureDetectorWorker) .thenApply(DetectorTask::fromBool); } /** * Schedules the failure detection and handling mechanism by detectorTaskScheduler. * It schedules exactly one instance of the following tasks. * - Failure detection tasks. * - Healing detection tasks. * * <pre> * The algorithm: * - wait until previous iteration finishes * - On every invocation, this task refreshes the runtime to fetch the latest layout and also updates * the local persisted copy of the latest layout. * - get corfu metrics (Sequencer, LogUnit etc). * - executes the poll using the failureDetector which generates a pollReport at the end of the round. * The report contains latest information about cluster: connectivity graph, failed and healed nodes, wrong epochs. * - refresh cluster state context by latest {@link ClusterState} collected on poll report step. * - run failure detector task composed from: * - the outOfPhase epoch server errors are corrected by resealing and patching these trailing layout servers. * - all unresponsive server failures are handled by either removing or marking * them as unresponsive based on a failure handling policy. * - make healed node responsive based on a healing detection mechanism * </pre> */ private synchronized CompletableFuture<DetectorTask> runDetectionTasks() { String localEndpoint = serverContext.getLocalEndpoint(); return getCorfuRuntime() .invalidateLayout() .thenApply(serverContext::saveManagementLayout) //check if this node can handle failures (if the node is in the cluster) .thenCompose(ourLayout -> { FailureDetectorHelper helper = new FailureDetectorHelper(ourLayout, localEndpoint); return helper.handleReconfigurationsAsync(); }) .thenCompose(ourLayout -> { //Get metrics from local monitoring service (local monitoring works in it's own thread) return localMonitoringService.getMetrics() //Poll report asynchronously using failureDetectorWorker executor .thenCompose(metrics -> pollReport(ourLayout, metrics)) //Update cluster view by latest cluster state given by the poll report. No need to be asynchronous .thenApply(pollReport -> { log.trace("Update cluster view: {}", pollReport.getClusterState()); clusterContext.refreshClusterView(ourLayout, pollReport); return pollReport; }) .thenApply(pollReport -> { if (!pollReport.getClusterState().isReady()) { throw FailureDetectorException.notReady(pollReport.getClusterState()); } return pollReport; }) //Execute failure detector task using failureDetectorWorker executor .thenCompose(pollReport -> fdService.runFailureDetectorTask(pollReport, ourLayout, localEndpoint)); }).thenApply(task -> { Issue issue = Issue.createIssue(Component.FAILURE_DETECTOR, SOME_NODES_ARE_UNRESPONSIVE, "There are nodes in the unresponsive list"); final Layout layout = serverContext.getCurrentLayout(); if (layout.getUnresponsiveServers().isEmpty()) { HealthMonitor.resolveIssue(issue); } else { HealthMonitor.reportIssue(issue); } return task; }) //Print exceptions to log .whenComplete((taskResult, ex) -> { if (ex != null) { log.error("Failure detection task finished with an error", ex); } if (ex != null || taskResult == DetectorTask.NOT_COMPLETED) { log.trace("Reporting issue"); HealthMonitor.reportIssue(new Issue(Component.FAILURE_DETECTOR, Issue.IssueId.FAILURE_DETECTOR_TASK_FAILED, "Last failure detector task was not completed")); } else { log.trace("Resolving issue"); HealthMonitor.resolveIssue(new Issue(Component.FAILURE_DETECTOR, Issue.IssueId.FAILURE_DETECTOR_TASK_FAILED, "Last failure detector task succeeded")); } }); } private CompletableFuture<PollReport> pollReport(Layout layout, SequencerMetrics sequencerMetrics) { return CompletableFuture.supplyAsync(() -> { PartitionAttribute partition = FileSystemAgent.getPartitionAttribute(); PartitionAttributeStats partitionAttributeStats = new PartitionAttributeStats( partition.isReadOnly(), partition.getAvailableSpace(), partition.getTotalSpace() ); BatchProcessorStats bpStats = new BatchProcessorStats(partition.getBatchProcessorStatus()); FileSystemStats fsStats = new FileSystemStats(partitionAttributeStats, bpStats); CorfuRuntime corfuRuntime = getCorfuRuntime(); return failureDetector.poll(layout, corfuRuntime, sequencerMetrics, fsStats); }, failureDetectorWorker); } @Override public void shutdown() { // Shutting the fault detector. detectionTasksScheduler.shutdownNow(); failureDetectorWorker.shutdownNow(); log.info("Fault detection service shutting down."); HealthMonitor.reportIssue(Issue.createInitIssue(Component.FAILURE_DETECTOR)); } public enum DetectorTask { /** * The task is completed successfully */ COMPLETED, /** * The task is completed with an exception */ NOT_COMPLETED, /** * Skipped task */ SKIPPED; public static DetectorTask fromBool(boolean taskResult) { return taskResult ? COMPLETED : NOT_COMPLETED; } } }
UTF-8
Java
16,239
java
RemoteMonitoringService.java
Java
[ { "context": "ed unresponsive but have now healed.\n * Created by zlokhandwala on 11/2/18.\n */\n@Slf4j\npublic class RemoteMonitor", "end": 3007, "score": 0.9996527433395386, "start": 2995, "tag": "USERNAME", "value": "zlokhandwala" } ]
null
[]
package org.corfudb.infrastructure; import com.google.common.util.concurrent.ThreadFactoryBuilder; import lombok.Getter; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; import org.corfudb.infrastructure.health.Component; import org.corfudb.infrastructure.health.HealthMonitor; import org.corfudb.infrastructure.health.Issue; import org.corfudb.infrastructure.log.FileSystemAgent; import org.corfudb.infrastructure.log.FileSystemAgent.PartitionAgent.PartitionAttribute; import org.corfudb.infrastructure.management.ClusterAdvisor; import org.corfudb.infrastructure.management.ClusterAdvisorFactory; import org.corfudb.infrastructure.management.ClusterStateContext; import org.corfudb.infrastructure.management.ClusterType; import org.corfudb.infrastructure.management.FailureDetector; import org.corfudb.infrastructure.management.FileSystemAdvisor; import org.corfudb.infrastructure.management.PollReport; import org.corfudb.infrastructure.management.failuredetector.EpochHandler; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorDataStore; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorException; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorHelper; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorService; import org.corfudb.infrastructure.management.failuredetector.FailureDetectorService.SequencerBootstrapper; import org.corfudb.infrastructure.management.failuredetector.FailuresAgent; import org.corfudb.infrastructure.management.failuredetector.HealingAgent; import org.corfudb.protocols.wireprotocol.ClusterState; import org.corfudb.protocols.wireprotocol.SequencerMetrics; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats.BatchProcessorStats; import org.corfudb.protocols.wireprotocol.failuredetector.FileSystemStats.PartitionAttributeStats; import org.corfudb.runtime.CorfuRuntime; import org.corfudb.runtime.view.Layout; import org.corfudb.util.LambdaUtils; import org.corfudb.util.concurrent.SingletonResource; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import static org.corfudb.infrastructure.health.Issue.IssueId.SOME_NODES_ARE_UNRESPONSIVE; /** * Remote Monitoring Service constitutes of failure and healing monitoring and handling. * This service is responsible for heartbeat and aggregating the cluster view. This is * updated in the shared context with the management server which serves the heartbeat responses. * The failure detector updates the unreachable nodes in the layout. * The healing detector heals nodes which were previously marked unresponsive but have now healed. * Created by zlokhandwala on 11/2/18. */ @Slf4j public class RemoteMonitoringService implements ManagementService { private static final CompletableFuture<DetectorTask> DETECTOR_TASK_NOT_COMPLETED = CompletableFuture.completedFuture(DetectorTask.NOT_COMPLETED); /** * Detectors to be used to detect failures and healing. */ @Getter private final FailureDetector failureDetector; /** * Detection Task Scheduler Service * This service schedules the following tasks every POLICY_EXECUTE_INTERVAL (1 sec): * - Detection of failed nodes. * - Detection of healed nodes. */ @Getter private final ScheduledExecutorService detectionTasksScheduler; /** * To dispatch tasks for failure or healed nodes detection. */ @Getter private final ExecutorService failureDetectorWorker; private final ServerContext serverContext; private final SingletonResource<CorfuRuntime> runtimeSingletonResource; private final ClusterStateContext clusterContext; private final LocalMonitoringService localMonitoringService; /** * Future for periodic failure and healed nodes detection task. */ private CompletableFuture<DetectorTask> failureDetectorFuture = DETECTOR_TASK_NOT_COMPLETED; private final FailureDetectorService fdService; /** * Number of workers for failure detector. Three workers used by default: * - failure/healing detection * - bootstrap sequencer * - merge segments */ private final int detectionWorkersCount = 3; RemoteMonitoringService(@NonNull ServerContext serverContext, @NonNull SingletonResource<CorfuRuntime> runtimeSingletonResource, @NonNull ClusterStateContext clusterContext, @NonNull FailureDetector failureDetector, @NonNull LocalMonitoringService localMonitoringService) { this.serverContext = serverContext; this.runtimeSingletonResource = runtimeSingletonResource; this.clusterContext = clusterContext; this.failureDetector = failureDetector; this.localMonitoringService = localMonitoringService; ClusterAdvisor advisor = ClusterAdvisorFactory.createForStrategy( ClusterType.COMPLETE_GRAPH ); this.detectionTasksScheduler = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(serverContext.getThreadPrefix() + "RemoteMonitoringService") .build()); // Creating the detection worker thread pool. // This thread pool is utilized to dispatch detection tasks at regular intervals in the // detectorTaskScheduler. ThreadFactory fdThreadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(serverContext.getThreadPrefix() + "DetectionWorker-%d") .build(); this.failureDetectorWorker = Executors.newFixedThreadPool(detectionWorkersCount, fdThreadFactory); FailureDetectorDataStore fdDataStore = FailureDetectorDataStore.builder() .localEndpoint(serverContext.getLocalEndpoint()) .dataStore(serverContext.getDataStore()) .build(); FileSystemAdvisor fsAdvisor = new FileSystemAdvisor(); EpochHandler epochHandler = EpochHandler.builder() .runtimeSingletonResource(runtimeSingletonResource) .serverContext(serverContext) .failureDetectorWorker(failureDetectorWorker) .build(); HealingAgent healingAgent = HealingAgent.builder() .advisor(advisor) .fsAdvisor(fsAdvisor) .runtimeSingleton(runtimeSingletonResource) .failureDetectorWorker(failureDetectorWorker) .dataStore(fdDataStore) .build(); FailuresAgent failuresAgent = FailuresAgent.builder() .fdDataStore(fdDataStore) .advisor(advisor) .fsAdvisor(fsAdvisor) .runtimeSingleton(runtimeSingletonResource) .build(); SequencerBootstrapper sequencerBootstrapper = SequencerBootstrapper.builder() .runtimeSingletonResource(runtimeSingletonResource) .clusterContext(clusterContext) .failureDetectorWorker(failureDetectorWorker) .build(); this.fdService = FailureDetectorService.builder() .epochHandler(epochHandler) .failuresAgent(failuresAgent) .healingAgent(healingAgent) .sequencerBootstrapper(sequencerBootstrapper) .failureDetectorWorker(failureDetectorWorker) .build(); } private CorfuRuntime getCorfuRuntime() { return runtimeSingletonResource.get(); } /** * Executes task to run failure and healing detection every poll interval. (Default: 1 sec) * <p> * During the initialization step, the method: * - triggers sequencer bootstrap * - starts failure and healing detection mechanism, by running <code>runDetectionTasks</code> * every second (by default). Next iteration of detection task can be run only if current iteration is completed. */ @Override public void start(Duration monitoringInterval) { // Trigger sequencer bootstrap on startup. sequencerBootstrap(serverContext); Runnable task = () -> { if (!failureDetectorFuture.isDone()) { return; } failureDetectorFuture = runDetectionTasks(); }; detectionTasksScheduler.scheduleAtFixedRate( () -> LambdaUtils.runSansThrow(task), 0, monitoringInterval.toMillis(), TimeUnit.MILLISECONDS ); HealthMonitor.resolveIssue(Issue.createInitIssue(Component.FAILURE_DETECTOR)); } /** * Trigger sequencer bootstrap mechanism. Get current layout management view and execute async bootstrap * * @param serverContext server context */ private CompletableFuture<DetectorTask> sequencerBootstrap(ServerContext serverContext) { log.info("Trigger sequencer bootstrap on startup"); return getCorfuRuntime() .getLayoutManagementView() .asyncSequencerBootstrap(serverContext.copyManagementLayout(), failureDetectorWorker) .thenApply(DetectorTask::fromBool); } /** * Schedules the failure detection and handling mechanism by detectorTaskScheduler. * It schedules exactly one instance of the following tasks. * - Failure detection tasks. * - Healing detection tasks. * * <pre> * The algorithm: * - wait until previous iteration finishes * - On every invocation, this task refreshes the runtime to fetch the latest layout and also updates * the local persisted copy of the latest layout. * - get corfu metrics (Sequencer, LogUnit etc). * - executes the poll using the failureDetector which generates a pollReport at the end of the round. * The report contains latest information about cluster: connectivity graph, failed and healed nodes, wrong epochs. * - refresh cluster state context by latest {@link ClusterState} collected on poll report step. * - run failure detector task composed from: * - the outOfPhase epoch server errors are corrected by resealing and patching these trailing layout servers. * - all unresponsive server failures are handled by either removing or marking * them as unresponsive based on a failure handling policy. * - make healed node responsive based on a healing detection mechanism * </pre> */ private synchronized CompletableFuture<DetectorTask> runDetectionTasks() { String localEndpoint = serverContext.getLocalEndpoint(); return getCorfuRuntime() .invalidateLayout() .thenApply(serverContext::saveManagementLayout) //check if this node can handle failures (if the node is in the cluster) .thenCompose(ourLayout -> { FailureDetectorHelper helper = new FailureDetectorHelper(ourLayout, localEndpoint); return helper.handleReconfigurationsAsync(); }) .thenCompose(ourLayout -> { //Get metrics from local monitoring service (local monitoring works in it's own thread) return localMonitoringService.getMetrics() //Poll report asynchronously using failureDetectorWorker executor .thenCompose(metrics -> pollReport(ourLayout, metrics)) //Update cluster view by latest cluster state given by the poll report. No need to be asynchronous .thenApply(pollReport -> { log.trace("Update cluster view: {}", pollReport.getClusterState()); clusterContext.refreshClusterView(ourLayout, pollReport); return pollReport; }) .thenApply(pollReport -> { if (!pollReport.getClusterState().isReady()) { throw FailureDetectorException.notReady(pollReport.getClusterState()); } return pollReport; }) //Execute failure detector task using failureDetectorWorker executor .thenCompose(pollReport -> fdService.runFailureDetectorTask(pollReport, ourLayout, localEndpoint)); }).thenApply(task -> { Issue issue = Issue.createIssue(Component.FAILURE_DETECTOR, SOME_NODES_ARE_UNRESPONSIVE, "There are nodes in the unresponsive list"); final Layout layout = serverContext.getCurrentLayout(); if (layout.getUnresponsiveServers().isEmpty()) { HealthMonitor.resolveIssue(issue); } else { HealthMonitor.reportIssue(issue); } return task; }) //Print exceptions to log .whenComplete((taskResult, ex) -> { if (ex != null) { log.error("Failure detection task finished with an error", ex); } if (ex != null || taskResult == DetectorTask.NOT_COMPLETED) { log.trace("Reporting issue"); HealthMonitor.reportIssue(new Issue(Component.FAILURE_DETECTOR, Issue.IssueId.FAILURE_DETECTOR_TASK_FAILED, "Last failure detector task was not completed")); } else { log.trace("Resolving issue"); HealthMonitor.resolveIssue(new Issue(Component.FAILURE_DETECTOR, Issue.IssueId.FAILURE_DETECTOR_TASK_FAILED, "Last failure detector task succeeded")); } }); } private CompletableFuture<PollReport> pollReport(Layout layout, SequencerMetrics sequencerMetrics) { return CompletableFuture.supplyAsync(() -> { PartitionAttribute partition = FileSystemAgent.getPartitionAttribute(); PartitionAttributeStats partitionAttributeStats = new PartitionAttributeStats( partition.isReadOnly(), partition.getAvailableSpace(), partition.getTotalSpace() ); BatchProcessorStats bpStats = new BatchProcessorStats(partition.getBatchProcessorStatus()); FileSystemStats fsStats = new FileSystemStats(partitionAttributeStats, bpStats); CorfuRuntime corfuRuntime = getCorfuRuntime(); return failureDetector.poll(layout, corfuRuntime, sequencerMetrics, fsStats); }, failureDetectorWorker); } @Override public void shutdown() { // Shutting the fault detector. detectionTasksScheduler.shutdownNow(); failureDetectorWorker.shutdownNow(); log.info("Fault detection service shutting down."); HealthMonitor.reportIssue(Issue.createInitIssue(Component.FAILURE_DETECTOR)); } public enum DetectorTask { /** * The task is completed successfully */ COMPLETED, /** * The task is completed with an exception */ NOT_COMPLETED, /** * Skipped task */ SKIPPED; public static DetectorTask fromBool(boolean taskResult) { return taskResult ? COMPLETED : NOT_COMPLETED; } } }
16,239
0.662787
0.662048
351
45.264957
32.363338
128
false
false
0
0
0
0
0
0
0.433048
false
false
0
f4fd75d34d5f51c29c8811042531f3d6d70914df
17,669,495,470,054
c90609e87815f83e570bc7c81e1532c8a8934991
/src/test/java/com/rcloud/server/sealtalk/util/ClassA.java
4cba8eee9835d5ef9caf567e67b5143a3b0409ed
[]
no_license
davidyangss/sealtalk-server-java
https://github.com/davidyangss/sealtalk-server-java
ef00b8ccaadb5482a5a7d70fa615f0171eeb84ff
a51b5146b1fc0f8c066edae49c38ef372d9432c6
refs/heads/master
2023-06-28T23:13:28.421000
2021-07-30T09:24:38
2021-07-30T09:24:38
328,527,393
0
1
null
true
2021-03-11T08:07:09
2021-01-11T02:27:40
2021-02-05T04:39:25
2021-03-11T08:07:08
1,454
0
1
0
Java
false
false
package com.rcloud.server.sealtalk.util; /** * @Author: Jianlu.Yu * @Date: 2020/8/22 * @Description: * @Copyright (c) 2020, rongcloud.cn All Rights Reserved */ public class ClassA { private String[] region; private String phone; private String password; public String[] getRegion() { return region; } public void setRegion(String[] region) { this.region = region; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
UTF-8
Java
711
java
ClassA.java
Java
[ { "context": " com.rcloud.server.sealtalk.util;\n\n/**\n * @Author: Jianlu.Yu\n * @Date: 2020/8/22\n * @Description:\n * @Copyrigh", "end": 67, "score": 0.9998167753219604, "start": 58, "tag": "NAME", "value": "Jianlu.Yu" } ]
null
[]
package com.rcloud.server.sealtalk.util; /** * @Author: Jianlu.Yu * @Date: 2020/8/22 * @Description: * @Copyright (c) 2020, rongcloud.cn All Rights Reserved */ public class ClassA { private String[] region; private String phone; private String password; public String[] getRegion() { return region; } public void setRegion(String[] region) { this.region = region; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
711
0.609001
0.59353
38
17.710526
15.867723
56
false
false
0
0
0
0
0
0
0.289474
false
false
0
350a63c0375f458fa52f27edf22697990d3d4484
28,965,259,481,110
687f35426d7443a2107c9486e65f7dc3e252d037
/ylineboye/Boyelicai/src/yc/com/by/fragment/Fragment1_1.java
c62e25ae00cdbc0122600a6f9ce33306a57e5475
[]
no_license
yline/windowmanager
https://github.com/yline/windowmanager
5a358934e1e5d12334bcb1367a39045afdb5d8d0
ed95b72f947526b3b2bb610d4c445b40f311d9a2
refs/heads/master
2016-09-13T06:06:15.773000
2016-09-12T23:55:29
2016-09-12T23:55:29
64,260,982
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package yc.com.by.fragment; import org.xutils.view.annotation.ContentView; import android.os.Bundle; import android.view.View; import com.by.base.BaseFragment; import com.example.boyelicai.R; @ContentView(R.layout.fragment1_1) public class Fragment1_1 extends BaseFragment { @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
UTF-8
Java
413
java
Fragment1_1.java
Java
[]
null
[]
package yc.com.by.fragment; import org.xutils.view.annotation.ContentView; import android.os.Bundle; import android.view.View; import com.by.base.BaseFragment; import com.example.boyelicai.R; @ContentView(R.layout.fragment1_1) public class Fragment1_1 extends BaseFragment { @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
413
0.794189
0.784504
18
21.944445
20.470772
66
false
false
0
0
0
0
0
0
0.833333
false
false
0
1f5a05db0e8405affa75c62947912bc95dcde5bf
3,083,786,543,148
7b1a7919b095384f9fb5cf8f545496324304cd06
/cim-common/src/main/java/com/crossoverjie/cim/common/route/algorithm/consistenthash/AbstractConsistentHash.java
73307b3612154fd6bdc1ba1caacc1daf8f78d07b
[ "MIT" ]
permissive
libofeng/cim
https://github.com/libofeng/cim
88444eb2cb52a410e23a581c5eeb84af934ce9b7
c342e0de08ef85c0fc2a10c3b8c68754c4f1507a
refs/heads/master
2022-11-23T09:39:02.537000
2020-07-24T07:52:06
2020-07-24T07:52:06
294,643,350
1
0
MIT
true
2020-09-11T08:51:38
2020-09-11T08:51:37
2020-09-11T08:45:03
2020-08-04T13:48:11
32,061
0
0
0
null
false
false
package com.crossoverjie.cim.common.route.algorithm.consistenthash; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; /** * Function:一致性 hash 算法抽象类 * * @author crossoverJie * Date: 2019-02-27 00:35 * @since JDK 1.8 */ public abstract class AbstractConsistentHash { /** * 新增节点 * @param key * @param value */ protected abstract void add(long key,String value); /** * 排序节点,数据结构自身支持排序可以不用重写 */ protected void sort(){} /** * 根据当前的 key 通过一致性 hash 算法的规则取出一个节点 * @param value * @return */ protected abstract String getFirstNodeValue(String value); /** * 传入节点列表以及客户端信息获取一个服务节点 * @param values * @param key * @return */ public String process(List<String> values,String key){ for (String value : values) { add(hash(value), value); } sort(); return getFirstNodeValue(key) ; } /** * hash 运算 * @param value * @return */ public Long hash(String value){ MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported", e); } md5.reset(); byte[] keyBytes = null; try { keyBytes = value.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unknown string :" + value, e); } md5.update(keyBytes); byte[] digest = md5.digest(); // hash code, Truncate to 32-bits long hashCode = ((long) (digest[3] & 0xFF) << 24) | ((long) (digest[2] & 0xFF) << 16) | ((long) (digest[1] & 0xFF) << 8) | (digest[0] & 0xFF); long truncateHashCode = hashCode & 0xffffffffL; return truncateHashCode; } }
UTF-8
Java
2,161
java
AbstractConsistentHash.java
Java
[ { "context": "ist;\n\n/**\n * Function:一致性 hash 算法抽象类\n *\n * @author crossoverJie\n * Date: 2019-02-27 00:35\n * @since JDK 1.8\n */\np", "end": 278, "score": 0.9924054741859436, "start": 266, "tag": "USERNAME", "value": "crossoverJie" } ]
null
[]
package com.crossoverjie.cim.common.route.algorithm.consistenthash; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.List; /** * Function:一致性 hash 算法抽象类 * * @author crossoverJie * Date: 2019-02-27 00:35 * @since JDK 1.8 */ public abstract class AbstractConsistentHash { /** * 新增节点 * @param key * @param value */ protected abstract void add(long key,String value); /** * 排序节点,数据结构自身支持排序可以不用重写 */ protected void sort(){} /** * 根据当前的 key 通过一致性 hash 算法的规则取出一个节点 * @param value * @return */ protected abstract String getFirstNodeValue(String value); /** * 传入节点列表以及客户端信息获取一个服务节点 * @param values * @param key * @return */ public String process(List<String> values,String key){ for (String value : values) { add(hash(value), value); } sort(); return getFirstNodeValue(key) ; } /** * hash 运算 * @param value * @return */ public Long hash(String value){ MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not supported", e); } md5.reset(); byte[] keyBytes = null; try { keyBytes = value.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Unknown string :" + value, e); } md5.update(keyBytes); byte[] digest = md5.digest(); // hash code, Truncate to 32-bits long hashCode = ((long) (digest[3] & 0xFF) << 24) | ((long) (digest[2] & 0xFF) << 16) | ((long) (digest[1] & 0xFF) << 8) | (digest[0] & 0xFF); long truncateHashCode = hashCode & 0xffffffffL; return truncateHashCode; } }
2,161
0.566517
0.547583
84
22.892857
19.594107
70
false
false
0
0
0
0
0
0
0.369048
false
false
0
d88020aff7a5184e0021738ca61169a042c090c3
27,513,560,548,640
e130cdc4dc2c16f40f989536adc0d002ab5bf71a
/src/main/java/com/ipplus360/service/impl/AlipayServiceImpl.java
dea0a981736ff200105f3df0e5803671745d454a
[]
no_license
mayanxi/testgit
https://github.com/mayanxi/testgit
281087dcde7eb46ce5a1ff3c945f560208a1ddc8
88c5d65acff74010d3d22f17443d35873722ef5c
refs/heads/master
2020-03-18T11:26:40.561000
2018-05-24T06:58:11
2018-05-24T06:58:24
134,671,805
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ipplus360.service.impl; import com.ipplus360.entity.*; import com.ipplus360.exception.AliPayException; import com.ipplus360.exception.OrderException; import com.ipplus360.pay.config.AlipayConfig; import com.ipplus360.pay.util.AlipaySubmit; import com.ipplus360.service.*; import com.ipplus360.service.mail.MailService; import com.ipplus360.util.DateUtil; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.Date; import java.util.Map; @Service public class AlipayServiceImpl implements AlipayService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private MailService mailService; @Autowired private OrderService orderService; @Autowired private UserService userService; @Autowired private FileOrderService fileOrderService; @Autowired private TokenService tokenService; @Autowired private GeoIPVersionService versionService; @Override public String payOnline(Map payParam) { //商户订单号,商户网站订单系统中唯一订单号,必填 //把请求参数打包成数组 payParam.put("service", AlipayConfig.service); payParam.put("partner", AlipayConfig.partner); payParam.put("seller_id", AlipayConfig.seller_id); payParam.put("_input_charset", AlipayConfig.input_charset); payParam.put("payment_type", AlipayConfig.payment_type); payParam.put("notify_url", AlipayConfig.notify_url); payParam.put("return_url", AlipayConfig.return_url); payParam.put("anti_phishing_key", AlipayConfig.anti_phishing_key); payParam.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip); //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1 //如sParaTemp.put("参数名","参数值"); //建立请求 String payHtmlText = AlipaySubmit.buildRequest(payParam,"post","确认"); return payHtmlText; } @Override public void sendOrderEmail(Map payResult) { LOGGER.info("out_trade_no:" + (String) payResult.get("out_trade_no")); Order orderby=orderService.getOrderByOrderSerial((String) payResult.get("out_trade_no")); LOGGER.info("orderby:" + orderby); LOGGER.info("orderby.getId:" + orderby.getId()); LOGGER.info("orderby.getUserId:" + orderby.getUserId()); Order order=orderService.getById(orderby.getId()); if (null == order) { order = orderService.getById1(orderby.getId()); } LOGGER.info("order:" + order); User user; if (order != null) { user = userService.getById(order.getUserId()); } else { user = userService.getById(orderby.getUserId()); } LOGGER.info("order getUserId:" + orderby.getUserId()); String email = user.getEmail(); if (StringUtils.isEmpty(email)) { throw new AliPayException("用户邮箱不能为空"); } if (!email.matches(User.EMAIL_PATTERN)) { throw new AliPayException("用户邮箱格式不正确"); } try { //发送邮箱验证码 mailService.sendOrderEmail(email, "埃文商城发货通知", order , user , payResult ); } catch (MailException e) { LOGGER.error("订单邮件发送失败", (String) payResult.get("out_trade_no")); throw new AliPayException("订单邮件发送失败"); } catch (Exception e) { LOGGER.error("订单邮件发送失败", (String) payResult.get("out_trade_no")); throw new AliPayException("购买成功订单信息发送失败"); } } @Override public void processDistrictDownload(OrderItem orderItem, Long userId, String version, boolean free) throws OrderException { version = version.trim(); String attrs = orderItem.getAttrs(); LOGGER.info("processDistrictDownload 22222222222222222222222"); String attrIds = orderItem.getAttrIds(); LOGGER.info("processDistrictDownload version:" + version); FileOrder fileOrder = new FileOrder(); if (attrs != null) { // 1. 取出用户已购数据 FileOrder userFileOrder = fileOrderService.getByAttrIdsAndVersion(userId, attrIds, version); if (null != userFileOrder) { throw new OrderException("您已购买过这个规格的区县库"); } fileOrder.setAttrs(attrs); fileOrder.setAttrIds(attrIds); } fileOrder.setCreateTime(new Date()); fileOrder.setOrderId(orderItem.getOrderId()); fileOrder.setUserId(userId); fileOrder.setDownloadCounts(0); fileOrder.setExpireTime(null); fileOrder.setFree(free); fileOrder.setVersion(version); LOGGER.info("processDistrictDownload fileOrder:" + fileOrder); fileOrderService.processAdd(fileOrder); } @Override public String processDistrictAPI(OrderItem orderItem, Long userId) { String deliveryToken = null; PricePackage districtPackage = orderItem.getPricePackage(); if (districtPackage.getType() == 1) { Long dailyLimit = districtPackage.getAmount(); LOGGER.info("no free dailyLimit:" + dailyLimit); // 购买年限 int yearCount = orderItem.getItemNum(); deliveryToken = addDistrictToken(userId, dailyLimit, yearCount); /*UserToken userToken = tokenService.getDistrictAPIByUser(userId, 5L); if (null == userToken) { LOGGER.info("null token {}" + dailyLimit); deliveryToken = addDistrictToken(userId, dailyLimit); } else { LOGGER.info("not null token {}" + dailyLimit); deliveryToken = updateDistrictToken(userToken, dailyLimit); }*/ } return deliveryToken; } @Override public String processFreeDistrictAPI(OrderItem orderItem, Long userId) { return addFreeDistrictToken(userId); } @Override public String processSceneAPI(OrderItem orderItem, Long userId) { String deliveryToken = null; PricePackage scenePackage = orderItem.getPricePackage(); LOGGER.info("scenePackage:" + scenePackage); if (scenePackage.getType() == 1) { Long packageAmount = scenePackage.getAmount(); LOGGER.info("packageAmount:" + packageAmount); int itemNum = orderItem.getItemNum(); Long count = packageAmount * itemNum; UserToken userToken = tokenService.getByUserAndProduct(userId, 3L); if (null == userToken) { LOGGER.info("1111111111111111111111111111111111"); deliveryToken = addSceneToken(userId, count); } else { LOGGER.info("22222222222222222222222222222222222"); deliveryToken = updateSceneToken(userToken, count); } } return deliveryToken; } /** * 更新区县库token * @param userToken * @param dailyLimit * @return */ private String updateDistrictToken(UserToken userToken, Long dailyLimit) { LOGGER.info("updateDistrictToken dailyLimit: " + dailyLimit.intValue()); userToken.setDailyLimit(dailyLimit.intValue()); tokenService.update(userToken); return userToken.getToken(); } /** * 添加区县库token * @param userId * @param dailyLimit * @param yearCount * @return */ private String addDistrictToken(Long userId, Long dailyLimit, int yearCount) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); Date now = new Date(); userToken.setCreatedDate(now); userToken.setEffectiveDate(now); userToken.setExpireDate(DateUtil.localDateTime2Date(DateUtil.getNextXYear(now, yearCount))); LOGGER.info("addDistrictToken dailyLimit:" + dailyLimit.intValue()); userToken.setDailyLimit(dailyLimit.intValue()); userToken.setProductId(5L); userToken.setTest(false); userToken.setTestCount(0L); userToken.setCounts(0L); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); return token; } /** * 添加免费区县TOKEN * @param userId * @return */ private String addFreeDistrictToken(Long userId) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); Date now = new Date(); userToken.setCreatedDate(now); userToken.setEffectiveDate(now); userToken.setExpireDate(DateUtil.localDateTime2Date(DateUtil.getNextYearTime(now))); userToken.setDailyLimit(1000); userToken.setProductId(5L); userToken.setTest(true); userToken.setTestCount(0L); userToken.setCounts(5000L); LOGGER.info("free userToken:" + userToken); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); User user = userService.getById(userId); user.setHasFreeDistrictApi(true); userService.updateFreeDistrictApi(userId); return token; } /** * 更新场景token * @param userToken * @param packageAmount */ private String updateSceneToken(UserToken userToken, Long packageAmount) { Long counts = userToken.getSceneCounts(); LOGGER.info("counts:" + counts); userToken.setSceneCounts(counts + packageAmount); LOGGER.info("userToken.getSceneCounts:" + userToken.getSceneCounts()); tokenService.update(userToken); return userToken.getToken(); } /** * 添加場景token,用户没有购买过场景 * @param userId * @param packageAmount */ private String addSceneToken(Long userId, Long packageAmount) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); userToken.setCreatedDate(new Date()); userToken.setEffectiveDate(new Date()); userToken.setSceneCounts(packageAmount); userToken.setCounts(0L); userToken.setDailyLimit(0); userToken.setProductId(3L); userToken.setTest(false); userToken.setTestCount(0L); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); return token; } }
UTF-8
Java
10,003
java
AlipayServiceImpl.java
Java
[]
null
[]
package com.ipplus360.service.impl; import com.ipplus360.entity.*; import com.ipplus360.exception.AliPayException; import com.ipplus360.exception.OrderException; import com.ipplus360.pay.config.AlipayConfig; import com.ipplus360.pay.util.AlipaySubmit; import com.ipplus360.service.*; import com.ipplus360.service.mail.MailService; import com.ipplus360.util.DateUtil; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import java.util.Date; import java.util.Map; @Service public class AlipayServiceImpl implements AlipayService { private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private MailService mailService; @Autowired private OrderService orderService; @Autowired private UserService userService; @Autowired private FileOrderService fileOrderService; @Autowired private TokenService tokenService; @Autowired private GeoIPVersionService versionService; @Override public String payOnline(Map payParam) { //商户订单号,商户网站订单系统中唯一订单号,必填 //把请求参数打包成数组 payParam.put("service", AlipayConfig.service); payParam.put("partner", AlipayConfig.partner); payParam.put("seller_id", AlipayConfig.seller_id); payParam.put("_input_charset", AlipayConfig.input_charset); payParam.put("payment_type", AlipayConfig.payment_type); payParam.put("notify_url", AlipayConfig.notify_url); payParam.put("return_url", AlipayConfig.return_url); payParam.put("anti_phishing_key", AlipayConfig.anti_phishing_key); payParam.put("exter_invoke_ip", AlipayConfig.exter_invoke_ip); //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.O9yorI&treeId=62&articleId=103740&docType=1 //如sParaTemp.put("参数名","参数值"); //建立请求 String payHtmlText = AlipaySubmit.buildRequest(payParam,"post","确认"); return payHtmlText; } @Override public void sendOrderEmail(Map payResult) { LOGGER.info("out_trade_no:" + (String) payResult.get("out_trade_no")); Order orderby=orderService.getOrderByOrderSerial((String) payResult.get("out_trade_no")); LOGGER.info("orderby:" + orderby); LOGGER.info("orderby.getId:" + orderby.getId()); LOGGER.info("orderby.getUserId:" + orderby.getUserId()); Order order=orderService.getById(orderby.getId()); if (null == order) { order = orderService.getById1(orderby.getId()); } LOGGER.info("order:" + order); User user; if (order != null) { user = userService.getById(order.getUserId()); } else { user = userService.getById(orderby.getUserId()); } LOGGER.info("order getUserId:" + orderby.getUserId()); String email = user.getEmail(); if (StringUtils.isEmpty(email)) { throw new AliPayException("用户邮箱不能为空"); } if (!email.matches(User.EMAIL_PATTERN)) { throw new AliPayException("用户邮箱格式不正确"); } try { //发送邮箱验证码 mailService.sendOrderEmail(email, "埃文商城发货通知", order , user , payResult ); } catch (MailException e) { LOGGER.error("订单邮件发送失败", (String) payResult.get("out_trade_no")); throw new AliPayException("订单邮件发送失败"); } catch (Exception e) { LOGGER.error("订单邮件发送失败", (String) payResult.get("out_trade_no")); throw new AliPayException("购买成功订单信息发送失败"); } } @Override public void processDistrictDownload(OrderItem orderItem, Long userId, String version, boolean free) throws OrderException { version = version.trim(); String attrs = orderItem.getAttrs(); LOGGER.info("processDistrictDownload 22222222222222222222222"); String attrIds = orderItem.getAttrIds(); LOGGER.info("processDistrictDownload version:" + version); FileOrder fileOrder = new FileOrder(); if (attrs != null) { // 1. 取出用户已购数据 FileOrder userFileOrder = fileOrderService.getByAttrIdsAndVersion(userId, attrIds, version); if (null != userFileOrder) { throw new OrderException("您已购买过这个规格的区县库"); } fileOrder.setAttrs(attrs); fileOrder.setAttrIds(attrIds); } fileOrder.setCreateTime(new Date()); fileOrder.setOrderId(orderItem.getOrderId()); fileOrder.setUserId(userId); fileOrder.setDownloadCounts(0); fileOrder.setExpireTime(null); fileOrder.setFree(free); fileOrder.setVersion(version); LOGGER.info("processDistrictDownload fileOrder:" + fileOrder); fileOrderService.processAdd(fileOrder); } @Override public String processDistrictAPI(OrderItem orderItem, Long userId) { String deliveryToken = null; PricePackage districtPackage = orderItem.getPricePackage(); if (districtPackage.getType() == 1) { Long dailyLimit = districtPackage.getAmount(); LOGGER.info("no free dailyLimit:" + dailyLimit); // 购买年限 int yearCount = orderItem.getItemNum(); deliveryToken = addDistrictToken(userId, dailyLimit, yearCount); /*UserToken userToken = tokenService.getDistrictAPIByUser(userId, 5L); if (null == userToken) { LOGGER.info("null token {}" + dailyLimit); deliveryToken = addDistrictToken(userId, dailyLimit); } else { LOGGER.info("not null token {}" + dailyLimit); deliveryToken = updateDistrictToken(userToken, dailyLimit); }*/ } return deliveryToken; } @Override public String processFreeDistrictAPI(OrderItem orderItem, Long userId) { return addFreeDistrictToken(userId); } @Override public String processSceneAPI(OrderItem orderItem, Long userId) { String deliveryToken = null; PricePackage scenePackage = orderItem.getPricePackage(); LOGGER.info("scenePackage:" + scenePackage); if (scenePackage.getType() == 1) { Long packageAmount = scenePackage.getAmount(); LOGGER.info("packageAmount:" + packageAmount); int itemNum = orderItem.getItemNum(); Long count = packageAmount * itemNum; UserToken userToken = tokenService.getByUserAndProduct(userId, 3L); if (null == userToken) { LOGGER.info("1111111111111111111111111111111111"); deliveryToken = addSceneToken(userId, count); } else { LOGGER.info("22222222222222222222222222222222222"); deliveryToken = updateSceneToken(userToken, count); } } return deliveryToken; } /** * 更新区县库token * @param userToken * @param dailyLimit * @return */ private String updateDistrictToken(UserToken userToken, Long dailyLimit) { LOGGER.info("updateDistrictToken dailyLimit: " + dailyLimit.intValue()); userToken.setDailyLimit(dailyLimit.intValue()); tokenService.update(userToken); return userToken.getToken(); } /** * 添加区县库token * @param userId * @param dailyLimit * @param yearCount * @return */ private String addDistrictToken(Long userId, Long dailyLimit, int yearCount) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); Date now = new Date(); userToken.setCreatedDate(now); userToken.setEffectiveDate(now); userToken.setExpireDate(DateUtil.localDateTime2Date(DateUtil.getNextXYear(now, yearCount))); LOGGER.info("addDistrictToken dailyLimit:" + dailyLimit.intValue()); userToken.setDailyLimit(dailyLimit.intValue()); userToken.setProductId(5L); userToken.setTest(false); userToken.setTestCount(0L); userToken.setCounts(0L); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); return token; } /** * 添加免费区县TOKEN * @param userId * @return */ private String addFreeDistrictToken(Long userId) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); Date now = new Date(); userToken.setCreatedDate(now); userToken.setEffectiveDate(now); userToken.setExpireDate(DateUtil.localDateTime2Date(DateUtil.getNextYearTime(now))); userToken.setDailyLimit(1000); userToken.setProductId(5L); userToken.setTest(true); userToken.setTestCount(0L); userToken.setCounts(5000L); LOGGER.info("free userToken:" + userToken); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); User user = userService.getById(userId); user.setHasFreeDistrictApi(true); userService.updateFreeDistrictApi(userId); return token; } /** * 更新场景token * @param userToken * @param packageAmount */ private String updateSceneToken(UserToken userToken, Long packageAmount) { Long counts = userToken.getSceneCounts(); LOGGER.info("counts:" + counts); userToken.setSceneCounts(counts + packageAmount); LOGGER.info("userToken.getSceneCounts:" + userToken.getSceneCounts()); tokenService.update(userToken); return userToken.getToken(); } /** * 添加場景token,用户没有购买过场景 * @param userId * @param packageAmount */ private String addSceneToken(Long userId, Long packageAmount) { String token = RandomStringUtils.randomAlphanumeric(64); UserToken userToken = new UserToken(); userToken.setToken(token); userToken.setUserId(userId); userToken.setCreatedDate(new Date()); userToken.setEffectiveDate(new Date()); userToken.setSceneCounts(packageAmount); userToken.setCounts(0L); userToken.setDailyLimit(0); userToken.setProductId(3L); userToken.setTest(false); userToken.setTestCount(0L); userToken.setAvailable(true); userToken.setNotified(false); tokenService.add(userToken); return token; } }
10,003
0.73343
0.715014
307
30.306189
24.264772
138
false
false
0
0
0
0
0
0
2.110749
false
false
0
84f4cb6415eaf8de2824e47e972cb560c1c8b158
28,398,323,829,894
c792d95eb7ac442aa93a34596655104d52567170
/src/main/java/com/btl/hecsdlpt/imageSearch/analysis/SummedAreaTable.java
fcd0ba55c9e072dcdb7ba7d9a6934dc14efd34fc
[]
no_license
ducanhkl/hecsdldpt
https://github.com/ducanhkl/hecsdldpt
7707cc00d7d703c35e9c44450c45513a6d6893eb
bb0fb19f6bf691094495462193ea4f0c7a49aa39
refs/heads/main
2023-06-04T12:54:05.780000
2021-06-22T06:30:03
2021-06-22T06:30:03
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.btl.hecsdlpt.imageSearch.analysis; import com.btl.hecsdlpt.imageSearch.core.GrayImage; public class SummedAreaTable { public GrayImage data; public SummedAreaTable(GrayImage image) { computeTable(image); } public float calculateArea(int x1, int y1, int x2, int y2) { final float A = data.pixels[y1][x1]; final float B = data.pixels[y1][x2]; final float C = data.pixels[y2][x2]; final float D = data.pixels[y2][x1]; return A + C - B - D; // công thức tính tổng cộng dồn cho khoảng (x1, y1) đến (x2, y2) // Nó giống với việc để tính từ x->y thì tính tổng từ 1->y trừ đi tổng từ 1->x-1 // ở đây các tọa độ không phải -1 vì ở bước tính tổng cộng dồn đã // thực hiện + 1 trước rồi } public void computeTable(GrayImage image) { data = new GrayImage(image.width + 1, image.height + 1); for (int y = 0; y < image.height; y++) { for (int x = 0; x < image.width; x++) { // +1 thì ở bước tính tổng cộng dồn sẽ không phải -1 nữa. data.pixels[y + 1][x + 1] = image.pixels[y][x] + data.pixels[y + 1][x] + data.pixels[y][x + 1] - data.pixels[y][x]; } } // mảng data là mảng cộng dồn. } }
UTF-8
Java
1,425
java
SummedAreaTable.java
Java
[]
null
[]
package com.btl.hecsdlpt.imageSearch.analysis; import com.btl.hecsdlpt.imageSearch.core.GrayImage; public class SummedAreaTable { public GrayImage data; public SummedAreaTable(GrayImage image) { computeTable(image); } public float calculateArea(int x1, int y1, int x2, int y2) { final float A = data.pixels[y1][x1]; final float B = data.pixels[y1][x2]; final float C = data.pixels[y2][x2]; final float D = data.pixels[y2][x1]; return A + C - B - D; // công thức tính tổng cộng dồn cho khoảng (x1, y1) đến (x2, y2) // Nó giống với việc để tính từ x->y thì tính tổng từ 1->y trừ đi tổng từ 1->x-1 // ở đây các tọa độ không phải -1 vì ở bước tính tổng cộng dồn đã // thực hiện + 1 trước rồi } public void computeTable(GrayImage image) { data = new GrayImage(image.width + 1, image.height + 1); for (int y = 0; y < image.height; y++) { for (int x = 0; x < image.width; x++) { // +1 thì ở bước tính tổng cộng dồn sẽ không phải -1 nữa. data.pixels[y + 1][x + 1] = image.pixels[y][x] + data.pixels[y + 1][x] + data.pixels[y][x + 1] - data.pixels[y][x]; } } // mảng data là mảng cộng dồn. } }
1,425
0.557663
0.534143
40
31.950001
28.006205
91
false
false
0
0
0
0
0
0
0.525
false
false
0
708f7223eebe73551faaf630206c29db1d4d54ba
9,191,230,028,572
ff589cd56e78993acb4fa45eebb8b985049a3ba6
/src/main/java/expedia/home.java
c99aa5f364b848232f1069b68dd735532bada4c5
[]
no_license
fabniki/expedia
https://github.com/fabniki/expedia
53001c0fc1b240801223293a0280763fc6243e11
3faf00eb877f07c43f509b04fc48a7083557d161
refs/heads/master
2023-02-05T14:57:28.091000
2020-12-26T01:08:31
2020-12-26T01:08:31
323,115,922
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package expedia; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class home { @FindBy(xpath = "//span[contains(text(),'Flights')]") WebElement flights; @FindBy(id="location-field-leg1-origin") WebElement leaving; @FindBy(className="uitk-faux-input") WebElement going; @FindBy(id="d1-btn") WebElement Departing; }
UTF-8
Java
370
java
home.java
Java
[]
null
[]
package expedia; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class home { @FindBy(xpath = "//span[contains(text(),'Flights')]") WebElement flights; @FindBy(id="location-field-leg1-origin") WebElement leaving; @FindBy(className="uitk-faux-input") WebElement going; @FindBy(id="d1-btn") WebElement Departing; }
370
0.735135
0.72973
19
18.473684
16.79401
54
false
false
0
0
0
0
0
0
0.947368
false
false
0
7a73d70d6881291e2e860242ce2e0d2fec67b948
5,875,515,328,535
f1d4992863c0576c6ef92b45966c49932a7482fc
/src/fr/eni_jpa/model/entity/Ville.java
1d00024915605610e2075296ad9e9b11acb20e52
[]
no_license
Qthr/ENI_JPA_1
https://github.com/Qthr/ENI_JPA_1
798cc32dbd091a6feaa34a5e26d6d3aca698dd83
e8a95c469f72ba259facf373b3a1e2c8c75ce5d2
refs/heads/master
2021-09-11T12:46:16.957000
2018-04-07T08:55:18
2018-04-07T08:55:18
121,544,234
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 fr.eni_jpa.model.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author Quentin Therre <quentin.therre@novarea-tec.com> */ @Entity @Table(name = "ville") public class Ville implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @Column(name = "capital") private boolean capital; @Basic @Column(name = "code_postal") private String codePostal; @Basic(optional = false) @Column(name = "nom") private String nom; @ManyToOne(optional = false) @JoinColumn(name = "pays", referencedColumnName = "id") private Pays pays; @OneToMany(mappedBy = "ville", cascade = CascadeType.ALL) private List<Adresse> adresseList = new ArrayList<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public boolean isCapital() { return capital; } public void setCapital(boolean capital) { this.capital = capital; } public String getCodePostal() { return codePostal; } public void setCodePostal(String codePostal) { this.codePostal = codePostal; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Pays getPays() { return pays; } public void setPays(Pays pays) { this.pays = pays; } public List<Adresse> getAdresseList() { return adresseList; } public void setAdresseList(List<Adresse> adresseList) { this.adresseList = adresseList; } public void addAdresse(Adresse adr){ this.getAdresseList().add(adr); adr.setVille(this); } public void removeAdresse(Adresse adr){ adr.setVille(null); this.getAdresseList().remove(adr); } public void removePersonneAdresses(){ for(Adresse adr : new ArrayList<>(this.adresseList)){ this.removeAdresse(adr); } } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Ville)) { return false; } Ville other = (Ville) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "fr.eni_jpa.model.entity.Ville[ id=" + id + " ]"; } }
UTF-8
Java
3,700
java
Ville.java
Java
[ { "context": "rt javax.persistence.Table;\r\n\r\n/**\r\n *\r\n * @author Quentin Therre <quentin.therre@novarea-tec.com>\r\n */\r\n@Entity\r\n@", "end": 744, "score": 0.9998847842216492, "start": 730, "tag": "NAME", "value": "Quentin Therre" }, { "context": "nce.Table;\r\n\r\n/**\r\n *\r\n * @author Quentin Therre <quentin.therre@novarea-tec.com>\r\n */\r\n@Entity\r\n@Table(name = \"ville\")\r\npublic cl", "end": 776, "score": 0.9999229311943054, "start": 746, "tag": "EMAIL", "value": "quentin.therre@novarea-tec.com" } ]
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 fr.eni_jpa.model.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author <NAME> <<EMAIL>> */ @Entity @Table(name = "ville") public class Ville implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Basic(optional = false) @Column(name = "capital") private boolean capital; @Basic @Column(name = "code_postal") private String codePostal; @Basic(optional = false) @Column(name = "nom") private String nom; @ManyToOne(optional = false) @JoinColumn(name = "pays", referencedColumnName = "id") private Pays pays; @OneToMany(mappedBy = "ville", cascade = CascadeType.ALL) private List<Adresse> adresseList = new ArrayList<>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public boolean isCapital() { return capital; } public void setCapital(boolean capital) { this.capital = capital; } public String getCodePostal() { return codePostal; } public void setCodePostal(String codePostal) { this.codePostal = codePostal; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public Pays getPays() { return pays; } public void setPays(Pays pays) { this.pays = pays; } public List<Adresse> getAdresseList() { return adresseList; } public void setAdresseList(List<Adresse> adresseList) { this.adresseList = adresseList; } public void addAdresse(Adresse adr){ this.getAdresseList().add(adr); adr.setVille(this); } public void removeAdresse(Adresse adr){ adr.setVille(null); this.getAdresseList().remove(adr); } public void removePersonneAdresses(){ for(Adresse adr : new ArrayList<>(this.adresseList)){ this.removeAdresse(adr); } } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Ville)) { return false; } Ville other = (Ville) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "fr.eni_jpa.model.entity.Ville[ id=" + id + " ]"; } }
3,669
0.591892
0.591081
151
22.503311
19.867399
102
false
false
0
0
0
0
0
0
0.357616
false
false
0
ae1a12e4b3c37d3922c91ef8391ba6c62888fa1f
23,716,809,476,874
86f4c6e9091860f038ec3f9686afac8e1df306ac
/astli/src/main/java/astli/postprocess/PlateauFilterProcessor.java
f26d27fc7568bfb5e9189d25b9491bde187768c5
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
kstudent/astli
https://github.com/kstudent/astli
6d758255df6be9ed192fd965df5d75e6a5c3e9e5
d764ef3289a2b882e828eaffb98084ac94a052c6
refs/heads/master
2020-06-04T06:41:30.830000
2019-06-14T08:43:13
2019-06-14T08:43:13
191,907,682
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package astli.postprocess; import java.util.ArrayList; import java.util.List; import astli.pojo.Match; import static java.util.stream.Collectors.toList; /** * * @author Christof Rabensteiner <christof.rabensteiner@gmail.com> */ public class PlateauFilterProcessor implements PostProcessor { private final PostProcessor actualProcessor; public PlateauFilterProcessor(PostProcessor actualProcessor) { this.actualProcessor = actualProcessor; } @Override public void init() { actualProcessor.init(); } @Override public void process(Match result) { double max = result.getItems().stream() .mapToDouble(item -> item.getScore()) .max() .orElse(0); List<Match.Item> plateau; if(max > 0) { plateau = result.getItems().stream() .filter(item -> item.getScore() == max) .collect(toList()); } else { plateau = new ArrayList<>(); } Match filteredResult = new Match(plateau, result.getApkH()); actualProcessor.process(filteredResult); } @Override public void done(int totalPackages, int keptPackages) { actualProcessor.done(totalPackages, keptPackages); } }
UTF-8
Java
1,337
java
PlateauFilterProcessor.java
Java
[ { "context": ".util.stream.Collectors.toList;\n\n/**\n *\n * @author Christof Rabensteiner <christof.rabensteiner@gmail.com>\n */\npublic clas", "end": 194, "score": 0.9999035000801086, "start": 173, "tag": "NAME", "value": "Christof Rabensteiner" }, { "context": "toList;\n\n/**\n *\n * @author Christof Rabensteiner <christof.rabensteiner@gmail.com>\n */\npublic class PlateauFilterProcessor implemen", "end": 227, "score": 0.9999302625656128, "start": 196, "tag": "EMAIL", "value": "christof.rabensteiner@gmail.com" } ]
null
[]
package astli.postprocess; import java.util.ArrayList; import java.util.List; import astli.pojo.Match; import static java.util.stream.Collectors.toList; /** * * @author <NAME> <<EMAIL>> */ public class PlateauFilterProcessor implements PostProcessor { private final PostProcessor actualProcessor; public PlateauFilterProcessor(PostProcessor actualProcessor) { this.actualProcessor = actualProcessor; } @Override public void init() { actualProcessor.init(); } @Override public void process(Match result) { double max = result.getItems().stream() .mapToDouble(item -> item.getScore()) .max() .orElse(0); List<Match.Item> plateau; if(max > 0) { plateau = result.getItems().stream() .filter(item -> item.getScore() == max) .collect(toList()); } else { plateau = new ArrayList<>(); } Match filteredResult = new Match(plateau, result.getApkH()); actualProcessor.process(filteredResult); } @Override public void done(int totalPackages, int keptPackages) { actualProcessor.done(totalPackages, keptPackages); } }
1,298
0.600598
0.599102
52
24.711538
21.862627
68
false
false
0
0
0
0
0
0
0.346154
false
false
0
472e4109c7fbda79459dc3edf300ebdadaf56b5b
5,566,277,678,273
c5596761823543cbcc2724019d692b23499158de
/src/test/java/applicationX/cukes/steps/GenericWebSteps.java
bd99eabf3d5eacfef88120e60ebcccf9720759c6
[]
no_license
Niemetz/MyFramework
https://github.com/Niemetz/MyFramework
1fc3ca9df3918a1998d10b5b72db0ba5b78d938c
4c4d1bd8716e2e9a8e63e7d280ce43172891f56b
refs/heads/master
2021-01-21T17:37:49.911000
2016-10-03T23:49:44
2016-10-03T23:49:44
91,970,682
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package applicationX.cukes.steps; import applicationX.projectY.cukes.web.components.impl.MultiSelectComboBox; import contractorX.projectY.cukes.core.Global; import contractorX.projectY.cukes.core.StepBase; import contractorX.projectY.cukes.web.Page; import contractorX.projectY.cukes.web.PageResolver; import contractorX.projectY.cukes.web.SessionManager; //import contractorX.projectY.cukes.web.URLResolver; import contractorX.projectY.cukes.web.URLResolver; import contractorX.projectY.cukes.web.components.Clickable; import contractorX.projectY.cukes.web.steps.StepsDefinitions; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import cucumber.api.java.en.Then; public class GenericWebSteps extends StepBase { @Global protected URLResolver urlResolver; @Global protected SessionManager sessionManager; @Global protected PageResolver pageResolver; private final int DEFAULT_WAIT_TIME_IN_SECONDS = 5; private StepsDefinitions websteps = new StepsDefinitions(); @Then("^he selects \'(.*)\' from the multi combo box \'(.*)\' $") public void lastUserSelectMultiComboBox( String textToSelect, String gherkinInutName) throws Throwable { log.debug(String.format("=> last user '%s' selects '%s' from combox box '%s' ", sessionManager.lastSession().getUser(), textToSelect, gherkinInutName)); MultiSelectComboBox comboBox = (MultiSelectComboBox)sessionManager.lastSession().getLastPage().getDomeState().getComponent(gherkinInutName); comboBox.selectText(sessionManager.lastSession().getDriver(), DEFAULT_WAIT_TIME_IN_SECONDS, textToSelect); } }
UTF-8
Java
1,629
java
GenericWebSteps.java
Java
[]
null
[]
package applicationX.cukes.steps; import applicationX.projectY.cukes.web.components.impl.MultiSelectComboBox; import contractorX.projectY.cukes.core.Global; import contractorX.projectY.cukes.core.StepBase; import contractorX.projectY.cukes.web.Page; import contractorX.projectY.cukes.web.PageResolver; import contractorX.projectY.cukes.web.SessionManager; //import contractorX.projectY.cukes.web.URLResolver; import contractorX.projectY.cukes.web.URLResolver; import contractorX.projectY.cukes.web.components.Clickable; import contractorX.projectY.cukes.web.steps.StepsDefinitions; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; import cucumber.api.java.en.Then; public class GenericWebSteps extends StepBase { @Global protected URLResolver urlResolver; @Global protected SessionManager sessionManager; @Global protected PageResolver pageResolver; private final int DEFAULT_WAIT_TIME_IN_SECONDS = 5; private StepsDefinitions websteps = new StepsDefinitions(); @Then("^he selects \'(.*)\' from the multi combo box \'(.*)\' $") public void lastUserSelectMultiComboBox( String textToSelect, String gherkinInutName) throws Throwable { log.debug(String.format("=> last user '%s' selects '%s' from combox box '%s' ", sessionManager.lastSession().getUser(), textToSelect, gherkinInutName)); MultiSelectComboBox comboBox = (MultiSelectComboBox)sessionManager.lastSession().getLastPage().getDomeState().getComponent(gherkinInutName); comboBox.selectText(sessionManager.lastSession().getDriver(), DEFAULT_WAIT_TIME_IN_SECONDS, textToSelect); } }
1,629
0.783303
0.782689
39
40.76923
34.491516
145
false
false
0
0
0
0
0
0
0.871795
false
false
0
a66884d7a8ab25ae44d1abd21d8d217fde183a0a
9,174,050,199,249
d6615e2ef977f3b59998e202b79e118f041ad193
/src/main/java/org/foocorp/exercise/contactlist/model/Phone.java
5c4f35f8dcf6a5c456f754212b9584c9562667bf
[]
no_license
sjw1066/contact-list
https://github.com/sjw1066/contact-list
07db09d1b6e18e9c40b33cf5e14f5908de018517
ed285416587401f2735d934afd4f68d6cbc59309
refs/heads/main
2023-04-10T11:03:32
2021-04-27T00:28:08
2021-04-27T00:28:08
361,580,262
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.foocorp.exercise.contactlist.model; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.Objects; /** * Phone entity */ @Entity @Table(name = "phones") public class Phone { @Id @GeneratedValue // let db auto generate the PK @JsonIgnore // don't render in JSON representation private Long id; @ManyToOne @JoinColumn(name = "contact_id", nullable = false) @JsonBackReference private Contact contact; @Column(name = "number") private String number; @Enumerated(EnumType.STRING) @Column(name = "type") private PhoneType type; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public PhoneType getType() { return type; } public void setType(PhoneType type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Phone phone = (Phone) o; return Objects.equals(id, phone.id) && Objects.equals(number, phone.number) && type == phone.type; } @Override public int hashCode() { return Objects.hash(id, number, type); } @Override public String toString() { return "Phone{" + "id=" + id + ", number='" + number + '\'' + ", type=" + type + '}'; } }
UTF-8
Java
1,698
java
Phone.java
Java
[]
null
[]
package org.foocorp.exercise.contactlist.model; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.Objects; /** * Phone entity */ @Entity @Table(name = "phones") public class Phone { @Id @GeneratedValue // let db auto generate the PK @JsonIgnore // don't render in JSON representation private Long id; @ManyToOne @JoinColumn(name = "contact_id", nullable = false) @JsonBackReference private Contact contact; @Column(name = "number") private String number; @Enumerated(EnumType.STRING) @Column(name = "type") private PhoneType type; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public PhoneType getType() { return type; } public void setType(PhoneType type) { this.type = type; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Phone phone = (Phone) o; return Objects.equals(id, phone.id) && Objects.equals(number, phone.number) && type == phone.type; } @Override public int hashCode() { return Objects.hash(id, number, type); } @Override public String toString() { return "Phone{" + "id=" + id + ", number='" + number + '\'' + ", type=" + type + '}'; } }
1,698
0.636042
0.636042
88
18.295454
16.755705
62
false
false
0
0
0
0
0
0
0.363636
false
false
0
ae0910145cd3db74f6ac26474a0eccaf0df95805
17,300,128,323,209
38eb28df2a52e6b55f7d4ff664bd0efd23bcb23e
/server/src/main/java/families/dbservice/FamilyDBService.java
a3b40555ac5dda02824835f9cbe8f6b5247aa856
[ "GPL-1.0-or-later", "MIT" ]
permissive
jacekwalaszczyk/inteca-families
https://github.com/jacekwalaszczyk/inteca-families
aa3154fbcc2d3361d9ae4f1f2d742c2700dc9cf1
1e2e508414465dab82b06edb758753d07416ca77
refs/heads/master
2020-03-27T05:21:33.106000
2019-11-06T18:57:39
2019-11-06T18:57:39
146,013,045
0
0
MIT
false
2019-11-06T18:57:41
2018-08-24T16:09:41
2019-07-12T21:10:15
2019-11-06T18:57:41
185
0
0
0
TypeScript
false
false
package families.dbservice; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import families.dao.IFamilyDAO; import families.Family; /** * A DB service class implementing data access methods for a Family class */ @Service public class FamilyDBService implements IFamilyDBService { /** * The Family DAO methods are used in this service for a DB access implementation */ @Autowired private IFamilyDAO familyDAO; /** * Returns a list with Family objects containing all Family entities stored in DB */ @Override public List<Family> getAllFamilies() { return familyDAO.getAllFamilies(); }; /** * Returns a Family object containing a Family's data stored in DB with a given id */ @Override public Family getFamilyById(int familyId) { return familyDAO.getFamilyById(familyId); }; /** * Stores in DB the data from a given Family object. * Returns a Family object containing the id value assigned by DB */ @Override public Family addFamily(Family family) { if (familyDAO.familyExists(family.getId())) {return null;}; return familyDAO.addFamily(family); }; }
UTF-8
Java
1,200
java
FamilyDBService.java
Java
[]
null
[]
package families.dbservice; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import families.dao.IFamilyDAO; import families.Family; /** * A DB service class implementing data access methods for a Family class */ @Service public class FamilyDBService implements IFamilyDBService { /** * The Family DAO methods are used in this service for a DB access implementation */ @Autowired private IFamilyDAO familyDAO; /** * Returns a list with Family objects containing all Family entities stored in DB */ @Override public List<Family> getAllFamilies() { return familyDAO.getAllFamilies(); }; /** * Returns a Family object containing a Family's data stored in DB with a given id */ @Override public Family getFamilyById(int familyId) { return familyDAO.getFamilyById(familyId); }; /** * Stores in DB the data from a given Family object. * Returns a Family object containing the id value assigned by DB */ @Override public Family addFamily(Family family) { if (familyDAO.familyExists(family.getId())) {return null;}; return familyDAO.addFamily(family); }; }
1,200
0.738333
0.738333
48
24
26.444124
83
false
false
0
0
0
0
0
0
0.916667
false
false
0
d1def5e77c186d7806b1aec202ed6a59de0342a6
8,203,387,544,547
21bcd1da03415fec0a4f3fa7287f250df1d14051
/sources/com/google/android/gms/internal/location/C4643j.java
b4e7efe19e839da93d00f56be7b63452c8141f5d
[]
no_license
lestseeandtest/Delivery
https://github.com/lestseeandtest/Delivery
9a5cc96bd6bd2316a535271ec9ca3865080c3ec8
bc3fae8f30804a2520e6699df92c2e6a4a0a7cfc
refs/heads/master
2022-04-24T12:14:22.396000
2020-04-25T21:50:29
2020-04-25T21:50:29
258,875,870
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.android.gms.internal.location; import android.os.IInterface; import android.os.RemoteException; /* renamed from: com.google.android.gms.internal.location.j */ public interface C4643j extends IInterface { /* renamed from: a */ void mo18718a(zzad zzad) throws RemoteException; }
UTF-8
Java
306
java
C4643j.java
Java
[]
null
[]
package com.google.android.gms.internal.location; import android.os.IInterface; import android.os.RemoteException; /* renamed from: com.google.android.gms.internal.location.j */ public interface C4643j extends IInterface { /* renamed from: a */ void mo18718a(zzad zzad) throws RemoteException; }
306
0.767974
0.738562
10
29.6
21.786234
62
false
false
0
0
0
0
0
0
0.4
false
false
0
bf66a98e29851b61fdb823430d8d48386c23a5f3
34,325,378,640,469
cfcd7968e8d8716d97df486209f42de5f0b06e02
/app/src/main/java/com/fil/github_client/helper/back_stack/BackStackManager.java
3479dac8d32e8adaddeea84eb5984140058e9270
[]
no_license
meltaran777/Github-Simple-Client
https://github.com/meltaran777/Github-Simple-Client
42db71580c7d68f2a164f7f2b4d5c48a0e9acfb6
25d8cd7d025d5e1565e373b90a04506372e64dca
refs/heads/master
2020-03-30T16:02:56.608000
2019-01-12T15:40:23
2019-01-12T15:40:23
151,391,009
0
0
null
false
2018-11-26T21:12:31
2018-10-03T09:43:43
2018-11-16T18:47:19
2018-11-26T21:12:30
249
1
0
0
Java
false
null
package com.fil.github_client.helper.back_stack; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import java.io.Serializable; import java.util.Deque; import java.util.LinkedList; import java.util.List; import timber.log.Timber; public class BackStackManager implements Serializable { private final String LOG_TAG = BackStackManager.class.getSimpleName(); private final LinkedList<BackStack> mBackStacks; private final BackStackListener mListener; private final BackStackFragmentManager mFragmentManager; public BackStackManager(@NonNull final BackStackListener listener, @NonNull final FragmentManager fragmentManager) { mBackStacks = new LinkedList<>(); mListener = listener; mFragmentManager = new BackStackFragmentManager(fragmentManager); } /** * When adding a new root fragment * IMPORTANT: Activity his holding the reference to the root. */ public void addRootFragment(@NonNull final Fragment fragment, final int layoutId) { if (!isAdded(fragment)) { Timber.tag(LOG_TAG).d("addRootFragment(): addRoot -> fragment = %s", fragment.getClass().getName()); setTopFragmentPlaying(false); addRoot(fragment, layoutId); setTopFragmentPlaying(true); } else if (isAdded(fragment) && isCurrent(fragment)) { refreshCurrentRoot(); Timber.tag(LOG_TAG).d("addRootFragment(): refreshCurrentRoot -> fragment = %s", fragment.getClass().getName()); Deque<String> childBackStackList = getBackStackChildFragment(fragment); if (childBackStackList != null) { childBackStackList.clear(); switchRoot(fragment); mFragmentManager.switchFragment(fragment); setTopFragmentPlaying(true); } } else { Timber.tag(LOG_TAG).d("addRootFragment(): switchRoot -> fragment = %s", fragment.getClass().getName()); setTopFragmentPlaying(false); switchRoot(fragment); mFragmentManager.switchFragment(fragment); //Show ChildFragment if exist showBackStackChildFragment(fragment); setTopFragmentPlaying(true); } } /** * When activity is calling onBackPressed */ public void onBackPressed() { final BackStack current = mBackStacks.peekLast(); if(current != null) { String uuid = current.pop(); if (uuid == null) { if (mBackStacks.size() > 1 || isChildExists()) setTopFragmentPlaying(false); removeRoot(current); } else { removeChild(current, uuid); } setTopFragmentPlaying(true); } else { Timber.tag(LOG_TAG).d("onBackPressed(): call onBackStackEmpty()"); mListener.onBackStackEmpty(); } } public boolean isChildExists() { final BackStack current = mBackStacks.peekLast(); if(current == null || current.isEmpty()) return false; else return true; } /** * Adding child fragment */ public void addChildFragment(@NonNull final Fragment fragment, final int layoutId) { Timber.tag(LOG_TAG).d("addChildFragment(): %s", fragment.getClass().getSimpleName()); setTopFragmentPlaying(false); //final String tag = UUID.randomUUID().toString(); final String tag = fragment.getClass().getName(); final BackStack backStack = mBackStacks.peekLast(); //TODO: added check null to prevent crash if(backStack != null) { backStack.push(tag); } else { Timber.tag(LOG_TAG).e("addChildFragment(): mBackStacks.peekLast() == NULL!"); } mFragmentManager.addChildFragment(fragment, layoutId, tag); } /** * Remove root */ private void removeRoot(@NonNull final BackStack backStack) { Timber.tag(LOG_TAG).d("removeRoot(): %s", backStack.mRootFragment.getClass().getSimpleName()); mBackStacks.remove(backStack); //After removing. Call close app listener if the backstack is empty if (mBackStacks.isEmpty()) { Timber.tag(LOG_TAG).d("removeRoot(): call onBackStackEmpty()"); mListener.onBackStackEmpty(); } else { //Change root since the old one is out BackStack newRoot = mBackStacks.peekLast(); mFragmentManager.switchFragment(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); mListener.onRootFragmentChangedBack(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); //Show ChildFragment if exist showBackStackChildFragment(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); } } /** * Remove child */ private void removeChild(@NonNull final BackStack backStack, @NonNull final String uuid) { Timber.tag(LOG_TAG).d("removeChild(): root = %s", backStack.mRootFragment.getClass().getSimpleName()); mFragmentManager.popBackStack(uuid); mFragmentManager.switchFragment(mFragmentManager.getFragmentManager().findFragmentByTag(backStack.mRootFragment)); showBackStackChildFragment(mFragmentManager.getFragmentManager().findFragmentByTag(backStack.mRootFragment)); } /** * Adding root fragment */ private void addRoot(@NonNull final Fragment fragment, final int layoutId) { mFragmentManager.addFragment(fragment, layoutId); //Create a new backstack and add it to the list final BackStack backStack = new BackStack(fragment); mBackStacks.offerLast(backStack); } /** * Switch root internally in the made up backstack */ private void switchRoot(@NonNull final Fragment fragment) { for (int i = 0; i < mBackStacks.size(); i++) { BackStack backStack = mBackStacks.get(i); if (backStack.mRootFragment.equals(fragment.getClass().getName())) { mBackStacks.remove(i); mBackStacks.offerLast(backStack); break; } } } private void setTopFragmentPlaying(boolean isPlaying) { /* try { Fragment topFragment = null; if (mBackStacks.peekLast() != null) if (isChildExists()) { String topUid = mBackStacks.peekLast().mStackItems.getFirst(); topFragment = mFragmentManager.getFragmentManager().findFragmentByTag(topUid); } else topFragment = mBackStacks.peekLast().mRootFragment; if (topFragment != null && topFragment instanceof ToroContainerFragment && topFragment.isAdded()) { ((ToroContainerFragment) topFragment).setNeedVideosPlaying(isPlaying); //Log.d(LOG_TAG, "setTopFragmentPlaying() - state: " + isPlaying + ", fragment: " + topFragment.getClass().getSimpleName()); } } catch (Exception exc) { exc.printStackTrace(); }*/ } /** * Let listener know to call onAddedExistingFragment */ private void refreshCurrentRoot() { //mListener.onAddedExistingFragment(); } /** * Convenience method */ public boolean isAdded(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { return true; } } return false; } /** * Convenience method */ private boolean isCurrent(@NonNull final Fragment fragment) { final BackStack backStack = mBackStacks.peekLast(); Timber.tag(LOG_TAG).d("isCurrent()->mBackStacks.peekLast()=" + mBackStacks.peekLast().mRootFragment.getClass().getName() + "\n" + "fragment=" + fragment.getClass().getName()); Timber.tag(LOG_TAG).d("backStack.mRootFragment == fragment-> %s", (backStack.mRootFragment.equals(fragment.getClass().getName()))); return backStack.mRootFragment.equals(fragment.getClass().getName()); } /** * Convenience method */ public boolean isFragmentExistsInBackStack(String fragmentClassName) { int count = 0; List<Fragment> fragments = mFragmentManager.getFragmentManager().getFragments(); if(!fragments.isEmpty()) { for (Fragment fr : fragments) { if(fr.getClass().getSimpleName().equals(fragmentClassName)) { count++; break; } } } return count > 0; } /** * For showing back stack child fragments */ private void showBackStackChildFragment(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { if (!backStack.isEmpty()) { Deque<String> childBackStackList = backStack.mStackItems; //Show ChildFragment Fragment childFragment = mFragmentManager .getFragmentManager() .findFragmentByTag(childBackStackList.getFirst()); Timber.tag(LOG_TAG).d("showBackStackChildFragment(): %s", childFragment.getClass().getSimpleName()); mFragmentManager.switchFragment(childFragment); } } } } /** * Get back stack child fragments */ private Deque<String> getBackStackChildFragment(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { if(!backStack.isEmpty()){ return backStack.mStackItems; } else { return null; } } } return null; } public void setFragmentManager(@NonNull final FragmentManager fragmentManager){ mFragmentManager.setFragmentManager(fragmentManager); } public Fragment findFragment(Class clazz) { return mFragmentManager.getFragmentManager().findFragmentByTag(clazz.getName()); } }
UTF-8
Java
10,610
java
BackStackManager.java
Java
[]
null
[]
package com.fil.github_client.helper.back_stack; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import java.io.Serializable; import java.util.Deque; import java.util.LinkedList; import java.util.List; import timber.log.Timber; public class BackStackManager implements Serializable { private final String LOG_TAG = BackStackManager.class.getSimpleName(); private final LinkedList<BackStack> mBackStacks; private final BackStackListener mListener; private final BackStackFragmentManager mFragmentManager; public BackStackManager(@NonNull final BackStackListener listener, @NonNull final FragmentManager fragmentManager) { mBackStacks = new LinkedList<>(); mListener = listener; mFragmentManager = new BackStackFragmentManager(fragmentManager); } /** * When adding a new root fragment * IMPORTANT: Activity his holding the reference to the root. */ public void addRootFragment(@NonNull final Fragment fragment, final int layoutId) { if (!isAdded(fragment)) { Timber.tag(LOG_TAG).d("addRootFragment(): addRoot -> fragment = %s", fragment.getClass().getName()); setTopFragmentPlaying(false); addRoot(fragment, layoutId); setTopFragmentPlaying(true); } else if (isAdded(fragment) && isCurrent(fragment)) { refreshCurrentRoot(); Timber.tag(LOG_TAG).d("addRootFragment(): refreshCurrentRoot -> fragment = %s", fragment.getClass().getName()); Deque<String> childBackStackList = getBackStackChildFragment(fragment); if (childBackStackList != null) { childBackStackList.clear(); switchRoot(fragment); mFragmentManager.switchFragment(fragment); setTopFragmentPlaying(true); } } else { Timber.tag(LOG_TAG).d("addRootFragment(): switchRoot -> fragment = %s", fragment.getClass().getName()); setTopFragmentPlaying(false); switchRoot(fragment); mFragmentManager.switchFragment(fragment); //Show ChildFragment if exist showBackStackChildFragment(fragment); setTopFragmentPlaying(true); } } /** * When activity is calling onBackPressed */ public void onBackPressed() { final BackStack current = mBackStacks.peekLast(); if(current != null) { String uuid = current.pop(); if (uuid == null) { if (mBackStacks.size() > 1 || isChildExists()) setTopFragmentPlaying(false); removeRoot(current); } else { removeChild(current, uuid); } setTopFragmentPlaying(true); } else { Timber.tag(LOG_TAG).d("onBackPressed(): call onBackStackEmpty()"); mListener.onBackStackEmpty(); } } public boolean isChildExists() { final BackStack current = mBackStacks.peekLast(); if(current == null || current.isEmpty()) return false; else return true; } /** * Adding child fragment */ public void addChildFragment(@NonNull final Fragment fragment, final int layoutId) { Timber.tag(LOG_TAG).d("addChildFragment(): %s", fragment.getClass().getSimpleName()); setTopFragmentPlaying(false); //final String tag = UUID.randomUUID().toString(); final String tag = fragment.getClass().getName(); final BackStack backStack = mBackStacks.peekLast(); //TODO: added check null to prevent crash if(backStack != null) { backStack.push(tag); } else { Timber.tag(LOG_TAG).e("addChildFragment(): mBackStacks.peekLast() == NULL!"); } mFragmentManager.addChildFragment(fragment, layoutId, tag); } /** * Remove root */ private void removeRoot(@NonNull final BackStack backStack) { Timber.tag(LOG_TAG).d("removeRoot(): %s", backStack.mRootFragment.getClass().getSimpleName()); mBackStacks.remove(backStack); //After removing. Call close app listener if the backstack is empty if (mBackStacks.isEmpty()) { Timber.tag(LOG_TAG).d("removeRoot(): call onBackStackEmpty()"); mListener.onBackStackEmpty(); } else { //Change root since the old one is out BackStack newRoot = mBackStacks.peekLast(); mFragmentManager.switchFragment(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); mListener.onRootFragmentChangedBack(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); //Show ChildFragment if exist showBackStackChildFragment(mFragmentManager.getFragmentManager().findFragmentByTag(newRoot.mRootFragment)); } } /** * Remove child */ private void removeChild(@NonNull final BackStack backStack, @NonNull final String uuid) { Timber.tag(LOG_TAG).d("removeChild(): root = %s", backStack.mRootFragment.getClass().getSimpleName()); mFragmentManager.popBackStack(uuid); mFragmentManager.switchFragment(mFragmentManager.getFragmentManager().findFragmentByTag(backStack.mRootFragment)); showBackStackChildFragment(mFragmentManager.getFragmentManager().findFragmentByTag(backStack.mRootFragment)); } /** * Adding root fragment */ private void addRoot(@NonNull final Fragment fragment, final int layoutId) { mFragmentManager.addFragment(fragment, layoutId); //Create a new backstack and add it to the list final BackStack backStack = new BackStack(fragment); mBackStacks.offerLast(backStack); } /** * Switch root internally in the made up backstack */ private void switchRoot(@NonNull final Fragment fragment) { for (int i = 0; i < mBackStacks.size(); i++) { BackStack backStack = mBackStacks.get(i); if (backStack.mRootFragment.equals(fragment.getClass().getName())) { mBackStacks.remove(i); mBackStacks.offerLast(backStack); break; } } } private void setTopFragmentPlaying(boolean isPlaying) { /* try { Fragment topFragment = null; if (mBackStacks.peekLast() != null) if (isChildExists()) { String topUid = mBackStacks.peekLast().mStackItems.getFirst(); topFragment = mFragmentManager.getFragmentManager().findFragmentByTag(topUid); } else topFragment = mBackStacks.peekLast().mRootFragment; if (topFragment != null && topFragment instanceof ToroContainerFragment && topFragment.isAdded()) { ((ToroContainerFragment) topFragment).setNeedVideosPlaying(isPlaying); //Log.d(LOG_TAG, "setTopFragmentPlaying() - state: " + isPlaying + ", fragment: " + topFragment.getClass().getSimpleName()); } } catch (Exception exc) { exc.printStackTrace(); }*/ } /** * Let listener know to call onAddedExistingFragment */ private void refreshCurrentRoot() { //mListener.onAddedExistingFragment(); } /** * Convenience method */ public boolean isAdded(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { return true; } } return false; } /** * Convenience method */ private boolean isCurrent(@NonNull final Fragment fragment) { final BackStack backStack = mBackStacks.peekLast(); Timber.tag(LOG_TAG).d("isCurrent()->mBackStacks.peekLast()=" + mBackStacks.peekLast().mRootFragment.getClass().getName() + "\n" + "fragment=" + fragment.getClass().getName()); Timber.tag(LOG_TAG).d("backStack.mRootFragment == fragment-> %s", (backStack.mRootFragment.equals(fragment.getClass().getName()))); return backStack.mRootFragment.equals(fragment.getClass().getName()); } /** * Convenience method */ public boolean isFragmentExistsInBackStack(String fragmentClassName) { int count = 0; List<Fragment> fragments = mFragmentManager.getFragmentManager().getFragments(); if(!fragments.isEmpty()) { for (Fragment fr : fragments) { if(fr.getClass().getSimpleName().equals(fragmentClassName)) { count++; break; } } } return count > 0; } /** * For showing back stack child fragments */ private void showBackStackChildFragment(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { if (!backStack.isEmpty()) { Deque<String> childBackStackList = backStack.mStackItems; //Show ChildFragment Fragment childFragment = mFragmentManager .getFragmentManager() .findFragmentByTag(childBackStackList.getFirst()); Timber.tag(LOG_TAG).d("showBackStackChildFragment(): %s", childFragment.getClass().getSimpleName()); mFragmentManager.switchFragment(childFragment); } } } } /** * Get back stack child fragments */ private Deque<String> getBackStackChildFragment(@NonNull final Fragment fragment) { for (BackStack backStack : mBackStacks) { if (backStack.mRootFragment.equals(fragment.getClass().getName())) { if(!backStack.isEmpty()){ return backStack.mStackItems; } else { return null; } } } return null; } public void setFragmentManager(@NonNull final FragmentManager fragmentManager){ mFragmentManager.setFragmentManager(fragmentManager); } public Fragment findFragment(Class clazz) { return mFragmentManager.getFragmentManager().findFragmentByTag(clazz.getName()); } }
10,610
0.612064
0.611499
280
36.892857
32.757813
140
false
false
0
0
0
0
0
0
0.446429
false
false
0
e926dfad2d2b2a1bed734f5dc6bce3be818da4b7
34,282,428,980,664
5fe19e97ddccc28b58c488c389a2998e8e003020
/kudytech-adeamx-webmex-ws-client/src/main/java/org/kudytech/adeamx/webmex/service/impl/SecurityClientServiceImpl.java
d7f68b47d5f7b1595fd75b62ca254a45aef4ce2e
[]
no_license
gcuero/poc
https://github.com/gcuero/poc
c9d77aeb9bcaed63f5c6c0c9b6b47a86e84f854a
cc5f90637fa17f8923357191f17af9a3f171e81f
refs/heads/master
2016-09-10T22:19:34.225000
2013-11-02T23:08:02
2013-11-02T23:08:02
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 org.kudytech.adeamx.webmex.service.impl; import java.util.List; import org.kudytech.adeamx.webmex.client.MenuResponseMessage; import org.kudytech.adeamx.webmex.domain.MenuWeb; import org.kudytech.adeamx.webmex.client.SeguridadWS; import org.kudytech.adeamx.webmex.client.SeguridadWSService; import org.kudytech.adeamx.webmex.domain.UsuarioWeb; import org.kudytech.adeamx.webmex.service.SecurityClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * @author gcuero */ @Service("securityClientService") public class SecurityClientServiceImpl implements SecurityClientService { @Autowired SeguridadWSService seguridadWSService; public List<MenuWeb> getMenuByUser(String login, int idAplicacion) throws Exception { SeguridadWS port = this.getSeguridadWS(); MenuResponseMessage menuByUser = port.getMenuByUser(login, idAplicacion); return menuByUser.getApplicationMenu(); } public List<MenuWeb> getSubMenuByUser(String login, int idAplicacion, double idParent) throws Exception { SeguridadWS port = this.getSeguridadWS(); MenuResponseMessage menuByUser = port.getSubMenuByUser(login, idAplicacion, idParent); return menuByUser.getApplicationMenu(); } public UsuarioWeb loadUsuarioWebByLogin(String login) throws Exception { SeguridadWS port = this.getSeguridadWS(); return port.getUsuarioWebByLogin(login).getUsuarioWeb(); } private SeguridadWS getSeguridadWS() { return this.seguridadWSService.getSeguridadWSPort(); } }
UTF-8
Java
1,828
java
SecurityClientServiceImpl.java
Java
[ { "context": "amework.stereotype.Service;\r\n\r\n/**\r\n *\r\n * @author gcuero\r\n */\r\n@Service(\"securityClientService\")\r\npublic c", "end": 671, "score": 0.9995894432067871, "start": 665, "tag": "USERNAME", "value": "gcuero" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.kudytech.adeamx.webmex.service.impl; import java.util.List; import org.kudytech.adeamx.webmex.client.MenuResponseMessage; import org.kudytech.adeamx.webmex.domain.MenuWeb; import org.kudytech.adeamx.webmex.client.SeguridadWS; import org.kudytech.adeamx.webmex.client.SeguridadWSService; import org.kudytech.adeamx.webmex.domain.UsuarioWeb; import org.kudytech.adeamx.webmex.service.SecurityClientService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * * @author gcuero */ @Service("securityClientService") public class SecurityClientServiceImpl implements SecurityClientService { @Autowired SeguridadWSService seguridadWSService; public List<MenuWeb> getMenuByUser(String login, int idAplicacion) throws Exception { SeguridadWS port = this.getSeguridadWS(); MenuResponseMessage menuByUser = port.getMenuByUser(login, idAplicacion); return menuByUser.getApplicationMenu(); } public List<MenuWeb> getSubMenuByUser(String login, int idAplicacion, double idParent) throws Exception { SeguridadWS port = this.getSeguridadWS(); MenuResponseMessage menuByUser = port.getSubMenuByUser(login, idAplicacion, idParent); return menuByUser.getApplicationMenu(); } public UsuarioWeb loadUsuarioWebByLogin(String login) throws Exception { SeguridadWS port = this.getSeguridadWS(); return port.getUsuarioWebByLogin(login).getUsuarioWeb(); } private SeguridadWS getSeguridadWS() { return this.seguridadWSService.getSeguridadWSPort(); } }
1,828
0.724836
0.724836
51
33.843136
25.933075
81
false
false
0
0
0
0
0
0
0.54902
false
false
0
33191cff11f64939c120e0ecd0c085b3b8ce9182
35,407,710,404,487
718a8498e6da032fcdd976691ad07fb646bd9703
/test_10.7/src/MyArrayList.java
55dd025cbd865f94f5bcf0f62f2c79aa47ec5dae
[]
no_license
Nineodes19/happy-end
https://github.com/Nineodes19/happy-end
716cb8026e5e9d1175ac068fdd866852a97f9494
07ec40c587f5247cd8e59e259c1c9dc14d1c488e
refs/heads/master
2022-07-13T05:53:10.808000
2020-10-24T15:18:36
2020-10-24T15:18:36
217,953,407
0
0
null
false
2022-06-21T04:03:12
2019-10-28T02:47:47
2020-10-24T15:18:57
2022-06-21T04:03:12
44,752
0
0
4
Java
false
false
/** * @program:test_10.7 * @author:Nine_odes * @description: * @create:2020-10-07 20:08 **/ public class MyArrayList<E> { private E[] array; private int size; public MyArrayList(){ array = (E[])new Object[16]; size = 0; } public void add(E e){ array[size++] = e; } public E remove(){ E element = array[size -1]; array[size-1] = null;//将容器置空,保证对象被正确释放 size --; return element; } }
UTF-8
Java
504
java
MyArrayList.java
Java
[ { "context": "/**\n * @program:test_10.7\n * @author:Nine_odes\n * @description:\n * @create:2020-10-07 20:08\n **/", "end": 46, "score": 0.9901217222213745, "start": 37, "tag": "USERNAME", "value": "Nine_odes" } ]
null
[]
/** * @program:test_10.7 * @author:Nine_odes * @description: * @create:2020-10-07 20:08 **/ public class MyArrayList<E> { private E[] array; private int size; public MyArrayList(){ array = (E[])new Object[16]; size = 0; } public void add(E e){ array[size++] = e; } public E remove(){ E element = array[size -1]; array[size-1] = null;//将容器置空,保证对象被正确释放 size --; return element; } }
504
0.521097
0.478903
24
18.75
11.861176
46
false
false
0
0
0
0
0
0
0.375
false
false
0
0dbb1e373d46bf7566ca4d61b43979ce033afd6b
21,758,304,391,830
13238164aff1598bc82dbc20f7371fdc0885135f
/Desktop/Splash/src/DAO/DAOPais.java
3bfb17d1b9d735eeb0e04de420c5a2a4f33c0f70
[]
no_license
RicardoCareta/FilmesJaTCC
https://github.com/RicardoCareta/FilmesJaTCC
d86a60416c7865d4d0202b8cde6f55da2871595a
cb3399ad9db11e687d510d65121735cadf30258b
refs/heads/master
2021-02-26T15:13:22.363000
2020-03-06T23:35:07
2020-03-06T23:35:07
245,535,302
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package DAO; public class DAOPais { }
UTF-8
Java
40
java
DAOPais.java
Java
[]
null
[]
package DAO; public class DAOPais { }
40
0.7
0.7
5
7
8.763561
22
false
false
0
0
0
0
0
0
0.2
false
false
0
94116830f05bee528775833fb2ccb46998a94d02
26,809,185,909,946
8722345547594f4d2cd2ef6f13789bd8adb96b88
/src/coreJavaTraining/AustralianTraffic.java
b59232ca3153c8a8f7e2bf917b9d87438f66c504
[]
no_license
JagadeeshmohanD/Practise
https://github.com/JagadeeshmohanD/Practise
0b8f7d23b93cec48718537df10a1d830978417dd
14876c5553fe70f4e2f96ba19295ee6c8463e386
refs/heads/master
2022-11-20T05:02:21.121000
2020-07-23T11:14:10
2020-07-23T11:14:10
271,560,974
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package coreJavaTraining; public class AustralianTraffic implements CentralTraffic,ContinentalTraffic { public static void main(String[] args) { // TODO Auto-generated method stub CentralTraffic a = new AustralianTraffic(); a.redStop(); a.greenGo(); a.flashYellow(); AustralianTraffic at = new AustralianTraffic(); at.walkonsymbol(); ContinentalTraffic ct = new AustralianTraffic(); ct.Trainsymbol(); } public void walkonsymbol() { System.out.println("walk on signal symbol"); } @Override public void greenGo() { // TODO Auto-generated method stub System.out.println("Green Go Implementation"); } @Override public void redStop() { // TODO Auto-generated method stub System.out.println("Red Stop implementation"); } @Override public void flashYellow() { // TODO Auto-generated method stub System.out.println("Yellow Flash implementation"); } @Override public void Trainsymbol() { // TODO Auto-generated method stub System.out.println("Stop on Train symbol"); } }
UTF-8
Java
1,054
java
AustralianTraffic.java
Java
[]
null
[]
package coreJavaTraining; public class AustralianTraffic implements CentralTraffic,ContinentalTraffic { public static void main(String[] args) { // TODO Auto-generated method stub CentralTraffic a = new AustralianTraffic(); a.redStop(); a.greenGo(); a.flashYellow(); AustralianTraffic at = new AustralianTraffic(); at.walkonsymbol(); ContinentalTraffic ct = new AustralianTraffic(); ct.Trainsymbol(); } public void walkonsymbol() { System.out.println("walk on signal symbol"); } @Override public void greenGo() { // TODO Auto-generated method stub System.out.println("Green Go Implementation"); } @Override public void redStop() { // TODO Auto-generated method stub System.out.println("Red Stop implementation"); } @Override public void flashYellow() { // TODO Auto-generated method stub System.out.println("Yellow Flash implementation"); } @Override public void Trainsymbol() { // TODO Auto-generated method stub System.out.println("Stop on Train symbol"); } }
1,054
0.701138
0.701138
48
20.958334
19.535181
77
false
false
0
0
0
0
0
0
1.166667
false
false
0
03ed238f627d5ae6de79b64f74a73c0684fd12e6
34,273,839,056,588
4273cdf42743ba52d2fdb9cb86e0683150724911
/app/src/main/java/me/keeptable/vozforums/models/Forum.java
ad70c58130b3486d22ae1df87d225aa4d9bfba66
[]
no_license
dungnt8805/voz
https://github.com/dungnt8805/voz
961113e6104ca12482b9124a079504cfeab02cff
ad1cb94479465cfa9fdb3fab6f9d07a9441a692a
refs/heads/master
2022-05-14T06:03:24.537000
2016-09-23T10:27:18
2016-09-23T10:27:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package me.keeptable.vozforums.models; /** * Created by vacasol on 9/22/16. */ public class Forum { protected boolean canCreateThread; protected String description; protected int id; protected boolean isSubForum; protected String name; protected int pageCount; protected Forum parentForum; protected int topicCount; protected String url; protected int viewingCount; }
UTF-8
Java
413
java
Forum.java
Java
[ { "context": " me.keeptable.vozforums.models;\n\n/**\n * Created by vacasol on 9/22/16.\n */\n\npublic class Forum {\n protect", "end": 65, "score": 0.9994942545890808, "start": 58, "tag": "USERNAME", "value": "vacasol" } ]
null
[]
package me.keeptable.vozforums.models; /** * Created by vacasol on 9/22/16. */ public class Forum { protected boolean canCreateThread; protected String description; protected int id; protected boolean isSubForum; protected String name; protected int pageCount; protected Forum parentForum; protected int topicCount; protected String url; protected int viewingCount; }
413
0.72155
0.709443
19
20.736841
14.059431
38
false
false
0
0
0
0
0
0
0.578947
false
false
0
fa2a489d34bc4619a38736211f8620002d3e2ee2
17,575,006,239,377
92b51074cfa06629ca3f09bfcdc5927769801813
/doc/HPZZTong6/src/com/handpay/zztong/hp/CustomerExceptionHandler.java
03fab0dff45e96acd28fd73e3a93014f12941178
[]
no_license
treejames/WashCar
https://github.com/treejames/WashCar
e59c9f28113855cb2eedc1d4cde78f81beb92e2b
bd667c30a0a03f1b4fc7b6774ee57810d68de031
refs/heads/master
2016-08-06T08:25:16.341000
2014-12-26T12:29:44
2014-12-26T12:29:44
34,467,329
1
0
null
true
2015-04-23T16:16:27
2015-04-23T16:16:27
2015-04-23T16:16:22
2014-12-26T12:33:03
220,904
0
0
0
null
null
null
package com.handpay.zztong.hp; import com.handpay.framework.HPLog; /** * Created by jmshuai on 2014/4/30. */ public class CustomerExceptionHandler implements Thread.UncaughtExceptionHandler { //Thread.UncaughtExceptionHandler mDefault; public CustomerExceptionHandler() { //mDefault = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { HPLog.i("CustomerExceptionHandler", thread.getName(), ex); ZZTApplication.getApp().exitApp(); System.exit(0); //mDefault.uncaughtException(thread, ex); } }
UTF-8
Java
627
java
CustomerExceptionHandler.java
Java
[ { "context": "rt com.handpay.framework.HPLog;\n\n/**\n * Created by jmshuai on 2014/4/30.\n */\npublic class CustomerExceptionH", "end": 94, "score": 0.9997038245201111, "start": 87, "tag": "USERNAME", "value": "jmshuai" } ]
null
[]
package com.handpay.zztong.hp; import com.handpay.framework.HPLog; /** * Created by jmshuai on 2014/4/30. */ public class CustomerExceptionHandler implements Thread.UncaughtExceptionHandler { //Thread.UncaughtExceptionHandler mDefault; public CustomerExceptionHandler() { //mDefault = Thread.getDefaultUncaughtExceptionHandler(); } @Override public void uncaughtException(Thread thread, Throwable ex) { HPLog.i("CustomerExceptionHandler", thread.getName(), ex); ZZTApplication.getApp().exitApp(); System.exit(0); //mDefault.uncaughtException(thread, ex); } }
627
0.709729
0.69697
20
30.35
25.48583
82
false
false
0
0
0
0
0
0
0.6
false
false
0
f6a58a3414433b56f4a0d35e71c8cb18758b75e3
11,252,814,372,689
7c9dd49ebfa24d827f969372fce91403d0b814d1
/compiler/src/main/java/jago/compiler/exception/NotAStatementException.java
5b8cab7527ab72e44542cdd06d99166972404f29
[]
no_license
JagoLang/JagoLang
https://github.com/JagoLang/JagoLang
1c6febb7be9ba00c502c34f55889ec52edb3db0c
8f7b30f7eefe80f836225356f5bb4c9830e42384
refs/heads/master
2020-03-18T16:37:57.539000
2018-06-18T18:08:44
2018-06-18T18:09:16
134,977,058
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jago.compiler.exception; public class NotAStatementException extends SemanticException { public NotAStatementException(String s) { super(s); } }
UTF-8
Java
171
java
NotAStatementException.java
Java
[]
null
[]
package jago.compiler.exception; public class NotAStatementException extends SemanticException { public NotAStatementException(String s) { super(s); } }
171
0.736842
0.736842
8
20.375
22.393847
63
false
false
0
0
0
0
0
0
0.25
false
false
0
7b9bbd0c85954f5a4e7da8022c84ec26125fee9e
20,091,857,078,378
a205340b3c34c3aaeba769a68150e12e8fd3ab34
/design-pattern/src/test/java/com/example/demo0/Decorator.java
9a0a05085bbef570fc40fc7d7bcd7ff3baa34433
[]
no_license
jorgezhong/demo-project
https://github.com/jorgezhong/demo-project
111eb1b6b3cf8451e4640501b31aba53baaa1f81
054eb91181cfe246f5aae83f9252d586c058627c
refs/heads/master
2022-10-20T13:36:41.839000
2019-08-09T10:20:58
2019-08-09T10:20:58
145,265,455
0
0
null
false
2022-10-04T23:33:02
2018-08-19T01:54:47
2019-08-09T10:21:38
2022-10-04T23:33:00
1,665
0
0
4
Java
false
false
package com.example.demo0; /** * Project <demo1-project> * Created by jorgezhong on 2018/9/20 18:04. */ public abstract class Decorator extends Weapon { Weapon weapon; }
UTF-8
Java
191
java
Decorator.java
Java
[ { "context": "\r\n\r\n/**\r\n * Project <demo1-project>\r\n * Created by jorgezhong on 2018/9/20 18:04.\r\n */\r\npublic abstract class D", "end": 87, "score": 0.9996656179428101, "start": 77, "tag": "USERNAME", "value": "jorgezhong" } ]
null
[]
package com.example.demo0; /** * Project <demo1-project> * Created by jorgezhong on 2018/9/20 18:04. */ public abstract class Decorator extends Weapon { Weapon weapon; }
191
0.659686
0.591623
11
15.363636
17.42137
48
false
false
0
0
0
0
0
0
0.181818
false
false
0
3bc8afa8179ba4de5c7733aa815d0acb846fc952
34,059,090,692,254
6b1c392a0850f6172ef9ca667f43d4088295a1b0
/Simple Paint Program/ColorPoint.java
f6718c28be0b19943100dab67c948e6668d4f525
[]
no_license
dwalls1/Java
https://github.com/dwalls1/Java
8f3f9ad62c5dc1e0bdd6401b933ce14538259083
ac4941059259b3376700f33a4fbe54810cb3a70d
refs/heads/master
2020-03-20T19:22:40.465000
2018-06-23T23:20:29
2018-06-23T23:20:29
137,635,046
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; /** * Write a description of class ColorPoint here. * * @author (Darion Walls) * */ public class ColorPoint { private Color color; private int x; //horizontal coordinate private int y; //vertical coordinate /** * Constructor for objects of class ColorPoint */ public ColorPoint() { color = Color.BLACK; x = 0; y = 0; } /** * three-argument constructor */ public ColorPoint(int x,int y, Color color) { this.x = x; this.y = y; this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setColor(Color c) { color = c; } public void setColor(String c) //set Color from a String description { //lists just a few possible colors if (c.equals("Red")) color = Color.RED; else if (c.equals("Blue")) color = Color.BLUE; else if (c.equals("Black")) color = Color.BLACK; else if (c.equals("Green")) color = Color.GREEN; else if (c.equals("Magenta")) color = Color.MAGENTA; else if (c.equals("Pink")) color = Color.PINK; else if (c.equals("Yellow")) color = Color.YELLOW; //etc } public int getX() { return x; } public int getY() { return y; } public Color getColor() { return color; } }
UTF-8
Java
1,775
java
ColorPoint.java
Java
[ { "context": "cription of class ColorPoint here.\n *\n * @author (Darion Walls)\n * \n */\npublic class ColorPoint\n{\n private Co", "end": 166, "score": 0.9998336434364319, "start": 154, "tag": "NAME", "value": "Darion Walls" } ]
null
[]
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; /** * Write a description of class ColorPoint here. * * @author (<NAME>) * */ public class ColorPoint { private Color color; private int x; //horizontal coordinate private int y; //vertical coordinate /** * Constructor for objects of class ColorPoint */ public ColorPoint() { color = Color.BLACK; x = 0; y = 0; } /** * three-argument constructor */ public ColorPoint(int x,int y, Color color) { this.x = x; this.y = y; this.color = color; } public void setX(int x) { this.x = x; } public void setY(int y) { this.y = y; } public void setColor(Color c) { color = c; } public void setColor(String c) //set Color from a String description { //lists just a few possible colors if (c.equals("Red")) color = Color.RED; else if (c.equals("Blue")) color = Color.BLUE; else if (c.equals("Black")) color = Color.BLACK; else if (c.equals("Green")) color = Color.GREEN; else if (c.equals("Magenta")) color = Color.MAGENTA; else if (c.equals("Pink")) color = Color.PINK; else if (c.equals("Yellow")) color = Color.YELLOW; //etc } public int getX() { return x; } public int getY() { return y; } public Color getColor() { return color; } }
1,769
0.467042
0.465916
94
17.882978
15.825415
76
false
false
0
0
0
0
0
0
0.297872
false
false
0
44977ff70b174785c606210605e770b7a646b866
32,014,686,284,997
20157795dab2c15e2a388861c24125696f703acf
/pr2.java
0734fc3f3f9ba247fd6b9c099c9fd80f74e851d3
[]
no_license
eamtcPROG/step
https://github.com/eamtcPROG/step
0101215c97ea8f3dc8136d3059c7c6a4ce56d4e6
ce070fc344c0206cb642cfda7607142a8108fd4a
refs/heads/master
2021-01-15T00:02:59.282000
2020-02-24T18:47:51
2020-02-24T18:47:51
242,804,992
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class pr2 { public static void main(String[] args) { int i = 0,n = 10,suma = 0; while(i <= n){ suma+=i; i++; } System.out.println(suma); } }
UTF-8
Java
163
java
pr2.java
Java
[]
null
[]
public class pr2 { public static void main(String[] args) { int i = 0,n = 10,suma = 0; while(i <= n){ suma+=i; i++; } System.out.println(suma); } }
163
0.552147
0.521472
10
15.4
12.595237
41
false
false
0
0
0
0
0
0
2.2
false
false
0
ba0b9b20cb490fd494a39fb038ab0f009b04c708
36,275,293,804,069
79d1c100ca4d5fc686bf1c26f466ab2fe11953cf
/app/src/main/java/com/example/sahil/f2/HomeServicesProvider/UnInstallService.java
1d7447d9a8c6338fe4284a415dd24792c0da8586
[]
no_license
vishwassingh47/f2
https://github.com/vishwassingh47/f2
b6e09b18292b02b2028e9982d4812f1071af111e
928fb75d3898567d63efb3c9f080d0bd5270e61b
refs/heads/master
2022-02-05T10:35:37.552000
2018-06-01T16:45:25
2018-06-01T16:45:25
133,171,326
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.sahil.f2.HomeServicesProvider; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.v7.app.NotificationCompat; import android.util.Log; import com.example.sahil.f2.Cache.MyCacheData; import com.example.sahil.f2.Cache.UnInstallData; import com.example.sahil.f2.Cache.tasksCache; import com.example.sahil.f2.Classes.MyApp; import com.example.sahil.f2.MainActivity; import com.example.sahil.f2.Maintenance.TinyDB; import com.example.sahil.f2.R; import com.example.sahil.f2.Utilities.AppManagerUtils; /** * Created by hit4man47 on 2/16/2018. */ public class UnInstallService extends Service { public NotificationCompat.Builder mBuilder; public NotificationManager mNotifyManager; public static Thread myOperationThread; private int oldTime=-1; private final int operationCode=199; private UnInstallData unInstallData; final String TAG="199_SERVICE"; @Override public int onStartCommand(Intent intent, int flags, final int startid) { Log.i(TAG,"service called"); Intent myIntent; PendingIntent myPendingIntent; myIntent= new Intent(this, MainActivity.class); myIntent.putExtra("notification",5); myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); myPendingIntent=PendingIntent.getActivity(getApplicationContext(),operationCode,myIntent,PendingIntent.FLAG_UPDATE_CURRENT); mNotifyManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder=new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.search_icon) .setContentTitle("UnInstalling") .setContentText("Calculating...") .setOngoing(true) .setAutoCancel(false) .setContentIntent(myPendingIntent) .setProgress(100,0,true); mNotifyManager.notify(operationCode,mBuilder.build()); myOperationThread=new Thread() { @Override public void run() { uninstallTask(); } }; myOperationThread.start(); return START_STICKY; } private void uninstallTask() { AppManagerUtils appManagerUtils=new AppManagerUtils(getApplicationContext()); for(int i=0;i<unInstallData.myFilesList.size();i++) { MyApp myApp=unInstallData.myFilesList.get(i).getMyApp(); unInstallData.progress=(i*100)/unInstallData.totalFiles; if(unInstallData.cancelPlease) { cancelProgress(); return; } if(oldTime<unInstallData.timeInSec) { notifyProgress(); } boolean x=appManagerUtils.unInstallAsSuperUser(myApp.getPackageName(),myApp.getApkPath(),false); if(x) { unInstallData.successCount++; } else { unInstallData.failedCount++; } unInstallData.isErrorList.set(i,!x); unInstallData.currentFileIndex++; } unInstallData.progress=100; notifyProgressWithMessage("UnInstallation Complete....."); stopSelf(); } @Override public void onCreate() { unInstallData=null; unInstallData= MyCacheData.getUnInstallData(operationCode); unInstallData.isServiceRunning=true; tasksCache.addTask(operationCode+""); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { Log.i(TAG,"destroyed"); unInstallData.isServiceRunning=false;//very very important if(unInstallData.cancelPlease || unInstallData.currentFileIndex==unInstallData.totalFiles) { tasksCache.removeTask(operationCode+""); } else { notifyProgressWithMessage("UnInstallation Failed....."); } } private void cancelProgress() { mBuilder.setContentTitle("UnInstallation Aborted....") .setOngoing(false).setAutoCancel(true); mNotifyManager.notify(operationCode,mBuilder.build()); mNotifyManager.cancel(operationCode); } private void notifyProgress() { oldTime=unInstallData.timeInSec; mBuilder.setContentText("Success:"+unInstallData.successCount+",Failed:"+unInstallData.failedCount); mBuilder.setProgress(100,(int)unInstallData.progress,false); mNotifyManager.notify(operationCode,mBuilder.build()); } private void notifyProgressWithMessage(String msg) { mBuilder.setContentTitle(msg) .setProgress(100,(int)unInstallData.progress,false) .setContentText("Success:"+unInstallData.successCount+",Failed:"+unInstallData.failedCount) .setOngoing(false) .setAutoCancel(true); mNotifyManager.notify(operationCode,mBuilder.build()); } }
UTF-8
Java
5,239
java
UnInstallService.java
Java
[ { "context": "l.f2.Utilities.AppManagerUtils;\n\n/**\n * Created by hit4man47 on 2/16/2018.\n */\n\npublic class UnInstallService ", "end": 709, "score": 0.9996164441108704, "start": 700, "tag": "USERNAME", "value": "hit4man47" } ]
null
[]
package com.example.sahil.f2.HomeServicesProvider; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.support.v7.app.NotificationCompat; import android.util.Log; import com.example.sahil.f2.Cache.MyCacheData; import com.example.sahil.f2.Cache.UnInstallData; import com.example.sahil.f2.Cache.tasksCache; import com.example.sahil.f2.Classes.MyApp; import com.example.sahil.f2.MainActivity; import com.example.sahil.f2.Maintenance.TinyDB; import com.example.sahil.f2.R; import com.example.sahil.f2.Utilities.AppManagerUtils; /** * Created by hit4man47 on 2/16/2018. */ public class UnInstallService extends Service { public NotificationCompat.Builder mBuilder; public NotificationManager mNotifyManager; public static Thread myOperationThread; private int oldTime=-1; private final int operationCode=199; private UnInstallData unInstallData; final String TAG="199_SERVICE"; @Override public int onStartCommand(Intent intent, int flags, final int startid) { Log.i(TAG,"service called"); Intent myIntent; PendingIntent myPendingIntent; myIntent= new Intent(this, MainActivity.class); myIntent.putExtra("notification",5); myIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); myPendingIntent=PendingIntent.getActivity(getApplicationContext(),operationCode,myIntent,PendingIntent.FLAG_UPDATE_CURRENT); mNotifyManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); mBuilder=new NotificationCompat.Builder(this); mBuilder.setSmallIcon(R.drawable.search_icon) .setContentTitle("UnInstalling") .setContentText("Calculating...") .setOngoing(true) .setAutoCancel(false) .setContentIntent(myPendingIntent) .setProgress(100,0,true); mNotifyManager.notify(operationCode,mBuilder.build()); myOperationThread=new Thread() { @Override public void run() { uninstallTask(); } }; myOperationThread.start(); return START_STICKY; } private void uninstallTask() { AppManagerUtils appManagerUtils=new AppManagerUtils(getApplicationContext()); for(int i=0;i<unInstallData.myFilesList.size();i++) { MyApp myApp=unInstallData.myFilesList.get(i).getMyApp(); unInstallData.progress=(i*100)/unInstallData.totalFiles; if(unInstallData.cancelPlease) { cancelProgress(); return; } if(oldTime<unInstallData.timeInSec) { notifyProgress(); } boolean x=appManagerUtils.unInstallAsSuperUser(myApp.getPackageName(),myApp.getApkPath(),false); if(x) { unInstallData.successCount++; } else { unInstallData.failedCount++; } unInstallData.isErrorList.set(i,!x); unInstallData.currentFileIndex++; } unInstallData.progress=100; notifyProgressWithMessage("UnInstallation Complete....."); stopSelf(); } @Override public void onCreate() { unInstallData=null; unInstallData= MyCacheData.getUnInstallData(operationCode); unInstallData.isServiceRunning=true; tasksCache.addTask(operationCode+""); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { Log.i(TAG,"destroyed"); unInstallData.isServiceRunning=false;//very very important if(unInstallData.cancelPlease || unInstallData.currentFileIndex==unInstallData.totalFiles) { tasksCache.removeTask(operationCode+""); } else { notifyProgressWithMessage("UnInstallation Failed....."); } } private void cancelProgress() { mBuilder.setContentTitle("UnInstallation Aborted....") .setOngoing(false).setAutoCancel(true); mNotifyManager.notify(operationCode,mBuilder.build()); mNotifyManager.cancel(operationCode); } private void notifyProgress() { oldTime=unInstallData.timeInSec; mBuilder.setContentText("Success:"+unInstallData.successCount+",Failed:"+unInstallData.failedCount); mBuilder.setProgress(100,(int)unInstallData.progress,false); mNotifyManager.notify(operationCode,mBuilder.build()); } private void notifyProgressWithMessage(String msg) { mBuilder.setContentTitle(msg) .setProgress(100,(int)unInstallData.progress,false) .setContentText("Success:"+unInstallData.successCount+",Failed:"+unInstallData.failedCount) .setOngoing(false) .setAutoCancel(true); mNotifyManager.notify(operationCode,mBuilder.build()); } }
5,239
0.64497
0.636381
184
27.472826
26.519257
132
false
false
0
0
0
0
0
0
0.538043
false
false
0
8baefd0ec5b758be825ce6242752fcb79557e40e
17,609,365,958,406
4394d9be3199b0c68a6e4ae0de285538655cd86b
/app/src/main/java/com/techm/telestra/assignment/JsonParserFactory.java
3fd055bc59474b8d121cc941979e50164b9e0352
[]
no_license
pradeepxbhagat/AndroidproficiencyExcercise
https://github.com/pradeepxbhagat/AndroidproficiencyExcercise
f5c8e98ba0714c26cca02974e2b3e9e775275bb8
7de30b88a49e878415ef450f3d9d6e67f3cd97b3
refs/heads/master
2021-06-01T05:52:06.543000
2016-07-21T12:48:31
2016-07-21T12:48:31
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.techm.telestra.assignment; import android.content.Context; import com.techm.telestra.assignment.feed.FeedJsonParser; import com.techm.telestra.assignment.feed.FeedParser; /** * Created by PP00344204 on 5/1/2016. * * Copyright (c) 2015, TechMahindra Limited and/or its affiliates. All rights reserved. * TECHMAHINDRA PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ public class JsonParserFactory extends ParserFactory { private Context mContext; public JsonParserFactory(Context mContext) { this.mContext = mContext; } @Override public FeedParser getFeedParser() { return new FeedJsonParser(); } }
UTF-8
Java
674
java
JsonParserFactory.java
Java
[ { "context": "tra.assignment.feed.FeedParser;\n\n/**\n * Created by PP00344204 on 5/1/2016.\n *\n * Copyright (c) 2015, TechMahind", "end": 214, "score": 0.9962873458862305, "start": 204, "tag": "USERNAME", "value": "PP00344204" } ]
null
[]
package com.techm.telestra.assignment; import android.content.Context; import com.techm.telestra.assignment.feed.FeedJsonParser; import com.techm.telestra.assignment.feed.FeedParser; /** * Created by PP00344204 on 5/1/2016. * * Copyright (c) 2015, TechMahindra Limited and/or its affiliates. All rights reserved. * TECHMAHINDRA PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ public class JsonParserFactory extends ParserFactory { private Context mContext; public JsonParserFactory(Context mContext) { this.mContext = mContext; } @Override public FeedParser getFeedParser() { return new FeedJsonParser(); } }
674
0.74184
0.715134
26
24.923077
25.522121
87
false
false
0
0
0
0
0
0
0.307692
false
false
0
0c6be57398f326c55f96f4843ce9e453ced6069d
8,005,819,082,474
c423695d2be0e04769ff33ca4821b648035c518f
/core/src/com/ray3k/template/entities/DecalEntity.java
59257f00cad0b5622f20f72f30e35235c743e9fe
[ "MIT" ]
permissive
raeleus/la-femme-dragonne
https://github.com/raeleus/la-femme-dragonne
90446fc4aa7c48b5a637843a3f643d05d7178a30
379d3d99eb76c9f31d3502c57fae9226773e8525
refs/heads/main
2023-02-07T19:13:30.024000
2020-12-27T09:07:22
2020-12-27T09:07:22
324,609,581
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ray3k.template.entities; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasSprite; import com.dongbat.jbump.Collisions; import com.dongbat.jbump.Response.Result; import com.ray3k.template.*; import static com.ray3k.template.Core.*; public class DecalEntity extends Entity { private AtlasSprite sprite; public DecalEntity(float centerX, float centerY, float scaleX, float scaleY, String regionName) { sprite = new AtlasSprite(Resources.textures_textures.findRegion(regionName)); sprite.setOriginCenter(); sprite.setPosition(centerX - sprite.getWidth() / 2, centerY - sprite.getHeight() / 2); sprite.setScale(scaleX, scaleY); depth = BACKGROUND_DEPTH; } @Override public void create() { } @Override public void actBefore(float delta) { } @Override public void act(float delta) { } @Override public void draw(float delta) { sprite.draw(batch); } @Override public void destroy() { } @Override public void projectedCollision(Result result) { } @Override public void collision(Collisions collisions) { } }
UTF-8
Java
1,234
java
DecalEntity.java
Java
[]
null
[]
package com.ray3k.template.entities; import com.badlogic.gdx.graphics.g2d.TextureAtlas.AtlasSprite; import com.dongbat.jbump.Collisions; import com.dongbat.jbump.Response.Result; import com.ray3k.template.*; import static com.ray3k.template.Core.*; public class DecalEntity extends Entity { private AtlasSprite sprite; public DecalEntity(float centerX, float centerY, float scaleX, float scaleY, String regionName) { sprite = new AtlasSprite(Resources.textures_textures.findRegion(regionName)); sprite.setOriginCenter(); sprite.setPosition(centerX - sprite.getWidth() / 2, centerY - sprite.getHeight() / 2); sprite.setScale(scaleX, scaleY); depth = BACKGROUND_DEPTH; } @Override public void create() { } @Override public void actBefore(float delta) { } @Override public void act(float delta) { } @Override public void draw(float delta) { sprite.draw(batch); } @Override public void destroy() { } @Override public void projectedCollision(Result result) { } @Override public void collision(Collisions collisions) { } }
1,234
0.645057
0.640194
55
21.436363
23.638769
101
false
false
0
0
0
0
0
0
0.345455
false
false
0
736523e34d21c7dd443613866396f8e62319df8c
8,005,819,084,308
f727a20bb00823bc966b420ab32a942a2dfb67db
/netx-api/src/main/java/com/netx/api/mapper/TransporterMapper.java
4bbccdccf1092ca0525680dbb0e11680a8909ec8
[]
no_license
CloudZou/longhua
https://github.com/CloudZou/longhua
9e423cdc526d4f90c3ecf9381bf0b19416459c8b
a744a1d8b8e12f18da3599878132998fcc20cf23
refs/heads/master
2020-03-26T13:33:33.514000
2020-03-23T12:10:06
2020-03-23T12:10:06
144,945,067
0
0
null
false
2020-03-04T22:18:21
2018-08-16T06:15:59
2019-11-20T03:10:53
2020-03-04T22:18:18
18,612
0
0
6
Java
false
false
package com.netx.api.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.netx.api.model.Transporter; public interface TransporterMapper extends BaseMapper<Transporter> { }
UTF-8
Java
192
java
TransporterMapper.java
Java
[]
null
[]
package com.netx.api.mapper; import com.baomidou.mybatisplus.mapper.BaseMapper; import com.netx.api.model.Transporter; public interface TransporterMapper extends BaseMapper<Transporter> { }
192
0.828125
0.828125
7
26.428572
25.252197
68
false
false
0
0
0
0
0
0
0.428571
false
false
0
6dfeb3169e58adb2e0bae06fad39f8b09f90aedf
14,018,773,298,249
bbf5a2124d36512f0b7960ef46c176ac106cbc2a
/ACM/090614/A.java
83f9744aaf83f8bbb845fcb063d013a3f07037d0
[]
no_license
thomasaeyo/Contest-Problems
https://github.com/thomasaeyo/Contest-Problems
d1ed06f2477b3fd800dca2538cfdfb2a7fc87dbb
8eb7c6b62d7bf891345b1d3eb39a4788e4816eb3
refs/heads/master
2021-01-25T00:09:54.536000
2015-01-13T15:23:12
2015-01-13T15:23:12
28,018,113
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class A { private static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { return reader.readLine(); } } public static void main(String[] args) throws IOException { Reader reader = new Reader(System.in); int y = reader.nextInt(); int k = reader.nextInt(); int n = reader.nextInt(); String ans = ""; int c = 1; int start = y % k; while(y + c * k - start <= n) { ans += (c * k - start) + " "; c++; } if (ans.length() == 0) System.out.println(-1); else System.out.println(ans); } }
UTF-8
Java
1,196
java
A.java
Java
[]
null
[]
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class A { private static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader(InputStream inputstream) { reader = new BufferedReader(new InputStreamReader(inputstream)); tokenizer = null; } public String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public String nextLine() throws IOException { return reader.readLine(); } } public static void main(String[] args) throws IOException { Reader reader = new Reader(System.in); int y = reader.nextInt(); int k = reader.nextInt(); int n = reader.nextInt(); String ans = ""; int c = 1; int start = y % k; while(y + c * k - start <= n) { ans += (c * k - start) + " "; c++; } if (ans.length() == 0) System.out.println(-1); else System.out.println(ans); } }
1,196
0.669732
0.667224
54
21.166666
18.294657
67
false
false
0
0
0
0
0
0
2.018518
false
false
0
8e992bc37785bc0479f3d242fffa9523c01a8356
20,804,821,636,535
721d1b50b1083e1317837b341de92906700b0a9d
/src/org/james/tabbedcmd/model/MessageSource.java
7f451e75479fd0680ce51b2e4d7c6baa3aa8d6de
[]
no_license
jreber/TabbedCmd
https://github.com/jreber/TabbedCmd
d832860a9432c4eda2c48d90e2beb5f82c52b19b
6e4cc7ddd729ca3f2f0b63df9c41e81c3d9e0cba
refs/heads/master
2015-08-09T01:32:09
2013-12-12T15:54:18
2013-12-12T15:54:18
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package org.james.tabbedcmd.model; import java.util.Queue; /** * Indicates classes that are able to be message source points. * * @author jreber */ public interface MessageSource { /** * Sends the specified message. * * @param type * the type of this message * @param message * the text contents of this message */ public void sendMessage(CmdMessage.Type type, String message); /** * Returns the queue into which all messages are placed. * * @return the queue into which all messages are placed */ public Queue<CmdMessage> getMessageQueue(); }
UTF-8
Java
629
java
MessageSource.java
Java
[ { "context": "able to be message source points.\r\n * \r\n * @author jreber\r\n */\r\npublic interface MessageSource {\r\n\t/**\r\n\t *", "end": 157, "score": 0.9995797276496887, "start": 151, "tag": "USERNAME", "value": "jreber" } ]
null
[]
package org.james.tabbedcmd.model; import java.util.Queue; /** * Indicates classes that are able to be message source points. * * @author jreber */ public interface MessageSource { /** * Sends the specified message. * * @param type * the type of this message * @param message * the text contents of this message */ public void sendMessage(CmdMessage.Type type, String message); /** * Returns the queue into which all messages are placed. * * @return the queue into which all messages are placed */ public Queue<CmdMessage> getMessageQueue(); }
629
0.645469
0.645469
27
21.296297
21.545498
63
false
false
0
0
0
0
0
0
0.740741
false
false
0
10e7dcb6f8d162bb08eae7bccb6d75adb458ee25
9,423,158,304,178
68ee806b580d7fc1b1ca2da9bdad85a97f710932
/netty-chatroom/src/main/java/com/lcl/springboot/nettychatroom/echo/EchoClientHandler.java
99ff30ce2f05e348628e08b91794273e6c56e7ed
[]
no_license
gotHot55/project
https://github.com/gotHot55/project
ceb7dad9c401703dc21bf93f1d6ccc51b455683c
c38d295d5d71a66341625f180398d3017c67ab00
refs/heads/master
2021-06-12T11:13:13.500000
2021-03-05T07:02:40
2021-03-05T07:02:40
155,802,180
2
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.lcl.springboot.nettychatroom.echo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.nio.charset.StandardCharsets; /** * Todo * * @author Administrator * @date 2021/1/2017:40 */ public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /** * 从服务器受到数据后调用此方法 */ @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception { System.out.println("echo client received message: " + byteBuf.toString(StandardCharsets.UTF_8)); } /** * 客户端与服务器的连接建立后调用此方法 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("hello echo server", StandardCharsets.UTF_8)); // super.channelActive(ctx); } /** * 捕获到异常时调用此方法 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // super.exceptionCaught(ctx, cause); cause.printStackTrace(); ctx.close(); } }
UTF-8
Java
1,285
java
EchoClientHandler.java
Java
[ { "context": "arset.StandardCharsets;\n\n/**\n * Todo\n *\n * @author Administrator\n * @date 2021/1/2017:40\n */\npublic class EchoClie", "end": 296, "score": 0.6233569383621216, "start": 283, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.lcl.springboot.nettychatroom.echo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.nio.charset.StandardCharsets; /** * Todo * * @author Administrator * @date 2021/1/2017:40 */ public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> { /** * 从服务器受到数据后调用此方法 */ @Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception { System.out.println("echo client received message: " + byteBuf.toString(StandardCharsets.UTF_8)); } /** * 客户端与服务器的连接建立后调用此方法 */ @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.writeAndFlush(Unpooled.copiedBuffer("hello echo server", StandardCharsets.UTF_8)); // super.channelActive(ctx); } /** * 捕获到异常时调用此方法 */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { // super.exceptionCaught(ctx, cause); cause.printStackTrace(); ctx.close(); } }
1,285
0.709758
0.698082
41
28.243902
30.64731
112
false
false
0
0
0
0
0
0
0.390244
false
false
0
ac012fb30e35366a4eecb459d2d0d00786d99a2c
5,231,270,221,362
84ca1c89f45c845b522e60353a087d23f353e801
/src/main/java/com/liziyi/ListNode.java
d51de452fb5e286ac7831ad9bf6272044c75c884
[]
no_license
Ciel1998/leecode
https://github.com/Ciel1998/leecode
a0d27388a7fca0e05c09d652fac96e604e05d17e
6566c2b740a52d3ee632a1e7829ce31ee95cbb94
refs/heads/master
2023-02-18T11:21:33.866000
2021-01-18T01:24:39
2021-01-18T01:24:39
328,049,880
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.liziyi; /** * @version 1.0 * @Description * @Author liziyi * @CreateDate 2021/1/11 14:15 * @UpdateUser * @UpdateDate * @UpdateRemark */ public class ListNode { int val; ListNode next; public ListNode(int i) { } }
UTF-8
Java
252
java
ListNode.java
Java
[ { "context": "i;\n\n/**\n * @version 1.0\n * @Description\n * @Author liziyi\n * @CreateDate 2021/1/11 14:15\n * @UpdateUser\n * ", "end": 74, "score": 0.9993137717247009, "start": 68, "tag": "USERNAME", "value": "liziyi" } ]
null
[]
package com.liziyi; /** * @version 1.0 * @Description * @Author liziyi * @CreateDate 2021/1/11 14:15 * @UpdateUser * @UpdateDate * @UpdateRemark */ public class ListNode { int val; ListNode next; public ListNode(int i) { } }
252
0.619048
0.56746
19
12.263158
9.221498
30
false
false
0
0
0
0
0
0
0.157895
false
false
0
1195f7b668e29ad1bdb3c2fe7707fbb52291e7b9
10,144,712,814,283
7634bcf556ede342cdb0bf7154f0bb9e3be9e0ce
/src/main/java/com/wuyou/service/impl/PromOrderServiceImpl.java
15b42be0400a401eec38f48d19667c857e0eb711
[]
no_license
Tig3rHu/XiaoMi
https://github.com/Tig3rHu/XiaoMi
380eba1ec58ffbe8fc99e1ae211879cc669725ac
b318e5ea6a8d89ce4056c094275bff976729522f
refs/heads/master
2023-06-10T06:41:54.529000
2021-07-04T10:38:27
2021-07-04T10:38:27
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * <p>Title: PromOrderServiceImpl.java</p> * <p>Description: </p> * @author 吴优 * @date 2018年9月22日 * @version 1.0 */ package com.wuyou.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wuyou.dao.PromOrderMapper; import com.wuyou.entity.PromOrder; import com.wuyou.service.PromOrderService; /** * @author 吴优 * desciption: * other: * @date 2018年9月22日 */ @Service public class PromOrderServiceImpl implements PromOrderService { @Autowired private PromOrderMapper promOrderMapper; /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#insert(com.wuyou.entity.PromOrder) */ @Override public int insert(PromOrder promOrder) { // TODO Auto-generated method stub return promOrderMapper.insert(promOrder); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#deletePromOrderById(java.lang.Long) */ @Override public int deletePromOrderById(Long id) { // TODO Auto-generated method stub return promOrderMapper.deleteByPrimaryKey(id); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#updatePromOrderById(java.lang.Long, com.wuyou.entity.PromOrder) */ @Override public int updatePromOrderById(Long id, PromOrder promOrder) { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#findPromOrderById(java.lang.Long) */ @Override public PromOrder findPromOrderById(Long id) { // TODO Auto-generated method stub return promOrderMapper.selectByPrimaryKey(id); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#findPromOrderAll() */ @Override public List<PromOrder> findPromOrderAll() { // TODO Auto-generated method stub return promOrderMapper.selectByExample(null); } }
UTF-8
Java
1,937
java
PromOrderServiceImpl.java
Java
[ { "context": ".java</p> \r\n* <p>Description: </p> \r\n* @author 吴优 \r\n* @date 2018年9月22日 \r\n* @version 1.0 \r\n*/\r\npac", "end": 91, "score": 0.9968475699424744, "start": 89, "tag": "NAME", "value": "吴优" }, { "context": "uyou.service.PromOrderService;\r\n\r\n/**\r\n * @author 吴优\r\n * desciption:\r\n * other:\r\n * @date 2018年9月22日 \r", "end": 452, "score": 0.996244490146637, "start": 450, "tag": "NAME", "value": "吴优" } ]
null
[]
/** * <p>Title: PromOrderServiceImpl.java</p> * <p>Description: </p> * @author 吴优 * @date 2018年9月22日 * @version 1.0 */ package com.wuyou.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.wuyou.dao.PromOrderMapper; import com.wuyou.entity.PromOrder; import com.wuyou.service.PromOrderService; /** * @author 吴优 * desciption: * other: * @date 2018年9月22日 */ @Service public class PromOrderServiceImpl implements PromOrderService { @Autowired private PromOrderMapper promOrderMapper; /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#insert(com.wuyou.entity.PromOrder) */ @Override public int insert(PromOrder promOrder) { // TODO Auto-generated method stub return promOrderMapper.insert(promOrder); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#deletePromOrderById(java.lang.Long) */ @Override public int deletePromOrderById(Long id) { // TODO Auto-generated method stub return promOrderMapper.deleteByPrimaryKey(id); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#updatePromOrderById(java.lang.Long, com.wuyou.entity.PromOrder) */ @Override public int updatePromOrderById(Long id, PromOrder promOrder) { // TODO Auto-generated method stub return 0; } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#findPromOrderById(java.lang.Long) */ @Override public PromOrder findPromOrderById(Long id) { // TODO Auto-generated method stub return promOrderMapper.selectByPrimaryKey(id); } /* (non-Javadoc) * @see com.wuyou.service.PromOrderSevice#findPromOrderAll() */ @Override public List<PromOrder> findPromOrderAll() { // TODO Auto-generated method stub return promOrderMapper.selectByExample(null); } }
1,937
0.712572
0.703704
76
23.223684
23.58445
106
false
false
0
0
0
0
0
0
0.894737
false
false
0
46de2855681213e07547ae67de242b51426f5f6e
26,955,214,816,509
75f512e704d2ef1393c0021736f56765a4608c70
/src/main/java/com/future/dao/TestDao.java
182ae27e926f3c8a4a6cc5a6ad2473fc0e8e1a43
[]
no_license
futureGroup511/CompeManager
https://github.com/futureGroup511/CompeManager
726250aba63386fc6af2275a52bf069220d1a0ec
8ec97027d28cdeb8c97e73bd851ad6ceeaf7fca4
refs/heads/master
2020-05-21T19:02:43.150000
2017-06-04T10:26:33
2017-06-04T10:26:33
65,434,938
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.future.dao; import com.future.domain.Admin; public interface TestDao { public void save(Admin admin); }
UTF-8
Java
120
java
TestDao.java
Java
[]
null
[]
package com.future.dao; import com.future.domain.Admin; public interface TestDao { public void save(Admin admin); }
120
0.758333
0.758333
8
14
13.96424
31
false
false
0
0
0
0
0
0
0.5
false
false
0
d1ddce7e4e9e5912739523c8c6464e061d1ed027
22,196,391,041,603
db68c6d8617a24b669e7bbfe209984905e0b45fe
/pms/src/main/java/com/zs/pms/controller/LoginController.java
f85f405e92841c02939fd7ec04c92afa1fd777c0
[]
no_license
EchoesC/gitCode
https://github.com/EchoesC/gitCode
7f6987747d799a791122af9942f19df045c5c9e7
99969074b199826c29e83df420c07f22c26b6272
refs/heads/master
2020-04-09T11:44:15.151000
2018-12-04T08:23:58
2018-12-04T08:35:41
160,322,085
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zs.pms.controller; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.zs.pms.exception.AppException; import com.zs.pms.po.TPermission; import com.zs.pms.po.TUser; import com.zs.pms.service.UserService; import com.zs.pms.vo.QueryUser; @Controller public class LoginController { @Autowired UserService us; @RequestMapping("/login.do") public String chkLogin(QueryUser user,String yanz,String online, ModelMap map,HttpSession session) { try { TUser tuser = us.chkLogin(user); List<TPermission> permission = tuser.getMenu(); //获取图片中验证码 String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (!yanz.equals(code)) { map.addAttribute("err","验证码错误,请重新输入"); return "login"; } map.addAttribute("user",tuser); session.setAttribute("CUSER", tuser); map.addAttribute("permission", permission); return "index"; } catch (AppException e) { map.addAttribute("err",e.getErrMsg()); return "login"; } } @RequestMapping("/tologin.do") public String toLogin(){ return "login"; } }
UTF-8
Java
1,454
java
LoginController.java
Java
[]
null
[]
package com.zs.pms.controller; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import com.zs.pms.exception.AppException; import com.zs.pms.po.TPermission; import com.zs.pms.po.TUser; import com.zs.pms.service.UserService; import com.zs.pms.vo.QueryUser; @Controller public class LoginController { @Autowired UserService us; @RequestMapping("/login.do") public String chkLogin(QueryUser user,String yanz,String online, ModelMap map,HttpSession session) { try { TUser tuser = us.chkLogin(user); List<TPermission> permission = tuser.getMenu(); //获取图片中验证码 String code = (String)session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY); if (!yanz.equals(code)) { map.addAttribute("err","验证码错误,请重新输入"); return "login"; } map.addAttribute("user",tuser); session.setAttribute("CUSER", tuser); map.addAttribute("permission", permission); return "index"; } catch (AppException e) { map.addAttribute("err",e.getErrMsg()); return "login"; } } @RequestMapping("/tologin.do") public String toLogin(){ return "login"; } }
1,454
0.714689
0.714689
52
25.23077
23.090637
101
false
false
0
0
0
0
0
0
1.903846
false
false
0
ebd6fe3031aaca1825f305d51e4568ea1b8d9253
23,493,471,170,165
6f8ad04cebb0895101046e97754689338f227494
/src/command/Client.java
d0f6e97327ae72549e446ce7f65536037a39eb9b
[]
no_license
PlumpMath/DesignPattern-639
https://github.com/PlumpMath/DesignPattern-639
0bbe71c47599ee08716fd493295f1583847226fe
0f45ae6cadcac03e7ac5278840f3b02b9fd81950
refs/heads/master
2021-01-20T09:42:21.059000
2016-08-29T13:18:14
2016-08-29T13:18:14
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package command; public class Client { public static void main(String[] args) { Television tv = new Television(); Command off= new CloseCommand(tv); Command open = new OpenCommand(tv); Command changeChannel = new ChangeChannel(tv); Controller controller = new Controller(open, off, changeChannel); controller.turnOn(); controller.changeChannel(); controller.turnOff(); } }
UTF-8
Java
395
java
Client.java
Java
[]
null
[]
package command; public class Client { public static void main(String[] args) { Television tv = new Television(); Command off= new CloseCommand(tv); Command open = new OpenCommand(tv); Command changeChannel = new ChangeChannel(tv); Controller controller = new Controller(open, off, changeChannel); controller.turnOn(); controller.changeChannel(); controller.turnOff(); } }
395
0.726582
0.726582
15
25.333334
18.792433
67
false
false
0
0
0
0
0
0
2.066667
false
false
0
ab59a33c5e9f377a3d7dee3617759275b8c4508b
6,098,853,624,737
fb3df40966782ab06967d06a0f9fdef94b6d038b
/LootCrates/src/com/pieter3457/lootcrates/util/CrateTracker.java
8d8918e13c911e1ffe7e718ee3791c05011338e5
[]
no_license
pieter3457/LootCrates
https://github.com/pieter3457/LootCrates
db011b85dd83ca9353081e34a631cfb49650282d
04524e43652948ca07332c00857e185e04eb5e68
refs/heads/master
2016-09-10T14:30:55.780000
2014-08-21T15:10:22
2014-08-21T15:10:22
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pieter3457.lootcrates.util; import java.util.HashMap; import java.util.UUID; public class CrateTracker { private static HashMap<UUID, Integer> itemsHeld = new HashMap<UUID, Integer>(); public static boolean hasLeft(UUID player) { return (itemsHeld.containsKey(player)); } public static int amount(UUID player) { if (hasLeft(player)) { return itemsHeld.get(player); } else { return 0; } } public static void remove(UUID player) { if (!(itemsHeld.get(player) - 1 > 0)) { itemsHeld.remove(player); } else { itemsHeld.put(player, itemsHeld.get(player) - 1); } } public static void addChest(UUID player) { if (itemsHeld.containsKey(player)) { itemsHeld.put(player, itemsHeld.get(player) + 1); } else { itemsHeld.put(player, 1); } } }
UTF-8
Java
832
java
CrateTracker.java
Java
[ { "context": "package com.pieter3457.lootcrates.util;\r\n\r\nimport java.util.HashMap;\r\nim", "end": 22, "score": 0.9959551692008972, "start": 12, "tag": "USERNAME", "value": "pieter3457" } ]
null
[]
package com.pieter3457.lootcrates.util; import java.util.HashMap; import java.util.UUID; public class CrateTracker { private static HashMap<UUID, Integer> itemsHeld = new HashMap<UUID, Integer>(); public static boolean hasLeft(UUID player) { return (itemsHeld.containsKey(player)); } public static int amount(UUID player) { if (hasLeft(player)) { return itemsHeld.get(player); } else { return 0; } } public static void remove(UUID player) { if (!(itemsHeld.get(player) - 1 > 0)) { itemsHeld.remove(player); } else { itemsHeld.put(player, itemsHeld.get(player) - 1); } } public static void addChest(UUID player) { if (itemsHeld.containsKey(player)) { itemsHeld.put(player, itemsHeld.get(player) + 1); } else { itemsHeld.put(player, 1); } } }
832
0.653846
0.641827
37
20.486486
20.305267
80
false
false
0
0
0
0
0
0
1.702703
false
false
0
a5fddf4dbe35d1fc4dde6967ca897f49bc5c451b
9,663,676,470,919
3b427f84b7092308b2012e974a54e41ee83b206e
/PronunciationMatch/app/src/main/java/com/pronunciation_match/pronunciationmatch/Phrase.java
ac360076bf0a532d91f0c15bd213f8515115188b
[]
no_license
dnacker/cs361group7
https://github.com/dnacker/cs361group7
da643a40d7271ac8300a0ddf0b1c1e063b6fefe1
0507878092000c5a834c48920d18cff7ee891311
refs/heads/master
2020-04-05T19:51:15.745000
2018-12-01T06:40:25
2018-12-01T06:40:25
157,153,497
0
3
null
false
2018-12-01T06:40:26
2018-11-12T03:51:56
2018-12-01T06:27:59
2018-12-01T06:40:25
2,323
0
3
0
Java
false
null
package com.pronunciation_match.pronunciationmatch; import android.content.Context; import java.util.LinkedList; import java.util.List; public class Phrase { private static final String TAG = Phrase.class.getSimpleName(); private PhonemeBank mPhonemeBank; private List<Phoneme> mPhonemes = new LinkedList<>(); /** * Constructs a phrase from text. * * The text is parsed according to the following schema: * * phonemetone phonemetone * * For example the word ní hǎo would be written: * * ni2 hao3 * * @param text */ public Phrase(String text, Context context) { mPhonemeBank = PhonemeBank.getInstance(context); String[] split = text.split(" "); for (int i = 0; i < split.length; i++) { String word = split[i].trim().toLowerCase(); int numIndex = word.length() - 1; char toneNumber = word.charAt(numIndex); word = word.substring(0, numIndex); Tone tone = Tone.getTone(toneNumber); Phoneme toAdd = mPhonemeBank.getPhoneme(word, tone); if (toAdd == null) { throw new IllegalArgumentException(String.format("Unable to parse %s", text)); } mPhonemes.add(toAdd); } } public List<Phoneme> getPhonemes() { return mPhonemes; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Phoneme p: mPhonemes) { stringBuilder.append(p); } return stringBuilder.toString(); } }
UTF-8
Java
1,658
java
Phrase.java
Java
[]
null
[]
package com.pronunciation_match.pronunciationmatch; import android.content.Context; import java.util.LinkedList; import java.util.List; public class Phrase { private static final String TAG = Phrase.class.getSimpleName(); private PhonemeBank mPhonemeBank; private List<Phoneme> mPhonemes = new LinkedList<>(); /** * Constructs a phrase from text. * * The text is parsed according to the following schema: * * phonemetone phonemetone * * For example the word ní hǎo would be written: * * ni2 hao3 * * @param text */ public Phrase(String text, Context context) { mPhonemeBank = PhonemeBank.getInstance(context); String[] split = text.split(" "); for (int i = 0; i < split.length; i++) { String word = split[i].trim().toLowerCase(); int numIndex = word.length() - 1; char toneNumber = word.charAt(numIndex); word = word.substring(0, numIndex); Tone tone = Tone.getTone(toneNumber); Phoneme toAdd = mPhonemeBank.getPhoneme(word, tone); if (toAdd == null) { throw new IllegalArgumentException(String.format("Unable to parse %s", text)); } mPhonemes.add(toAdd); } } public List<Phoneme> getPhonemes() { return mPhonemes; } public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Phoneme p: mPhonemes) { stringBuilder.append(p); } return stringBuilder.toString(); } }
1,658
0.578502
0.575483
54
28.666666
22.579899
94
false
false
0
0
0
0
0
0
0.5
false
false
0
e68fbc1dc554c442530bae6078757a619d4edddc
23,081,154,309,338
eba9d322368612c8597ae74ae389bb7c68f3921b
/prairie_dogs/src/main/java/jp/gushed/BaseMessageCnst.java
262f7b21a60d2066c4b56787b4c640f93a5c0b56
[]
no_license
onesword0618/prairie_dogs
https://github.com/onesword0618/prairie_dogs
10dd44e1b69c6a2bf2269acc7f69b542fec7b34f
75f57e5176b20ceba25e33c214c599ce2f4d82ba
refs/heads/master
2021-07-07T07:52:40.632000
2019-01-30T13:40:21
2019-01-30T13:40:21
140,086,300
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package jp.gushed; /** * 基底のメッセージクラス<br> * <p> * システムを運用する上で必要なメッセージのEnum定数クラス * * @author onesword0618 * */ public enum BaseMessageCnst implements MessageInterface{ // パラメタの値がありません notFindParams("パラメタの値がありません") // 正しい拡張子のファイル名ではありません , notCorrectTypeFile("正しい拡張子のファイルではありません") // 対象のリソースファイルは読み込むことができません , canNotReadTargetResourceFiles("対象のリソースファイルは読み込むことができません"); private final String msg; private BaseMessageCnst(String msg) { this.msg = msg; } /** * メッセージを出力する<br> * <p> * @return メッセージ */ public String getMessage() { return msg; } }
UTF-8
Java
897
java
BaseMessageCnst.java
Java
[ { "context": "p>\n * システムを運用する上で必要なメッセージのEnum定数クラス\n * \n * @author onesword0618\n *\n */\npublic enum BaseMessageCnst implements Mes", "end": 110, "score": 0.9995062947273254, "start": 98, "tag": "USERNAME", "value": "onesword0618" } ]
null
[]
package jp.gushed; /** * 基底のメッセージクラス<br> * <p> * システムを運用する上で必要なメッセージのEnum定数クラス * * @author onesword0618 * */ public enum BaseMessageCnst implements MessageInterface{ // パラメタの値がありません notFindParams("パラメタの値がありません") // 正しい拡張子のファイル名ではありません , notCorrectTypeFile("正しい拡張子のファイルではありません") // 対象のリソースファイルは読み込むことができません , canNotReadTargetResourceFiles("対象のリソースファイルは読み込むことができません"); private final String msg; private BaseMessageCnst(String msg) { this.msg = msg; } /** * メッセージを出力する<br> * <p> * @return メッセージ */ public String getMessage() { return msg; } }
897
0.715771
0.708839
35
15.514286
16.160572
61
false
false
0
0
0
0
0
0
0.771429
false
false
0
9a7995414d4b551e0243aa6b2847654dfdc8bb15
18,330,920,474,109
cfbd567f60c1deaddd57a05899f4587df13e699a
/src/Test2.java
48be22e17e0b691a0963e5f6e782f4bee1e1a977
[]
no_license
lwm9704/test2
https://github.com/lwm9704/test2
c741e1d6675496398410bafcaec978a9348b662a
cd9313f35712eaef50f7cbebec99aab58ecfd543
refs/heads/master
2021-03-26T00:46:30
2020-03-16T09:06:19
2020-03-16T09:06:19
247,659,874
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Test2 { public static void main(String[] args){ Test2 test1 = new Test2(); test1.sort1(); test1.sort2(); test1.merge(); test1.splicing(); test1.separate(); test1.count(); } /** * {1,23,6,74,8,19,104} 按 从小到大排序 */ public void sort1(){ int temp; int[] a = {1,23,6,74,8,19,104}; for(int i = 0;i < a.length-1;i++){ //冒泡排序 for(int j = 0;j < a.length-i-1;j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println("-------------数组练习一答案-------------"); for(int k = 0;k < a.length;k++) { System.out.print(a[k] + " "); } System.out.println(""); } /** * 2. 数组{1,2,3,4,5,5,5,5,5,6,7,8,9},去掉数组中的5 生成新的数组。 */ public void sort2(){ int[] b = {1,2,3,4,5,5,5,5,5,6,7,8,9}; int num = b.length; int cnt=0 ; int[] group = new int[num]; //根据数组b的长度来设置存储新数组的长度 System.out.println("-------------数组练习二答案-------------"); for(int i = 0;i < b.length;i++){ if(b[i] != 5){ //当数组b的元素不是5时存入新数组 group[cnt++] = b[i]; } } for(int k = 0; k < cnt-1; k++){ System.out.print(group[k]+" "); } System.out.println(""); } /** * 3. 数字 a{1,3,5,7,9} b{2,4,6,8,10},将两个数组合并,并按照从小到大的顺序排序 */ public void merge(){ int[] a = {1,3,5,7,9}; int[] b = {2,4,6,8,10}; int cnt = a.length; int num = a.length + b.length; int[] c = new int[num]; //根据数组a,b的长度设置合并后新数组的长度 int temp; for(int i = 0; i < a.length; i++){ //将数组a元素存入数组c c[i] = a[i]; } for(int k = 0;k < b.length; k++){ //将数组b元数存入数组c c[cnt++] = b[k]; } for(int i = 0;i < c.length-1;i++){ //冒泡排序 for(int j = 0;j < c.length-i-1;j++){ if(c[j] > c[j+1]){ temp = c[j]; c[j] = c[j+1]; c[j+1] = temp; } } } System.out.println("-------------数组练习三答案-------------"); for(int k = 0;k < c.length;k++) { System.out.print(c[k] + " "); } System.out.println(""); } /** * 4 字符串:“Hello World!”,在字符串前面拼接自己的名字 */ public void splicing(){ String myname = "梁维明"; String word = "Hello World!"; String newword = myname.concat(word); //用concat将两个字符串合并 System.out.println("-------------字符串操作练习一答案-------------"); System.out.println(newword); } /** * 5 字符串“1,2,3,4,5,6,7”,根据“,”分开,将其转化为字符串数组 */ public void separate(){ String a = "1,2,3,4,5,6,7"; String[] b = a.split(","); //用split将字符串分开 System.out.println("-------------字符串操作练习二答案-------------"); for(int i = 0;i < b.length;i++){ if(i==b.length-1){ System.out.println(b[i]); } else{ System.out.print(b[i]+" "); } } } /** * 6. 计算Hello World! 中出现了几次l */ public void count(){ int count=0; String a="Hello World!"; String[] b = a.split("l"); //用split将字符串分割 count=b.length-1; //通过分割的段数来推出字符串中含有l的次数 System.out.println("-------------字符串操作练习三答案-------------"); System.out.println(count); } }
UTF-8
Java
4,149
java
Test2.java
Java
[ { "context": " public void splicing(){\n String myname = \"梁维明\";\n String word = \"Hello World!\";\n S", "end": 2569, "score": 0.999809980392456, "start": 2566, "tag": "NAME", "value": "梁维明" } ]
null
[]
public class Test2 { public static void main(String[] args){ Test2 test1 = new Test2(); test1.sort1(); test1.sort2(); test1.merge(); test1.splicing(); test1.separate(); test1.count(); } /** * {1,23,6,74,8,19,104} 按 从小到大排序 */ public void sort1(){ int temp; int[] a = {1,23,6,74,8,19,104}; for(int i = 0;i < a.length-1;i++){ //冒泡排序 for(int j = 0;j < a.length-i-1;j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } System.out.println("-------------数组练习一答案-------------"); for(int k = 0;k < a.length;k++) { System.out.print(a[k] + " "); } System.out.println(""); } /** * 2. 数组{1,2,3,4,5,5,5,5,5,6,7,8,9},去掉数组中的5 生成新的数组。 */ public void sort2(){ int[] b = {1,2,3,4,5,5,5,5,5,6,7,8,9}; int num = b.length; int cnt=0 ; int[] group = new int[num]; //根据数组b的长度来设置存储新数组的长度 System.out.println("-------------数组练习二答案-------------"); for(int i = 0;i < b.length;i++){ if(b[i] != 5){ //当数组b的元素不是5时存入新数组 group[cnt++] = b[i]; } } for(int k = 0; k < cnt-1; k++){ System.out.print(group[k]+" "); } System.out.println(""); } /** * 3. 数字 a{1,3,5,7,9} b{2,4,6,8,10},将两个数组合并,并按照从小到大的顺序排序 */ public void merge(){ int[] a = {1,3,5,7,9}; int[] b = {2,4,6,8,10}; int cnt = a.length; int num = a.length + b.length; int[] c = new int[num]; //根据数组a,b的长度设置合并后新数组的长度 int temp; for(int i = 0; i < a.length; i++){ //将数组a元素存入数组c c[i] = a[i]; } for(int k = 0;k < b.length; k++){ //将数组b元数存入数组c c[cnt++] = b[k]; } for(int i = 0;i < c.length-1;i++){ //冒泡排序 for(int j = 0;j < c.length-i-1;j++){ if(c[j] > c[j+1]){ temp = c[j]; c[j] = c[j+1]; c[j+1] = temp; } } } System.out.println("-------------数组练习三答案-------------"); for(int k = 0;k < c.length;k++) { System.out.print(c[k] + " "); } System.out.println(""); } /** * 4 字符串:“Hello World!”,在字符串前面拼接自己的名字 */ public void splicing(){ String myname = "梁维明"; String word = "Hello World!"; String newword = myname.concat(word); //用concat将两个字符串合并 System.out.println("-------------字符串操作练习一答案-------------"); System.out.println(newword); } /** * 5 字符串“1,2,3,4,5,6,7”,根据“,”分开,将其转化为字符串数组 */ public void separate(){ String a = "1,2,3,4,5,6,7"; String[] b = a.split(","); //用split将字符串分开 System.out.println("-------------字符串操作练习二答案-------------"); for(int i = 0;i < b.length;i++){ if(i==b.length-1){ System.out.println(b[i]); } else{ System.out.print(b[i]+" "); } } } /** * 6. 计算Hello World! 中出现了几次l */ public void count(){ int count=0; String a="Hello World!"; String[] b = a.split("l"); //用split将字符串分割 count=b.length-1; //通过分割的段数来推出字符串中含有l的次数 System.out.println("-------------字符串操作练习三答案-------------"); System.out.println(count); } }
4,149
0.394074
0.356965
125
27.879999
18.690575
67
false
false
0
0
0
0
0
0
1.16
false
false
0
2ac16a1c4815b15ba67ec022febcd4ad5498fc77
16,939,351,082,378
4df8cf7d6d118f9aabdc20cab684269f1548ac02
/src/main/java/frc/robot/commands/WristStowed.java
f9e6fe7734212367d584ea44e2f0fd14eee971c6
[]
no_license
BobcatRobotics/DeepSpace-2020-port
https://github.com/BobcatRobotics/DeepSpace-2020-port
e42407b7668510f655606f0f76c465add91537bc
a0b4c65c0e8c65187f3438e4a4c2a5acaa34e940
refs/heads/master
2020-12-20T21:17:24.927000
2020-01-29T15:59:31
2020-01-29T15:59:31
236,212,403
2
1
null
false
2020-01-27T23:01:04
2020-01-25T18:35:11
2020-01-26T14:44:49
2020-01-27T23:01:03
128
2
0
0
Java
false
false
package frc.robot.commands; import edu.wpi.first.wpilibj.command.Command; import frc.robot.OI; public class WristStowed extends Command { boolean toggle = false; private CargoRollerInWrist cargoRollerInWrist; public WristStowed() { super(); requires(OI.wrist); } @Override protected void initialize() { // check the state, if 2, then run cargo in for 4 seconds if (OI.wrist.getWristState() == 2) { cargoRollerInWrist = new CargoRollerInWrist(); cargoRollerInWrist.start(); } OI.wrist.stow(); } @Override protected void execute() { // TODO update these once the wrist is more defined // Possibly extend to individual commands OI.wrist.stow(); } @Override protected boolean isFinished() { return true; } @Override protected void end() { OI.wrist.stow(); } @Override protected void interrupted() { OI.wrist.stow(); } }
UTF-8
Java
1,020
java
WristStowed.java
Java
[]
null
[]
package frc.robot.commands; import edu.wpi.first.wpilibj.command.Command; import frc.robot.OI; public class WristStowed extends Command { boolean toggle = false; private CargoRollerInWrist cargoRollerInWrist; public WristStowed() { super(); requires(OI.wrist); } @Override protected void initialize() { // check the state, if 2, then run cargo in for 4 seconds if (OI.wrist.getWristState() == 2) { cargoRollerInWrist = new CargoRollerInWrist(); cargoRollerInWrist.start(); } OI.wrist.stow(); } @Override protected void execute() { // TODO update these once the wrist is more defined // Possibly extend to individual commands OI.wrist.stow(); } @Override protected boolean isFinished() { return true; } @Override protected void end() { OI.wrist.stow(); } @Override protected void interrupted() { OI.wrist.stow(); } }
1,020
0.601961
0.59902
47
20.723404
18.130381
65
false
false
0
0
0
0
0
0
0.340426
false
false
0
628ff4b2ba6a94e44ef9b51fa8c1446cb81786eb
32,263,794,381,547
8e448d46ed98d3bef27efcb707d342b94b815102
/Serveur/src/Luminosite/YahooWeatherService.java
0a3ea02fa367fcb7c83a92eab7460cfaf7f7c1a9
[]
no_license
ThomasBertiere/SmartHouse
https://github.com/ThomasBertiere/SmartHouse
2f9ba7a6df699fa9ec940592db1a8a948f6390fb
71135710ca02f36f28ae9fd1e025cb3526857c9d
refs/heads/master
2021-06-24T08:55:45.307000
2017-07-22T22:26:25
2017-07-22T22:26:25
83,288,415
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Luminosite; import java.io.*; import java.net.*; import java.util.Scanner; import org.json.*; public class YahooWeatherService { private static String result; private static String addr; private static double longitude; private static double latitude; @SuppressWarnings("static-access") public YahooWeatherService(String _addr){ this.setResult(""); this.setAddr(_addr); this.setLongitude(0.0); this.setLatitude(0.0); } @SuppressWarnings("static-access") public String askWeather() throws IOException, JSONException{ try { String s = "http://maps.google.com/maps/api/geocode/json?" + "sensor=false&address="; s += URLEncoder.encode(this.addr, "UTF-8"); URL url = new URL(s); Scanner scan = new Scanner(url.openStream()); String str = new String(); while (scan.hasNext()) str += scan.nextLine(); scan.close(); JSONObject obj = new JSONObject(str); //Si la requête s'est bien passé, on a l'attribut status qui passe à OK dans la réponse JSON if (! obj.getString("status").equals("OK")){ return ""; } //getting longitude and latitude of given address JSONObject res = obj.getJSONArray("results").getJSONObject(0); this.setAddr((res.getString("formatted_address"))); JSONObject loc = res.getJSONObject("geometry").getJSONObject("location"); this.setLatitude(loc.getDouble("lat")); this.setLongitude(loc.getDouble("lng")); String meteo_url ="http://api.openweathermap.org/data/2.5/forecast?lat="+this.getLatitude()+"&lon="+this.getLongitude()+"&units=metric&APPID=54976f408a942655f0062c0e546c6312"; URL url_weather = new URL(meteo_url) ; //Id de Toulouse : 2972315 //Donne la météo toutes les 3h à partir de minuit pendant 5 jours (en comptant aujourd'hui) HttpURLConnection conn = (HttpURLConnection) url_weather.openConnection() ; conn.setRequestMethod("GET"); if(conn.getResponseCode()!=200) { // ON REGARDE SI LA REQUETE EST BIEN PASSÉ } BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())) ; String output=""; while((output = br.readLine()) != null) { result+=output; } conn.disconnect(); // get the first result corresponding to weather closest to current time JSONObject object = new JSONObject(this.result); JSONObject result_json = object.getJSONArray("list").getJSONObject(0); this.result=result_json.toString(); } catch (IOException e) { e.printStackTrace(); } return this.result; } public static String getResult() { return result; } public static void setResult(String result) { YahooWeatherService.result = result; } public static String getAddr() { return addr; } public static void setAddr(String addr) { YahooWeatherService.addr = addr; } public static double getLongitude() { return longitude; } public static void setLongitude(double longitude) { YahooWeatherService.longitude = longitude; } public static double getLatitude() { return latitude; } public static void setLatitude(double latitude) { YahooWeatherService.latitude = latitude; } }
UTF-8
Java
3,108
java
YahooWeatherService.java
Java
[]
null
[]
package Luminosite; import java.io.*; import java.net.*; import java.util.Scanner; import org.json.*; public class YahooWeatherService { private static String result; private static String addr; private static double longitude; private static double latitude; @SuppressWarnings("static-access") public YahooWeatherService(String _addr){ this.setResult(""); this.setAddr(_addr); this.setLongitude(0.0); this.setLatitude(0.0); } @SuppressWarnings("static-access") public String askWeather() throws IOException, JSONException{ try { String s = "http://maps.google.com/maps/api/geocode/json?" + "sensor=false&address="; s += URLEncoder.encode(this.addr, "UTF-8"); URL url = new URL(s); Scanner scan = new Scanner(url.openStream()); String str = new String(); while (scan.hasNext()) str += scan.nextLine(); scan.close(); JSONObject obj = new JSONObject(str); //Si la requête s'est bien passé, on a l'attribut status qui passe à OK dans la réponse JSON if (! obj.getString("status").equals("OK")){ return ""; } //getting longitude and latitude of given address JSONObject res = obj.getJSONArray("results").getJSONObject(0); this.setAddr((res.getString("formatted_address"))); JSONObject loc = res.getJSONObject("geometry").getJSONObject("location"); this.setLatitude(loc.getDouble("lat")); this.setLongitude(loc.getDouble("lng")); String meteo_url ="http://api.openweathermap.org/data/2.5/forecast?lat="+this.getLatitude()+"&lon="+this.getLongitude()+"&units=metric&APPID=54976f408a942655f0062c0e546c6312"; URL url_weather = new URL(meteo_url) ; //Id de Toulouse : 2972315 //Donne la météo toutes les 3h à partir de minuit pendant 5 jours (en comptant aujourd'hui) HttpURLConnection conn = (HttpURLConnection) url_weather.openConnection() ; conn.setRequestMethod("GET"); if(conn.getResponseCode()!=200) { // ON REGARDE SI LA REQUETE EST BIEN PASSÉ } BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())) ; String output=""; while((output = br.readLine()) != null) { result+=output; } conn.disconnect(); // get the first result corresponding to weather closest to current time JSONObject object = new JSONObject(this.result); JSONObject result_json = object.getJSONArray("list").getJSONObject(0); this.result=result_json.toString(); } catch (IOException e) { e.printStackTrace(); } return this.result; } public static String getResult() { return result; } public static void setResult(String result) { YahooWeatherService.result = result; } public static String getAddr() { return addr; } public static void setAddr(String addr) { YahooWeatherService.addr = addr; } public static double getLongitude() { return longitude; } public static void setLongitude(double longitude) { YahooWeatherService.longitude = longitude; } public static double getLatitude() { return latitude; } public static void setLatitude(double latitude) { YahooWeatherService.latitude = latitude; } }
3,108
0.709355
0.694194
112
26.678572
28.532003
178
false
false
0
0
0
0
0
0
2.017857
false
false
0
ff360bdb074d1748ff6b92adcaadf55891e06fcf
25,271,587,625,439
8824eca5f1219697c13af33be464e58db236dac7
/workspace/2021_01_23_a/src/白本継承01/Pug.java
7650634de3b49ff34e0c2d16b80ce8c9519de920
[]
no_license
KudoYumi/test
https://github.com/KudoYumi/test
774d019e6c38c28627823be7f3d5e404199f6315
3cb03a25ad5f591b5f832618468259922a5e4d5e
refs/heads/main
2023-04-02T04:41:42.467000
2021-03-29T15:08:21
2021-03-29T15:08:21
319,495,604
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package 白本継承01; public class Pug extends Dog{ public void walk() { System.out.println("pug is walk"); } }
UTF-8
Java
119
java
Pug.java
Java
[]
null
[]
package 白本継承01; public class Pug extends Dog{ public void walk() { System.out.println("pug is walk"); } }
119
0.684685
0.666667
7
14.857142
13.431611
36
false
false
0
0
0
0
0
0
0.857143
false
false
0
62e89eb7a9126120866d9c2269e064da5f4f1775
18,854,906,474,717
9770776de01fec391966dbcae7f467894209a57d
/oss-lib-common/src/main/java/cn/home1/oss/lib/common/crypto/Cryptos.java
d403d6c879c11e5ad50e16a3d145d924625d0be9
[ "MIT" ]
permissive
home1-oss/oss-lib
https://github.com/home1-oss/oss-lib
2c4ecd6e7237f97f445d02934c930c85bc32080a
d1bdb563970cf6dfffdd6c47f3f924456ee3c3e7
refs/heads/develop
2021-01-19T07:41:33.633000
2017-09-11T18:06:47
2017-09-11T18:06:47
87,564,690
1
7
null
true
2017-04-28T12:00:08
2017-04-07T16:14:25
2017-04-12T04:36:38
2017-04-28T12:00:08
11,280
1
2
0
Java
null
null
package cn.home1.oss.lib.common.crypto; import static cn.home1.oss.lib.common.crypto.CryptoConstants.ALGO_AES; import static cn.home1.oss.lib.common.crypto.CryptoConstants.ALGO_RSA; import static com.google.common.base.Preconditions.checkArgument; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.Provider; @Slf4j public abstract class Cryptos { private static final Provider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider(); private Cryptos() { } public static Provider provider() { return BOUNCY_CASTLE_PROVIDER; } @SuppressWarnings("unchecked") public static <T extends EncodeCipher> T cipher(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new Aes(Cryptos.provider(), keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new Rsa(Cryptos.provider(), keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new Jwt(keyExpression); } } if (result != null) { final String test = "test"; try { checkArgument(test.equals(result.decrypt(result.encrypt(test))), "bad cipher, test failed"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported cipher operation", ignored); } try { checkArgument(test.equals(result.decrypt(result.encrypt(test, 3600))), "bad cipher, test failed"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported cipher operation", ignored); } } return result; } @SuppressWarnings("unchecked") public static <T extends EncodeEncryptor> T encryptor(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new AesEncryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new RsaEncryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new JwtEncryptor(keyExpression); } } if (result != null) { try { result.encrypt("test"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported encryptor operation", ignored); } try { result.encrypt("test", 3600); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported encryptor operation", ignored); } } return result; } @SuppressWarnings("unchecked") public static <T extends EncodeDecryptor> T decryptor(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new AesDecryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new RsaDecryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new JwtDecryptor(keyExpression); } } return result; } }
UTF-8
Java
3,694
java
Cryptos.java
Java
[]
null
[]
package cn.home1.oss.lib.common.crypto; import static cn.home1.oss.lib.common.crypto.CryptoConstants.ALGO_AES; import static cn.home1.oss.lib.common.crypto.CryptoConstants.ALGO_RSA; import static com.google.common.base.Preconditions.checkArgument; import io.jsonwebtoken.SignatureAlgorithm; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.jce.provider.BouncyCastleProvider; import java.security.Provider; @Slf4j public abstract class Cryptos { private static final Provider BOUNCY_CASTLE_PROVIDER = new BouncyCastleProvider(); private Cryptos() { } public static Provider provider() { return BOUNCY_CASTLE_PROVIDER; } @SuppressWarnings("unchecked") public static <T extends EncodeCipher> T cipher(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new Aes(Cryptos.provider(), keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new Rsa(Cryptos.provider(), keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new Jwt(keyExpression); } } if (result != null) { final String test = "test"; try { checkArgument(test.equals(result.decrypt(result.encrypt(test))), "bad cipher, test failed"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported cipher operation", ignored); } try { checkArgument(test.equals(result.decrypt(result.encrypt(test, 3600))), "bad cipher, test failed"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported cipher operation", ignored); } } return result; } @SuppressWarnings("unchecked") public static <T extends EncodeEncryptor> T encryptor(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new AesEncryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new RsaEncryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new JwtEncryptor(keyExpression); } } if (result != null) { try { result.encrypt("test"); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported encryptor operation", ignored); } try { result.encrypt("test", 3600); } catch (final UnsupportedOperationException ignored) { // ignored log.trace("unsupported encryptor operation", ignored); } } return result; } @SuppressWarnings("unchecked") public static <T extends EncodeDecryptor> T decryptor(final KeyExpression keyExpression) { final T result; if (keyExpression == null || !keyExpression.isPresent()) { result = null; } else { final String spec = keyExpression.getSpec(); if (spec.startsWith(ALGO_AES)) { result = (T) new AesDecryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else if (spec.startsWith(ALGO_RSA)) { result = (T) new RsaDecryptor(BOUNCY_CASTLE_PROVIDER, keyExpression); } else { SignatureAlgorithm.forName(spec); result = (T) new JwtDecryptor(keyExpression); } } return result; } }
3,694
0.657282
0.653492
116
30.844828
27.333698
106
false
false
0
0
0
0
0
0
0.560345
false
false
0
80a418742dd4c87693fb4784a93696cbfedf8919
3,839,700,795,945
0f5063462542c1f9e9dc637ed91e98555f787073
/AnagramChecker/src/main/java/com/coding/anagrams/AnagramCheckerApplication.java
70d76146ccf5bbf4703fbaf9613aab5568cb41f1
[]
no_license
ramyakuppili1990/viafoura-final-project
https://github.com/ramyakuppili1990/viafoura-final-project
240fe7673270e0025b4de3e521806b3c1e16afaa
749bb8ea3245a278837cc213ae965a37e0bb2229
refs/heads/master
2022-09-25T08:57:20.725000
2020-06-02T21:01:56
2020-06-02T21:01:56
268,902,161
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.coding.anagrams; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AnagramCheckerApplication { public static void main(String[] args) { SpringApplication.run(AnagramCheckerApplication.class, args); } }
UTF-8
Java
328
java
AnagramCheckerApplication.java
Java
[]
null
[]
package com.coding.anagrams; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AnagramCheckerApplication { public static void main(String[] args) { SpringApplication.run(AnagramCheckerApplication.class, args); } }
328
0.829268
0.829268
13
24.23077
24.829121
68
false
false
0
0
0
0
0
0
0.692308
false
false
0
1eb7f365326e91748edaa35aa3c2659426f990b9
9,079,560,931,486
511e1f55ffffaaa21a58bf28aa25c891a737ab4c
/src/main/java/io/jenkins/plugins/cloudevents/model/Model.java
f528cd8938b2b59da4d159a87423584002ee664b
[ "MIT" ]
permissive
ShrutiC-git/cloudevents-plugin
https://github.com/ShrutiC-git/cloudevents-plugin
ae01e542a306d0b14e53ecf033b2442abaabf3ce
8207c5049272461bf9b7fb5dd3a67507a771e651
refs/heads/main
2023-07-23T13:05:17.525000
2021-09-06T09:49:01
2021-09-06T09:49:01
377,398,083
1
0
MIT
true
2021-09-06T09:49:02
2021-06-16T06:45:17
2021-07-29T04:42:38
2021-09-06T09:49:01
376
1
0
0
Java
false
false
package io.jenkins.plugins.cloudevents.model; /** * Interface to set the type and source for each CloudEvent. */ public interface Model { public String getType(); public String getSource(); }
UTF-8
Java
205
java
Model.java
Java
[]
null
[]
package io.jenkins.plugins.cloudevents.model; /** * Interface to set the type and source for each CloudEvent. */ public interface Model { public String getType(); public String getSource(); }
205
0.712195
0.712195
11
17.636364
20.186731
60
false
false
0
0
0
0
0
0
0.272727
false
false
0
38e39aff5978894e41778acd1f1073598fdbd02a
2,121,713,899,705
6ae4809fdbfee5d13022787d973a7b7bebe92c5f
/app/src/main/java/com/radicalninja/restoid/data/db/SqlResult.java
e6504a5e76773c6fce941d2b22ebaf2e1e15eaaf
[]
no_license
geeksunny/restoid
https://github.com/geeksunny/restoid
cd1d5f8f7b1c245d92c7768867770c1c1ab32802
9c0a3b3d25f434f58587e4cdf1b9891f9b480421
refs/heads/master
2020-05-21T00:08:48.556000
2015-07-09T04:51:16
2015-07-09T04:51:16
38,376,584
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.radicalninja.restoid.data.db; public enum SqlResult { CREATED, UPDATED, DELETED, NONE }
UTF-8
Java
117
java
SqlResult.java
Java
[]
null
[]
package com.radicalninja.restoid.data.db; public enum SqlResult { CREATED, UPDATED, DELETED, NONE }
117
0.675214
0.675214
8
13.625
12.358575
41
false
false
0
0
0
0
0
0
0.5
false
false
0
ac04dd54dedc18cc97ab4d4cfc4a13fd1f956418
19,430,432,102,768
714a7973ff58aea725ac053aa0436e8e62e8fae7
/src/oopHomeWork1/Entities/Program.java
bb62cec1d8b4ba05dfe2d4c54da0123109b2b26e
[]
no_license
mustafaylmaz/oopHomeWork1
https://github.com/mustafaylmaz/oopHomeWork1
a204c9093ffd92998f99441735dc2bea107a3522
f899f4bd7d55942632652c5d989f0f07bb84a064
refs/heads/main
2023-04-16T12:06:36.658000
2021-04-26T00:38:57
2021-04-26T00:38:57
361,570,923
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package oopHomeWork1.Entities; public class Program implements IEntity { public int ProgramId; public int Day; public String RecordName; public String RecordDescription; public boolean isActive; }
UTF-8
Java
203
java
Program.java
Java
[]
null
[]
package oopHomeWork1.Entities; public class Program implements IEntity { public int ProgramId; public int Day; public String RecordName; public String RecordDescription; public boolean isActive; }
203
0.807882
0.802956
9
21.555555
13.039351
41
false
false
0
0
0
0
0
0
1.222222
false
false
0
0b90baecc3269c366d6f42e73d7f16cfb60b03cd
24,816,321,073,893
fdb2b4f2ad5d41618afa5f88ee59bca6625cd8e1
/Login/ActionEvent1.java
0d2939506a7ed559b305e74f33a49de316fde6ca
[]
no_license
RabinMaharjan00/Java-swing
https://github.com/RabinMaharjan00/Java-swing
d0bf7a224b5e8186dfa5c45305f417a1d5d51f59
05f6ad3aeba2967137eb868325f5c71d29e555f8
refs/heads/master
2020-05-24T08:22:17.964000
2019-08-03T09:19:12
2019-08-03T09:19:12
187,183,390
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package Login; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTextField; class Myframe extends JFrame implements ActionListener { Container c; JTextField tf =new JTextField(); JComboBox cb; Myframe(){ c = this.getContentPane(); c.setLayout(null); Color[] clr = {Color.yellow,Color.red,Color.green}; cb = new JComboBox(clr); cb.addActionListener(this); cb.setBounds(100,200,300,50); c.add(cb); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // String text = tf.getText(); // String ntext = text.toUpperCase(); // tf.setText(ntext); // // Color cl = (Color)cb.getSelectedItem(); c.setBackground(cl); } } public class ActionEvent1 { public static void main(String[] args) { // TODO Auto-generated method stub Myframe frame = new Myframe(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100,150,600,500); } }
UTF-8
Java
1,167
java
ActionEvent1.java
Java
[]
null
[]
package Login; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTextField; class Myframe extends JFrame implements ActionListener { Container c; JTextField tf =new JTextField(); JComboBox cb; Myframe(){ c = this.getContentPane(); c.setLayout(null); Color[] clr = {Color.yellow,Color.red,Color.green}; cb = new JComboBox(clr); cb.addActionListener(this); cb.setBounds(100,200,300,50); c.add(cb); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub // String text = tf.getText(); // String ntext = text.toUpperCase(); // tf.setText(ntext); // // Color cl = (Color)cb.getSelectedItem(); c.setBackground(cl); } } public class ActionEvent1 { public static void main(String[] args) { // TODO Auto-generated method stub Myframe frame = new Myframe(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100,150,600,500); } }
1,167
0.681234
0.660668
54
19.611111
16.598099
55
false
false
0
0
0
0
0
0
1.62963
false
false
0
ecce54e9371631cb1edacf5ca7b1005623bb81e8
15,152,644,654,268
235210581f34ff78147f7933dcf760788dff711a
/rxhttp/src/main/java/rxhttp/wrapper/parse/MapParser.java
31d079ab5a8721718c1f490d905262793b44b2c5
[ "Apache-2.0" ]
permissive
username2magotan/okhttp-RxHttp
https://github.com/username2magotan/okhttp-RxHttp
fe3f82b386a51820971ef66c7c65c560d6211ddc
a22026a130af2957c6f92ce861f725d4c5d574f1
refs/heads/master
2020-12-07T10:17:40.116000
2019-12-30T14:38:10
2019-12-30T14:38:10
232,701,786
2
0
Apache-2.0
true
2020-01-09T02:11:38
2020-01-09T02:11:37
2020-01-09T02:01:56
2019-12-30T14:38:19
6,048
0
0
0
null
false
false
package rxhttp.wrapper.parse; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import okhttp3.Response; import rxhttp.wrapper.entity.ParameterizedTypeImpl; import rxhttp.wrapper.utils.TypeUtil; /** * 将Response对象解析成泛型Map对象 * User: ljx * Date: 2018/10/23 * Time: 13:49 */ public class MapParser<K, V> implements Parser<Map<K, V>> { private Type kType, vType; protected MapParser() { kType = TypeUtil.getActualTypeParameter(this.getClass(), 0); kType = TypeUtil.getActualTypeParameter(this.getClass(), 1); } private MapParser(Type kType, Type vType) { this.kType = kType; this.vType = vType; } public static <K, V> MapParser<K, V> get(Class<K> kType, Class<V> vType) { return new MapParser<>(kType, vType); } @Override public Map<K, V> onParse(Response response) throws IOException { final Type type = ParameterizedTypeImpl.getParameterized(Map.class, kType, vType); return convert(response, type); } }
UTF-8
Java
1,061
java
MapParser.java
Java
[ { "context": "s.TypeUtil;\n\n/**\n * 将Response对象解析成泛型Map对象\n * User: ljx\n * Date: 2018/10/23\n * Time: 13:49\n */\npublic cla", "end": 271, "score": 0.999543309211731, "start": 268, "tag": "USERNAME", "value": "ljx" } ]
null
[]
package rxhttp.wrapper.parse; import java.io.IOException; import java.lang.reflect.Type; import java.util.Map; import okhttp3.Response; import rxhttp.wrapper.entity.ParameterizedTypeImpl; import rxhttp.wrapper.utils.TypeUtil; /** * 将Response对象解析成泛型Map对象 * User: ljx * Date: 2018/10/23 * Time: 13:49 */ public class MapParser<K, V> implements Parser<Map<K, V>> { private Type kType, vType; protected MapParser() { kType = TypeUtil.getActualTypeParameter(this.getClass(), 0); kType = TypeUtil.getActualTypeParameter(this.getClass(), 1); } private MapParser(Type kType, Type vType) { this.kType = kType; this.vType = vType; } public static <K, V> MapParser<K, V> get(Class<K> kType, Class<V> vType) { return new MapParser<>(kType, vType); } @Override public Map<K, V> onParse(Response response) throws IOException { final Type type = ParameterizedTypeImpl.getParameterized(Map.class, kType, vType); return convert(response, type); } }
1,061
0.679155
0.664745
40
25.025
24.673353
90
false
false
0
0
0
0
0
0
0.725
false
false
12
d836fe6ed857268f38802a5c201d8c38acf7f869
22,797,686,450,519
2cd0dd3a6c68cb1b033901d27f4ccdcb0dbc29b0
/src/semanticAnalyzer/types/TypeVariable.java
a05602032081badf67db93f2eba02f60a834bb91
[]
no_license
brianpak/GrouseCompiler
https://github.com/brianpak/GrouseCompiler
3b0787a6958bae6937117fb221b484d6ad70620a
0a304c10d315d179adfcf2fbf27db1b91fd5e63b
refs/heads/master
2021-01-10T12:55:55.500000
2017-09-22T07:20:05
2017-09-22T07:20:05
49,410,889
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package semanticAnalyzer.types; public class TypeVariable implements Type { Type original; Type reference; public TypeVariable() { original = null; reference = null; } public int getSize() { return 0; } public String typeString() { return ""; } public boolean isReferenceType() { return false; } public Type getOriginal() { return original; } public Type getReference() { return reference; } public void restoreRef() { reference = original; //System.out.println(reference.typeString()); } public void reset() { reference = null; } public boolean match(Type type) { if (reference == null) { original = type; reference = type; return true; } else { boolean rtn = reference.match(type); restoreRef(); return rtn; } } }
UTF-8
Java
791
java
TypeVariable.java
Java
[]
null
[]
package semanticAnalyzer.types; public class TypeVariable implements Type { Type original; Type reference; public TypeVariable() { original = null; reference = null; } public int getSize() { return 0; } public String typeString() { return ""; } public boolean isReferenceType() { return false; } public Type getOriginal() { return original; } public Type getReference() { return reference; } public void restoreRef() { reference = original; //System.out.println(reference.typeString()); } public void reset() { reference = null; } public boolean match(Type type) { if (reference == null) { original = type; reference = type; return true; } else { boolean rtn = reference.match(type); restoreRef(); return rtn; } } }
791
0.659924
0.65866
48
15.479167
12.642504
47
false
false
0
0
0
0
0
0
1.854167
false
false
12
a939c289a0d3c3e2fd17c2014762713c2cd3d0cf
28,716,151,366,849
6348951b33c647693a2c8c63f8697b943baf499a
/WebApplicationTesting/src/com/BasicJava/VowelMatch.java
812031765bd5c1574c7596cf873b52058ae01485
[]
no_license
aniveditha/Testing
https://github.com/aniveditha/Testing
1bc34c6fcd3dd306639c68df41eb44ad9c2124cb
730265fa9b8d7c054f98457f300211b3f37f4e46
refs/heads/master
2022-12-24T06:25:01.733000
2020-05-06T03:10:12
2020-05-06T03:10:12
261,638,512
0
0
null
false
2020-10-13T21:46:29
2020-05-06T03:04:43
2020-05-06T03:15:56
2020-10-13T21:46:28
83,170
0
0
1
JavaScript
false
false
package com.BasicJava; public class VowelMatch { public static void main(String[] args) { char ch='o'; switch(ch) { case 'a': System.out.println("a is an vowel"); break; case 'e': System.out.println("e is an vowel"); break; case 'i': System.out.println("i is an vowel"); break; case 'o': System.out.println("o is an vowel"); break; case 'u': System.out.println("u is an vowel"); break; default: System.out.println("the given character is a consonant"); } } }
UTF-8
Java
503
java
VowelMatch.java
Java
[]
null
[]
package com.BasicJava; public class VowelMatch { public static void main(String[] args) { char ch='o'; switch(ch) { case 'a': System.out.println("a is an vowel"); break; case 'e': System.out.println("e is an vowel"); break; case 'i': System.out.println("i is an vowel"); break; case 'o': System.out.println("o is an vowel"); break; case 'u': System.out.println("u is an vowel"); break; default: System.out.println("the given character is a consonant"); } } }
503
0.630219
0.630219
26
18.346153
20.454344
68
false
false
0
0
0
0
0
0
1.961538
false
false
12
66755db4b672174e6df19f2887512784697ca2ef
11,338,713,720,407
63c4a8a840083c46d6239da0e2a720a6f5aa0e7a
/src/main/java/com/bruno/infra/repository/package-info.java
d9685f58eff83f115a1514f72dd412745ac243e9
[]
no_license
brunolsilva/infra
https://github.com/brunolsilva/infra
1128f7cc4e9024f5146659d1057ee8bc4990a9ff
215fff1459b33abf396f52822a902a1393175939
refs/heads/master
2021-01-16T19:36:45.484000
2017-08-13T14:31:19
2017-08-13T14:31:19
100,180,991
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * Spring Data JPA repositories. */ package com.bruno.infra.repository;
UTF-8
Java
77
java
package-info.java
Java
[]
null
[]
/** * Spring Data JPA repositories. */ package com.bruno.infra.repository;
77
0.714286
0.714286
4
18.25
15.28684
35
false
false
0
0
0
0
0
0
0.25
false
false
12
a51481e4416ae7616819ef1d85514abbd7eb4d64
20,040,317,406,158
93408941ff5990d3ae1dff2facfb7a0fa515c0e0
/service_client_common_src_business/com/path/bo/core/giftclass/GiftClassLookupBO.java
a72850cb519cdf2a32acc4b418ecdd7906e6c61e
[]
no_license
aleemkhowaja/imal_common_business_code
https://github.com/aleemkhowaja/imal_common_business_code
d210d4e585095d1a27ffb85912bc787eb5552a37
1b34da83d546ca1bad02788763dc927bcb3237b0
refs/heads/master
2023-02-17T09:58:24.419000
2021-01-11T07:10:34
2021-01-11T07:10:34
328,573,717
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.path.bo.core.giftclass; import java.util.List; import com.path.dbmaps.vo.CRM_PARAMVO; import com.path.lib.common.exception.BaseException; import com.path.vo.core.giftclass.GiftClassLookupSC; /** * * Copyright 2016, Path Solutions Path Solutions retains all ownership rights to * this source code * */ public interface GiftClassLookupBO { public int returnGiftClassLookupCount(GiftClassLookupSC criteria) throws BaseException; public List<CRM_PARAMVO> returnGiftClassLookup(GiftClassLookupSC criteria) throws BaseException; }
UTF-8
Java
574
java
GiftClassLookupBO.java
Java
[]
null
[]
package com.path.bo.core.giftclass; import java.util.List; import com.path.dbmaps.vo.CRM_PARAMVO; import com.path.lib.common.exception.BaseException; import com.path.vo.core.giftclass.GiftClassLookupSC; /** * * Copyright 2016, Path Solutions Path Solutions retains all ownership rights to * this source code * */ public interface GiftClassLookupBO { public int returnGiftClassLookupCount(GiftClassLookupSC criteria) throws BaseException; public List<CRM_PARAMVO> returnGiftClassLookup(GiftClassLookupSC criteria) throws BaseException; }
574
0.771777
0.764808
20
26.799999
31.881969
100
false
false
0
0
0
0
0
0
0.4
false
false
12
15e84f0f6a209010eef7886c3844dfee262f0db8
28,930,899,760,085
f92733be1f78c2c923e1b3a76804265e932f144b
/app/src/main/java/com/clauzon/clauzcliente/Clases/Repartidor.java
a20b54fa18a791710944d080fee890b2d16dca07
[]
no_license
valtitec19/Claudia_Z_Cliente
https://github.com/valtitec19/Claudia_Z_Cliente
a4be5de05dd3b5b96d7c7c59ea57cf138b2bbc61
1c07b49cadc8e8256a785ddb95601cbc21c5cb29
refs/heads/master
2022-11-30T00:19:46.258000
2020-08-06T04:01:11
2020-08-06T04:01:11
273,075,222
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.clauzon.clauzcliente.Clases; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Repartidor implements Serializable { private String nombre,apellidos,correo,telefono,id,fecha,genero,foto,direccion,horario_inicio,horario_fin; private Boolean estado; private List<String> entregas=new ArrayList<>(); private String token; public Repartidor() { } public Repartidor(String nombre, String apellidos, String correo, String telefono, String id, String fecha, String genero, Boolean estado,String foto,String direccion, String horario_inicio,String horario_fin, List<String> entregas,String token) { this.nombre = nombre; this.apellidos = apellidos; this.correo = correo; this.telefono = telefono; this.id = id; this.fecha = fecha; this.genero = genero; this.estado = estado; this.foto=foto; this.horario_inicio=horario_inicio; this.horario_fin=horario_fin; this.direccion=direccion; this.entregas=entregas; this.token=token; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public Boolean getEstado() { return estado; } public void setEstado(Boolean estado) { this.estado = estado; } public String getFoto() { return foto; } public void setFoto(String foto) { this.foto = foto; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getHorario_inicio() { return horario_inicio; } public void setHorario_inicio(String horario_inicio) { this.horario_inicio = horario_inicio; } public String getHorario_fin() { return horario_fin; } public void setHorario_fin(String horario_fin) { this.horario_fin = horario_fin; } public List<String> getEntregas() { return entregas; } public void setEntregas(List<String> entregas) { this.entregas = entregas; } public void addEntrega(String id_entrega){ entregas.add(id_entrega); } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
UTF-8
Java
3,303
java
Repartidor.java
Java
[]
null
[]
package com.clauzon.clauzcliente.Clases; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Repartidor implements Serializable { private String nombre,apellidos,correo,telefono,id,fecha,genero,foto,direccion,horario_inicio,horario_fin; private Boolean estado; private List<String> entregas=new ArrayList<>(); private String token; public Repartidor() { } public Repartidor(String nombre, String apellidos, String correo, String telefono, String id, String fecha, String genero, Boolean estado,String foto,String direccion, String horario_inicio,String horario_fin, List<String> entregas,String token) { this.nombre = nombre; this.apellidos = apellidos; this.correo = correo; this.telefono = telefono; this.id = id; this.fecha = fecha; this.genero = genero; this.estado = estado; this.foto=foto; this.horario_inicio=horario_inicio; this.horario_fin=horario_fin; this.direccion=direccion; this.entregas=entregas; this.token=token; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getApellidos() { return apellidos; } public void setApellidos(String apellidos) { this.apellidos = apellidos; } public String getCorreo() { return correo; } public void setCorreo(String correo) { this.correo = correo; } public String getTelefono() { return telefono; } public void setTelefono(String telefono) { this.telefono = telefono; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getGenero() { return genero; } public void setGenero(String genero) { this.genero = genero; } public Boolean getEstado() { return estado; } public void setEstado(Boolean estado) { this.estado = estado; } public String getFoto() { return foto; } public void setFoto(String foto) { this.foto = foto; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getHorario_inicio() { return horario_inicio; } public void setHorario_inicio(String horario_inicio) { this.horario_inicio = horario_inicio; } public String getHorario_fin() { return horario_fin; } public void setHorario_fin(String horario_fin) { this.horario_fin = horario_fin; } public List<String> getEntregas() { return entregas; } public void setEntregas(List<String> entregas) { this.entregas = entregas; } public void addEntrega(String id_entrega){ entregas.add(id_entrega); } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
3,303
0.61762
0.61762
148
21.317568
26.105824
251
false
false
0
0
0
0
0
0
0.5
false
false
12
139c463960e8f77b6a93b102f841445afc342b8e
30,339,649,031,957
494be16e37ea7b31e5a5522eace260b8529be7c1
/AddressBook/src/main/java/com/eaiti/addressBook/contact/ContactController.java
874a21c3cd9b9e53408a6b994ed99c8205260544
[]
no_license
shashank-raghunath15/AddressBook
https://github.com/shashank-raghunath15/AddressBook
e43c16b8f01a251ee23d2ca2703cdf5cc9b19e31
147e3a9868f2e0004507d5f6aff91c146f2dfa4b
refs/heads/master
2020-04-08T20:20:35.078000
2018-12-01T05:26:02
2018-12-01T05:26:02
159,695,119
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * ContactController handles REST endpoints for contacts */ package com.eaiti.addressBook.contact; import static spark.Spark.delete; import static spark.Spark.exception; import static spark.Spark.get; import static spark.Spark.post; import static spark.Spark.put; import java.util.List; import org.eclipse.jetty.http.HttpStatus; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchStatusException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.eaiti.addressBook.AddressBook; import com.eaiti.addressBook.exception.InvalidContactException; import com.eaiti.addressBook.exception.NotUniqueException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import spark.QueryParamsMap; /** * @author Shashank Raghunath * */ public class ContactController { public static final Logger LOGGER = LoggerFactory.getLogger(AddressBook.class); public ContactController(final ContactService service) { ObjectMapper mapper = new ObjectMapper(); get("/contact/:name", (request, response) -> { response.type("application/json"); Contact contact = service.getContactByName(request.params("name")); if (contact == null) { response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contact not found"); } response.status(HttpStatus.OK_200); return mapper.writeValueAsString(contact); }); get("/contact", (request, response) -> { response.type("application/json"); QueryParamsMap map = request.queryMap(); if (map.get("query").hasValue() && map.get("pageSize").hasValue() && map.get("page").hasValue()) { List<Contact> contacts = service.getContactByQuery(map.get("pageSize").integerValue(), map.get("page").integerValue(), map.get("query").value()); if (contacts != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(contacts); } response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contacts Not Found!"); } response.status(HttpStatus.BAD_REQUEST_400); return mapper.writeValueAsString("Bad Request! Parameters needed are pageSize, page and query"); }); post("/contact/", (request, response) -> { response.type("application/json"); response.status(HttpStatus.CREATED_201); return "\"" + service.saveContact(mapper.readValue(request.body(), Contact.class)) + "\""; }); put("/contact/:name", (request, response) -> { response.type("application/json"); String result = service.updateContact(mapper.readValue(request.body(), Contact.class), request.params("name")); if (result != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(result); } response.status(HttpStatus.NO_CONTENT_204); return mapper.writeValueAsString("Contact with name " + request.params("name") + " Not Found"); }); delete("/contact/:name", (request, response) -> { response.type("application/json"); String result = service.deleteContact(request.params("name")); if (result != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(result); } response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contact with name " + request.params("name") + " Not Found"); }); exception(UnrecognizedPropertyException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Contact has unrecognized fields\""); }); exception(NumberFormatException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Bad Query", exception); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Page Size and Page should be integers.\""); }); exception(ElasticsearchStatusException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Exception in ElasticSearch", exception); response.status(HttpStatus.NOT_FOUND_404); response.body("\"Contact not found.\""); }); exception(ElasticsearchException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Exception in ElasticSearch", exception); response.status(HttpStatus.INTERNAL_SERVER_ERROR_500); response.body("\"Internal Server Error. Please Contact System Administrator.\""); }); exception(NotUniqueException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Contact already exists", exception.getMessage()); response.status(HttpStatus.CONFLICT_409); response.body("\"Contact already exists\""); }); exception(InvalidContactException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact Values", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"" + exception.getMessage() + "\""); }); exception(MismatchedInputException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact Values", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Invalid Contact Values\""); }); } }
UTF-8
Java
5,607
java
ContactController.java
Java
[ { "context": "\n\r\nimport spark.QueryParamsMap;\r\n\r\n/**\r\n * @author Shashank Raghunath\r\n *\r\n */\r\npublic class ContactController {\r\n\r\n\tpu", "end": 950, "score": 0.9998761415481567, "start": 932, "tag": "NAME", "value": "Shashank Raghunath" } ]
null
[]
/** * ContactController handles REST endpoints for contacts */ package com.eaiti.addressBook.contact; import static spark.Spark.delete; import static spark.Spark.exception; import static spark.Spark.get; import static spark.Spark.post; import static spark.Spark.put; import java.util.List; import org.eclipse.jetty.http.HttpStatus; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchStatusException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.eaiti.addressBook.AddressBook; import com.eaiti.addressBook.exception.InvalidContactException; import com.eaiti.addressBook.exception.NotUniqueException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.exc.MismatchedInputException; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import spark.QueryParamsMap; /** * @author <NAME> * */ public class ContactController { public static final Logger LOGGER = LoggerFactory.getLogger(AddressBook.class); public ContactController(final ContactService service) { ObjectMapper mapper = new ObjectMapper(); get("/contact/:name", (request, response) -> { response.type("application/json"); Contact contact = service.getContactByName(request.params("name")); if (contact == null) { response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contact not found"); } response.status(HttpStatus.OK_200); return mapper.writeValueAsString(contact); }); get("/contact", (request, response) -> { response.type("application/json"); QueryParamsMap map = request.queryMap(); if (map.get("query").hasValue() && map.get("pageSize").hasValue() && map.get("page").hasValue()) { List<Contact> contacts = service.getContactByQuery(map.get("pageSize").integerValue(), map.get("page").integerValue(), map.get("query").value()); if (contacts != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(contacts); } response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contacts Not Found!"); } response.status(HttpStatus.BAD_REQUEST_400); return mapper.writeValueAsString("Bad Request! Parameters needed are pageSize, page and query"); }); post("/contact/", (request, response) -> { response.type("application/json"); response.status(HttpStatus.CREATED_201); return "\"" + service.saveContact(mapper.readValue(request.body(), Contact.class)) + "\""; }); put("/contact/:name", (request, response) -> { response.type("application/json"); String result = service.updateContact(mapper.readValue(request.body(), Contact.class), request.params("name")); if (result != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(result); } response.status(HttpStatus.NO_CONTENT_204); return mapper.writeValueAsString("Contact with name " + request.params("name") + " Not Found"); }); delete("/contact/:name", (request, response) -> { response.type("application/json"); String result = service.deleteContact(request.params("name")); if (result != null) { response.status(HttpStatus.OK_200); return mapper.writeValueAsString(result); } response.status(HttpStatus.NOT_FOUND_404); return mapper.writeValueAsString("Contact with name " + request.params("name") + " Not Found"); }); exception(UnrecognizedPropertyException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Contact has unrecognized fields\""); }); exception(NumberFormatException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Bad Query", exception); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Page Size and Page should be integers.\""); }); exception(ElasticsearchStatusException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Exception in ElasticSearch", exception); response.status(HttpStatus.NOT_FOUND_404); response.body("\"Contact not found.\""); }); exception(ElasticsearchException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Exception in ElasticSearch", exception); response.status(HttpStatus.INTERNAL_SERVER_ERROR_500); response.body("\"Internal Server Error. Please Contact System Administrator.\""); }); exception(NotUniqueException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Contact already exists", exception.getMessage()); response.status(HttpStatus.CONFLICT_409); response.body("\"Contact already exists\""); }); exception(InvalidContactException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact Values", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"" + exception.getMessage() + "\""); }); exception(MismatchedInputException.class, (exception, request, response) -> { response.type("application/json"); LOGGER.error("Invalid Contact Values", exception.getMessage()); response.status(HttpStatus.BAD_REQUEST_400); response.body("\"Invalid Contact Values\""); }); } }
5,595
0.709114
0.699661
139
38.338131
26.976824
101
false
false
0
0
0
0
0
0
3.007194
false
false
12
e06d2bccd994dd37eec5df6c956c6a590324fa5c
8,315,056,703,146
562b80e71b937d2e05cadef2b6deed3654bcf473
/src/main/java/com/yanglies/thread/ThreadDemo.java
d4449646b6c48a2d637ae4777eb95876ac244c61
[]
no_license
yangliiii/thread
https://github.com/yangliiii/thread
aca70caf912600f79cb56b95ab3f0493b6dd031b
5a7d2a28ce16a7f69a3783a56005ef2b5ab863d9
refs/heads/master
2021-05-08T19:11:16.774000
2018-01-30T15:41:21
2018-01-30T15:41:21
119,556,394
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.yanglies.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Administrator on 2018/1/30. */ public class ThreadDemo { // 怎样控制线程的执行顺序 static Thread thread1 = new Thread(new Runnable() { public void run() { System.out.println("thread1。。。"); } }); static Thread thread2 = new Thread(new Runnable() { public void run() { System.out.println("thread2。。。"); } }); static Thread thread3 = new Thread(new Runnable() { public void run() { System.out.println("thread3。。。"); } }); static ExecutorService executor = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { // thread1.start(); // thread1.join(); // thread2.start(); // thread2.join(); // thread3.start(); executor.execute(thread1); executor.execute(thread2); executor.execute(thread3); executor.shutdown(); } }
UTF-8
Java
1,122
java
ThreadDemo.java
Java
[ { "context": "java.util.concurrent.Executors;\n\n/**\n * Created by Administrator on 2018/1/30.\n */\npublic class ThreadDemo {\n\n ", "end": 146, "score": 0.9406905770301819, "start": 133, "tag": "NAME", "value": "Administrator" } ]
null
[]
package com.yanglies.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * Created by Administrator on 2018/1/30. */ public class ThreadDemo { // 怎样控制线程的执行顺序 static Thread thread1 = new Thread(new Runnable() { public void run() { System.out.println("thread1。。。"); } }); static Thread thread2 = new Thread(new Runnable() { public void run() { System.out.println("thread2。。。"); } }); static Thread thread3 = new Thread(new Runnable() { public void run() { System.out.println("thread3。。。"); } }); static ExecutorService executor = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws InterruptedException { // thread1.start(); // thread1.join(); // thread2.start(); // thread2.join(); // thread3.start(); executor.execute(thread1); executor.execute(thread2); executor.execute(thread3); executor.shutdown(); } }
1,122
0.592421
0.573013
43
24.16279
20.259859
74
false
false
0
0
0
0
0
0
0.44186
false
false
12
452489713c356e81b58c8468f6e86b4f015a00a3
11,261,404,265,701
fb333629967e82f88af213f648513d8ca72e866f
/common/src/main/java/com/nm/base/interfaces/Command.java
b7555af30967f03cae530fca2a260ea4e8dadbe3
[]
no_license
whuthm/WeBoth
https://github.com/whuthm/WeBoth
e1f006cfc2e086c3012dc057994f7979113eccba
18b640471b388d49e220e116a080183f35c4cb16
refs/heads/master
2021-01-11T07:48:37.218000
2016-11-02T10:26:09
2016-11-02T10:26:09
72,098,944
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.nm.base.interfaces; /** * Created by huangming on 2016/9/30. */ public interface Command { void execute(); void undo(); }
UTF-8
Java
149
java
Command.java
Java
[ { "context": "package com.nm.base.interfaces;\n\n/**\n * Created by huangming on 2016/9/30.\n */\n\npublic interface Command {\n\n ", "end": 60, "score": 0.9995608329772949, "start": 51, "tag": "USERNAME", "value": "huangming" } ]
null
[]
package com.nm.base.interfaces; /** * Created by huangming on 2016/9/30. */ public interface Command { void execute(); void undo(); }
149
0.630872
0.583893
13
10.461538
13.065606
37
false
false
0
0
0
0
0
0
0.230769
false
false
12
7e3bbc6b0bcc8ee9cbc7a5f9c53801aca9177b24
21,036,749,832,420
1eb8ff83998b741552208295b1c93942ac2bdc49
/app/src/main/java/com/zhq/exclusivememory/ui/activity/web_view/WebViewActivity.java
4b50f283f1a630320047bfaf089ef592ac0debc4
[]
no_license
zhq573524642/MyAndroidStudy
https://github.com/zhq573524642/MyAndroidStudy
c39e60b7dbbe0ae010678f8b854be5cc3070f346
7d1aa3114c5495e6d6afadaa74bbf75b1840816c
refs/heads/master
2022-11-05T17:32:34.162000
2020-06-23T13:12:34
2020-06-23T13:12:34
274,402,175
1
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.zhq.exclusivememory.ui.activity.web_view; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.JavascriptInterface; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.zhq.exclusivememory.R; import com.zhq.exclusivememory.base.BaseSimpleActivity; import com.zhq.exclusivememory.constant.Constant; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Huiqiang Zhang * on 2018/11/23. */ public class WebViewActivity extends BaseSimpleActivity { private static final int REQUEST_SELECT_ADDRESS = 1001; private static final int REQUEST_SELECT_SUPERIOR = 1002; @BindView(R.id.web_view) WebView mWebView; @BindView(R.id.rl_parent_layout) RelativeLayout mRlParentLayout; @BindView(R.id.tv_center_title) TextView mTvCenterTitle; @BindView(R.id.progress_bar) ProgressBar mProgressBar; private WebSettings mSettings; @SuppressLint("JavascriptInterface") @Override protected void initView() { final Intent intent = getIntent(); String url = intent.getStringExtra(Constant.WEB_PAGE_URL); String title = intent.getStringExtra(Constant.TITLE_NAME); mSettings = mWebView.getSettings(); mSettings.setJavaScriptEnabled(true);//开启与JavaScript交互 mSettings.setUseWideViewPort(true);//将图片调整到适合webview的大小 mSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小 mSettings.setSupportZoom(true);//设置支持缩放 mSettings.setDisplayZoomControls(false);//隐藏原生的缩放控件 mSettings.setAllowFileAccess(true);//设置可以访问文件 mSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); mSettings.setDomStorageEnabled(true); mSettings.setSaveFormData(true); mSettings.setSavePassword(true); mSettings.setGeolocationEnabled(true); mSettings.setBlockNetworkImage(false); // mSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } mSettings.setJavaScriptCanOpenWindowsAutomatically(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.setWebContentsDebuggingEnabled(true); } if (!TextUtils.isEmpty(title)) { mTvCenterTitle.setText(title); } if(!TextUtils.isEmpty(url)){ mWebView.loadUrl(url); } mWebView.setWebViewClient(new myWebClient()); mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if(mProgressBar!=null){ if (newProgress < 100) { mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setProgress(newProgress); } else { mProgressBar.setVisibility(View.GONE); mProgressBar.setProgress(newProgress); } } } }); } @Override protected int getLayoutResId() { return R.layout.activity_web_view; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //保存图片权限申请回调 } @Override protected void onResume() { mWebView.onResume(); mWebView.resumeTimers(); mSettings.setJavaScriptEnabled(true); super.onResume(); } @Override protected void onStop() { super.onStop(); mSettings.setJavaScriptEnabled(false); } @Override protected void onPause() { super.onPause(); mWebView.pauseTimers(); mWebView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); if (mWebView != null) { mRlParentLayout.removeView(mWebView); mWebView.destroy(); mWebView = null; } } @Override protected void initData() { } @OnClick(R.id.ll_left_back) public void onViewClicked(View view) { switch (view.getId()) { case R.id.ll_left_back: finish(); break; } } public class myWebClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
UTF-8
Java
6,902
java
WebViewActivity.java
Java
[ { "context": "e;\nimport butterknife.OnClick;\n\n\n/**\n * Created by Huiqiang Zhang\n * on 2018/11/23.\n */\n\npublic class WebViewActivi", "end": 1234, "score": 0.9998499751091003, "start": 1220, "tag": "NAME", "value": "Huiqiang Zhang" } ]
null
[]
package com.zhq.exclusivememory.ui.activity.web_view; import android.annotation.SuppressLint; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.KeyEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.webkit.JavascriptInterface; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.zhq.exclusivememory.R; import com.zhq.exclusivememory.base.BaseSimpleActivity; import com.zhq.exclusivememory.constant.Constant; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by <NAME> * on 2018/11/23. */ public class WebViewActivity extends BaseSimpleActivity { private static final int REQUEST_SELECT_ADDRESS = 1001; private static final int REQUEST_SELECT_SUPERIOR = 1002; @BindView(R.id.web_view) WebView mWebView; @BindView(R.id.rl_parent_layout) RelativeLayout mRlParentLayout; @BindView(R.id.tv_center_title) TextView mTvCenterTitle; @BindView(R.id.progress_bar) ProgressBar mProgressBar; private WebSettings mSettings; @SuppressLint("JavascriptInterface") @Override protected void initView() { final Intent intent = getIntent(); String url = intent.getStringExtra(Constant.WEB_PAGE_URL); String title = intent.getStringExtra(Constant.TITLE_NAME); mSettings = mWebView.getSettings(); mSettings.setJavaScriptEnabled(true);//开启与JavaScript交互 mSettings.setUseWideViewPort(true);//将图片调整到适合webview的大小 mSettings.setLoadWithOverviewMode(true);// 缩放至屏幕的大小 mSettings.setSupportZoom(true);//设置支持缩放 mSettings.setDisplayZoomControls(false);//隐藏原生的缩放控件 mSettings.setAllowFileAccess(true);//设置可以访问文件 mSettings.setRenderPriority(WebSettings.RenderPriority.HIGH); mSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); mSettings.setDomStorageEnabled(true); mSettings.setSaveFormData(true); mSettings.setSavePassword(true); mSettings.setGeolocationEnabled(true); mSettings.setBlockNetworkImage(false); // mSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { mSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } mSettings.setJavaScriptCanOpenWindowsAutomatically(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.setWebContentsDebuggingEnabled(true); } if (!TextUtils.isEmpty(title)) { mTvCenterTitle.setText(title); } if(!TextUtils.isEmpty(url)){ mWebView.loadUrl(url); } mWebView.setWebViewClient(new myWebClient()); mWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { if(mProgressBar!=null){ if (newProgress < 100) { mProgressBar.setVisibility(View.VISIBLE); mProgressBar.setProgress(newProgress); } else { mProgressBar.setVisibility(View.GONE); mProgressBar.setProgress(newProgress); } } } }); } @Override protected int getLayoutResId() { return R.layout.activity_web_view; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { //保存图片权限申请回调 } @Override protected void onResume() { mWebView.onResume(); mWebView.resumeTimers(); mSettings.setJavaScriptEnabled(true); super.onResume(); } @Override protected void onStop() { super.onStop(); mSettings.setJavaScriptEnabled(false); } @Override protected void onPause() { super.onPause(); mWebView.pauseTimers(); mWebView.onPause(); } @Override protected void onDestroy() { super.onDestroy(); if (mWebView != null) { mRlParentLayout.removeView(mWebView); mWebView.destroy(); mWebView = null; } } @Override protected void initData() { } @OnClick(R.id.ll_left_back) public void onViewClicked(View view) { switch (view.getId()) { case R.id.ll_left_back: finish(); break; } } public class myWebClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { // TODO Auto-generated method stub view.loadUrl(url); return false; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // TODO Auto-generated method stub super.onPageStarted(view, url, favicon); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); } @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public void onPageFinished(WebView view, String url) { // TODO Auto-generated method stub super.onPageFinished(view, url); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } }
6,894
0.653212
0.650265
232
28.258621
23.71549
121
false
false
0
0
0
0
0
0
0.5
false
false
12
463907767bc7ace9a2d3348e6bbffbb9b2bae13a
28,845,000,380,003
0065764cdcea450571908bce5862fa0201bc7483
/src/palmPrint/LoadForm.java
796e73b1640b11655078aa3548bc4b2434355e52
[]
no_license
kaushalkabra/Palmprint_Authentication
https://github.com/kaushalkabra/Palmprint_Authentication
01e95dc9aba8bb9ec2f1026e1df6fb5163a4408c
49c6f11f424fae4396c1cb65f01b3b70a22c4021
refs/heads/master
2021-01-17T15:58:19.348000
2017-03-06T20:49:01
2017-03-06T20:49:01
84,119,404
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 palmPrint; /** * * @author kaushal */ public class LoadForm { public LoadForm() { //compiled code throw new RuntimeException("Compiled Code"); } }
UTF-8
Java
299
java
LoadForm.java
Java
[ { "context": "r.\r\n */\r\npackage palmPrint;\r\n\r\n/**\r\n *\r\n * @author kaushal\r\n */\r\npublic class LoadForm {\r\n\r\n public LoadFor", "end": 153, "score": 0.9075645208358765, "start": 146, "tag": "USERNAME", "value": "kaushal" } ]
null
[]
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package palmPrint; /** * * @author kaushal */ public class LoadForm { public LoadForm() { //compiled code throw new RuntimeException("Compiled Code"); } }
299
0.598662
0.598662
17
15.705882
17.203846
52
false
false
0
0
0
0
0
0
0.235294
false
false
12
60b5519cde8a23340c9b73c406ece5905f090be4
24,481,313,625,831
f7a25da32609d722b7ac9220bf4694aa0476f7b2
/net/minecraft/advancements/critereon/FishingRodHookedTrigger.java
0cdb5971639072752536328b91dd007d11009891
[]
no_license
basaigh/temp
https://github.com/basaigh/temp
89e673227e951a7c282c50cce72236bdce4870dd
1c3091333f4edb2be6d986faaa026826b05008ab
refs/heads/master
2023-05-04T22:27:28.259000
2021-05-31T17:15:09
2021-05-31T17:15:09
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package net.minecraft.advancements.critereon; import java.util.List; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Set; import com.google.gson.JsonElement; import java.util.Iterator; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.advancements.CriterionTriggerInstance; import java.util.Collection; import net.minecraft.world.entity.fishing.FishingHook; import net.minecraft.world.item.ItemStack; import net.minecraft.server.level.ServerPlayer; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.common.collect.Maps; import net.minecraft.server.PlayerAdvancements; import java.util.Map; import net.minecraft.resources.ResourceLocation; import net.minecraft.advancements.CriterionTrigger; public class FishingRodHookedTrigger implements CriterionTrigger<TriggerInstance> { private static final ResourceLocation ID; private final Map<PlayerAdvancements, PlayerListeners> players; public FishingRodHookedTrigger() { this.players = (Map<PlayerAdvancements, PlayerListeners>)Maps.newHashMap(); } public ResourceLocation getId() { return FishingRodHookedTrigger.ID; } public void addPlayerListener(final PlayerAdvancements re, final Listener<TriggerInstance> a) { PlayerListeners a2 = (PlayerListeners)this.players.get(re); if (a2 == null) { a2 = new PlayerListeners(re); this.players.put(re, a2); } a2.addListener(a); } public void removePlayerListener(final PlayerAdvancements re, final Listener<TriggerInstance> a) { final PlayerListeners a2 = (PlayerListeners)this.players.get(re); if (a2 != null) { a2.removeListener(a); if (a2.isEmpty()) { this.players.remove(re); } } } public void removePlayerListeners(final PlayerAdvancements re) { this.players.remove(re); } public TriggerInstance createInstance(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext) { final ItemPredicate bc4 = ItemPredicate.fromJson(jsonObject.get("rod")); final EntityPredicate av5 = EntityPredicate.fromJson(jsonObject.get("entity")); final ItemPredicate bc5 = ItemPredicate.fromJson(jsonObject.get("item")); return new TriggerInstance(bc4, av5, bc5); } public void trigger(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { final PlayerListeners a6 = (PlayerListeners)this.players.get(vl.getAdvancements()); if (a6 != null) { a6.trigger(vl, bcj, ats, collection); } } static { ID = new ResourceLocation("fishing_rod_hooked"); } public static class TriggerInstance extends AbstractCriterionTriggerInstance { private final ItemPredicate rod; private final EntityPredicate entity; private final ItemPredicate item; public TriggerInstance(final ItemPredicate bc1, final EntityPredicate av, final ItemPredicate bc3) { super(FishingRodHookedTrigger.ID); this.rod = bc1; this.entity = av; this.item = bc3; } public static TriggerInstance fishedItem(final ItemPredicate bc1, final EntityPredicate av, final ItemPredicate bc3) { return new TriggerInstance(bc1, av, bc3); } public boolean matches(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { if (!this.rod.matches(bcj)) { return false; } if (!this.entity.matches(vl, ats.hookedIn)) { return false; } if (this.item != ItemPredicate.ANY) { boolean boolean6 = false; if (ats.hookedIn instanceof ItemEntity) { final ItemEntity atx7 = (ItemEntity)ats.hookedIn; if (this.item.matches(atx7.getItem())) { boolean6 = true; } } for (final ItemStack bcj2 : collection) { if (this.item.matches(bcj2)) { boolean6 = true; break; } } if (!boolean6) { return false; } } return true; } public JsonElement serializeToJson() { final JsonObject jsonObject2 = new JsonObject(); jsonObject2.add("rod", this.rod.serializeToJson()); jsonObject2.add("entity", this.entity.serializeToJson()); jsonObject2.add("item", this.item.serializeToJson()); return (JsonElement)jsonObject2; } } static class PlayerListeners { private final PlayerAdvancements player; private final Set<Listener<TriggerInstance>> listeners; public PlayerListeners(final PlayerAdvancements re) { this.listeners = (Set<Listener<TriggerInstance>>)Sets.newHashSet(); this.player = re; } public boolean isEmpty() { return this.listeners.isEmpty(); } public void addListener(final Listener<TriggerInstance> a) { this.listeners.add(a); } public void removeListener(final Listener<TriggerInstance> a) { this.listeners.remove(a); } public void trigger(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { List<Listener<TriggerInstance>> list6 = null; for (final Listener<TriggerInstance> a8 : this.listeners) { if (a8.getTriggerInstance().matches(vl, bcj, ats, collection)) { if (list6 == null) { list6 = (List<Listener<TriggerInstance>>)Lists.newArrayList(); } list6.add(a8); } } if (list6 != null) { for (final Listener<TriggerInstance> a8 : list6) { a8.run(this.player); } } } } }
UTF-8
Java
6,442
java
FishingRodHookedTrigger.java
Java
[]
null
[]
package net.minecraft.advancements.critereon; import java.util.List; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Set; import com.google.gson.JsonElement; import java.util.Iterator; import net.minecraft.world.entity.item.ItemEntity; import net.minecraft.advancements.CriterionTriggerInstance; import java.util.Collection; import net.minecraft.world.entity.fishing.FishingHook; import net.minecraft.world.item.ItemStack; import net.minecraft.server.level.ServerPlayer; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.common.collect.Maps; import net.minecraft.server.PlayerAdvancements; import java.util.Map; import net.minecraft.resources.ResourceLocation; import net.minecraft.advancements.CriterionTrigger; public class FishingRodHookedTrigger implements CriterionTrigger<TriggerInstance> { private static final ResourceLocation ID; private final Map<PlayerAdvancements, PlayerListeners> players; public FishingRodHookedTrigger() { this.players = (Map<PlayerAdvancements, PlayerListeners>)Maps.newHashMap(); } public ResourceLocation getId() { return FishingRodHookedTrigger.ID; } public void addPlayerListener(final PlayerAdvancements re, final Listener<TriggerInstance> a) { PlayerListeners a2 = (PlayerListeners)this.players.get(re); if (a2 == null) { a2 = new PlayerListeners(re); this.players.put(re, a2); } a2.addListener(a); } public void removePlayerListener(final PlayerAdvancements re, final Listener<TriggerInstance> a) { final PlayerListeners a2 = (PlayerListeners)this.players.get(re); if (a2 != null) { a2.removeListener(a); if (a2.isEmpty()) { this.players.remove(re); } } } public void removePlayerListeners(final PlayerAdvancements re) { this.players.remove(re); } public TriggerInstance createInstance(final JsonObject jsonObject, final JsonDeserializationContext jsonDeserializationContext) { final ItemPredicate bc4 = ItemPredicate.fromJson(jsonObject.get("rod")); final EntityPredicate av5 = EntityPredicate.fromJson(jsonObject.get("entity")); final ItemPredicate bc5 = ItemPredicate.fromJson(jsonObject.get("item")); return new TriggerInstance(bc4, av5, bc5); } public void trigger(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { final PlayerListeners a6 = (PlayerListeners)this.players.get(vl.getAdvancements()); if (a6 != null) { a6.trigger(vl, bcj, ats, collection); } } static { ID = new ResourceLocation("fishing_rod_hooked"); } public static class TriggerInstance extends AbstractCriterionTriggerInstance { private final ItemPredicate rod; private final EntityPredicate entity; private final ItemPredicate item; public TriggerInstance(final ItemPredicate bc1, final EntityPredicate av, final ItemPredicate bc3) { super(FishingRodHookedTrigger.ID); this.rod = bc1; this.entity = av; this.item = bc3; } public static TriggerInstance fishedItem(final ItemPredicate bc1, final EntityPredicate av, final ItemPredicate bc3) { return new TriggerInstance(bc1, av, bc3); } public boolean matches(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { if (!this.rod.matches(bcj)) { return false; } if (!this.entity.matches(vl, ats.hookedIn)) { return false; } if (this.item != ItemPredicate.ANY) { boolean boolean6 = false; if (ats.hookedIn instanceof ItemEntity) { final ItemEntity atx7 = (ItemEntity)ats.hookedIn; if (this.item.matches(atx7.getItem())) { boolean6 = true; } } for (final ItemStack bcj2 : collection) { if (this.item.matches(bcj2)) { boolean6 = true; break; } } if (!boolean6) { return false; } } return true; } public JsonElement serializeToJson() { final JsonObject jsonObject2 = new JsonObject(); jsonObject2.add("rod", this.rod.serializeToJson()); jsonObject2.add("entity", this.entity.serializeToJson()); jsonObject2.add("item", this.item.serializeToJson()); return (JsonElement)jsonObject2; } } static class PlayerListeners { private final PlayerAdvancements player; private final Set<Listener<TriggerInstance>> listeners; public PlayerListeners(final PlayerAdvancements re) { this.listeners = (Set<Listener<TriggerInstance>>)Sets.newHashSet(); this.player = re; } public boolean isEmpty() { return this.listeners.isEmpty(); } public void addListener(final Listener<TriggerInstance> a) { this.listeners.add(a); } public void removeListener(final Listener<TriggerInstance> a) { this.listeners.remove(a); } public void trigger(final ServerPlayer vl, final ItemStack bcj, final FishingHook ats, final Collection<ItemStack> collection) { List<Listener<TriggerInstance>> list6 = null; for (final Listener<TriggerInstance> a8 : this.listeners) { if (a8.getTriggerInstance().matches(vl, bcj, ats, collection)) { if (list6 == null) { list6 = (List<Listener<TriggerInstance>>)Lists.newArrayList(); } list6.add(a8); } } if (list6 != null) { for (final Listener<TriggerInstance> a8 : list6) { a8.run(this.player); } } } } }
6,442
0.609904
0.602142
167
37.574852
30.112644
139
false
false
0
0
0
0
0
0
0.628743
false
false
12
938b3acf192aff00e65fcc49fafa2274cb85984d
32,710,470,963,763
d6b6abe73a0c82656b04875135b4888c644d2557
/sources/com/google/firebase/messaging/a.java
39e2ed49840b109e6905b732ab97a32af2c46816
[]
no_license
chanyaz/and_unimed
https://github.com/chanyaz/and_unimed
4344d1a8ce8cb13b6880ca86199de674d770304b
fb74c460f8c536c16cca4900da561c78c7035972
refs/heads/master
2020-03-29T09:07:09.224000
2018-08-30T06:29:32
2018-08-30T06:29:32
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.google.firebase.messaging; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import java.util.regex.Pattern; public class a { private static final Pattern a = Pattern.compile("[a-zA-Z0-9-_.~%]{1,900}"); private static a b; private final FirebaseInstanceId c; private a(FirebaseInstanceId firebaseInstanceId) { this.c = firebaseInstanceId; } public static synchronized a a() { a aVar; synchronized (a.class) { if (b == null) { b = new a(FirebaseInstanceId.a()); } aVar = b; } return aVar; } public void a(String str) { Object str2; if (str2 != null && str2.startsWith("/topics/")) { Log.w("FirebaseMessaging", "Format /topics/topic-name is deprecated. Only 'topic-name' should be used in subscribeToTopic."); str2 = str2.substring(8); } if (str2 == null || !a.matcher(str2).matches()) { throw new IllegalArgumentException(new StringBuilder(String.valueOf(str2).length() + 78).append("Invalid topic name: ").append(str2).append(" does not match the allowed format [a-zA-Z0-9-_.~%]{1,900}").toString()); } FirebaseInstanceId firebaseInstanceId = this.c; String valueOf = String.valueOf("S!"); String valueOf2 = String.valueOf(str2); firebaseInstanceId.a(valueOf2.length() != 0 ? valueOf.concat(valueOf2) : new String(valueOf)); } }
UTF-8
Java
1,508
java
a.java
Java
[]
null
[]
package com.google.firebase.messaging; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import java.util.regex.Pattern; public class a { private static final Pattern a = Pattern.compile("[a-zA-Z0-9-_.~%]{1,900}"); private static a b; private final FirebaseInstanceId c; private a(FirebaseInstanceId firebaseInstanceId) { this.c = firebaseInstanceId; } public static synchronized a a() { a aVar; synchronized (a.class) { if (b == null) { b = new a(FirebaseInstanceId.a()); } aVar = b; } return aVar; } public void a(String str) { Object str2; if (str2 != null && str2.startsWith("/topics/")) { Log.w("FirebaseMessaging", "Format /topics/topic-name is deprecated. Only 'topic-name' should be used in subscribeToTopic."); str2 = str2.substring(8); } if (str2 == null || !a.matcher(str2).matches()) { throw new IllegalArgumentException(new StringBuilder(String.valueOf(str2).length() + 78).append("Invalid topic name: ").append(str2).append(" does not match the allowed format [a-zA-Z0-9-_.~%]{1,900}").toString()); } FirebaseInstanceId firebaseInstanceId = this.c; String valueOf = String.valueOf("S!"); String valueOf2 = String.valueOf(str2); firebaseInstanceId.a(valueOf2.length() != 0 ? valueOf.concat(valueOf2) : new String(valueOf)); } }
1,508
0.612732
0.593501
41
35.780487
41.366013
226
false
false
0
0
0
0
0
0
0.609756
false
false
12
a72ab40fb946d26156f59bdb29fe4aaf79bb748d
4,569,845,203,729
51c7c78f7232b1589d4c78de1fcf69c90ef06a38
/src/main/java/com/cyngn/chrono/api/Report.java
7453aeead947d3a745d506cd362e18c51f16b22d
[ "Apache-2.0" ]
permissive
cyngn/ChronoServer
https://github.com/cyngn/ChronoServer
6f62ddb829bc8d6b973315f2ea70fc9d1feb3046
dd4b52e3cfa10c8eafc9143c7c2408c671214b05
refs/heads/master
2021-01-01T05:36:27.781000
2016-03-22T18:28:03
2016-03-22T18:28:03
41,709,313
3
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.cyngn.chrono.api; import com.cyngn.chrono.http.CacheUtil; import com.cyngn.chrono.storage.ReportStorage; import com.cyngn.chrono.storage.entity.MetricReport; import com.cyngn.vertx.web.HttpHelper; import com.cyngn.vertx.web.RestApi; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.RoutingContext; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The API to support the client app reporting timing data back to us. * * @author truelove@cyngn.com (Jeremy Truelove) 9/11/14 */ public class Report implements RestApi { private static final Logger logger = LoggerFactory.getLogger(Report.class); public final static String REPORT_API_V1 = "/api/v1/report"; private final RestApiDescriptor [] supportApi = {new RestApi.RestApiDescriptor(HttpMethod.POST, REPORT_API_V1, this::add)}; private final ReportStorage storage; public Report(ReportStorage storage) { this.storage = storage; } /** * Adds a api measurement to our reporting store */ protected void add(RoutingContext context) { HttpServerRequest request = context.request(); HttpServerResponse response = context.response(); request.bodyHandler(body -> { MetricReport report = HttpHelper.attemptToParse(body.toString(), MetricReport.class, request.response()); if(isValidRequest(report)) { report.created = DateTime.now(DateTimeZone.UTC).toDate(); report.client_ip = context.request().remoteAddress().host(); logger.info("add - report: {}", report); storage.createReport(report, success -> { if(success) { CacheUtil.setNoCacheHeaders(response.headers()); HttpHelper.processResponse(response); } else { HttpHelper.processErrorResponse("Failed to persist report to DB", response, HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } }); } else { HttpHelper.processErrorResponse("Invalid report", response, HttpResponseStatus.BAD_REQUEST.code()); } }); } private boolean isValidRequest(MetricReport data) { return data != null && StringUtils.isNotEmpty(data.deviceId) && data.measurements != null && data.measurements.size() > 0; } @Override public RestApiDescriptor[] supportedApi() { return supportApi; } }
UTF-8
Java
2,810
java
Report.java
Java
[ { "context": "pp reporting timing data back to us.\n *\n * @author truelove@cyngn.com (Jeremy Truelove) 9/11/14\n */\npublic class Report", "end": 745, "score": 0.9999324083328247, "start": 727, "tag": "EMAIL", "value": "truelove@cyngn.com" }, { "context": "ata back to us.\n *\n * @author truelove@cyngn.com (Jeremy Truelove) 9/11/14\n */\npublic class Report implements RestA", "end": 762, "score": 0.9998795390129089, "start": 747, "tag": "NAME", "value": "Jeremy Truelove" } ]
null
[]
package com.cyngn.chrono.api; import com.cyngn.chrono.http.CacheUtil; import com.cyngn.chrono.storage.ReportStorage; import com.cyngn.chrono.storage.entity.MetricReport; import com.cyngn.vertx.web.HttpHelper; import com.cyngn.vertx.web.RestApi; import io.netty.handler.codec.http.HttpResponseStatus; import io.vertx.core.http.HttpMethod; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.http.HttpServerResponse; import io.vertx.ext.web.RoutingContext; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The API to support the client app reporting timing data back to us. * * @author <EMAIL> (<NAME>) 9/11/14 */ public class Report implements RestApi { private static final Logger logger = LoggerFactory.getLogger(Report.class); public final static String REPORT_API_V1 = "/api/v1/report"; private final RestApiDescriptor [] supportApi = {new RestApi.RestApiDescriptor(HttpMethod.POST, REPORT_API_V1, this::add)}; private final ReportStorage storage; public Report(ReportStorage storage) { this.storage = storage; } /** * Adds a api measurement to our reporting store */ protected void add(RoutingContext context) { HttpServerRequest request = context.request(); HttpServerResponse response = context.response(); request.bodyHandler(body -> { MetricReport report = HttpHelper.attemptToParse(body.toString(), MetricReport.class, request.response()); if(isValidRequest(report)) { report.created = DateTime.now(DateTimeZone.UTC).toDate(); report.client_ip = context.request().remoteAddress().host(); logger.info("add - report: {}", report); storage.createReport(report, success -> { if(success) { CacheUtil.setNoCacheHeaders(response.headers()); HttpHelper.processResponse(response); } else { HttpHelper.processErrorResponse("Failed to persist report to DB", response, HttpResponseStatus.INTERNAL_SERVER_ERROR.code()); } }); } else { HttpHelper.processErrorResponse("Invalid report", response, HttpResponseStatus.BAD_REQUEST.code()); } }); } private boolean isValidRequest(MetricReport data) { return data != null && StringUtils.isNotEmpty(data.deviceId) && data.measurements != null && data.measurements.size() > 0; } @Override public RestApiDescriptor[] supportedApi() { return supportApi; } }
2,790
0.65694
0.653025
74
36.972973
30.328371
127
false
false
0
0
0
0
0
0
0.608108
false
false
12
a49d9f3b83363bc72c994657836b6ff415c5a86b
12,463,995,142,799
a62008c8485e048833237264ce1de6b97e686cee
/src/LieDetector/LieMachine.java
92c4a3702db1bd0a62306ae28a51073243bf64b0
[]
no_license
akhlul/liedetector-analisis
https://github.com/akhlul/liedetector-analisis
c9382f1e46e4d965262596e3fd95afbd440fc757
07a5f560db91e601da4f582c3d9d98e6b966ff31
refs/heads/master
2016-09-10T20:48:58.902000
2015-04-18T14:07:03
2015-04-18T14:07:03
34,120,005
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package LieDetector; /** * * @author Kahrom */ public class LieMachine { public static void main(String[] args) throws IndexOutOfBoundsException { Analisis A01 = new Analisis("Alat Tes Kebohongan 1", ""); Analisis A02 = new Analisis("Alat Tes Kebohongan 2", ""); Peserta S01 = new Peserta("pes01", "Sanni"); Peserta S02 = new Peserta("pes02", "Ridman"); Peserta S03 = new Peserta("pes03", "Orelo"); A01.addseseorang(S01); A01.addseseorang(S02); A02.addseseorang(S03); // reaksi fisiologis ketika berbohong RF Ref00 = new RF(true, true, false, false); RF Ref01 = new RF(true, true, false, true); // reaksi fisiologis ketika jujur RF Ref02 = new RF(true, false, false, false); RF Ref03 = new RF(false, false, false, false); Jawaban Ans01 = new Jawaban("01001a", "Saine", Ref01); Pertanyaan P01 = new Pertanyaan("01001", "Siapa nama Anda", Ans01); Jawaban Ans02 = new Jawaban("101002a", "Ridman", Ref02); Pertanyaan P02 = new Pertanyaan("101002", "Siapa nama Anda", Ans02); Jawaban Ans03 = new Jawaban("201001a", "Orelo", Ref03); Pertanyaan P03 = new Pertanyaan("201001", "Siapa nama Anda", Ans03); Jawaban Ans03_2 = new Jawaban("201001a", "Mathilda", Ref00); Pertanyaan P03_2 = new Pertanyaan("201001", "Siapa nama Ibu Anda", Ans03_2); S01.addpertanyaaan(P01); S02.addpertanyaaan(P02); S03.addpertanyaaan(P03); S03.addpertanyaaan(P03_2); String Kata = "" + "Dalam dua buah tes menggunakan alat kebohongan, tiga orang responden " + "akan menjadi peserta uji alat kebohongan yaitu sebagai berikut : " + "\n - " + S01.namaPeserta + "\n - " + S02.namaPeserta + "\n - " + S03.namaPeserta + "\n\n" + "Berikut ini adalah hasil analisa dari percobaan tes kebohongan ini ::\n\n"; System.out.println(Kata); OutputAnalisa(A01); OutputAnalisa(A02); // System.out.println(A02.seseorang.get(0).pertanyaandiajukan.size()); // System.out.println(A02.seseorang.get(0).pertanyaandiajukan.get(1).isi_pertanyaan); } public static void OutputAnalisa(Analisis AA) { StringBuffer x = new StringBuffer(); x.append(AA.namaanalisis + "\n >> " + AA.ttg_analisis ); for(int i = 0; i < AA.seseorang.size(); i++){ x.append( "\n >> " // + AA.seseorang.get(i).idPeserta // + "\n >> " + AA.seseorang.get(i).namaPeserta ); for(int j = 0; j < AA.seseorang.get(i).pertanyaandiajukan.size(); j++){ AA.analisajawaban( AA.seseorang.get(i), AA.seseorang.get(i).pertanyaandiajukan.get(j) ); boolean r = AA.hasil_analisis; x.append( "\n >> ?? " // + AA.seseorang.get(i).pertanyaandiajukan.get(j).idpertanyaan // + "\n >> " + AA.seseorang.get(i).pertanyaandiajukan.get(j).isi_pertanyaan + "\n >> | " + AA.seseorang.get(i).pertanyaandiajukan.get(j).jawabanpertanyaan.isi_jawaban + "\n >> | " + strKebohongan(r) ); } } System.out.println(x); } public static String strKebohongan(boolean r){ String s = ""; if(r) s = "Pernyataan >> Bohong"; else s = "Pernyataan >> Jujur" ; return s; } }
UTF-8
Java
3,966
java
LieMachine.java
Java
[ { "context": "package LieDetector;\r\n\r\n/**\r\n *\r\n * @author Kahrom\r\n */\r\npublic class LieMachine {\r\n public stati", "end": 50, "score": 0.9997343420982361, "start": 44, "tag": "NAME", "value": "Kahrom" }, { "context": " \r\n Peserta S01 = new Peserta(\"pes01\", \"Sanni\");\r\n Peserta S02 = new Peserta(\"pes02\", \"R", "end": 356, "score": 0.9993757605552673, "start": 351, "tag": "NAME", "value": "Sanni" }, { "context": "i\");\r\n Peserta S02 = new Peserta(\"pes02\", \"Ridman\");\r\n Peserta S03 = new Peserta(\"pes03\", \"O", "end": 411, "score": 0.9996469616889954, "start": 405, "tag": "NAME", "value": "Ridman" }, { "context": "n\");\r\n Peserta S03 = new Peserta(\"pes03\", \"Orelo\");\r\n \r\n A01.addseseorang(S01);\r\n ", "end": 465, "score": 0.9966504573822021, "start": 460, "tag": "NAME", "value": "Orelo" }, { "context": " \r\n Jawaban Ans01 = new Jawaban(\"01001a\", \"Saine\", Ref01);\r\n Pertanyaan P01 = new Pertanyaa", "end": 956, "score": 0.7733126878738403, "start": 951, "tag": "NAME", "value": "Saine" }, { "context": "\r\n Jawaban Ans02 = new Jawaban(\"101002a\", \"Ridman\", Ref02);\r\n Pertanyaan P02 = new Pertanyaa", "end": 1109, "score": 0.999029815196991, "start": 1103, "tag": "NAME", "value": "Ridman" }, { "context": " Jawaban Ans03_2 = new Jawaban(\"201001a\", \"Mathilda\", Ref00);\r\n Pertanyaan P03_2 = new Pertany", "end": 1420, "score": 0.9997842907905579, "start": 1412, "tag": "NAME", "value": "Mathilda" } ]
null
[]
package LieDetector; /** * * @author Kahrom */ public class LieMachine { public static void main(String[] args) throws IndexOutOfBoundsException { Analisis A01 = new Analisis("Alat Tes Kebohongan 1", ""); Analisis A02 = new Analisis("Alat Tes Kebohongan 2", ""); Peserta S01 = new Peserta("pes01", "Sanni"); Peserta S02 = new Peserta("pes02", "Ridman"); Peserta S03 = new Peserta("pes03", "Orelo"); A01.addseseorang(S01); A01.addseseorang(S02); A02.addseseorang(S03); // reaksi fisiologis ketika berbohong RF Ref00 = new RF(true, true, false, false); RF Ref01 = new RF(true, true, false, true); // reaksi fisiologis ketika jujur RF Ref02 = new RF(true, false, false, false); RF Ref03 = new RF(false, false, false, false); Jawaban Ans01 = new Jawaban("01001a", "Saine", Ref01); Pertanyaan P01 = new Pertanyaan("01001", "Siapa nama Anda", Ans01); Jawaban Ans02 = new Jawaban("101002a", "Ridman", Ref02); Pertanyaan P02 = new Pertanyaan("101002", "Siapa nama Anda", Ans02); Jawaban Ans03 = new Jawaban("201001a", "Orelo", Ref03); Pertanyaan P03 = new Pertanyaan("201001", "Siapa nama Anda", Ans03); Jawaban Ans03_2 = new Jawaban("201001a", "Mathilda", Ref00); Pertanyaan P03_2 = new Pertanyaan("201001", "Siapa nama Ibu Anda", Ans03_2); S01.addpertanyaaan(P01); S02.addpertanyaaan(P02); S03.addpertanyaaan(P03); S03.addpertanyaaan(P03_2); String Kata = "" + "Dalam dua buah tes menggunakan alat kebohongan, tiga orang responden " + "akan menjadi peserta uji alat kebohongan yaitu sebagai berikut : " + "\n - " + S01.namaPeserta + "\n - " + S02.namaPeserta + "\n - " + S03.namaPeserta + "\n\n" + "Berikut ini adalah hasil analisa dari percobaan tes kebohongan ini ::\n\n"; System.out.println(Kata); OutputAnalisa(A01); OutputAnalisa(A02); // System.out.println(A02.seseorang.get(0).pertanyaandiajukan.size()); // System.out.println(A02.seseorang.get(0).pertanyaandiajukan.get(1).isi_pertanyaan); } public static void OutputAnalisa(Analisis AA) { StringBuffer x = new StringBuffer(); x.append(AA.namaanalisis + "\n >> " + AA.ttg_analisis ); for(int i = 0; i < AA.seseorang.size(); i++){ x.append( "\n >> " // + AA.seseorang.get(i).idPeserta // + "\n >> " + AA.seseorang.get(i).namaPeserta ); for(int j = 0; j < AA.seseorang.get(i).pertanyaandiajukan.size(); j++){ AA.analisajawaban( AA.seseorang.get(i), AA.seseorang.get(i).pertanyaandiajukan.get(j) ); boolean r = AA.hasil_analisis; x.append( "\n >> ?? " // + AA.seseorang.get(i).pertanyaandiajukan.get(j).idpertanyaan // + "\n >> " + AA.seseorang.get(i).pertanyaandiajukan.get(j).isi_pertanyaan + "\n >> | " + AA.seseorang.get(i).pertanyaandiajukan.get(j).jawabanpertanyaan.isi_jawaban + "\n >> | " + strKebohongan(r) ); } } System.out.println(x); } public static String strKebohongan(boolean r){ String s = ""; if(r) s = "Pernyataan >> Bohong"; else s = "Pernyataan >> Jujur" ; return s; } }
3,966
0.500504
0.461422
97
38.886597
26.486284
101
false
false
0
0
0
0
0
0
0.85567
false
false
12
7bead060c4a9f3f3f221bf57dda4a523846045b2
21,028,159,901,588
c1143257a27419113e52a344df8d0c5b7bf9d87f
/retailstore-core/src/main/java/com/pc/retail/cache/Cache.java
4461ae01ac58a400feb77a19cb0d52ca625055db
[]
no_license
pavanchoukhada/kiranastore-app
https://github.com/pavanchoukhada/kiranastore-app
a99b625981b4165a4efcc81f5fd72f7d3a4b7df9
7937049577c2539f0b3f7e667c87c164d9bbd8c5
refs/heads/master
2021-01-20T12:56:58.824000
2019-04-23T12:55:34
2019-04-23T12:55:34
90,430,508
0
1
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pc.retail.cache; import com.pc.retail.dao.DataAccessException; public interface Cache { public void refresh() throws DataAccessException; }
UTF-8
Java
158
java
Cache.java
Java
[]
null
[]
package com.pc.retail.cache; import com.pc.retail.dao.DataAccessException; public interface Cache { public void refresh() throws DataAccessException; }
158
0.78481
0.78481
9
16.555555
19.494223
50
true
false
0
0
0
0
0
0
0.555556
false
false
12
72df0b8bb08e8b3fd13c3b904e78517e87465a9c
15,736,760,180,470
e001dddd661362669dc1fbe959886e09be307fa6
/src/main/java/com/leighton/OperatingMode.java
e3aea7f85d50d602c622e408200c25ffad1c3149
[]
no_license
Rodneystar/heating-timer
https://github.com/Rodneystar/heating-timer
75519e6cd8d336ea0d89e767d7e1a25b57206c7f
b024cc1c0095b8b428fcb0c9f11001cbe13e54aa
refs/heads/master
2020-04-10T21:44:47.689000
2018-07-23T18:29:49
2018-07-23T18:29:49
124,295,886
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.leighton; public enum OperatingMode { ON, OFF, TIMED }
UTF-8
Java
80
java
OperatingMode.java
Java
[]
null
[]
package com.leighton; public enum OperatingMode { ON, OFF, TIMED }
80
0.6375
0.6375
7
10.428572
9.286813
27
false
false
0
0
0
0
0
0
0.428571
false
false
12
a3f2f7f5a17c8c96aaa0a108ed2fe4aa03b948ca
22,995,254,915,974
4ad8fc4bf6d71bdd84007ac9a0649984152717ea
/src/TreeNode.java
f631b2589a8e9b36c9b3f1cc125dab688fd6f45a
[]
no_license
ndkheswa/binarytree
https://github.com/ndkheswa/binarytree
44af86b612e030c75d4772abb3f2570e6ab19553
d09758b7622f4e07cdf3ec22076dbaf0b16e946f
refs/heads/master
2021-01-23T02:23:24.414000
2016-09-17T20:43:30
2016-09-17T20:43:30
68,411,730
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.BufferedReader; import java.io.InputStreamReader; /** * Created by ndodakheswa on 2016/09/14. */ public class TreeNode { String item; private static Node root; //Points to root of the tree public TreeNode() { this.root = null; } public void treeInsert(String newItem) { if (root == null) { root = new Node(newItem); return; } Node runner; //Runs down the tree to find a place for newItem runner = root; //Start at the root while ( true ) { if (newItem.compareTo(runner.item) < 0) { //newItem is less than item. Look in the left subtree if (runner.left == null) { runner.left = new Node( newItem ); return; } else { runner = runner.left; } } else { if (runner.right == null) { runner.right = new Node( newItem ); return; } else { runner = runner.right; } } }//End while() } //End treeInsert() public boolean treeContains(Node root, String item) { if (root == null) { return false; } else if (item.equals(root.item)) { return true; //item found in the root node } else if (item.compareTo(root.item) < 0) { //item must be on the left side of the root node return treeContains(root.left, item); } else { return treeContains(root.right, item); } } public void treeList(Node root) { if (root != null) { treeList(root.left); System.out.println(" " + root.item); treeList(root.right); } } public static void main(String[] args) { System.out.print("Please enter an item to insert in the tree\n"); System.out.print("If an item is already in the list it will be ignored\n"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); TreeNode newNode = new TreeNode(); try { while (bufferedReader != null) { String newItem = bufferedReader.readLine(); newNode.treeInsert(newItem); newNode.treeList(root); } } catch (Exception e) { e.printStackTrace(); } } }
UTF-8
Java
2,583
java
TreeNode.java
Java
[ { "context": "port java.io.InputStreamReader;\n\n/**\n * Created by ndodakheswa on 2016/09/14.\n */\npublic class TreeNode {\n\n S", "end": 95, "score": 0.9990613460540771, "start": 84, "tag": "USERNAME", "value": "ndodakheswa" } ]
null
[]
import java.io.BufferedReader; import java.io.InputStreamReader; /** * Created by ndodakheswa on 2016/09/14. */ public class TreeNode { String item; private static Node root; //Points to root of the tree public TreeNode() { this.root = null; } public void treeInsert(String newItem) { if (root == null) { root = new Node(newItem); return; } Node runner; //Runs down the tree to find a place for newItem runner = root; //Start at the root while ( true ) { if (newItem.compareTo(runner.item) < 0) { //newItem is less than item. Look in the left subtree if (runner.left == null) { runner.left = new Node( newItem ); return; } else { runner = runner.left; } } else { if (runner.right == null) { runner.right = new Node( newItem ); return; } else { runner = runner.right; } } }//End while() } //End treeInsert() public boolean treeContains(Node root, String item) { if (root == null) { return false; } else if (item.equals(root.item)) { return true; //item found in the root node } else if (item.compareTo(root.item) < 0) { //item must be on the left side of the root node return treeContains(root.left, item); } else { return treeContains(root.right, item); } } public void treeList(Node root) { if (root != null) { treeList(root.left); System.out.println(" " + root.item); treeList(root.right); } } public static void main(String[] args) { System.out.print("Please enter an item to insert in the tree\n"); System.out.print("If an item is already in the list it will be ignored\n"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); TreeNode newNode = new TreeNode(); try { while (bufferedReader != null) { String newItem = bufferedReader.readLine(); newNode.treeInsert(newItem); newNode.treeList(root); } } catch (Exception e) { e.printStackTrace(); } } }
2,583
0.491676
0.487805
80
31.262501
23.416204
96
false
false
0
0
0
0
0
0
0.4125
false
false
12
011e079c88a143c30ffb1cc38c704c117c067c56
300,647,716,802
1b5a48b2f83358b772e6e1811d3a4242532e1773
/Permo/src/ch/uzh/ifi/seal/permo/common/core/model/types/TypeSerializerImpl.java
c879ad6f4b40d9f8abd9f5dc11a4e35da4c29d84
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
sealuzh/Permo
https://github.com/sealuzh/Permo
36a5c7a140cdfa07082c316a2bd6688123ec6a65
b3cf77cce84e639ab35532a2bc3950459d086ae5
refs/heads/master
2021-01-21T07:30:08.430000
2015-05-15T14:30:38
2015-05-15T14:30:38
35,678,735
1
1
null
null
null
null
null
null
null
null
null
null
null
null
null
/******************************************************************************* * Copyright 2015 Software Evolution and Architecture Lab, University of Zurich * * 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 ch.uzh.ifi.seal.permo.common.core.model.types; import java.util.List; import com.google.common.collect.Lists; /** * Implementation of {@link TypeSerializer}. */ public class TypeSerializerImpl implements TypeSerializer { private static final String POINT = "."; private static final List<String> PRIMITIVE_TYPES = Lists.newArrayList("byte", "short", "int", "long", "float", "double", "boolean", "char"); /** * {@inheritDoc} */ @Override public String serialize(final Type type) { return type.getQualifiedName(); } /** * {@inheritDoc} */ @Override public Type deserialize(final String serializedType) { final boolean isArray = serializedType.endsWith(ArrayType.ARRAY_SUFFIX); if (isArray) { final String serializedElementType = serializedType.substring(0, serializedType.length() - ArrayType.ARRAY_SUFFIX.length()); return ArrayType.of(deserialize(serializedElementType)); } final int lastPoint = serializedType.lastIndexOf(POINT); if (lastPoint == -1) { if (PRIMITIVE_TYPES.contains(serializedType)) { return PrimitiveType.of(serializedType); } return GenericType.of(serializedType); } final String packageName = serializedType.substring(0, lastPoint); final String name = serializedType.substring(lastPoint + 1); return ReferenceType.of(packageName, name); } }
UTF-8
Java
2,189
java
TypeSerializerImpl.java
Java
[]
null
[]
/******************************************************************************* * Copyright 2015 Software Evolution and Architecture Lab, University of Zurich * * 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 ch.uzh.ifi.seal.permo.common.core.model.types; import java.util.List; import com.google.common.collect.Lists; /** * Implementation of {@link TypeSerializer}. */ public class TypeSerializerImpl implements TypeSerializer { private static final String POINT = "."; private static final List<String> PRIMITIVE_TYPES = Lists.newArrayList("byte", "short", "int", "long", "float", "double", "boolean", "char"); /** * {@inheritDoc} */ @Override public String serialize(final Type type) { return type.getQualifiedName(); } /** * {@inheritDoc} */ @Override public Type deserialize(final String serializedType) { final boolean isArray = serializedType.endsWith(ArrayType.ARRAY_SUFFIX); if (isArray) { final String serializedElementType = serializedType.substring(0, serializedType.length() - ArrayType.ARRAY_SUFFIX.length()); return ArrayType.of(deserialize(serializedElementType)); } final int lastPoint = serializedType.lastIndexOf(POINT); if (lastPoint == -1) { if (PRIMITIVE_TYPES.contains(serializedType)) { return PrimitiveType.of(serializedType); } return GenericType.of(serializedType); } final String packageName = serializedType.substring(0, lastPoint); final String name = serializedType.substring(lastPoint + 1); return ReferenceType.of(packageName, name); } }
2,189
0.665601
0.660119
59
36.101696
33.312946
143
false
false
0
0
0
0
0
0
0.525424
false
false
12
a06f23963d5c1bca2b454ee6402bb95d72969f48
29,566,554,911,388
d365c4cc0717e94ca5d0f11046c1fd800e584613
/ModelMappingDTO/src/main/java/com/bridgelabz/demo/ModelmapperExplicitMappingApplication.java
ef8aa354310a1d23926ebfb1eed0602302336902
[]
no_license
Pramila0526/SpringBootPrograms
https://github.com/Pramila0526/SpringBootPrograms
a47de9eb1d3a81dce13c471eeea4b5d6969e481f
2216795988be048630edd34f5f931502678a2c1c
refs/heads/master
2020-12-06T04:04:39.481000
2020-01-11T05:12:23
2020-01-11T05:12:23
232,336,012
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.bridgelabz.demo; import org.modelmapper.ModelMapper; import org.modelmapper.PropertyMap; import com.bridgelabz.dto.UserDTO; import com.bridgelabz.model.User; /************************************************************************************* * @author :Pramila Tawari * Purpose :Explicit Model Mapper * ***********************************************************************************/ public class ModelmapperExplicitMappingApplication { public static void main(String[] args) { explicitModelMappingDemo(); } private static void explicitModelMappingDemo() { User sourceUser = new User(1, "Pramila", "pramila@gmail.com", "86417361", "Mumbai"); UserDTO targetUserDTO = new UserDTO(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new PropertyMap<User, UserDTO>() { protected void configure() { map().setUserCity(source.getCity()); } }); modelMapper.map(sourceUser, targetUserDTO); System.out.println(targetUserDTO.getName()); System.out.println(targetUserDTO.getEmailAddress()); System.out.println(targetUserDTO.getMobileNumber()); System.out.println(targetUserDTO.getUserCity()); } }
UTF-8
Java
1,180
java
ModelmapperExplicitMappingApplication.java
Java
[ { "context": "************************************\n * @author \t:Pramila Tawari\n * Purpose\t:Explicit Model Mapper \n *\n *****", "end": 286, "score": 0.9998847842216492, "start": 272, "tag": "NAME", "value": "Pramila Tawari" }, { "context": "appingDemo() {\n\t\tUser sourceUser = new User(1, \"Pramila\", \"pramila@gmail.com\", \"86417361\", \"Mumbai\");\n", "end": 633, "score": 0.45805585384368896, "start": 631, "tag": "NAME", "value": "am" }, { "context": "o() {\n\t\tUser sourceUser = new User(1, \"Pramila\", \"pramila@gmail.com\", \"86417361\", \"Mumbai\");\n\n\t\tUserDTO targetUserDTO", "end": 657, "score": 0.9999241232872009, "start": 640, "tag": "EMAIL", "value": "pramila@gmail.com" } ]
null
[]
package com.bridgelabz.demo; import org.modelmapper.ModelMapper; import org.modelmapper.PropertyMap; import com.bridgelabz.dto.UserDTO; import com.bridgelabz.model.User; /************************************************************************************* * @author :<NAME> * Purpose :Explicit Model Mapper * ***********************************************************************************/ public class ModelmapperExplicitMappingApplication { public static void main(String[] args) { explicitModelMappingDemo(); } private static void explicitModelMappingDemo() { User sourceUser = new User(1, "Pramila", "<EMAIL>", "86417361", "Mumbai"); UserDTO targetUserDTO = new UserDTO(); ModelMapper modelMapper = new ModelMapper(); modelMapper.addMappings(new PropertyMap<User, UserDTO>() { protected void configure() { map().setUserCity(source.getCity()); } }); modelMapper.map(sourceUser, targetUserDTO); System.out.println(targetUserDTO.getName()); System.out.println(targetUserDTO.getEmailAddress()); System.out.println(targetUserDTO.getMobileNumber()); System.out.println(targetUserDTO.getUserCity()); } }
1,162
0.637288
0.629661
39
29.256411
26.015497
86
false
false
0
0
0
0
0
0
1.538462
false
false
12
d574a0b4c4e2d2a91e8ecf153f4828d0ee82a082
721,554,573,317
71d9def39db34baa8109888f9e03efcdf607c38c
/ecommerce-login/ecommerce-login-client/ecommerce-login-client-cxf/src/main/java/com/ecommerce/login/client/cxf/ListMerchantCommand.java
be56d72a7d18e13db2336243fca56b9e95d4cc7b
[]
no_license
vladimirrv/ecommerce
https://github.com/vladimirrv/ecommerce
cfb3c6664b7ae1136a34c674f77753fbab67d021
5e8a072a484468a4972867f29943cfb1ceeb3941
refs/heads/master
2022-12-18T11:24:39.079000
2020-09-29T13:42:39
2020-09-29T13:42:39
299,628,554
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.ecommerce.login.client.cxf; import com.ecommerce.login.api.Merchant; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.Option; import org.apache.karaf.shell.api.action.lifecycle.Service; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; @Service @Command(scope = "merchant", name = "list", description = "List merchant") public class ListMerchantCommand implements Action { @Option(name = "--url", description = "Location of the REST service", required = false, multiValued = false) String restLocation = "http://localhost:8181/cxf/login/"; @Override public Object execute() throws Exception { List providers = new ArrayList(); providers.add(new JacksonJsonProvider()); WebClient webClient = WebClient.create(restLocation, providers); List<Merchant> merchants = (List<Merchant>) webClient.accept(MediaType.APPLICATION_JSON).getCollection(Merchant.class); for (Merchant merchant : merchants) { System.out.println(merchant.getMerchantType() + " " + merchant.getMerchantName() + " " + merchant.getOwnerName()); } return null; } }
UTF-8
Java
1,368
java
ListMerchantCommand.java
Java
[]
null
[]
package com.ecommerce.login.client.cxf; import com.ecommerce.login.api.Merchant; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.Option; import org.apache.karaf.shell.api.action.lifecycle.Service; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; @Service @Command(scope = "merchant", name = "list", description = "List merchant") public class ListMerchantCommand implements Action { @Option(name = "--url", description = "Location of the REST service", required = false, multiValued = false) String restLocation = "http://localhost:8181/cxf/login/"; @Override public Object execute() throws Exception { List providers = new ArrayList(); providers.add(new JacksonJsonProvider()); WebClient webClient = WebClient.create(restLocation, providers); List<Merchant> merchants = (List<Merchant>) webClient.accept(MediaType.APPLICATION_JSON).getCollection(Merchant.class); for (Merchant merchant : merchants) { System.out.println(merchant.getMerchantType() + " " + merchant.getMerchantName() + " " + merchant.getOwnerName()); } return null; } }
1,368
0.727339
0.724415
36
37
34.527767
127
false
false
0
0
0
0
0
0
0.666667
false
false
12
75e73175ae7a76b6dce54e1b068f93f4353e13c5
3,315,714,786,281
1ca99595d9fc8c0d6d5d84eaf019df673e4c35d5
/mestrado/artigos/wat2017/experimento/src/main/java/br/com/appworks/mestrado/wat2017/experimento/common/TypeNameNormalizer.java
401fb4378eee2374815ba73edb177b4b0eb57cc5
[]
no_license
bsofiato/bsofiato-mono
https://github.com/bsofiato/bsofiato-mono
afd0378ef8409534c425121c038dec44afe9d9d0
a7a6a54a242ac96bcf25372a8bbc6d98656204e3
refs/heads/master
2017-04-23T07:09:20.924000
2017-02-08T00:19:26
2017-02-08T00:19:26
25,411,890
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package br.com.appworks.mestrado.wat2017.experimento.common; public class TypeNameNormalizer { public static final String normalizeTypeName(Class klass) { return (klass == null) ? null : normalizeTypeName(klass.getName()); } public static final String normalizeTypeNameByObject(Object klass) { return normalizeTypeName((klass == null) ? null : klass.getClass()); } public static final String normalizeTypeName(String name) { if (name == null) { return name; } else { switch (name.trim()) { case "java.lang.Integer" : case "int" : case "Integer" : return "Int"; case "java.lang.Long" : case "long" : case "Long" : return "Long"; case "java.lang.Short" : case "short" : case "Short" : return "Short"; case "java.lang.Character" : case "char" : case "Character" : return "Char"; case "java.lang.Double" : case "double" : case "Double" : return "Double"; case "java.lang.Boolean" : case "boolean" : case "Boolean" : return "Boolean"; case "java.lang.Byte" : case "byte" : case "Byte" : return "Byte"; case "java.lang.Float" : case "float" : case "Float" : return "Float"; default: return "Object"; } } } }
UTF-8
Java
1,228
java
TypeNameNormalizer.java
Java
[]
null
[]
package br.com.appworks.mestrado.wat2017.experimento.common; public class TypeNameNormalizer { public static final String normalizeTypeName(Class klass) { return (klass == null) ? null : normalizeTypeName(klass.getName()); } public static final String normalizeTypeNameByObject(Object klass) { return normalizeTypeName((klass == null) ? null : klass.getClass()); } public static final String normalizeTypeName(String name) { if (name == null) { return name; } else { switch (name.trim()) { case "java.lang.Integer" : case "int" : case "Integer" : return "Int"; case "java.lang.Long" : case "long" : case "Long" : return "Long"; case "java.lang.Short" : case "short" : case "Short" : return "Short"; case "java.lang.Character" : case "char" : case "Character" : return "Char"; case "java.lang.Double" : case "double" : case "Double" : return "Double"; case "java.lang.Boolean" : case "boolean" : case "Boolean" : return "Boolean"; case "java.lang.Byte" : case "byte" : case "Byte" : return "Byte"; case "java.lang.Float" : case "float" : case "Float" : return "Float"; default: return "Object"; } } } }
1,228
0.628664
0.625407
28
42.857143
32.284134
86
false
false
0
0
0
0
0
0
0.464286
false
false
12
db22770265ecc77ad32dae66c9c0f7c3384fcdc2
3,289,944,951,443
3d2f06ea3eeee473d6ef63f8dd2959a9a14693da
/ListofPlaces/app/src/main/java/com/example/listofplaces/AddAPlaceMapActivity.java
336d6d93ce070aedf3cfa1477ef614aee25d2cb8
[]
no_license
snowfire5492/AlertDemo
https://github.com/snowfire5492/AlertDemo
bfdd76890705e93311889dafedc8af155eab78fb
6f2ec4506eadfaa41acf92338a39c72c9441a265
refs/heads/master
2022-11-30T14:24:32.123000
2020-08-12T09:41:26
2020-08-12T09:41:26
286,973,118
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.example.listofplaces; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.List; import java.util.Locale; public class AddAPlaceMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { private GoogleMap mMap; LocationManager locationManager; LocationListener locationListener; public void centerMapOnLocation(Location location, String title) { if (location != null) { mMap.clear(); LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); mMap.addMarker(new MarkerOptions().position(userLocation).title(title)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14)); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centerMapOnLocation(lastKnownLocation, "Your Location"); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_a_place_map); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; final Intent intent = getIntent(); // Toast.makeText(this, "" + intent.getIntExtra("placeNumber", 0), Toast.LENGTH_SHORT ).show(); mMap.setOnMapLongClickListener(this); if(intent.getIntExtra("placeNumber", -1) == 0) { locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { // Log.i("LOCATION", location.toString()); // zoom in on user location centerMapOnLocation(location, "user"); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centerMapOnLocation(lastLocation, "lastLocation"); } }else { { Location placeLocation = new Location(LocationManager.GPS_PROVIDER); placeLocation.setLatitude(MainActivity.latlng.get(intent.getIntExtra("placeNumber", 0)).latitude); placeLocation.setLongitude(MainActivity.latlng.get(intent.getIntExtra("placeNumber", 0)).longitude); centerMapOnLocation(placeLocation, MainActivity.places.get(intent.getIntExtra("placeNumber", 0))); } } } @Override public void onMapLongClick(LatLng latLng) { Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); String address = ""; try { List<Address> list = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); if (list != null && list.size() > 0) { Log.i("ADDRESS", list.get(0).toString()); if (list.get(0).getThoroughfare() != null) { address = list.get(0).getFeatureName() + " " + list.get(0).getThoroughfare(); }else if (list.get(0).getThoroughfare() == null) { address = "[" + latLng.latitude + ", " + latLng.longitude + "]"; } } } catch (Exception e) { e.printStackTrace(); } mMap.addMarker(new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))); MainActivity.places.add(address); MainActivity.latlng.add(latLng); MainActivity.arrayAdapter.notifyDataSetChanged(); Toast.makeText(this, "Location Saved!", Toast.LENGTH_SHORT).show(); } }
UTF-8
Java
6,363
java
AddAPlaceMapActivity.java
Java
[]
null
[]
package com.example.listofplaces; import androidx.annotation.NonNull; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.util.List; import java.util.Locale; public class AddAPlaceMapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapLongClickListener { private GoogleMap mMap; LocationManager locationManager; LocationListener locationListener; public void centerMapOnLocation(Location location, String title) { if (location != null) { mMap.clear(); LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude()); mMap.addMarker(new MarkerOptions().position(userLocation).title(title)); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14)); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centerMapOnLocation(lastKnownLocation, "Your Location"); } } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_a_place_map); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; final Intent intent = getIntent(); // Toast.makeText(this, "" + intent.getIntExtra("placeNumber", 0), Toast.LENGTH_SHORT ).show(); mMap.setOnMapLongClickListener(this); if(intent.getIntExtra("placeNumber", -1) == 0) { locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { // Log.i("LOCATION", location.toString()); // zoom in on user location centerMapOnLocation(location, "user"); } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); } else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); centerMapOnLocation(lastLocation, "lastLocation"); } }else { { Location placeLocation = new Location(LocationManager.GPS_PROVIDER); placeLocation.setLatitude(MainActivity.latlng.get(intent.getIntExtra("placeNumber", 0)).latitude); placeLocation.setLongitude(MainActivity.latlng.get(intent.getIntExtra("placeNumber", 0)).longitude); centerMapOnLocation(placeLocation, MainActivity.places.get(intent.getIntExtra("placeNumber", 0))); } } } @Override public void onMapLongClick(LatLng latLng) { Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); String address = ""; try { List<Address> list = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1); if (list != null && list.size() > 0) { Log.i("ADDRESS", list.get(0).toString()); if (list.get(0).getThoroughfare() != null) { address = list.get(0).getFeatureName() + " " + list.get(0).getThoroughfare(); }else if (list.get(0).getThoroughfare() == null) { address = "[" + latLng.latitude + ", " + latLng.longitude + "]"; } } } catch (Exception e) { e.printStackTrace(); } mMap.addMarker(new MarkerOptions().position(latLng).title(address).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))); MainActivity.places.add(address); MainActivity.latlng.add(latLng); MainActivity.arrayAdapter.notifyDataSetChanged(); Toast.makeText(this, "Location Saved!", Toast.LENGTH_SHORT).show(); } }
6,363
0.664466
0.661009
183
33.775955
36.844513
154
false
false
0
0
0
0
0
0
0.595628
false
false
12
e464ff67bee1fe92dcb7c383c2304939c6d02399
10,342,281,282,463
67ee16d166c1501e9f930a16ab34dd8d26c381a5
/src/cs/iit/edu/cs550/PerformanceEvaluation.java
505647c20492e3c7710632c4ef54f508fc57f6e5
[]
no_license
bcarthic/P2P-Napster
https://github.com/bcarthic/P2P-Napster
08ec1b7e54a50a1013681d364a304f269d93a65b
f5fb80a023e701836e1d4cd6ecc24e96ab837657
refs/heads/master
2021-10-11T05:51:18.007000
2019-01-23T00:10:26
2019-01-23T00:10:26
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package cs.iit.edu.cs550; import java.io.IOException; public class PerformanceEvaluation { /** * @param args * @throws IOException * @throws InterruptedException */ @SuppressWarnings("unused") public static void main(String[] args) throws IOException, InterruptedException { int NUM_PEERS = 5; // Starting indexing server Process proc = Runtime.getRuntime().exec( "java -jar IndexingServer.jar 4554"); Process peer = Runtime.getRuntime().exec( "java -jar PeerNode.jar 127.0.0.1 4554 4999 E:\\P\\"); int portNum = 4555; for (int count = 1; count <= NUM_PEERS; count++) { String folderName = " E:\\P" + count + "\\ "; Process proc1 = Runtime.getRuntime().exec( "java -jar PeerNode.jar 127.0.0.1 4554 " + portNum++ + folderName + "-p testfile.txt"); } } }
UTF-8
Java
822
java
PerformanceEvaluation.java
Java
[ { "context": "me.getRuntime().exec(\n\t\t\t\t\"java -jar PeerNode.jar 127.0.0.1 4554 4999 E:\\\\P\\\\\");\n\t\t\n\t\tint portNum = 4555;\n\t\tf", "end": 516, "score": 0.9983848929405212, "start": 507, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "e.getRuntime().exec(\n\t\t\t\t\t\"java -jar PeerNode.jar 127.0.0.1 4554 \" + portNum++\n\t\t\t\t\t\t\t+ folderName + \"-p test", "end": 750, "score": 0.9986140727996826, "start": 741, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
null
[]
package cs.iit.edu.cs550; import java.io.IOException; public class PerformanceEvaluation { /** * @param args * @throws IOException * @throws InterruptedException */ @SuppressWarnings("unused") public static void main(String[] args) throws IOException, InterruptedException { int NUM_PEERS = 5; // Starting indexing server Process proc = Runtime.getRuntime().exec( "java -jar IndexingServer.jar 4554"); Process peer = Runtime.getRuntime().exec( "java -jar PeerNode.jar 127.0.0.1 4554 4999 E:\\P\\"); int portNum = 4555; for (int count = 1; count <= NUM_PEERS; count++) { String folderName = " E:\\P" + count + "\\ "; Process proc1 = Runtime.getRuntime().exec( "java -jar PeerNode.jar 127.0.0.1 4554 " + portNum++ + folderName + "-p testfile.txt"); } } }
822
0.648418
0.60219
35
22.485714
21.87676
82
false
false
0
0
0
0
0
0
1.857143
false
false
12
f0cd5ccd35f19978e905aac4ce5608b4fbce53a2
17,884,243,829,123
85afd9fe01cb673b54def462f23db551cba67c37
/src/co/marcin/novaguilds/command/CommandAdminRegionBypass.java
6238626f10fcb02094def8b1cea39b2291dda128
[]
no_license
TWSSYesterday/NovaGuilds
https://github.com/TWSSYesterday/NovaGuilds
7cd62d7fc0ccef71249886afae99bb799b207c4a
1f970608508ec05f65ad7da6b75bba7ee3af8156
refs/heads/master
2020-12-03T04:05:11.891000
2015-06-10T16:15:36
2015-06-10T16:15:36
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package co.marcin.novaguilds.command; import co.marcin.novaguilds.NovaGuilds; import co.marcin.novaguilds.basic.NovaPlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import java.util.HashMap; public class CommandAdminRegionBypass implements CommandExecutor { private final NovaGuilds plugin; public CommandAdminRegionBypass(NovaGuilds pl) { plugin = pl; } /* * Changing bypass * no args - for sender * args[1] - for specified player * */ public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args.length==0) { if(sender.hasPermission("novaguilds.admin.region.bypass")) { NovaPlayer nPlayer = plugin.getPlayerManager().getPlayerByName(sender.getName()); nPlayer.toggleBypass(); HashMap<String,String> vars = new HashMap<>(); vars.put("BYPASS",nPlayer.getBypass()+""); plugin.sendMessagesMsg(sender,"chat.admin.region.rgbypass.toggled",vars); } else { plugin.sendMessagesMsg(sender,"chat.nopermissions"); } } else { //for other if(sender.hasPermission("novaguilds.admin.region.bypass.other")) { NovaPlayer nPlayer = plugin.getPlayerManager().getPlayerByName(args[0]); if(nPlayer == null) { plugin.sendMessagesMsg(sender,"chat.player.notexists"); return true; } nPlayer.toggleBypass(); HashMap<String,String> vars = new HashMap<>(); vars.put("PLAYER",nPlayer.getName()); vars.put("BYPASS",nPlayer.getBypass()+""); if(nPlayer.isOnline()) { plugin.sendMessagesMsg(nPlayer.getPlayer(), "chat.admin.rgbypass.notifyother"); } plugin.sendMessagesMsg(sender,"chat.admin.rgbypass.toggledother",vars); } else { plugin.sendMessagesMsg(sender, "chat.nopermissions"); } } return true; } }
UTF-8
Java
1,830
java
CommandAdminRegionBypass.java
Java
[]
null
[]
package co.marcin.novaguilds.command; import co.marcin.novaguilds.NovaGuilds; import co.marcin.novaguilds.basic.NovaPlayer; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import java.util.HashMap; public class CommandAdminRegionBypass implements CommandExecutor { private final NovaGuilds plugin; public CommandAdminRegionBypass(NovaGuilds pl) { plugin = pl; } /* * Changing bypass * no args - for sender * args[1] - for specified player * */ public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if(args.length==0) { if(sender.hasPermission("novaguilds.admin.region.bypass")) { NovaPlayer nPlayer = plugin.getPlayerManager().getPlayerByName(sender.getName()); nPlayer.toggleBypass(); HashMap<String,String> vars = new HashMap<>(); vars.put("BYPASS",nPlayer.getBypass()+""); plugin.sendMessagesMsg(sender,"chat.admin.region.rgbypass.toggled",vars); } else { plugin.sendMessagesMsg(sender,"chat.nopermissions"); } } else { //for other if(sender.hasPermission("novaguilds.admin.region.bypass.other")) { NovaPlayer nPlayer = plugin.getPlayerManager().getPlayerByName(args[0]); if(nPlayer == null) { plugin.sendMessagesMsg(sender,"chat.player.notexists"); return true; } nPlayer.toggleBypass(); HashMap<String,String> vars = new HashMap<>(); vars.put("PLAYER",nPlayer.getName()); vars.put("BYPASS",nPlayer.getBypass()+""); if(nPlayer.isOnline()) { plugin.sendMessagesMsg(nPlayer.getPlayer(), "chat.admin.rgbypass.notifyother"); } plugin.sendMessagesMsg(sender,"chat.admin.rgbypass.toggledother",vars); } else { plugin.sendMessagesMsg(sender, "chat.nopermissions"); } } return true; } }
1,830
0.714754
0.713115
63
28.047619
26.600172
91
false
false
0
0
0
0
0
0
2.714286
false
false
12
eb38fcbc736bbb51d29d1b59b4c13a858369b15e
31,456,340,500,802
47e66aa6f98e4bcd9b5e2400cd7f88af08261855
/modules/api/src/main/java/org/apache/fluo/api/config/SimpleConfiguration.java
86ff1b785d0d0b2dc9a75a327886ba1c103e6996
[ "Apache-2.0" ]
permissive
garvitbansal/incubator-fluo
https://github.com/garvitbansal/incubator-fluo
0c5daaf977c8937e0eaffdf6ffc3ebdcff11a49e
def5d82143da34c229f62c61d1cb502cc782aa6d
refs/heads/master
2020-12-24T18:55:37.756000
2016-07-08T15:44:39
2016-07-08T15:44:39
62,450,795
0
0
null
true
2016-07-20T20:51:21
2016-07-02T12:56:22
2016-07-02T12:56:23
2016-07-18T18:49:50
3,151
0
0
0
Java
null
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. */ package org.apache.fluo.api.config; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.ConfigurationUtils; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.fluo.api.exceptions.FluoException; /** * A simple configuration wrapper for Apache Commons configuration. The implementation supports * reading and writing properties style config and interpolation. * * <p> * This simple wrapper was created to keep 3rd party APIs out of the Fluo API. * * @since 1.0.0 */ public class SimpleConfiguration { private Configuration internalConfig; public SimpleConfiguration() { CompositeConfiguration compositeConfig = new CompositeConfiguration(); compositeConfig.setThrowExceptionOnMissing(true); compositeConfig.setDelimiterParsingDisabled(true); internalConfig = compositeConfig; } private SimpleConfiguration(Configuration subset) { this.internalConfig = subset; } /** * Read a properties style config from given file. */ public SimpleConfiguration(File propertiesFile) { this(); try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(propertiesFile); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } } /** * Read a properties style config from given input stream. */ public SimpleConfiguration(InputStream in) { this(); try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(in); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } } /** * Copy constructor. */ public SimpleConfiguration(SimpleConfiguration other) { this(); Iterator<String> iter = other.internalConfig.getKeys(); while (iter.hasNext()) { String key = iter.next(); internalConfig.setProperty(key, other.internalConfig.getProperty(key)); } } public void clear() { internalConfig.clear(); } public void clearProperty(String key) { internalConfig.clearProperty(key); } public boolean containsKey(String key) { return internalConfig.containsKey(key); } public boolean getBoolean(String key) { return internalConfig.getBoolean(key); } public boolean getBoolean(String key, boolean defaultValue) { return internalConfig.getBoolean(key, defaultValue); } public int getInt(String key) { return internalConfig.getInt(key); } public int getInt(String key, int defaultValue) { return internalConfig.getInt(key, defaultValue); } public Iterator<String> getKeys() { return internalConfig.getKeys(); } public Iterator<String> getKeys(String key) { return internalConfig.getKeys(key); } public long getLong(String key) { return internalConfig.getLong(key); } public long getLong(String key, long defaultValue) { return internalConfig.getLong(key, defaultValue); } /** * @return raw property without interpolation or null if not set. */ public String getRawString(String key) { Object val = internalConfig.getProperty(key); if (val == null) { return null; } return val.toString(); } public String getString(String key) { return internalConfig.getString(key); } public String getString(String key, String defaultValue) { return internalConfig.getString(key, defaultValue); } public void save(File file) { PropertiesConfiguration pconf = new PropertiesConfiguration(); pconf.append(internalConfig); try { pconf.save(file); } catch (ConfigurationException e) { throw new FluoException(e); } } public void save(OutputStream out) { PropertiesConfiguration pconf = new PropertiesConfiguration(); pconf.append(internalConfig); try { pconf.save(out); } catch (ConfigurationException e) { throw new FluoException(e); } } public void setProperty(String key, Boolean value) { internalConfig.setProperty(key, value); } public void setProperty(String key, Integer value) { internalConfig.setProperty(key, value); } public void setProperty(String key, Long value) { internalConfig.setProperty(key, value); } public void setProperty(String key, String value) { internalConfig.setProperty(key, value); } /** * Returns a subset of config that start with given prefix. The prefix will not be present in keys * of the returned config. Any changes made to the returned config will be made to this and visa * versa. */ public SimpleConfiguration subset(String prefix) { return new SimpleConfiguration(internalConfig.subset(prefix)); } @Override public String toString() { return ConfigurationUtils.toString(internalConfig); } }
UTF-8
Java
6,235
java
SimpleConfiguration.java
Java
[]
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. */ package org.apache.fluo.api.config; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.util.Iterator; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.ConfigurationUtils; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.fluo.api.exceptions.FluoException; /** * A simple configuration wrapper for Apache Commons configuration. The implementation supports * reading and writing properties style config and interpolation. * * <p> * This simple wrapper was created to keep 3rd party APIs out of the Fluo API. * * @since 1.0.0 */ public class SimpleConfiguration { private Configuration internalConfig; public SimpleConfiguration() { CompositeConfiguration compositeConfig = new CompositeConfiguration(); compositeConfig.setThrowExceptionOnMissing(true); compositeConfig.setDelimiterParsingDisabled(true); internalConfig = compositeConfig; } private SimpleConfiguration(Configuration subset) { this.internalConfig = subset; } /** * Read a properties style config from given file. */ public SimpleConfiguration(File propertiesFile) { this(); try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(propertiesFile); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } } /** * Read a properties style config from given input stream. */ public SimpleConfiguration(InputStream in) { this(); try { PropertiesConfiguration config = new PropertiesConfiguration(); // disabled to prevent accumulo classpath value from being shortened config.setDelimiterParsingDisabled(true); config.load(in); ((CompositeConfiguration) internalConfig).addConfiguration(config); } catch (ConfigurationException e) { throw new IllegalArgumentException(e); } } /** * Copy constructor. */ public SimpleConfiguration(SimpleConfiguration other) { this(); Iterator<String> iter = other.internalConfig.getKeys(); while (iter.hasNext()) { String key = iter.next(); internalConfig.setProperty(key, other.internalConfig.getProperty(key)); } } public void clear() { internalConfig.clear(); } public void clearProperty(String key) { internalConfig.clearProperty(key); } public boolean containsKey(String key) { return internalConfig.containsKey(key); } public boolean getBoolean(String key) { return internalConfig.getBoolean(key); } public boolean getBoolean(String key, boolean defaultValue) { return internalConfig.getBoolean(key, defaultValue); } public int getInt(String key) { return internalConfig.getInt(key); } public int getInt(String key, int defaultValue) { return internalConfig.getInt(key, defaultValue); } public Iterator<String> getKeys() { return internalConfig.getKeys(); } public Iterator<String> getKeys(String key) { return internalConfig.getKeys(key); } public long getLong(String key) { return internalConfig.getLong(key); } public long getLong(String key, long defaultValue) { return internalConfig.getLong(key, defaultValue); } /** * @return raw property without interpolation or null if not set. */ public String getRawString(String key) { Object val = internalConfig.getProperty(key); if (val == null) { return null; } return val.toString(); } public String getString(String key) { return internalConfig.getString(key); } public String getString(String key, String defaultValue) { return internalConfig.getString(key, defaultValue); } public void save(File file) { PropertiesConfiguration pconf = new PropertiesConfiguration(); pconf.append(internalConfig); try { pconf.save(file); } catch (ConfigurationException e) { throw new FluoException(e); } } public void save(OutputStream out) { PropertiesConfiguration pconf = new PropertiesConfiguration(); pconf.append(internalConfig); try { pconf.save(out); } catch (ConfigurationException e) { throw new FluoException(e); } } public void setProperty(String key, Boolean value) { internalConfig.setProperty(key, value); } public void setProperty(String key, Integer value) { internalConfig.setProperty(key, value); } public void setProperty(String key, Long value) { internalConfig.setProperty(key, value); } public void setProperty(String key, String value) { internalConfig.setProperty(key, value); } /** * Returns a subset of config that start with given prefix. The prefix will not be present in keys * of the returned config. Any changes made to the returned config will be made to this and visa * versa. */ public SimpleConfiguration subset(String prefix) { return new SimpleConfiguration(internalConfig.subset(prefix)); } @Override public String toString() { return ConfigurationUtils.toString(internalConfig); } }
6,235
0.727025
0.725742
212
28.410378
27.883459
100
false
false
0
0
0
0
0
0
0.400943
false
false
12
7c03fd86a82801f3ec83188d1a89834ae9d137ac
11,802,570,141,977
5de8325bb474df61edbd022689bbe4516fa3e86b
/basic/src/main/java/KnowledgePoints/Lambda_Inter/Demo05.java
6d1aed6d342cf16c9ca62aafa1230fced667b820
[]
no_license
Hal-L/echo
https://github.com/Hal-L/echo
e6257da00a8d698e7aba121b13485bbfacbe38a0
bfcbb9065124dab98b97222fc9f71a3a5b5663fa
refs/heads/main
2023-02-23T23:58:41.004000
2021-01-29T05:17:36
2021-01-29T05:17:36
328,142,425
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package KnowledgePoints.Lambda_Inter; public class Demo05 { public static void main(String[] args) { // 1,从右开始找比基准数小的 // 2,从左开始找比基准数大的 // 3,交换两个值的位置 // 4,红色继续往左找,蓝色继续往右找,直到两个箭头指向同一个索引为止 // 5,基准数归位 int[] arr = {6, 1, 2, 7, 9, 11, 3, 4, 5, 10, 14, 8}; quiteSort(arr, 0, arr.length - 1); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } private static void quiteSort(int[] arr, int left, int right) { // 特例: 当left 大于 right 不需要排序了 (递归的出口) if (left > right) { return; } // left和right的值后边会发生变化, 先把他们的值记录下来,留着备用 int left0 = left; int right0 = right; //计算出基准数 int baseNumber = arr[left0]; while (left != right) { // 1,从右开始找比基准数小的 // 循环什么时候会停? 右边的数 小于 基准数 // 目前这个数需要给他换到左边 while (arr[right] >= baseNumber && right > left) { right--; } // 2,从左开始找比基准数大的 // 什么时候停? 左边数 大于 基准数时会停 , 左边这个数一会要把他换到右边 while (arr[left] <= baseNumber && right > left) { left++; } // 3,交换两个值的位置 int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //基准数归位 int temp = arr[left]; arr[left] = arr[left0]; arr[left0] = temp; // 处理左边(排序左边) quiteSort(arr, left0, left - 1); // 处理右边 (排序右边) quiteSort(arr, left + 1, right0); } }
UTF-8
Java
2,079
java
Demo05.java
Java
[]
null
[]
package KnowledgePoints.Lambda_Inter; public class Demo05 { public static void main(String[] args) { // 1,从右开始找比基准数小的 // 2,从左开始找比基准数大的 // 3,交换两个值的位置 // 4,红色继续往左找,蓝色继续往右找,直到两个箭头指向同一个索引为止 // 5,基准数归位 int[] arr = {6, 1, 2, 7, 9, 11, 3, 4, 5, 10, 14, 8}; quiteSort(arr, 0, arr.length - 1); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } private static void quiteSort(int[] arr, int left, int right) { // 特例: 当left 大于 right 不需要排序了 (递归的出口) if (left > right) { return; } // left和right的值后边会发生变化, 先把他们的值记录下来,留着备用 int left0 = left; int right0 = right; //计算出基准数 int baseNumber = arr[left0]; while (left != right) { // 1,从右开始找比基准数小的 // 循环什么时候会停? 右边的数 小于 基准数 // 目前这个数需要给他换到左边 while (arr[right] >= baseNumber && right > left) { right--; } // 2,从左开始找比基准数大的 // 什么时候停? 左边数 大于 基准数时会停 , 左边这个数一会要把他换到右边 while (arr[left] <= baseNumber && right > left) { left++; } // 3,交换两个值的位置 int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //基准数归位 int temp = arr[left]; arr[left] = arr[left0]; arr[left0] = temp; // 处理左边(排序左边) quiteSort(arr, left0, left - 1); // 处理右边 (排序右边) quiteSort(arr, left + 1, right0); } }
2,079
0.45269
0.429808
58
25.844828
17.31135
67
false
false
0
0
0
0
0
0
0.724138
false
false
12
3399eefc89343f08aac025d0817d69696c8f6a00
10,299,331,586,196
fd9883721b39677493149b3897248c19fe25e4e0
/src/BusinessLogic/WeaponPopulationAdministrator.java
27e171678aaca948304154b9d075743e996d85b7
[]
no_license
FabiJhoel/TheEndlessGame
https://github.com/FabiJhoel/TheEndlessGame
f7ab1b4f5ee1b8154ff0539f346f91055fc38512
eef08670d33e51d6e2b8f5c71b7b2d8e0035283d
refs/heads/master
2021-01-13T01:30:44.215000
2014-06-10T15:51:25
2014-06-10T15:51:25
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package BusinessLogic; import java.util.ArrayList; import java.util.Random; public class WeaponPopulationAdministrator { private ArrayList<WeaponProperties> weaponsPopulation = new ArrayList<>(); private GeneticAlgorithmManager geneticAlgorithmManager; public WeaponPopulationAdministrator() { geneticAlgorithmManager = new GeneticAlgorithmManager(); } public void addWeapon(WeaponProperties pWeapon){ weaponsPopulation.add(pWeapon); } public WeaponProperties generateDefaultWeapon(){ try { Random rand = new Random(); //random function: ((max-min)+1)+min byte thicknessByteRepresentacion = (byte)(rand.nextInt((255-0)+1)+0); byte polygonPointsByteRepresentacion = (byte)(rand.nextInt((255-0)+1)+0); byte laneAmountByteRepresentation = (byte)(rand.nextInt((255-0)+1)+0); int colorSelected = rand.nextInt((3-1)+1)+1; int[] color = new int[3]; switch(colorSelected){ case 1: //verde color[0] = 0; color[1] = 255; color[2] = 77; break; case 2: //rojo color[0] = 255; color[1] = 0; color[2] = 51; break; case 3: //amarillo color[0] = 255; color[1] = 255; color[2] = 0; break; } return new WeaponProperties(thicknessByteRepresentacion, polygonPointsByteRepresentacion, laneAmountByteRepresentation, color); } catch(Exception e) { System.out.println("ERROR: WeaponPopulationAdministrator.generateDefaultWeapon() failure"); return null; } } public WeaponProperties generateWeapon(WeaponProperties pWeapon){ try { WeaponProperties newWeapon = geneticAlgorithmManager.createNewGeneration(pWeapon, weaponsPopulation); return newWeapon; } catch(Exception e) { System.out.println("ERROR: WeaponPopulationAdministrator.generateWeapon() failure"); return null; } } }
UTF-8
Java
2,185
java
WeaponPopulationAdministrator.java
Java
[]
null
[]
package BusinessLogic; import java.util.ArrayList; import java.util.Random; public class WeaponPopulationAdministrator { private ArrayList<WeaponProperties> weaponsPopulation = new ArrayList<>(); private GeneticAlgorithmManager geneticAlgorithmManager; public WeaponPopulationAdministrator() { geneticAlgorithmManager = new GeneticAlgorithmManager(); } public void addWeapon(WeaponProperties pWeapon){ weaponsPopulation.add(pWeapon); } public WeaponProperties generateDefaultWeapon(){ try { Random rand = new Random(); //random function: ((max-min)+1)+min byte thicknessByteRepresentacion = (byte)(rand.nextInt((255-0)+1)+0); byte polygonPointsByteRepresentacion = (byte)(rand.nextInt((255-0)+1)+0); byte laneAmountByteRepresentation = (byte)(rand.nextInt((255-0)+1)+0); int colorSelected = rand.nextInt((3-1)+1)+1; int[] color = new int[3]; switch(colorSelected){ case 1: //verde color[0] = 0; color[1] = 255; color[2] = 77; break; case 2: //rojo color[0] = 255; color[1] = 0; color[2] = 51; break; case 3: //amarillo color[0] = 255; color[1] = 255; color[2] = 0; break; } return new WeaponProperties(thicknessByteRepresentacion, polygonPointsByteRepresentacion, laneAmountByteRepresentation, color); } catch(Exception e) { System.out.println("ERROR: WeaponPopulationAdministrator.generateDefaultWeapon() failure"); return null; } } public WeaponProperties generateWeapon(WeaponProperties pWeapon){ try { WeaponProperties newWeapon = geneticAlgorithmManager.createNewGeneration(pWeapon, weaponsPopulation); return newWeapon; } catch(Exception e) { System.out.println("ERROR: WeaponPopulationAdministrator.generateWeapon() failure"); return null; } } }
2,185
0.589474
0.564302
68
31.132353
27.230986
110
false
false
0
0
0
0
0
0
1.264706
false
false
12
4e32304d9d3ca8cb16a7bbde67e87bdb7957b7ad
23,450,521,446,312
58bcaf19ab49ac410535ac724c7e22e216d1236d
/IntroToCompSci/hw8/edu/yu/cs/intro/bank/exceptions/NoSuchAccountException.java
919ba8f9a7439f7db64538ba25142bfe1b8f4568
[]
no_license
davidlifschitz/trialProjects
https://github.com/davidlifschitz/trialProjects
6a8beed09f1cd848982c8493ad05bbd0b761d702
463421cd502e3daab58037c93b8be173fa7b039f
refs/heads/master
2022-05-28T20:26:12.776000
2021-05-06T16:34:09
2021-05-06T16:34:09
251,500,660
0
0
null
false
2022-05-20T21:58:33
2020-03-31T04:31:05
2021-05-06T16:34:12
2022-05-20T21:58:32
2,275
0
0
13
Java
false
false
package edu.yu.cs.intro.bank.exceptions; public class NoSuchAccountException extends Exception { }
UTF-8
Java
104
java
NoSuchAccountException.java
Java
[]
null
[]
package edu.yu.cs.intro.bank.exceptions; public class NoSuchAccountException extends Exception { }
104
0.788462
0.788462
4
24
24.093567
55
false
false
0
0
0
0
0
0
0.25
false
false
12
095bbfb3155cb85793d217e86f7fb70cb206db12
884,763,296,808
6c435c37d2665c839b380776c02a6dcdf74f434f
/src/Acs.java
b14e02731c3b2d28d9ba859ec0ca545ebd739724
[]
no_license
elvman/id06reader
https://github.com/elvman/id06reader
8cc547f1c3cc409968304c4cc48aa72a2c104100
3356bc1881dd419f320f37a593b646fd184c5cfe
refs/heads/master
2018-01-09T01:22:45.034000
2015-11-25T16:30:04
2015-11-25T16:30:04
45,628,746
2
1
null
null
null
null
null
null
null
null
null
null
null
null
null
public class Acs { public static final int P1_LOAD_KEY_INTO_VOLATILE_MEM = 0x00; public static final int P1_LOAD_KEY_INTO_NON_VOLATILE_MEM = 0x20; public static final byte P2_SESSION_KEY = 0x20; public static final byte KEY_A = 0x60; public static final byte KEY_B = 0x61; //Linux: FILE_DEVICE_SMARTCARD = 0x42000000 // IOCTL_X = FILE_DEVICE_SMARTCARD + X //Windows: 0x310000 + X * 4 private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows"); private static final int FILE_DEVICE_SMARTCARD_WINDOWS = 0x310000; private static final int FILE_DEVICE_SMARTCARD_LINUX = 0x42000000; public static final int MakeIoctl(int command) { int base = IS_WINDOWS ? FILE_DEVICE_SMARTCARD_WINDOWS : FILE_DEVICE_SMARTCARD_LINUX; base += IS_WINDOWS ? command * 4 : command; return base; } // Reader action IOCTLs public static final int IOCTL_SMARTCARD_DIRECT = MakeIoctl(2050); public static final int IOCTL_SMARTCARD_SELECT_SLOT = MakeIoctl(2051); public static final int IOCTL_SMARTCARD_DRAW_LCDBMP = MakeIoctl(2052); public static final int IOCTL_SMARTCARD_DISPLAY_LCD = MakeIoctl(2053); public static final int IOCTL_SMARTCARD_CLR_LCD = MakeIoctl(2054); public static final int IOCTL_SMARTCARD_READ_KEYPAD = MakeIoctl(2055); public static final int IOCTL_SMARTCARD_READ_RTC = MakeIoctl(2057); public static final int IOCTL_SMARTCARD_SET_RTC = MakeIoctl(2058); public static final int IOCTL_SMARTCARD_SET_OPTION = MakeIoctl(2059); public static final int IOCTL_SMARTCARD_SET_LED = MakeIoctl(2060); public static final int IOCTL_SMARTCARD_LOAD_KEY = MakeIoctl(2062); public static final int IOCTL_SMARTCARD_READ_EEPROM = MakeIoctl(2065); public static final int IOCTL_SMARTCARD_WRITE_EEPROM = MakeIoctl(2066); public static final int IOCTL_SMARTCARD_GET_VERSION = MakeIoctl(2067); public static final int IOCTL_SMARTCARD_GET_READER_INFO = MakeIoctl(2051); public static final int IOCTL_SMARTCARD_SET_CARD_TYPE = MakeIoctl(2060); public static final int IOCTL_SMARTCARD_ACR128_ESCAPE_COMMAND = MakeIoctl(2079); public static final int IOCTL_SMARTCARD_ACR122_ESCAPE_COMMAND = MakeIoctl(3500); public static final byte[] CMD_GET_FIRMWARE_VERSION = new byte[] { 0x18, 0x00 }; public static final byte[] CMD_SET_BUZZER_DURATION = new byte[] { 0x28, 0x01 }; public static final byte[] CMD_SET_LED_AND_BUZZER_BEHAVIOR = new byte[] { 0x21, 0x01 }; public static final byte[] CMD_GET_LED_AND_BUZZER_BEHAVIOR = new byte[] { 0x21, 0x00 }; }
UTF-8
Java
2,502
java
Acs.java
Java
[ { "context": "_KEY = 0x20;\n\n\tpublic static final byte KEY_A = 0x60;\n\tpublic static final byte KEY_B = 0x61;\n\n\t//Linu", "end": 238, "score": 0.8220528364181519, "start": 236, "tag": "KEY", "value": "60" }, { "context": "KEY_A = 0x60;\n\tpublic static final byte KEY_B = 0x61;\n\n\t//Linux: FILE_DEVICE_SMARTCARD = 0x42000000\n\t/", "end": 278, "score": 0.9403841495513916, "start": 276, "tag": "KEY", "value": "61" } ]
null
[]
public class Acs { public static final int P1_LOAD_KEY_INTO_VOLATILE_MEM = 0x00; public static final int P1_LOAD_KEY_INTO_NON_VOLATILE_MEM = 0x20; public static final byte P2_SESSION_KEY = 0x20; public static final byte KEY_A = 0x60; public static final byte KEY_B = 0x61; //Linux: FILE_DEVICE_SMARTCARD = 0x42000000 // IOCTL_X = FILE_DEVICE_SMARTCARD + X //Windows: 0x310000 + X * 4 private static final boolean IS_WINDOWS = System.getProperty("os.name").startsWith("Windows"); private static final int FILE_DEVICE_SMARTCARD_WINDOWS = 0x310000; private static final int FILE_DEVICE_SMARTCARD_LINUX = 0x42000000; public static final int MakeIoctl(int command) { int base = IS_WINDOWS ? FILE_DEVICE_SMARTCARD_WINDOWS : FILE_DEVICE_SMARTCARD_LINUX; base += IS_WINDOWS ? command * 4 : command; return base; } // Reader action IOCTLs public static final int IOCTL_SMARTCARD_DIRECT = MakeIoctl(2050); public static final int IOCTL_SMARTCARD_SELECT_SLOT = MakeIoctl(2051); public static final int IOCTL_SMARTCARD_DRAW_LCDBMP = MakeIoctl(2052); public static final int IOCTL_SMARTCARD_DISPLAY_LCD = MakeIoctl(2053); public static final int IOCTL_SMARTCARD_CLR_LCD = MakeIoctl(2054); public static final int IOCTL_SMARTCARD_READ_KEYPAD = MakeIoctl(2055); public static final int IOCTL_SMARTCARD_READ_RTC = MakeIoctl(2057); public static final int IOCTL_SMARTCARD_SET_RTC = MakeIoctl(2058); public static final int IOCTL_SMARTCARD_SET_OPTION = MakeIoctl(2059); public static final int IOCTL_SMARTCARD_SET_LED = MakeIoctl(2060); public static final int IOCTL_SMARTCARD_LOAD_KEY = MakeIoctl(2062); public static final int IOCTL_SMARTCARD_READ_EEPROM = MakeIoctl(2065); public static final int IOCTL_SMARTCARD_WRITE_EEPROM = MakeIoctl(2066); public static final int IOCTL_SMARTCARD_GET_VERSION = MakeIoctl(2067); public static final int IOCTL_SMARTCARD_GET_READER_INFO = MakeIoctl(2051); public static final int IOCTL_SMARTCARD_SET_CARD_TYPE = MakeIoctl(2060); public static final int IOCTL_SMARTCARD_ACR128_ESCAPE_COMMAND = MakeIoctl(2079); public static final int IOCTL_SMARTCARD_ACR122_ESCAPE_COMMAND = MakeIoctl(3500); public static final byte[] CMD_GET_FIRMWARE_VERSION = new byte[] { 0x18, 0x00 }; public static final byte[] CMD_SET_BUZZER_DURATION = new byte[] { 0x28, 0x01 }; public static final byte[] CMD_SET_LED_AND_BUZZER_BEHAVIOR = new byte[] { 0x21, 0x01 }; public static final byte[] CMD_GET_LED_AND_BUZZER_BEHAVIOR = new byte[] { 0x21, 0x00 }; }
2,502
0.756595
0.695044
50
49.040001
31.089521
95
false
false
0
0
0
0
0
0
1.62
false
false
12
6fbb4092a2ea006406317beba7ec67c31490356a
16,131,897,172,830
1f61af5e558fdd5c01df86f306965e18711b3f6c
/src/main/java/com/rentacar/utils/Constantes.java
a2528de323d7df19bc5aede477c00de668b02219
[]
no_license
davidparraz41/SpringBoot-RESTFUL-jBPM
https://github.com/davidparraz41/SpringBoot-RESTFUL-jBPM
84971b1a0b8262e0f8ffc0c19aa301fd1e92377a
8a7845309ef8f8393751d4bcc57516ffdf85dc63
refs/heads/master
2020-06-12T01:24:18.982000
2019-07-31T17:36:23
2019-07-31T17:36:23
194,150,787
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.rentacar.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Clase con constantes que se inicializan a partir de un archivo de propiedades * * @author David Parra * */ public class Constantes { private static final Logger logger = LoggerFactory.getLogger(Constantes.class); private static Properties props = new Properties(); public static final String URL_SERVER_KIE; public static final String DEFAULT_USER_SERVER_KIE; public static final String DEFAULT_USER_PASS_SERVER_KIE; public static final String PROCESO_SOLICITUD_COTIZACION; public static final String ID_CONTENEDOR; static { init(); URL_SERVER_KIE = props.getProperty("URL_KIE_SERVER"); DEFAULT_USER_SERVER_KIE = props.getProperty("DEFAULT_USER_SERVER_KIE"); DEFAULT_USER_PASS_SERVER_KIE = props.getProperty("DEFAULT_USER_PASS_SERVER_KIE"); PROCESO_SOLICITUD_COTIZACION = props.getProperty("PROCESO_SOLICITUD_COTIZACION"); ID_CONTENEDOR = props.getProperty("ID_CONTENEDOR"); } /** * Inicializa las constantes de la clase * * @param pResourceFile * @throws IOException */ public static void init() { try { Properties others = new Properties(); InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("application.properties"); others.load(inputStream); inputStream.close(); props.putAll(others); } catch (IOException e) { logger.error("Error al leer el archivo de propiedades, Detalle > " + e.getMessage()); } } }
UTF-8
Java
1,618
java
Constantes.java
Java
[ { "context": "partir de un archivo de propiedades\n * \n * @author David Parra\n *\n */\npublic class Constantes {\n\n\tprivate static", "end": 296, "score": 0.9998376965522766, "start": 285, "tag": "NAME", "value": "David Parra" } ]
null
[]
/** * */ package com.rentacar.utils; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Clase con constantes que se inicializan a partir de un archivo de propiedades * * @author <NAME> * */ public class Constantes { private static final Logger logger = LoggerFactory.getLogger(Constantes.class); private static Properties props = new Properties(); public static final String URL_SERVER_KIE; public static final String DEFAULT_USER_SERVER_KIE; public static final String DEFAULT_USER_PASS_SERVER_KIE; public static final String PROCESO_SOLICITUD_COTIZACION; public static final String ID_CONTENEDOR; static { init(); URL_SERVER_KIE = props.getProperty("URL_KIE_SERVER"); DEFAULT_USER_SERVER_KIE = props.getProperty("DEFAULT_USER_SERVER_KIE"); DEFAULT_USER_PASS_SERVER_KIE = props.getProperty("DEFAULT_USER_PASS_SERVER_KIE"); PROCESO_SOLICITUD_COTIZACION = props.getProperty("PROCESO_SOLICITUD_COTIZACION"); ID_CONTENEDOR = props.getProperty("ID_CONTENEDOR"); } /** * Inicializa las constantes de la clase * * @param pResourceFile * @throws IOException */ public static void init() { try { Properties others = new Properties(); InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("application.properties"); others.load(inputStream); inputStream.close(); props.putAll(others); } catch (IOException e) { logger.error("Error al leer el archivo de propiedades, Detalle > " + e.getMessage()); } } }
1,613
0.736094
0.734858
59
26.423729
26.642138
88
false
false
0
0
0
0
0
0
1.423729
false
false
12
6eea1ff050cbeb8989bc04035fb1ca9d1574a302
6,167,573,067,597
ee18fcb4cc046c0a39997e1bc53cc9e34ee8c30f
/EstruturaCondicional/src/StudentTest.java
b1eb9d4e75a0d07c84bfc8cf8f61caf425559122
[]
no_license
PolixeniaCorreia/JavaComoProgramar
https://github.com/PolixeniaCorreia/JavaComoProgramar
13f9b6eea69f8a0f4e59a4c0e2535fc31ab5a03c
93ca131b084f64e3e7d5d3faec436524c994321f
refs/heads/master
2020-07-03T14:21:03.400000
2019-09-24T19:31:35
2019-09-24T19:31:35
201,933,507
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
public class StudentTest { public static void main(String[] args) { Student nota1 = new Student("Polixenia", 100.0); Student nota2 = new Student("Jonathan", 6.0); System.out.printf("%s letter grade is: %s%n", nota1.getName(), nota1.getLetterGrade()); System.out.printf("%s letter grade is: %s%n", nota2.getName(), nota2.getLetterGrade()); } }
UTF-8
Java
365
java
StudentTest.java
Java
[ { "context": "(String[] args) {\n\t\n\tStudent nota1 = new Student(\"Polixenia\", 100.0);\n\tStudent nota2 = new Student(\"Jonathan\"", "end": 115, "score": 0.9998488426208496, "start": 106, "tag": "NAME", "value": "Polixenia" }, { "context": "Polixenia\", 100.0);\n\tStudent nota2 = new Student(\"Jonathan\", 6.0);\n\t\n\tSystem.out.printf(\"%s letter grade is", "end": 164, "score": 0.9998593330383301, "start": 156, "tag": "NAME", "value": "Jonathan" } ]
null
[]
public class StudentTest { public static void main(String[] args) { Student nota1 = new Student("Polixenia", 100.0); Student nota2 = new Student("Jonathan", 6.0); System.out.printf("%s letter grade is: %s%n", nota1.getName(), nota1.getLetterGrade()); System.out.printf("%s letter grade is: %s%n", nota2.getName(), nota2.getLetterGrade()); } }
365
0.665753
0.632877
13
27
32.04084
89
false
false
0
0
0
0
0
0
1.307692
false
false
12
e227ef62e5eb76e18d8b29ffacba5954b8492e01
26,577,257,671,388
1f47b0b2f4a778be030f1ad7340de7659e64e834
/src/com/io/WhyFileInputStream_Deprecated.java
03de47b6c2f807006812b0722753a16d04d7fa26
[]
no_license
HiuKwok/FlashCard-All-About-Java
https://github.com/HiuKwok/FlashCard-All-About-Java
cbce4479ff3b0f50ff89806d251a6b948f003505
85e9850f0270296c59c1e2982be8bf7289b1a211
refs/heads/master
2020-03-19T19:42:09.516000
2018-11-07T22:34:10
2018-11-07T22:34:10
136,870,233
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.io; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; /* */ /** * This short demo would show how to call Files.newInputStream for ordinary file I/O operation * Instead of conventional FileInputStream method, in order to avoid the performance cost of * Finalize () which implemented on FileInputStream class. * * * As you may wonder how does this oepration help to achieve high performance. * It turn out that as FileOutputStream used, brand new object created along with the finalize method. * And the object only be cleaned up on next GC operation. It would cuase problem for some long-life / daemon app. * Because the resources would be occuptied till next GC and take computing power to destroy it. * * Ref: https://dzone.com/articles/fileinputstream-fileoutputstream-considered-harmful?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed:%20dzone%2Fjava */ public class WhyFileInputStream_Deprecated { public static void main(String[] args) throws FileNotFoundException, IOException { String test = "Testing"; byte[] content = test.getBytes(); oldWrite(content, "./test.txt"); newWrite(content, "./test2.txt"); } public static void oldWrite (byte[] content, String fileName ) throws FileNotFoundException, IOException { try (FileOutputStream fout = new FileOutputStream((fileName)) ) { fout.write(content); } } public static void newWrite (byte[] content, String fileName ) throws IOException { try ( OutputStream os = Files.newOutputStream(Paths.get(fileName) ) ) { os.write(content); } } }
UTF-8
Java
1,727
java
WhyFileInputStream_Deprecated.java
Java
[]
null
[]
package com.io; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; /* */ /** * This short demo would show how to call Files.newInputStream for ordinary file I/O operation * Instead of conventional FileInputStream method, in order to avoid the performance cost of * Finalize () which implemented on FileInputStream class. * * * As you may wonder how does this oepration help to achieve high performance. * It turn out that as FileOutputStream used, brand new object created along with the finalize method. * And the object only be cleaned up on next GC operation. It would cuase problem for some long-life / daemon app. * Because the resources would be occuptied till next GC and take computing power to destroy it. * * Ref: https://dzone.com/articles/fileinputstream-fileoutputstream-considered-harmful?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed:%20dzone%2Fjava */ public class WhyFileInputStream_Deprecated { public static void main(String[] args) throws FileNotFoundException, IOException { String test = "Testing"; byte[] content = test.getBytes(); oldWrite(content, "./test.txt"); newWrite(content, "./test2.txt"); } public static void oldWrite (byte[] content, String fileName ) throws FileNotFoundException, IOException { try (FileOutputStream fout = new FileOutputStream((fileName)) ) { fout.write(content); } } public static void newWrite (byte[] content, String fileName ) throws IOException { try ( OutputStream os = Files.newOutputStream(Paths.get(fileName) ) ) { os.write(content); } } }
1,727
0.741749
0.739433
53
31.584906
39.141945
160
false
false
0
0
0
0
0
0
1.037736
false
false
12
1f39b625429cf8553da7879bcf2969c49fd80516
3,100,966,411,770
f43f351acabf02900bc70adb593a4504fcece44b
/src/main/java/electricPrice/PowerLow.java
48a9492259308e8719dd2f210bde560cde44f6e0
[]
no_license
sonnguyen0610/Inheritance
https://github.com/sonnguyen0610/Inheritance
0d63fee054b2f7eb3d67bbd9e9bf027ffbbeacd1
08f76af65a3009d22a35a98326a224e68e7c3464
refs/heads/master
2023-08-04T01:23:00.071000
2021-09-20T13:12:03
2021-09-20T13:12:03
404,258,281
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package electricPrice; public class PowerLow extends Business { private int normalHour = 2442; private int lowHour = 1361; private int highHour = 4251; @Override public double calcBill() { double totalPrice = normalHour * getNormalHour() + lowHour * getLowHour() + highHour * getHighHour(); return totalPrice * 0.1; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Calculate bill of Business Low power:"); sb.append(calcBill()); return sb.toString(); } }
UTF-8
Java
568
java
PowerLow.java
Java
[]
null
[]
package electricPrice; public class PowerLow extends Business { private int normalHour = 2442; private int lowHour = 1361; private int highHour = 4251; @Override public double calcBill() { double totalPrice = normalHour * getNormalHour() + lowHour * getLowHour() + highHour * getHighHour(); return totalPrice * 0.1; } @Override public String toString() { final StringBuilder sb = new StringBuilder("Calculate bill of Business Low power:"); sb.append(calcBill()); return sb.toString(); } }
568
0.649648
0.625
20
27.4
27.846724
109
false
false
0
0
0
0
0
0
0.45
false
false
12
f5cb61185fbdebd7cf2acece0fd05bea0f21f4f3
7,404,523,659,507
6b4f641859dd5802520b90e9be43a669ba7b4d6a
/src/main/java/com/casehistory/graph/utils/DirectoryUtil.java
828ead9757eddfbb40a2bba4f31cc8297f12b3b8
[]
no_license
newsguy/casehistory-graph
https://github.com/newsguy/casehistory-graph
de31b20be25bccce9183fb4626fb33fd8d7445be
d7baadd3dab493e5ff46638635969f68085822e5
refs/heads/master
2021-01-15T17:29:18.234000
2012-03-27T04:36:07
2012-03-27T04:36:07
3,404,113
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
/** * */ package com.casehistory.graph.utils; import java.io.File; /** * @author Abhinav Tripathi */ public class DirectoryUtil { public static final String PATH_DELIMETER = "/"; public static void build(String path, boolean lastPartIsAFile) { if (pathExists(path)) { int nextDelimIndex = path.indexOf(PATH_DELIMETER, 1); while (nextDelimIndex != -1) { File currentDir = new File(path.substring(0, nextDelimIndex)); if (!currentDir.exists()) { currentDir.mkdir(); } } if (!lastPartIsAFile) { new File(path).mkdir(); } } } public static boolean pathExists(String path) { return new File(path).exists(); } }
UTF-8
Java
664
java
DirectoryUtil.java
Java
[ { "context": "graph.utils;\n\nimport java.io.File;\n\n/**\n * @author Abhinav Tripathi\n */\npublic class DirectoryUtil {\n\n\tpublic static ", "end": 103, "score": 0.9998524785041809, "start": 87, "tag": "NAME", "value": "Abhinav Tripathi" } ]
null
[]
/** * */ package com.casehistory.graph.utils; import java.io.File; /** * @author <NAME> */ public class DirectoryUtil { public static final String PATH_DELIMETER = "/"; public static void build(String path, boolean lastPartIsAFile) { if (pathExists(path)) { int nextDelimIndex = path.indexOf(PATH_DELIMETER, 1); while (nextDelimIndex != -1) { File currentDir = new File(path.substring(0, nextDelimIndex)); if (!currentDir.exists()) { currentDir.mkdir(); } } if (!lastPartIsAFile) { new File(path).mkdir(); } } } public static boolean pathExists(String path) { return new File(path).exists(); } }
654
0.656627
0.652108
34
18.529411
20.162918
66
false
false
0
0
0
0
0
0
1.705882
false
false
12
1c915464ce1af4fb788ad6022c2d6fa9949108c3
32,787,780,366,325
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/java/com/gensym/uitools/attrdisplays/layoutui/AttributeLayoutComponent.java
baea9ab28b09515a6ec5b7b6f6f2c9dbbc8d68a3
[]
no_license
UtsavChokshiCNU/GenSym-Test2
https://github.com/UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559000
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.gensym.uitools.attrdisplays.layoutui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.DefaultListModel; import com.gensym.dlg.StandardDialog; import com.gensym.dlg.StandardDialogClient; import com.gensym.dlg.InputDialog; import com.gensym.message.Resource; import com.gensym.message.Trace; import com.gensym.uitools.attrdisplays.layoutmodel.CollectionListener; import com.gensym.uitools.attrdisplays.layoutmodel.CollectionEvent; import com.gensym.uitools.attrdisplays.layoutmodel.AttributeDisplayLayout; import com.gensym.uitools.attrdisplays.layoutmodel.AttributeDisplayLayoutEditor; import com.gensym.uitools.attrdisplays.layoutmodel.LayoutStructure; import com.gensym.uitools.attrdisplays.layoutmodel.LayoutTableModel; public class AttributeLayoutComponent extends TabbedControlPanel implements ActionListener, StandardDialogClient, CollectionListener { private static Resource dlgLabels = Trace.getBundle("com.gensym.uitools.attrdisplays.DialogLabels"); private JButton removeTabButton; private JButton insertTabButton; private JButton editLabelButton; private int tabNo = 0; private Vector tabLabels = new Vector(); protected String newTabLabel; protected boolean editFlag = false; protected AttributeDisplayLayoutEditor editor; private AttributeLayoutComponent (JButton[] buttons, AttributeDisplayLayoutEditor editor) { super(buttons); removeTabButton = buttons[1]; insertTabButton = buttons[0]; editLabelButton = buttons[2]; removeTabButton.addActionListener(this); insertTabButton.addActionListener(this); editLabelButton.addActionListener(this); removeTabButton.setToolTipText("Remove this display"); insertTabButton.setToolTipText("Add a new display"); editLabelButton.setToolTipText("Name this display"); this.editor = editor; if (editor.getCurrentAttributeDisplayLayouts().length == 0) editor.addAttributeDisplay(null); editor.addCollectionListener(this); } public AttributeLayoutComponent (AttributeDisplayLayoutEditor editor) throws ComponentConstructionException { this(new JButton[]{new JButton(dlgLabels.getString("insert")), new JButton(dlgLabels.getString("remove")), new JButton(dlgLabels.getString("nameDisplay"))}, editor); if (editor == null) throw new ComponentConstructionException("Null editor given to component"); } public void setSelectedIndex(int i) { tabbedPane.setSelectedComponent(tabbedPane.getComponentAt(i)); } public void removeCurrentTab() { tabLabels.removeElementAt(tabbedPane.getSelectedIndex()); tabbedPane.removeTabAt(tabbedPane.getSelectedIndex()); if (tabbedPane.getTabCount() == 0) addTab(editor.createAttributeDisplayLayout()); } public void addTab(AttributeDisplayLayout adl) { AttributeDisplayLayoutPanel tabToAdd = createTab(adl); String tabLabel = tabToAdd.getLabel(); tabbedPane.addTab(tabLabel, (JComponent)tabToAdd); tabLabels.addElement(tabLabel); } AttributeDisplayLayoutPanel createTab(AttributeDisplayLayout adl) { LayoutTableModel tableModel = editor.createLayoutTableModel(adl); DefaultListModel listModel = editor.createListModel(tableModel); String tabLabel; if (newTabLabel == null || newTabLabel.compareTo("") == 0) tabLabel = "display " +(tabNo++); else tabLabel = newTabLabel; newTabLabel = ""; AttributeDisplayLayoutPanel tabToAdd = new AttributeDisplayLayoutPanel(listModel, tableModel, tabLabel, adl.getGlobalLayout(), editor); tabToAdd.addCollectionListener(this); return tabToAdd; } public void insertNewTabAt(int i) { Object title = tabLabels.elementAt(i); AttributeDisplayLayoutPanel tabToAdd = createTab(editor.createAttributeDisplayLayout()); tabbedPane.add((JComponent)tabToAdd, i); tabLabels.insertElementAt("", i); String newtitle = tabToAdd.getLabel(); setTitleOf(i, newtitle); setTitleOf(i+1, title); } public void setTitleOf(int index, Object title) { tabbedPane.setTitleAt(index, title.toString()); tabLabels.setElementAt(title, index); } @Override public void dialogDismissed(StandardDialog labelDlg, int i) { if (labelDlg instanceof InputDialog) if (i == labelDlg.OK || i == labelDlg.APPLY) { newTabLabel = ((InputDialog)labelDlg).getResults()[0]; if (editFlag == true && -1 < tabbedPane.getTabCount()) { if (newTabLabel.compareTo("") !=0) { setTitleOf(tabbedPane.getSelectedIndex(), newTabLabel); } editFlag = false; newTabLabel = ""; } } } public Object[] getTitles() { return tabLabels.toArray(); } public void dispose() { AttributeDisplayLayoutPanel panel; editor.removeCollectionListener(this); for (int i = 0; i<tabbedPane.getTabCount(); i++ ) { panel = (AttributeDisplayLayoutPanel)tabbedPane.getComponentAt(i); panel.removeCollectionListener(this); } } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource() == insertTabButton) editor.insertAttributeDisplayAt(tabbedPane.getSelectedIndex(), null); else if (ae.getSource() == removeTabButton) editor.removeAttributeDisplayAt(tabbedPane.getSelectedIndex()); else if (ae.getSource() == editLabelButton) { InputDialog labelDlg = new InputDialog(null, dlgLabels.getString ("namingNewAttributeDisp"), true, new String[] {dlgLabels.getString ("nameLabelForNewAttDisplay")}, new String[] {""}, this); editFlag = true; labelDlg.setVisible(true); } } public AttributeDisplayLayoutEditor getEditor() { return editor; } @Override public void collectionChanged(CollectionEvent collectionEvent){ Object source = collectionEvent.getSource(); if (source instanceof AttributeDisplayLayoutPanel) { panelEvent((AttributeDisplayLayoutPanel)source); } else if (source instanceof AttributeDisplayLayoutEditor) { editorEvent((AttributeDisplayLayoutEditor)source); } } private void editorEvent(AttributeDisplayLayoutEditor editor) { LayoutTableModel tableModel; DefaultListModel listModel; int length = editor.getCurrentAttributeDisplayLayouts().length; int tabCount = tabbedPane.getTabCount(); if (length > tabCount) insertNewTabAt(tabbedPane.getSelectedIndex()); else if (length < tabCount) removeCurrentTab(); else { int index = tabbedPane.getSelectedIndex(); ((AttributeDisplayLayoutPanel)tabbedPane.getSelectedComponent()). resetLists(editor.getListModelAt(index), editor.getTableModelAt(index)); } } private void panelEvent(AttributeDisplayLayoutPanel panel) { int sourceIndex = tabbedPane.indexOfComponent(panel); AttributeDisplayLayout[] adls = editor.getCurrentAttributeDisplayLayouts(); int edLength = adls.length; int tabCount = tabbedPane.getTabCount(); AttributeDisplayLayout adl; if (edLength >= tabCount) adl = adls[sourceIndex]; else adl = null; if (adl == null) adl = editor.createAttributeDisplayLayout(); if (edLength > 0) { editor.setAttributeDisplayLayoutAt(sourceIndex, panel.getResults(adl)); } else{ editor.addAttributeDisplay(null); editor.setAttributeDisplayLayoutAt(sourceIndex, panel.getResults(adl)); } } }
UTF-8
Java
7,566
java
AttributeLayoutComponent.java
Java
[]
null
[]
package com.gensym.uitools.attrdisplays.layoutui; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.Vector; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.DefaultListModel; import com.gensym.dlg.StandardDialog; import com.gensym.dlg.StandardDialogClient; import com.gensym.dlg.InputDialog; import com.gensym.message.Resource; import com.gensym.message.Trace; import com.gensym.uitools.attrdisplays.layoutmodel.CollectionListener; import com.gensym.uitools.attrdisplays.layoutmodel.CollectionEvent; import com.gensym.uitools.attrdisplays.layoutmodel.AttributeDisplayLayout; import com.gensym.uitools.attrdisplays.layoutmodel.AttributeDisplayLayoutEditor; import com.gensym.uitools.attrdisplays.layoutmodel.LayoutStructure; import com.gensym.uitools.attrdisplays.layoutmodel.LayoutTableModel; public class AttributeLayoutComponent extends TabbedControlPanel implements ActionListener, StandardDialogClient, CollectionListener { private static Resource dlgLabels = Trace.getBundle("com.gensym.uitools.attrdisplays.DialogLabels"); private JButton removeTabButton; private JButton insertTabButton; private JButton editLabelButton; private int tabNo = 0; private Vector tabLabels = new Vector(); protected String newTabLabel; protected boolean editFlag = false; protected AttributeDisplayLayoutEditor editor; private AttributeLayoutComponent (JButton[] buttons, AttributeDisplayLayoutEditor editor) { super(buttons); removeTabButton = buttons[1]; insertTabButton = buttons[0]; editLabelButton = buttons[2]; removeTabButton.addActionListener(this); insertTabButton.addActionListener(this); editLabelButton.addActionListener(this); removeTabButton.setToolTipText("Remove this display"); insertTabButton.setToolTipText("Add a new display"); editLabelButton.setToolTipText("Name this display"); this.editor = editor; if (editor.getCurrentAttributeDisplayLayouts().length == 0) editor.addAttributeDisplay(null); editor.addCollectionListener(this); } public AttributeLayoutComponent (AttributeDisplayLayoutEditor editor) throws ComponentConstructionException { this(new JButton[]{new JButton(dlgLabels.getString("insert")), new JButton(dlgLabels.getString("remove")), new JButton(dlgLabels.getString("nameDisplay"))}, editor); if (editor == null) throw new ComponentConstructionException("Null editor given to component"); } public void setSelectedIndex(int i) { tabbedPane.setSelectedComponent(tabbedPane.getComponentAt(i)); } public void removeCurrentTab() { tabLabels.removeElementAt(tabbedPane.getSelectedIndex()); tabbedPane.removeTabAt(tabbedPane.getSelectedIndex()); if (tabbedPane.getTabCount() == 0) addTab(editor.createAttributeDisplayLayout()); } public void addTab(AttributeDisplayLayout adl) { AttributeDisplayLayoutPanel tabToAdd = createTab(adl); String tabLabel = tabToAdd.getLabel(); tabbedPane.addTab(tabLabel, (JComponent)tabToAdd); tabLabels.addElement(tabLabel); } AttributeDisplayLayoutPanel createTab(AttributeDisplayLayout adl) { LayoutTableModel tableModel = editor.createLayoutTableModel(adl); DefaultListModel listModel = editor.createListModel(tableModel); String tabLabel; if (newTabLabel == null || newTabLabel.compareTo("") == 0) tabLabel = "display " +(tabNo++); else tabLabel = newTabLabel; newTabLabel = ""; AttributeDisplayLayoutPanel tabToAdd = new AttributeDisplayLayoutPanel(listModel, tableModel, tabLabel, adl.getGlobalLayout(), editor); tabToAdd.addCollectionListener(this); return tabToAdd; } public void insertNewTabAt(int i) { Object title = tabLabels.elementAt(i); AttributeDisplayLayoutPanel tabToAdd = createTab(editor.createAttributeDisplayLayout()); tabbedPane.add((JComponent)tabToAdd, i); tabLabels.insertElementAt("", i); String newtitle = tabToAdd.getLabel(); setTitleOf(i, newtitle); setTitleOf(i+1, title); } public void setTitleOf(int index, Object title) { tabbedPane.setTitleAt(index, title.toString()); tabLabels.setElementAt(title, index); } @Override public void dialogDismissed(StandardDialog labelDlg, int i) { if (labelDlg instanceof InputDialog) if (i == labelDlg.OK || i == labelDlg.APPLY) { newTabLabel = ((InputDialog)labelDlg).getResults()[0]; if (editFlag == true && -1 < tabbedPane.getTabCount()) { if (newTabLabel.compareTo("") !=0) { setTitleOf(tabbedPane.getSelectedIndex(), newTabLabel); } editFlag = false; newTabLabel = ""; } } } public Object[] getTitles() { return tabLabels.toArray(); } public void dispose() { AttributeDisplayLayoutPanel panel; editor.removeCollectionListener(this); for (int i = 0; i<tabbedPane.getTabCount(); i++ ) { panel = (AttributeDisplayLayoutPanel)tabbedPane.getComponentAt(i); panel.removeCollectionListener(this); } } @Override public void actionPerformed(ActionEvent ae) { if (ae.getSource() == insertTabButton) editor.insertAttributeDisplayAt(tabbedPane.getSelectedIndex(), null); else if (ae.getSource() == removeTabButton) editor.removeAttributeDisplayAt(tabbedPane.getSelectedIndex()); else if (ae.getSource() == editLabelButton) { InputDialog labelDlg = new InputDialog(null, dlgLabels.getString ("namingNewAttributeDisp"), true, new String[] {dlgLabels.getString ("nameLabelForNewAttDisplay")}, new String[] {""}, this); editFlag = true; labelDlg.setVisible(true); } } public AttributeDisplayLayoutEditor getEditor() { return editor; } @Override public void collectionChanged(CollectionEvent collectionEvent){ Object source = collectionEvent.getSource(); if (source instanceof AttributeDisplayLayoutPanel) { panelEvent((AttributeDisplayLayoutPanel)source); } else if (source instanceof AttributeDisplayLayoutEditor) { editorEvent((AttributeDisplayLayoutEditor)source); } } private void editorEvent(AttributeDisplayLayoutEditor editor) { LayoutTableModel tableModel; DefaultListModel listModel; int length = editor.getCurrentAttributeDisplayLayouts().length; int tabCount = tabbedPane.getTabCount(); if (length > tabCount) insertNewTabAt(tabbedPane.getSelectedIndex()); else if (length < tabCount) removeCurrentTab(); else { int index = tabbedPane.getSelectedIndex(); ((AttributeDisplayLayoutPanel)tabbedPane.getSelectedComponent()). resetLists(editor.getListModelAt(index), editor.getTableModelAt(index)); } } private void panelEvent(AttributeDisplayLayoutPanel panel) { int sourceIndex = tabbedPane.indexOfComponent(panel); AttributeDisplayLayout[] adls = editor.getCurrentAttributeDisplayLayouts(); int edLength = adls.length; int tabCount = tabbedPane.getTabCount(); AttributeDisplayLayout adl; if (edLength >= tabCount) adl = adls[sourceIndex]; else adl = null; if (adl == null) adl = editor.createAttributeDisplayLayout(); if (edLength > 0) { editor.setAttributeDisplayLayoutAt(sourceIndex, panel.getResults(adl)); } else{ editor.addAttributeDisplay(null); editor.setAttributeDisplayLayoutAt(sourceIndex, panel.getResults(adl)); } } }
7,566
0.738567
0.736849
217
33.86636
23.941858
102
false
false
0
0
0
0
0
0
0.9447
false
false
12
7e244db1bc5af5d18d029924d62c2f743098e2d5
10,952,166,663,797
743540992a26e435939620c6d8ea9260a52fd9e2
/university-service/src/main/java/com/pavel/university/service/impl/StudentObjectServiceImpl.java
7339d51fb4eb43533535462ffcd8c3186cbd40b8
[]
no_license
birladeanuPavel/University
https://github.com/birladeanuPavel/University
e1886171b31f52f38262c6df46525a7713c8551a
dfadb43fdc7b217ec0ebb2b24a10b54612b4dcdc
refs/heads/master
2016-09-06T21:28:08.250000
2014-05-04T14:51:37
2014-05-04T14:51:37
null
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
package com.pavel.university.service.impl; /** * Created by Pavel on 30.04.2014. */ import com.pavel.university.dao.StudentObjectDao; import com.pavel.university.dao.impl.StudentObjectDaoImpl; import com.pavel.university.entity.StudentObject; import com.pavel.university.service.StudentObjectService; import java.util.List; public class StudentObjectServiceImpl implements StudentObjectService { private StudentObjectDao studentObjectDao; public StudentObjectServiceImpl() { studentObjectDao = new StudentObjectDaoImpl(); } @Override public void addStudentObject(StudentObject studentObject) { studentObjectDao.save(studentObject); } @Override public void editStudentObject(StudentObject studentObject) { studentObjectDao.update(studentObject); } @Override public List<StudentObject> getAllStudentObject() { return studentObjectDao.loadAll(); } @Override public void removeStudentObject(StudentObject studentObject) { studentObjectDao.delete(studentObject); } @Override public StudentObject getStudentObjectById(Integer id) { return studentObjectDao.findById(id); } }
UTF-8
Java
1,208
java
StudentObjectServiceImpl.java
Java
[ { "context": ".pavel.university.service.impl;\n\n/**\n * Created by Pavel on 30.04.2014.\n */\nimport com.pavel.university.da", "end": 67, "score": 0.9997254014015198, "start": 62, "tag": "NAME", "value": "Pavel" } ]
null
[]
package com.pavel.university.service.impl; /** * Created by Pavel on 30.04.2014. */ import com.pavel.university.dao.StudentObjectDao; import com.pavel.university.dao.impl.StudentObjectDaoImpl; import com.pavel.university.entity.StudentObject; import com.pavel.university.service.StudentObjectService; import java.util.List; public class StudentObjectServiceImpl implements StudentObjectService { private StudentObjectDao studentObjectDao; public StudentObjectServiceImpl() { studentObjectDao = new StudentObjectDaoImpl(); } @Override public void addStudentObject(StudentObject studentObject) { studentObjectDao.save(studentObject); } @Override public void editStudentObject(StudentObject studentObject) { studentObjectDao.update(studentObject); } @Override public List<StudentObject> getAllStudentObject() { return studentObjectDao.loadAll(); } @Override public void removeStudentObject(StudentObject studentObject) { studentObjectDao.delete(studentObject); } @Override public StudentObject getStudentObjectById(Integer id) { return studentObjectDao.findById(id); } }
1,208
0.739238
0.732616
52
22.211538
24.346329
71
false
false
0
0
0
0
0
0
0.25
false
false
12
5ff3ea6e5b572b8f4c7a0354239310c18b083b11
23,124,103,937,784
2524e90b91b608ddd16ed143b5b3bf5ab1bcec6b
/codeforces/1077/E.java
985207ef03be943b4fa2c1eb72a8ec2ce81362ed
[]
no_license
skittles1412/Harwest-Submissions
https://github.com/skittles1412/Harwest-Submissions
2fa5f179eb48930cd7d8c62178bf17c263cdbeee
42f42fb658b882842173997f6b9911f0d3c632aa
refs/heads/master
2023-04-27T15:34:25.227000
2021-05-02T22:13:00
2021-05-06T18:03:37
325,848,839
0
0
null
null
null
null
null
null
null
null
null
null
null
null
null
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.util.Map; import java.io.Flushable; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Objects; import java.io.Closeable; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); EThematicContests solver = new EThematicContests(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class EThematicContests { public EThematicContests() { } public void solve(int kase, Input in, Output pw) { int n = in.nextInt(); HashMap<Integer, Integer> hm = new HashMap<>(); for(int i = 0; i<n; i++) { int x = in.nextInt(); hm.put(x, hm.getOrDefault(x, 0)+1); } int[] arr = new int[n+1]; int cnt = 0; for(Map.Entry<Integer, Integer> e: hm.entrySet()) { arr[e.getValue()]++; if(arr[e.getValue()]==1) { cnt++; } } Pair<Integer, Integer>[] pairs = new Pair[cnt]; int ind = 0; for(int i = 0; i<=n; i++) { if(arr[i]>0) { pairs[ind++] = new Pair<>(i, arr[i]); } } int ans = 0; for(int i = 1; i<=n; i++) { HashMap<Integer, Integer> used = new HashMap<>(); int sum = 0, cur = i; while(true) { ind = Utilities.lowerBound(pairs, new Pair<>(cur, -1)); while(ind!=cnt&&pairs[ind].b-used.getOrDefault(pairs[ind].a, 0)<=0) { ind++; } if(ind==cnt) { break; } used.put(pairs[ind].a, used.getOrDefault(pairs[ind].a, 0)+1); sum += cur; cur <<= 1; } if(cur==i) { break; } if(i%1000==0) { Utilities.Debug.dbg(i); } ans = Math.max(ans, sum); } pw.println(ans); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class Utilities { public static <T extends Comparable<T>> int lowerBound(T[] arr, T target) { int l = 0, h = arr.length; while(l<h) { int mid = l+h >> 1; if(arr[mid].compareTo(target)<0) { l = mid+1; }else { h = mid; } } return l; } public static class Debug { public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> { public T1 a; public T2 b; public Pair(T1 a, T2 b) { this.a = a; this.b = b; } public String toString() { return a+" "+b; } public int hashCode() { return Objects.hash(a, b); } public boolean equals(Object o) { if(o instanceof Pair) { Pair p = (Pair) o; return a.equals(p.a)&&b.equals(p.b); } return false; } public int compareTo(Pair<T1, T2> p) { int cmp = ((Comparable<T1>) a).compareTo(p.a); if(cmp==0) { return ((Comparable<T2>) b).compareTo(p.b); } return cmp; } } }
UTF-8
Java
7,275
java
E.java
Java
[]
null
[]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.HashMap; import java.util.InputMismatchException; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.util.Map; import java.io.Flushable; import java.io.OutputStream; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Objects; import java.io.Closeable; import java.util.Map.Entry; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); EThematicContests solver = new EThematicContests(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class EThematicContests { public EThematicContests() { } public void solve(int kase, Input in, Output pw) { int n = in.nextInt(); HashMap<Integer, Integer> hm = new HashMap<>(); for(int i = 0; i<n; i++) { int x = in.nextInt(); hm.put(x, hm.getOrDefault(x, 0)+1); } int[] arr = new int[n+1]; int cnt = 0; for(Map.Entry<Integer, Integer> e: hm.entrySet()) { arr[e.getValue()]++; if(arr[e.getValue()]==1) { cnt++; } } Pair<Integer, Integer>[] pairs = new Pair[cnt]; int ind = 0; for(int i = 0; i<=n; i++) { if(arr[i]>0) { pairs[ind++] = new Pair<>(i, arr[i]); } } int ans = 0; for(int i = 1; i<=n; i++) { HashMap<Integer, Integer> used = new HashMap<>(); int sum = 0, cur = i; while(true) { ind = Utilities.lowerBound(pairs, new Pair<>(cur, -1)); while(ind!=cnt&&pairs[ind].b-used.getOrDefault(pairs[ind].a, 0)<=0) { ind++; } if(ind==cnt) { break; } used.put(pairs[ind].a, used.getOrDefault(pairs[ind].a, 0)+1); sum += cur; cur <<= 1; } if(cur==i) { break; } if(i%1000==0) { Utilities.Debug.dbg(i); } ans = Math.max(ans, sum); } pw.println(ans); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class Utilities { public static <T extends Comparable<T>> int lowerBound(T[] arr, T target) { int l = 0, h = arr.length; while(l<h) { int mid = l+h >> 1; if(arr[mid].compareTo(target)<0) { l = mid+1; }else { h = mid; } } return l; } public static class Debug { public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null; private static <T> String ts(T t) { if(t==null) { return "null"; } try { return ts((Iterable) t); }catch(ClassCastException e) { if(t instanceof int[]) { String s = Arrays.toString((int[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof long[]) { String s = Arrays.toString((long[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof char[]) { String s = Arrays.toString((char[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof double[]) { String s = Arrays.toString((double[]) t); return "{"+s.substring(1, s.length()-1)+"}"; }else if(t instanceof boolean[]) { String s = Arrays.toString((boolean[]) t); return "{"+s.substring(1, s.length()-1)+"}"; } try { return ts((Object[]) t); }catch(ClassCastException e1) { return t.toString(); } } } private static <T> String ts(T[] arr) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: arr) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } private static <T> String ts(Iterable<T> iter) { StringBuilder ret = new StringBuilder(); ret.append("{"); boolean first = true; for(T t: iter) { if(!first) { ret.append(", "); } first = false; ret.append(ts(t)); } ret.append("}"); return ret.toString(); } public static void dbg(Object... o) { if(LOCAL) { System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": ["); for(int i = 0; i<o.length; i++) { if(i!=0) { System.err.print(", "); } System.err.print(ts(o[i])); } System.err.println("]"); } } } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> { public T1 a; public T2 b; public Pair(T1 a, T2 b) { this.a = a; this.b = b; } public String toString() { return a+" "+b; } public int hashCode() { return Objects.hash(a, b); } public boolean equals(Object o) { if(o instanceof Pair) { Pair p = (Pair) o; return a.equals(p.a)&&b.equals(p.b); } return false; } public int compareTo(Pair<T1, T2> p) { int cmp = ((Comparable<T1>) a).compareTo(p.a); if(cmp==0) { return ((Comparable<T2>) b).compareTo(p.b); } return cmp; } } }
7,275
0.585567
0.57622
335
20.710447
17.15695
96
false
false
0
0
0
0
0
0
3.391045
false
false
12