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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d4ccd41502a89c6fc6231100c8a978a2e0ce37ca | 11,665,131,227,516 | 4b244b3bd51905f168ad7f4c4d7515d742410a07 | /src/main/java/com/flyback/TableNamesReader.java | de9df996c9b68f874a4f73b04fd03dc74ec77523 | [
"MIT"
] | permissive | AlexCue987/flyback | https://github.com/AlexCue987/flyback | d8860a1e041d2b0e15d7b19cd15a5fe392413889 | de89d5eea16065fcafb241e91d8ffc1ccddf14d8 | refs/heads/master | 2020-12-30T13:10:12.388000 | 2017-06-22T14:57:02 | 2017-06-22T14:57:02 | 91,340,088 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.flyback;
import java.sql.SQLException;
import java.util.List;
public interface TableNamesReader {
List<String> get(String owner) throws SQLException, ClassNotFoundException;
}
| UTF-8 | Java | 194 | java | TableNamesReader.java | Java | [] | null | [] | package com.flyback;
import java.sql.SQLException;
import java.util.List;
public interface TableNamesReader {
List<String> get(String owner) throws SQLException, ClassNotFoundException;
}
| 194 | 0.798969 | 0.798969 | 8 | 23.25 | 24.666527 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.625 | false | false | 12 |
f3cfbc97697c0a5a4890fbbc683067b2e2b7fcc5 | 6,030,134,144,406 | 6185225201723db09644a63468c805a4693a150d | /template-domain/src/main/java/br/com/localone/dao/BalancoDAO.java | 738efd6f50c42e85a966bf04ea40523b7e341445 | [] | no_license | pedroaugustogti/template | https://github.com/pedroaugustogti/template | 7838e1c762cc3ea0bc1b3575930ef4819ba18f93 | 6ce62847d70cfc02ff74b687d6fc8aae2005a2a7 | refs/heads/HEAD | 2021-01-17T08:07:11.002000 | 2016-06-21T19:17:37 | 2016-06-21T19:17:37 | 31,964,062 | 0 | 0 | null | false | 2016-06-21T19:17:37 | 2015-03-10T15:07:08 | 2015-04-13T18:50:15 | 2016-06-21T19:17:37 | 120,208 | 0 | 0 | 0 | Java | null | null | package br.com.localone.dao;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Persistence;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import br.com.template.entidades.Balanco;
import br.com.template.generics.ConsultasDaoJpa;
@Stateless
public class BalancoDAO extends ConsultasDaoJpa<Balanco>{
@SuppressWarnings("unchecked")
public List<Balanco> pesquisar(Calendar dataInicio, Calendar dataFim) {
Criteria criteria = super.novoCriterio();
criteria.add(Restrictions.between("fechamentoConta", dataInicio, dataFim));
criteria.addOrder(Order.asc("fechamentoConta"));
return criteria.list();
}
public static void main(String[] args) {
Persistence.generateSchema("desenvolvimento", null);
}
} | UTF-8 | Java | 877 | java | BalancoDAO.java | Java | [] | null | [] | package br.com.localone.dao;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.Persistence;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import br.com.template.entidades.Balanco;
import br.com.template.generics.ConsultasDaoJpa;
@Stateless
public class BalancoDAO extends ConsultasDaoJpa<Balanco>{
@SuppressWarnings("unchecked")
public List<Balanco> pesquisar(Calendar dataInicio, Calendar dataFim) {
Criteria criteria = super.novoCriterio();
criteria.add(Restrictions.between("fechamentoConta", dataInicio, dataFim));
criteria.addOrder(Order.asc("fechamentoConta"));
return criteria.list();
}
public static void main(String[] args) {
Persistence.generateSchema("desenvolvimento", null);
}
} | 877 | 0.754846 | 0.754846 | 33 | 24.636364 | 22.8431 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.272727 | false | false | 12 |
286a339f9328d2872997bf03e6b281c5f1740265 | 19,481,971,702,641 | d04d278f3d223611a564cb50557f5feda86ec089 | /app/src/main/java/com/example/michaelslevin/interfacesegregationsolution/GrizzlyBear.java | 2c7b11f5076c64a13e720873e6ba4fabdc5e5279 | [] | no_license | MichaelCSlevin/BearNeccesities | https://github.com/MichaelCSlevin/BearNeccesities | 1736a037f9d0208a0064d4983f5449dd6a694c87 | 8342b6fa259bf9475033c370d336b2f8a227e9c3 | refs/heads/master | 2021-05-07T19:08:18.116000 | 2017-10-30T12:05:22 | 2017-10-30T12:05:22 | 108,845,056 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.michaelslevin.interfacesegregationsolution;
/**
* Created by michaelslevin on 30/10/2017.
*/
public class GrizzlyBear extends Bear implements NorthAmerican {
public GrizzlyBear() {
}
@Override
public Salmon riverFish() {
return new Salmon();
}
@Override
public Honey harvestHoney() {
return new Honey();
}
@Override
public String climbRocks() {
return "I'm on a rock!";
}
@Override
public String climbTrees() {
return "I'm climbing a tree and haven't fallen down like a stupid panda!";
}
}
| UTF-8 | Java | 607 | java | GrizzlyBear.java | Java | [
{
"context": "package com.example.michaelslevin.interfacesegregationsolution;\n\n/**\n * Created by ",
"end": 33,
"score": 0.7404048442840576,
"start": 20,
"tag": "USERNAME",
"value": "michaelslevin"
},
{
"context": "n.interfacesegregationsolution;\n\n/**\n * Created by michaelslevin... | null | [] | package com.example.michaelslevin.interfacesegregationsolution;
/**
* Created by michaelslevin on 30/10/2017.
*/
public class GrizzlyBear extends Bear implements NorthAmerican {
public GrizzlyBear() {
}
@Override
public Salmon riverFish() {
return new Salmon();
}
@Override
public Honey harvestHoney() {
return new Honey();
}
@Override
public String climbRocks() {
return "I'm on a rock!";
}
@Override
public String climbTrees() {
return "I'm climbing a tree and haven't fallen down like a stupid panda!";
}
}
| 607 | 0.630972 | 0.617792 | 31 | 18.580645 | 21.237177 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.16129 | false | false | 12 |
0bc3c6b09cb037bf360015503c7fbd3eba296c05 | 15,564,961,532,943 | cf63e9efc2eb1a499604b144e628df597f8a7e5e | /prac4c/Truck.java | 56b900df066e15b3b80ed1fe1fe416121e081b19 | [
"MIT"
] | permissive | aghorler/test4-p1 | https://github.com/aghorler/test4-p1 | 3337c9a5c12c76c3d1680b264da5eabaefb2fb0c | b9c1c480e03e8f84680a1184e5e407d4c64f8d20 | refs/heads/master | 2021-01-22T19:58:58.060000 | 2017-06-30T12:22:48 | 2017-06-30T12:22:48 | 85,263,206 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* Subclass of Vehicle */
package prac4c;
public class Truck extends Vehicle{
private String optLoad; //Operation load?
public Truck(){
}
public Truck(String make, String model, int year, boolean isRented, String optLoad){
super(make, model, year);
super.isRented = isRented; //Optionally could have used set method in RentABomb class.
this.optLoad = optLoad;
}
public String getOptLoad(){
return optLoad;
}
public String toString(){
return super.toString() + "\nOperation load: " + optLoad;
}
}
| UTF-8 | Java | 551 | java | Truck.java | Java | [] | null | [] | /* Subclass of Vehicle */
package prac4c;
public class Truck extends Vehicle{
private String optLoad; //Operation load?
public Truck(){
}
public Truck(String make, String model, int year, boolean isRented, String optLoad){
super(make, model, year);
super.isRented = isRented; //Optionally could have used set method in RentABomb class.
this.optLoad = optLoad;
}
public String getOptLoad(){
return optLoad;
}
public String toString(){
return super.toString() + "\nOperation load: " + optLoad;
}
}
| 551 | 0.673321 | 0.671506 | 25 | 20.040001 | 25.003168 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.44 | false | false | 12 |
cd6be1ba119b463895d69cb135ea87b605a74ba1 | 20,358,145,048,419 | eba270447d8ec742dc031bd4f89a6cddd6d4574a | /app/src/main/java/com/example/ummiiii/androidlearner/external.java | 88ea025336f9c1beaf0461acd298b0fa51716c0a | [] | no_license | umerhassan2426/Quiz | https://github.com/umerhassan2426/Quiz | 653a5f4e452d5de9f38a76f39dfbad4c317bfee8 | 018e490e633758409b0ef97e908b2fd419ba86f5 | refs/heads/master | 2020-04-01T18:04:03.110000 | 2018-10-18T06:03:27 | 2018-10-18T06:03:27 | 153,469,319 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.ummiiii.androidlearner;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class external extends Fragment {
public external() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_external, container, false);
ImageView xml16 = (ImageView) view.findViewById(R.id.xml16);
ImageView java16 = (ImageView) view.findViewById(R.id.java16);
ImageView play16 = (ImageView) view.findViewById(R.id.play16);
xml16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externalxml());
fr.commit();
}
});
java16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externaljava());
fr.commit();
}
});
play16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externalplay());
fr.commit();
}
});
return view;
}
}
| UTF-8 | Java | 1,981 | java | external.java | Java | [] | null | [] | package com.example.ummiiii.androidlearner;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
/**
* A simple {@link Fragment} subclass.
*/
public class external extends Fragment {
public external() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_external, container, false);
ImageView xml16 = (ImageView) view.findViewById(R.id.xml16);
ImageView java16 = (ImageView) view.findViewById(R.id.java16);
ImageView play16 = (ImageView) view.findViewById(R.id.play16);
xml16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externalxml());
fr.commit();
}
});
java16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externaljava());
fr.commit();
}
});
play16.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.external_change, new externalplay());
fr.commit();
}
});
return view;
}
}
| 1,981 | 0.618375 | 0.608279 | 62 | 30.951612 | 26.667866 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.516129 | false | false | 12 |
d4a4ab862d78f1e4330309a23ee39fecec420024 | 695,784,771,609 | de3a3b121bb58900134eec13c702509109015843 | /src/main/java/com/xnjr/mall/enums/EStockStatus.java | 94b8677ebf71383dc4d76241e976a4c65050c530 | [] | no_license | yiwocao2017/cswstdmall | https://github.com/yiwocao2017/cswstdmall | 8d422afef6ba338fe5db34683c115b30c03336ff | ad2c10994e7d844429cd74131e903e7b326000e9 | refs/heads/master | 2022-06-27T13:59:26.488000 | 2019-07-01T06:30:05 | 2019-07-01T06:30:05 | 194,613,061 | 0 | 0 | null | false | 2022-06-17T02:17:53 | 2019-07-01T06:30:04 | 2019-07-01T06:30:12 | 2022-06-17T02:17:52 | 251 | 0 | 0 | 6 | Java | false | false | package com.xnjr.mall.enums;
public enum EStockStatus {
TO_effect("1", "待形成"), WILL_effect("2", "待生效"), ING_effect("3", "生效中"), DONE(
"4", "结算完成");
EStockStatus(String code, String value) {
this.code = code;
this.value = value;
}
private String code;
private String value;
public String getCode() {
return code;
}
public String getValue() {
return value;
}
}
| UTF-8 | Java | 472 | java | EStockStatus.java | Java | [] | null | [] | package com.xnjr.mall.enums;
public enum EStockStatus {
TO_effect("1", "待形成"), WILL_effect("2", "待生效"), ING_effect("3", "生效中"), DONE(
"4", "结算完成");
EStockStatus(String code, String value) {
this.code = code;
this.value = value;
}
private String code;
private String value;
public String getCode() {
return code;
}
public String getValue() {
return value;
}
}
| 472 | 0.553812 | 0.544843 | 24 | 17.583334 | 18.779236 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 12 |
53bc438af052e2b1c81511dbf6813fef284a74d8 | 26,568,667,751,254 | 7f2ef2431bdfab02fd51fb47b79b82d749b6ac10 | /DesignPatterns/src/com/construction/BridgeClient.java | 0b15db9f8b6c8439dbd6c7b98048c4aa2c2c115b | [] | no_license | jiveshrelhan/DesignPatterns | https://github.com/jiveshrelhan/DesignPatterns | a9b121cfef48f448a7f3091b6c01537d422c3b4d | 66caedc535a049d1a1e77fa349990af04605068e | refs/heads/master | 2023-08-18T14:51:22.159000 | 2021-09-25T04:41:12 | 2021-09-25T04:41:12 | 410,176,602 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.construction;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.LocalDate;
public class BridgeClient {
public static void main(String[] args) {
StudentRepository repo = new StudentRepository(new FileStorage());
repo.save(new Student());
repo = new StudentRepository(new DataBaseStorage());
repo.save(new Student());
CourseRepository courseRepo = new CourseRepository(new FileStorage());
courseRepo.save(new Course());
courseRepo = new CourseRepository(new DataBaseStorage());
courseRepo.save(new Course());
}
}
class Entity implements Serializable {
private static final long serialVersionUID = -8886785021312618734L;
public int id;
public LocalDate creationDate;
}
class Student extends Entity {
private static final long serialVersionUID = 239093900197332319L;
public String name;
public String section;
}
class Course extends Entity {
private static final long serialVersionUID = 3030456075387849965L;
public String courseName;
public String specialization;
}
interface BaseRepository {
public void save(Entity entity);
}
interface StorageRepository {
public void store(Entity entity);
}
class FileStorage implements StorageRepository {
public void store(Entity entity) {
try {
FileOutputStream fileOut = new FileOutputStream("file");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(entity);
objectOut.close();
System.out.println("Saved to file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DataBaseStorage implements StorageRepository {
@Override
public void store(Entity entity) {
System.out.println("Saving to database");
}
}
class StudentRepository implements BaseRepository {
StorageRepository repo;
StudentRepository(StorageRepository repo) {
this.repo = repo;
}
@Override
public void save(Entity entity) {
repo.store(entity);
}
}
class CourseRepository implements BaseRepository {
StorageRepository repo;
CourseRepository(StorageRepository repo) {
this.repo = repo;
}
@Override
public void save(Entity entity) {
repo.store(entity);
}
}
| UTF-8 | Java | 2,209 | java | BridgeClient.java | Java | [] | null | [] | package com.construction;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.LocalDate;
public class BridgeClient {
public static void main(String[] args) {
StudentRepository repo = new StudentRepository(new FileStorage());
repo.save(new Student());
repo = new StudentRepository(new DataBaseStorage());
repo.save(new Student());
CourseRepository courseRepo = new CourseRepository(new FileStorage());
courseRepo.save(new Course());
courseRepo = new CourseRepository(new DataBaseStorage());
courseRepo.save(new Course());
}
}
class Entity implements Serializable {
private static final long serialVersionUID = -8886785021312618734L;
public int id;
public LocalDate creationDate;
}
class Student extends Entity {
private static final long serialVersionUID = 239093900197332319L;
public String name;
public String section;
}
class Course extends Entity {
private static final long serialVersionUID = 3030456075387849965L;
public String courseName;
public String specialization;
}
interface BaseRepository {
public void save(Entity entity);
}
interface StorageRepository {
public void store(Entity entity);
}
class FileStorage implements StorageRepository {
public void store(Entity entity) {
try {
FileOutputStream fileOut = new FileOutputStream("file");
ObjectOutputStream objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(entity);
objectOut.close();
System.out.println("Saved to file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
class DataBaseStorage implements StorageRepository {
@Override
public void store(Entity entity) {
System.out.println("Saving to database");
}
}
class StudentRepository implements BaseRepository {
StorageRepository repo;
StudentRepository(StorageRepository repo) {
this.repo = repo;
}
@Override
public void save(Entity entity) {
repo.store(entity);
}
}
class CourseRepository implements BaseRepository {
StorageRepository repo;
CourseRepository(StorageRepository repo) {
this.repo = repo;
}
@Override
public void save(Entity entity) {
repo.store(entity);
}
}
| 2,209 | 0.762336 | 0.736985 | 98 | 21.540817 | 20.607195 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.255102 | false | false | 12 |
e68affd010f961fd230733f8a28dcc83a67660f3 | 35,373,350,676,415 | 8a4264374f371f68a74fd41a1c2689e57b58e68c | /application/src/main/java/ec/com/dinersclub/dddmodules/application/logs/ILogging.java | 705da1934ab1d4b90220cb73dd5f722b02d0b23d | [] | no_license | oscarmorocho/ms-core-archetype | https://github.com/oscarmorocho/ms-core-archetype | bec2c328493b44359f7efdb156f47b7b7d3a1234 | d872fb68d2e5324428e94b83ae87b811fad23a6f | refs/heads/main | 2023-04-07T06:01:03.415000 | 2021-04-12T20:21:16 | 2021-04-12T20:21:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ec.com.dinersclub.dddmodules.application.logs;
public interface ILogging {
void debug(String message);
void info(String message);
void warn(String message);
void error(String message);
}
| UTF-8 | Java | 209 | java | ILogging.java | Java | [] | null | [] | package ec.com.dinersclub.dddmodules.application.logs;
public interface ILogging {
void debug(String message);
void info(String message);
void warn(String message);
void error(String message);
}
| 209 | 0.746412 | 0.746412 | 13 | 15.076923 | 16.91818 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 12 |
a33f20258bbf194c62dcdc088deccc02356ec38e | 35,373,350,675,216 | 32cc6b8b56a96dd733ee5042f5c53b8b7c55c455 | /src/main/java/com/blade/mvc/handler/RouteViewResolve.java | 74d0eabe8645533d4a3a5e29de69fccee7a5efd9 | [
"Apache-2.0"
] | permissive | wanken/blade | https://github.com/wanken/blade | ccdd0643a57c5eea299f6ebc35289cd62bc47ad2 | aa9d571ac34b0718602a6e56207522872c0d25be | refs/heads/master | 2021-09-21T17:00:23.730000 | 2017-08-07T07:03:54 | 2017-08-07T07:03:54 | 100,589,140 | 0 | 0 | Apache-2.0 | true | 2018-08-29T09:42:24 | 2017-08-17T09:57:12 | 2017-08-17T09:57:15 | 2018-08-29T09:42:16 | 3,999 | 0 | 0 | 1 | Java | false | null | package com.blade.mvc.handler;
import com.blade.Blade;
import com.blade.exception.BladeException;
import com.blade.ioc.Ioc;
import com.blade.kit.ReflectKit;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.http.Response;
import com.blade.mvc.route.Route;
import com.blade.mvc.ui.ModelAndView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RouteViewResolve {
private Ioc ioc;
public RouteViewResolve(Blade blade) {
this.ioc = blade.ioc();
}
public boolean handle(Signature signature) throws Exception {
try {
Method actionMethod = signature.getAction();
Object target = signature.getRoute().getTarget();
Class<?> returnType = actionMethod.getReturnType();
Response response = signature.response();
Path path = target.getClass().getAnnotation(Path.class);
JSON JSON = actionMethod.getAnnotation(JSON.class);
boolean isRestful = (null != JSON) || (null != path && path.restful());
if (isRestful && !signature.request().userAgent().contains("MSIE")) {
signature.response().contentType("application/json; charset=UTF-8");
}
int len = actionMethod.getParameterTypes().length;
Object returnParam;
if (len > 0) {
returnParam = ReflectKit.invokeMehod(target, actionMethod, signature.getParameters());
} else {
returnParam = ReflectKit.invokeMehod(target, actionMethod);
}
if (null != returnParam) {
if (isRestful) {
response.json(returnParam);
} else {
if (returnType == String.class) {
response.render(returnParam.toString());
} else if (returnType == ModelAndView.class) {
ModelAndView modelAndView = (ModelAndView) returnParam;
response.render(modelAndView);
}
}
return true;
}
} catch (Exception e) {
Throwable t = e;
if (e instanceof InvocationTargetException) {
t = e.getCause();
}
if (t instanceof BladeException) {
throw (BladeException) t;
}
throw new BladeException(t);
}
return false;
}
public boolean invokeHook(Signature routeSignature, Route route) throws BladeException {
Method actionMethod = route.getAction();
Object target = route.getTarget();
if (null == target) {
Class<?> clazz = route.getAction().getDeclaringClass();
target = ioc.getBean(clazz);
route.setTarget(target);
}
// execute
int len = actionMethod.getParameterTypes().length;
actionMethod.setAccessible(true);
try {
Object returnParam;
if (len > 0) {
Signature signature = Signature.builder().route(route)
.request(routeSignature.request()).response(routeSignature.response())
.parameters(routeSignature.getParameters())
.action(actionMethod).build();
Object[] args = MethodArgument.getArgs(signature);
returnParam = ReflectKit.invokeMehod(target, actionMethod, args);
} else {
returnParam = ReflectKit.invokeMehod(target, actionMethod);
}
if (null != returnParam) {
Class<?> returnType = returnParam.getClass();
if (returnType == Boolean.class || returnType == boolean.class) {
return (Boolean) returnParam;
}
}
return true;
} catch (Exception e) {
throw new BladeException(e);
}
}
} | UTF-8 | Java | 4,091 | java | RouteViewResolve.java | Java | [] | null | [] | package com.blade.mvc.handler;
import com.blade.Blade;
import com.blade.exception.BladeException;
import com.blade.ioc.Ioc;
import com.blade.kit.ReflectKit;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.hook.Signature;
import com.blade.mvc.http.Response;
import com.blade.mvc.route.Route;
import com.blade.mvc.ui.ModelAndView;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class RouteViewResolve {
private Ioc ioc;
public RouteViewResolve(Blade blade) {
this.ioc = blade.ioc();
}
public boolean handle(Signature signature) throws Exception {
try {
Method actionMethod = signature.getAction();
Object target = signature.getRoute().getTarget();
Class<?> returnType = actionMethod.getReturnType();
Response response = signature.response();
Path path = target.getClass().getAnnotation(Path.class);
JSON JSON = actionMethod.getAnnotation(JSON.class);
boolean isRestful = (null != JSON) || (null != path && path.restful());
if (isRestful && !signature.request().userAgent().contains("MSIE")) {
signature.response().contentType("application/json; charset=UTF-8");
}
int len = actionMethod.getParameterTypes().length;
Object returnParam;
if (len > 0) {
returnParam = ReflectKit.invokeMehod(target, actionMethod, signature.getParameters());
} else {
returnParam = ReflectKit.invokeMehod(target, actionMethod);
}
if (null != returnParam) {
if (isRestful) {
response.json(returnParam);
} else {
if (returnType == String.class) {
response.render(returnParam.toString());
} else if (returnType == ModelAndView.class) {
ModelAndView modelAndView = (ModelAndView) returnParam;
response.render(modelAndView);
}
}
return true;
}
} catch (Exception e) {
Throwable t = e;
if (e instanceof InvocationTargetException) {
t = e.getCause();
}
if (t instanceof BladeException) {
throw (BladeException) t;
}
throw new BladeException(t);
}
return false;
}
public boolean invokeHook(Signature routeSignature, Route route) throws BladeException {
Method actionMethod = route.getAction();
Object target = route.getTarget();
if (null == target) {
Class<?> clazz = route.getAction().getDeclaringClass();
target = ioc.getBean(clazz);
route.setTarget(target);
}
// execute
int len = actionMethod.getParameterTypes().length;
actionMethod.setAccessible(true);
try {
Object returnParam;
if (len > 0) {
Signature signature = Signature.builder().route(route)
.request(routeSignature.request()).response(routeSignature.response())
.parameters(routeSignature.getParameters())
.action(actionMethod).build();
Object[] args = MethodArgument.getArgs(signature);
returnParam = ReflectKit.invokeMehod(target, actionMethod, args);
} else {
returnParam = ReflectKit.invokeMehod(target, actionMethod);
}
if (null != returnParam) {
Class<?> returnType = returnParam.getClass();
if (returnType == Boolean.class || returnType == boolean.class) {
return (Boolean) returnParam;
}
}
return true;
} catch (Exception e) {
throw new BladeException(e);
}
}
} | 4,091 | 0.55781 | 0.557077 | 112 | 35.535713 | 26.172821 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.580357 | false | false | 12 |
99240910df38dd013a416cd4a0e6e17aec068779 | 35,665,408,447,627 | 4fff554e4c5b8d3acfd3161313c1694171d15dbe | /ecp-web/ecp-web-mall/src/main/java/com/zengshi/ecp/busi/seller/order/vo/ROfflineQueryReqVO.java | 5373a992ea78cef410491d1e3895c703ed4e45bb | [] | no_license | lhllhl2/ecp-busi | https://github.com/lhllhl2/ecp-busi | b21f46374bf0b01342b5a2bef1c2accbbfd0f6e9 | a13d84e59cf4fa14f98db2d443b1ff2b37fafbbb | refs/heads/master | 2020-04-28T18:49:13.731000 | 2019-03-13T20:30:08 | 2019-03-13T20:30:08 | 175,491,111 | 1 | 3 | null | false | 2020-06-15T21:16:34 | 2019-03-13T20:07:34 | 2019-09-09T12:09:22 | 2020-06-15T21:16:32 | 42,414 | 1 | 2 | 6 | Java | false | false | package com.zengshi.ecp.busi.seller.order.vo;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.format.annotation.DateTimeFormat;
import com.zengshi.ecp.base.vo.EcpBasePageReqVO;
public class ROfflineQueryReqVO extends EcpBasePageReqVO{
/**
*
*/
private static final long serialVersionUID = 8923358076454966206L;
/**
* 开始时间
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date begDate;
/**
* 截止时间
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date endDate;
private String orderId;
private String staffId;
private Long shopId;
private Long siteId;
private String applyType;
private String status;
public Long getSiteId() {
return siteId;
}
public void setSiteId(Long siteId) {
this.siteId = siteId;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public Date getBegDate() {
return begDate;
}
public void setBegDate(Date begDate) {
this.begDate = begDate;
}
public Date getEndDate() {
if(endDate!=null){
return DateUtils.addDays(endDate, 1);
}
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getStaffId() {
return staffId;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getApplyType() {
return applyType;
}
public void setApplyType(String applyType) {
this.applyType = applyType;
}
}
| UTF-8 | Java | 2,016 | java | ROfflineQueryReqVO.java | Java | [] | null | [] | package com.zengshi.ecp.busi.seller.order.vo;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.format.annotation.DateTimeFormat;
import com.zengshi.ecp.base.vo.EcpBasePageReqVO;
public class ROfflineQueryReqVO extends EcpBasePageReqVO{
/**
*
*/
private static final long serialVersionUID = 8923358076454966206L;
/**
* 开始时间
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date begDate;
/**
* 截止时间
*/
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date endDate;
private String orderId;
private String staffId;
private Long shopId;
private Long siteId;
private String applyType;
private String status;
public Long getSiteId() {
return siteId;
}
public void setSiteId(Long siteId) {
this.siteId = siteId;
}
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public Date getBegDate() {
return begDate;
}
public void setBegDate(Date begDate) {
this.begDate = begDate;
}
public Date getEndDate() {
if(endDate!=null){
return DateUtils.addDays(endDate, 1);
}
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getStaffId() {
return staffId;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getApplyType() {
return applyType;
}
public void setApplyType(String applyType) {
this.applyType = applyType;
}
}
| 2,016 | 0.6125 | 0.6025 | 103 | 18.407766 | 17.317949 | 70 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.31068 | false | false | 12 |
4fd25fd8f92ef6c9039c5226b0e266eba8c3f7b9 | 21,792,664,117,819 | c62412a636260ea9c6a21648e3db4ab511bcde30 | /Applet/appjbutton.java | 4bcdd85b58de6dc23a8e41b8affec66914388915 | [] | no_license | RajiBala/Java-Lab | https://github.com/RajiBala/Java-Lab | 8a742a5f39764e14e586d19cf62ce605ac838e7a | f26c4d6e64502ee4507a2c4b3ece5328e048cc55 | refs/heads/master | 2020-06-30T13:32:06.054000 | 2016-11-21T13:31:45 | 2016-11-21T13:31:45 | 74,366,874 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*<applet code = "appjbutton.java" width = "320" height = "120">
</applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class appjbutton extends Applet implements ActionListener,TextListener
{
JTextField txtf,res;
Label l1,l3;
JButton get;
public void init()
{
txtf = new JTextField(10);
//txtf.addTextListener(this);
res = new JTextField(10);
txtf.setText("ENTER");
res.setText("number of words in the text field");
setLayout(new GridLayout(0,2));
get = new JButton("get");
get.addActionListener(this);
add(txtf);
add(res);
add(get);
}
public void stop()
{
}
public void actionPerformed(ActionEvent a1)
{
if (a1.getSource()== get)
{
String s = (txtf.getText());
int a = s.length();
String x = String.valueOf(a);
res.setText(x);
repaint();
}
}
public void textValueChanged(TextEvent te)
{
}
}
| UTF-8 | Java | 852 | java | appjbutton.java | Java | [] | null | [] | /*<applet code = "appjbutton.java" width = "320" height = "120">
</applet>*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class appjbutton extends Applet implements ActionListener,TextListener
{
JTextField txtf,res;
Label l1,l3;
JButton get;
public void init()
{
txtf = new JTextField(10);
//txtf.addTextListener(this);
res = new JTextField(10);
txtf.setText("ENTER");
res.setText("number of words in the text field");
setLayout(new GridLayout(0,2));
get = new JButton("get");
get.addActionListener(this);
add(txtf);
add(res);
add(get);
}
public void stop()
{
}
public void actionPerformed(ActionEvent a1)
{
if (a1.getSource()== get)
{
String s = (txtf.getText());
int a = s.length();
String x = String.valueOf(a);
res.setText(x);
repaint();
}
}
public void textValueChanged(TextEvent te)
{
}
}
| 852 | 0.703052 | 0.684272 | 49 | 16.387754 | 17.128347 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.55102 | false | false | 12 |
14b14a51d0ef628d0a0e8e07e4dc97234c697f35 | 35,888,746,751,337 | 50031d204aa1a9d02cc2b06adc1b0fd048ee477a | /src/main/java/uk/liamp/cleaner/Exception/GlobalExceptionHandler.java | fbb857e3bbf360d5fd0fc15094326bc6e2c0a5e8 | [] | no_license | liampuk/marshmallow-backend-test | https://github.com/liampuk/marshmallow-backend-test | c29b1ee914a5a635eb2569e471bc0608b49e6d00 | de19e2a766bb6be954a976428421b2adab7c523f | refs/heads/master | 2022-11-20T22:12:03.071000 | 2020-07-21T08:41:33 | 2020-07-21T08:41:33 | 281,343,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package uk.liamp.cleaner.Exception;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Global exception handler class for the application.
* @author liampuk
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Handler for validation exceptions thrown while parsing JSON. As multiple validation
* errors can occur, a list of error messages is returned.
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
List<String> errorMessages = ex.getBindingResult().getAllErrors().stream().map(e -> e.getDefaultMessage())
.collect(Collectors.toList());
HashMap<String, Object> response = new HashMap<>();
response.put("timestamp", new Date());
response.put("status", "400");
response.put("error", "Bad Request");
response.put("messages", errorMessages);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
/**
* Exception handler for invalid navigation exceptions, for use when the ship
* goes out of bounds or an invalid string is provided in the request.
*/
@ExceptionHandler(InvalidNavigationInstructionsException.class)
public ResponseEntity<Object> handleInvalidNavigationInstructionsException(
InvalidNavigationInstructionsException ex) {
HashMap<String, Object> response = new HashMap<>();
response.put("timestamp", new Date());
response.put("status", "400");
response.put("error", "Bad Request");
response.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}
| UTF-8 | Java | 1,977 | java | GlobalExceptionHandler.java | Java | [
{
"context": "tion handler class for the application.\n * @author liampuk\n */\n@RestControllerAdvice\npublic class GlobalExce",
"end": 519,
"score": 0.999638020992279,
"start": 512,
"tag": "USERNAME",
"value": "liampuk"
}
] | null | [] | package uk.liamp.cleaner.Exception;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* Global exception handler class for the application.
* @author liampuk
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Handler for validation exceptions thrown while parsing JSON. As multiple validation
* errors can occur, a list of error messages is returned.
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleValidationExceptions(MethodArgumentNotValidException ex) {
List<String> errorMessages = ex.getBindingResult().getAllErrors().stream().map(e -> e.getDefaultMessage())
.collect(Collectors.toList());
HashMap<String, Object> response = new HashMap<>();
response.put("timestamp", new Date());
response.put("status", "400");
response.put("error", "Bad Request");
response.put("messages", errorMessages);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
/**
* Exception handler for invalid navigation exceptions, for use when the ship
* goes out of bounds or an invalid string is provided in the request.
*/
@ExceptionHandler(InvalidNavigationInstructionsException.class)
public ResponseEntity<Object> handleInvalidNavigationInstructionsException(
InvalidNavigationInstructionsException ex) {
HashMap<String, Object> response = new HashMap<>();
response.put("timestamp", new Date());
response.put("status", "400");
response.put("error", "Bad Request");
response.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}
| 1,977 | 0.772888 | 0.769853 | 58 | 33.086208 | 29.294159 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.482759 | false | false | 12 |
dd51f67ddddbcc6df05f488db9439b291e0a2c11 | 35,673,998,390,875 | 163f465f7cebdbe319e8a8236a413804af052b13 | /app/src/main/java/com/codekun/androidfirstcode/ch3/Ch3EditTextActivity.java | 94c96d2dc10b73cecfd5360f3066571ad757df21 | [] | no_license | zhstar/AndroidFirstCode | https://github.com/zhstar/AndroidFirstCode | 13c342472f166a409919f91087dce72ab94c33ce | 6d0285d42b7669f3567348928cf9a6c20a3e5d02 | refs/heads/master | 2021-01-10T01:47:39.331000 | 2015-12-12T09:12:34 | 2015-12-12T09:12:34 | 47,251,457 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codekun.androidfirstcode.ch3;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.codekun.androidfirstcode.R;
import com.codekun.androidfirstcode.core.TitleBarActivity;
public class Ch3EditTextActivity extends TitleBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button login_demo = (Button)findViewById(R.id.ch3_login_demo_button);
login_demo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.codekun.androidfirstcode.ACTION_VIEW_LOGIN");
startActivity(i);
}
});
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_ch3_edit_text;
}
}
| UTF-8 | Java | 1,017 | java | Ch3EditTextActivity.java | Java | [] | null | [] | package com.codekun.androidfirstcode.ch3;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.codekun.androidfirstcode.R;
import com.codekun.androidfirstcode.core.TitleBarActivity;
public class Ch3EditTextActivity extends TitleBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button login_demo = (Button)findViewById(R.id.ch3_login_demo_button);
login_demo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.codekun.androidfirstcode.ACTION_VIEW_LOGIN");
startActivity(i);
}
});
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_ch3_edit_text;
}
}
| 1,017 | 0.702065 | 0.697149 | 36 | 27.25 | 24.03282 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 12 |
aa7e7deaf9dcd9d712a67c29f65a36528a286597 | 20,246,475,879,259 | f364d40a8358affb82aa1482e1f92d90dfa3f340 | /src/main/java/com/github/mstraub/exceptions/TryFinally.java | 56f2e701c83c27c2c7b20925ec411b269a8da38a | [
"MIT"
] | permissive | markusstraub/java-playground | https://github.com/markusstraub/java-playground | 7ffc546eedbb1b3745e50585b238fc76fa228642 | 95242661298bc2b03ae656c2068cade088164fb2 | refs/heads/master | 2021-06-20T15:38:51.634000 | 2019-08-20T14:26:14 | 2019-08-20T14:26:14 | 202,143,904 | 0 | 0 | MIT | false | 2021-03-31T21:29:30 | 2019-08-13T12:51:48 | 2019-08-20T14:26:34 | 2021-03-31T21:29:29 | 63 | 0 | 0 | 2 | Java | false | false | package com.github.mstraub.exceptions;
import java.util.List;
import com.google.common.collect.ImmutableList;
public class TryFinally {
public static void main(String[] args) {
List<TestSubject> subjects = ImmutableList.of(new UncaughtExceptionInTryBlock(),
new CaughtExceptionInTryBlock(), new ExceptionInFinallyBlockMaskingPreviousException());
for (TestSubject subject : subjects) {
System.err.println("results for " + subject.getClass().getSimpleName() + ":");
try {
subject.doSomething();
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("\n\n");
}
}
private static interface TestSubject {
void doSomething();
}
private static class UncaughtExceptionInTryBlock implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} finally {
}
}
}
private static class CaughtExceptionInTryBlock implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} catch (Exception e) {
throw new RuntimeException("wrapping the previous exception in another one", e);
} finally {
}
}
}
private static class ExceptionInFinallyBlockMaskingPreviousException implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} finally {
throw new RuntimeException("exception in finally block");
}
}
}
}
| UTF-8 | Java | 1,510 | java | TryFinally.java | Java | [
{
"context": "package com.github.mstraub.exceptions;\n\nimport java.util.List;\n\nimport com.g",
"end": 26,
"score": 0.980421245098114,
"start": 19,
"tag": "USERNAME",
"value": "mstraub"
}
] | null | [] | package com.github.mstraub.exceptions;
import java.util.List;
import com.google.common.collect.ImmutableList;
public class TryFinally {
public static void main(String[] args) {
List<TestSubject> subjects = ImmutableList.of(new UncaughtExceptionInTryBlock(),
new CaughtExceptionInTryBlock(), new ExceptionInFinallyBlockMaskingPreviousException());
for (TestSubject subject : subjects) {
System.err.println("results for " + subject.getClass().getSimpleName() + ":");
try {
subject.doSomething();
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("\n\n");
}
}
private static interface TestSubject {
void doSomething();
}
private static class UncaughtExceptionInTryBlock implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} finally {
}
}
}
private static class CaughtExceptionInTryBlock implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} catch (Exception e) {
throw new RuntimeException("wrapping the previous exception in another one", e);
} finally {
}
}
}
private static class ExceptionInFinallyBlockMaskingPreviousException implements TestSubject {
@Override
public void doSomething() {
try {
throw new RuntimeException("exception in try block");
} finally {
throw new RuntimeException("exception in finally block");
}
}
}
}
| 1,510 | 0.71457 | 0.71457 | 61 | 23.754099 | 27.072857 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.131148 | false | false | 12 |
93e2df5911f9d298450bb7d32611bb92f44f2745 | 26,637,387,192,471 | e60489ac9cb78176821a583b21bb244e3124d285 | /binding/org.openhab.binding.zigbee/src/main/java/org/openhab/binding/zigbee/internal/protocol/ZigbeeEndpoint.java | b8ea5a8e37201a996ce7c1849e7234e6a710a107 | [] | no_license | idau2012/ha | https://github.com/idau2012/ha | 35591273d70bdadbe99f47a694fe292dabecb95f | 166c57f25d59510f77702fd6c25a406da3a3b0d4 | refs/heads/master | 2020-04-05T14:42:57.214000 | 2015-01-05T13:17:25 | 2015-01-05T13:17:25 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright (c) 2010-2014, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zigbee.internal.protocol;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.openhab.binding.zigbee.internal.protocol.commandclass.ZigbeeCommandClass;
import org.openhab.binding.zigbee.internal.protocol.commandclass.ZigbeeCommandClass.CommandClass;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Basic;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Generic;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Specific;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* ZigbeeEndpoint class. Represents an endpoint in case of a Multi-channel node.
*
* @author Jan-Willem Spuij
* @since 1.3.0
*/
@XStreamAlias("endPoint")
public class ZigbeeEndpoint {
private final ZigbeeDeviceClass deviceClass;
private final int endpointId;
private Map<CommandClass, ZigbeeCommandClass> supportedCommandClasses = new HashMap<CommandClass, ZigbeeCommandClass>();
/**
* Constructor. Creates a new instance of the ZigbeeEndpoint class.
* @param node the parent node of this endpoint.
* @param endpointId the endpoint ID.
*/
public ZigbeeEndpoint(int endpointId) {
this.endpointId = endpointId;
this.deviceClass = new ZigbeeDeviceClass(Basic.NOT_KNOWN,
Generic.NOT_KNOWN, Specific.NOT_USED);
}
/**
* Gets the endpoint ID
* @return endpointId the endpointId
*/
public int getEndpointId() {
return endpointId;
}
/**
* Gets the Command classes this endpoint implements.
* @return the command classes.
*/
public Collection<ZigbeeCommandClass> getCommandClasses() {
return supportedCommandClasses.values();
}
/**
* Gets a commandClass object this endpoint implements. Returns null if
* this endpoint does not support this command class.
*
* @param commandClass
* The command class to get.
* @return the command class.
*/
public ZigbeeCommandClass getCommandClass(CommandClass commandClass) {
return supportedCommandClasses.get(commandClass);
}
/**
* Adds a command class to the list of supported command classes by this
* endpoint. Does nothing if command class is already added.
* @param commandClass the command class instance to add.
*/
public void addCommandClass(ZigbeeCommandClass commandClass) {
CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key))
supportedCommandClasses.put(key, commandClass);
}
/**
* Returns the device class for this endpoint.
* @return the deviceClass
*/
public ZigbeeDeviceClass getDeviceClass() {
return deviceClass;
}
}
| UTF-8 | Java | 3,045 | java | ZigbeeEndpoint.java | Java | [
{
"context": " in case of a Multi-channel node.\r\n * \r\n * @author Jan-Willem Spuij\r\n * @since 1.3.0\r\n */\r\n@XStreamAlias(\"endPoint\")\r",
"end": 1062,
"score": 0.9997873306274414,
"start": 1046,
"tag": "NAME",
"value": "Jan-Willem Spuij"
}
] | null | [] | /**
* Copyright (c) 2010-2014, openHAB.org and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zigbee.internal.protocol;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.openhab.binding.zigbee.internal.protocol.commandclass.ZigbeeCommandClass;
import org.openhab.binding.zigbee.internal.protocol.commandclass.ZigbeeCommandClass.CommandClass;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Basic;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Generic;
import org.openhab.binding.zigbee.internal.protocol.ZigbeeDeviceClass.Specific;
import com.thoughtworks.xstream.annotations.XStreamAlias;
/**
* ZigbeeEndpoint class. Represents an endpoint in case of a Multi-channel node.
*
* @author <NAME>
* @since 1.3.0
*/
@XStreamAlias("endPoint")
public class ZigbeeEndpoint {
private final ZigbeeDeviceClass deviceClass;
private final int endpointId;
private Map<CommandClass, ZigbeeCommandClass> supportedCommandClasses = new HashMap<CommandClass, ZigbeeCommandClass>();
/**
* Constructor. Creates a new instance of the ZigbeeEndpoint class.
* @param node the parent node of this endpoint.
* @param endpointId the endpoint ID.
*/
public ZigbeeEndpoint(int endpointId) {
this.endpointId = endpointId;
this.deviceClass = new ZigbeeDeviceClass(Basic.NOT_KNOWN,
Generic.NOT_KNOWN, Specific.NOT_USED);
}
/**
* Gets the endpoint ID
* @return endpointId the endpointId
*/
public int getEndpointId() {
return endpointId;
}
/**
* Gets the Command classes this endpoint implements.
* @return the command classes.
*/
public Collection<ZigbeeCommandClass> getCommandClasses() {
return supportedCommandClasses.values();
}
/**
* Gets a commandClass object this endpoint implements. Returns null if
* this endpoint does not support this command class.
*
* @param commandClass
* The command class to get.
* @return the command class.
*/
public ZigbeeCommandClass getCommandClass(CommandClass commandClass) {
return supportedCommandClasses.get(commandClass);
}
/**
* Adds a command class to the list of supported command classes by this
* endpoint. Does nothing if command class is already added.
* @param commandClass the command class instance to add.
*/
public void addCommandClass(ZigbeeCommandClass commandClass) {
CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key))
supportedCommandClasses.put(key, commandClass);
}
/**
* Returns the device class for this endpoint.
* @return the deviceClass
*/
public ZigbeeDeviceClass getDeviceClass() {
return deviceClass;
}
}
| 3,035 | 0.739245 | 0.734319 | 95 | 30.052631 | 28.61261 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.010526 | false | false | 12 |
e5e40ce7caf298c0c3785fc3f8155e2d29a24453 | 7,438,883,384,374 | 2121abd81ebbefce55ecdbfa4b08083f9509f1e7 | /src/main/java/fourword/InviteDialogFragment.java | e427d4559ec631003eccad12080c72f360ce15fa | [] | no_license | JonathanMurray/4-word | https://github.com/JonathanMurray/4-word | ad85d4a8882da470425d65ca75591078a1d6bd67 | 7f95c7af75ec6ad660d5b7f82501c425204039f7 | refs/heads/master | 2021-01-17T09:33:49.935000 | 2015-08-03T13:49:30 | 2015-08-03T13:49:30 | 37,878,521 | 1 | 3 | null | null | null | null | null | null | null | null | null | null | null | null | null | package fourword;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import fourword_shared.messages.ClientMsg;
import fourword_shared.messages.Msg;
import java.io.IOException;
/**
* Created by jonathan on 2015-06-27.
*/
public class InviteDialogFragment extends DialogFragment{
private String inviterName;
private Bundle args;
public final static String INVITER_NAME = "INVITER_NAME";
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.args = args;
args.putBoolean(LobbyActivity.IS_HOST, false);
inviterName = args.getString(INVITER_NAME);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(inviterName + " has invited you to a game!")
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Connection.instance().sendMessage(new Msg.AcceptInvite());
ChangeActivity.change(getActivity(), LobbyActivity.class, args);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Connection.instance().sendMessage(new Msg.DeclineInvite());
} catch (IOException e) {
e.printStackTrace();
}
}
});
return builder.create();
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
try {
Connection.instance().sendMessage(new Msg.DeclineInvite());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 2,237 | java | InviteDialogFragment.java | Java | [
{
"context": "g;\n\nimport java.io.IOException;\n\n/**\n * Created by jonathan on 2015-06-27.\n */\npublic class InviteDialogFragm",
"end": 315,
"score": 0.9780228137969971,
"start": 307,
"tag": "USERNAME",
"value": "jonathan"
}
] | null | [] | package fourword;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import fourword_shared.messages.ClientMsg;
import fourword_shared.messages.Msg;
import java.io.IOException;
/**
* Created by jonathan on 2015-06-27.
*/
public class InviteDialogFragment extends DialogFragment{
private String inviterName;
private Bundle args;
public final static String INVITER_NAME = "INVITER_NAME";
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.args = args;
args.putBoolean(LobbyActivity.IS_HOST, false);
inviterName = args.getString(INVITER_NAME);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(inviterName + " has invited you to a game!")
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Connection.instance().sendMessage(new Msg.AcceptInvite());
ChangeActivity.change(getActivity(), LobbyActivity.class, args);
} catch (IOException e) {
e.printStackTrace();
}
}
})
.setNegativeButton("Decline", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
Connection.instance().sendMessage(new Msg.DeclineInvite());
} catch (IOException e) {
e.printStackTrace();
}
}
});
return builder.create();
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
try {
Connection.instance().sendMessage(new Msg.DeclineInvite());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 2,237 | 0.582477 | 0.5789 | 66 | 32.89394 | 25.66753 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.515152 | false | false | 12 |
962fbab6ab5770b212ac8dc866c46f91715933f4 | 28,595,892,282,433 | 8f11c2c2162313e92010e10091f41675e47d0555 | /src/com/bijo/learning/oops/Lab264.java | 7e176db79ea216db403298ff09135f749851ae68 | [] | no_license | BIJOAK/JLC | https://github.com/BIJOAK/JLC | c8a03491310974a5a42dce139ab47c84ed2eac83 | c039dbd6b5f29819f027007d04a3147784e9560a | refs/heads/master | 2020-03-21T02:43:56.041000 | 2018-10-06T13:09:23 | 2018-10-06T13:09:23 | 138,015,116 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bijo.learning.oops;
public class Lab264 {
public static void main(String as[]){
Student264 stu1=new Student264(99,"Bijo");
stu1.show();
}
}
class Student264{
int sId;
String sName;
Student264(int id,String name){
System.out.println("2 Arg");
sId=id;
sName=name;
}
Student264(){
System.out.println("Default");
}
void show(){
System.out.println(sId+"\t"+sName);
}
}
| UTF-8 | Java | 478 | java | Lab264.java | Java | [
{
"context": "as[]){\n Student264 stu1=new Student264(99,\"Bijo\");\n stu1.show();\n }\n}\n\nclass Student264",
"end": 145,
"score": 0.9997221827507019,
"start": 141,
"tag": "NAME",
"value": "Bijo"
}
] | null | [] | package com.bijo.learning.oops;
public class Lab264 {
public static void main(String as[]){
Student264 stu1=new Student264(99,"Bijo");
stu1.show();
}
}
class Student264{
int sId;
String sName;
Student264(int id,String name){
System.out.println("2 Arg");
sId=id;
sName=name;
}
Student264(){
System.out.println("Default");
}
void show(){
System.out.println(sId+"\t"+sName);
}
}
| 478 | 0.562761 | 0.514644 | 28 | 16.071428 | 15.25949 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 12 |
28b2824ac0fb82ec3f657608627932d70e994c75 | 29,755,533,459,501 | c26e82f084e617962acc9531fa2b4eb0d0abf699 | /src/org/sosy_lab/cpachecker/util/ci/translators/TranslatorsUtils.java | ec964cbd37559a5b571c7afc39ed0a144ffbf7f6 | [
"Apache-2.0"
] | permissive | niuzhi/cpachecker | https://github.com/niuzhi/cpachecker | 95254eb12d07fb22a1ebbc507f66a402dcf19c48 | 0dd65d278f9d805e3fa2298c2e864d905051d3b5 | refs/heads/trunk | 2023-01-28T06:29:02.450000 | 2020-05-08T11:27:02 | 2020-05-08T11:27:02 | 262,470,214 | 0 | 0 | NOASSERTION | true | 2020-12-11T10:00:03 | 2020-05-09T02:17:11 | 2020-05-09T02:17:13 | 2020-12-11T10:00:01 | 726,798 | 0 | 0 | 1 | null | false | false | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2015 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.util.ci.translators;
public class TranslatorsUtils {
private TranslatorsUtils() {
}
public static String getVarLessOrEqualValRequirement(final String pVar, final Number pVal) {
StringBuilder sb = new StringBuilder();
sb.append("(<= ");
sb.append(pVar);
sb.append(" ");
sb.append(pVal.longValue());
sb.append(")");
return sb.toString();
}
public static String getVarGreaterOrEqualValRequirement(final String pVar, final Number pVal) {
StringBuilder sb = new StringBuilder();
sb.append("(>= ");
sb.append(pVar);
sb.append(" ");
sb.append(pVal.longValue());
sb.append(")");
return sb.toString();
}
public static String getVarInBoundsRequirement(final String pVar, final Number pLow, final Number pHigh) {
StringBuilder sb = new StringBuilder();
sb.append("(and ");
sb.append(getVarGreaterOrEqualValRequirement(pVar, pLow));
sb.append(" ");
sb.append(getVarLessOrEqualValRequirement(pVar, pHigh));
sb.append(")");
return sb.toString();
}
}
| UTF-8 | Java | 1,886 | java | TranslatorsUtils.java | Java | [
{
"context": "art of CPAchecker.\n *\n * Copyright (C) 2007-2015 Dirk Beyer\n * All rights reserved.\n *\n * Licensed under th",
"end": 147,
"score": 0.9998084902763367,
"start": 137,
"tag": "NAME",
"value": "Dirk Beyer"
}
] | null | [] | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2015 <NAME>
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.util.ci.translators;
public class TranslatorsUtils {
private TranslatorsUtils() {
}
public static String getVarLessOrEqualValRequirement(final String pVar, final Number pVal) {
StringBuilder sb = new StringBuilder();
sb.append("(<= ");
sb.append(pVar);
sb.append(" ");
sb.append(pVal.longValue());
sb.append(")");
return sb.toString();
}
public static String getVarGreaterOrEqualValRequirement(final String pVar, final Number pVal) {
StringBuilder sb = new StringBuilder();
sb.append("(>= ");
sb.append(pVar);
sb.append(" ");
sb.append(pVal.longValue());
sb.append(")");
return sb.toString();
}
public static String getVarInBoundsRequirement(final String pVar, final Number pLow, final Number pHigh) {
StringBuilder sb = new StringBuilder();
sb.append("(and ");
sb.append(getVarGreaterOrEqualValRequirement(pVar, pLow));
sb.append(" ");
sb.append(getVarLessOrEqualValRequirement(pVar, pHigh));
sb.append(")");
return sb.toString();
}
}
| 1,882 | 0.69088 | 0.684518 | 61 | 29.918034 | 27.437737 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540984 | false | false | 12 |
2445acf34b1796e2af27aabfc3caabc392f214fd | 10,892,037,072,637 | a98ba4173005f26f00109ad577b112a5f9f85cf0 | /mini-app-service/src/main/java/com/fengchao/miniapp/utils/JSONUtil.java | b12b805caa20b3c1ffac43b01e199c69130a4dbe | [] | no_license | songbw/mini-app | https://github.com/songbw/mini-app | 96c08fa08c02d402dc4493d4699f68135492ead9 | c4b154bfbd88ed6b22357070e5af993d44a397f8 | refs/heads/master | 2023-06-15T01:55:34.821000 | 2020-07-10T03:42:24 | 2020-07-10T03:42:24 | 382,788,659 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.fengchao.miniapp.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JSONUtil {
public static final String toJsonString(Object obj) {
String json = null;
try {
json = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
} catch (Exception e) {
log.error("JSONUtil#toJsonString 异常:{}", e.getMessage(), e);
json = null;
}
return json;
}
public static void main(String args[]) {
Map<String,String> paramMap = new HashMap<>();
paramMap.put("a", "1");
paramMap.put("b", "2");
paramMap.put("c", null);
String dataJson = JSON.toJSONString(paramMap, SerializerFeature.WriteNullStringAsEmpty);
String json = JSON.toJSONString(paramMap, SerializerFeature.WriteMapNullValue);
System.out.println(dataJson);
System.out.println(json);
}
}
| UTF-8 | Java | 1,066 | java | JSONUtil.java | Java | [] | null | [] | package com.fengchao.miniapp.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JSONUtil {
public static final String toJsonString(Object obj) {
String json = null;
try {
json = JSON.toJSONString(obj, SerializerFeature.WriteMapNullValue);
} catch (Exception e) {
log.error("JSONUtil#toJsonString 异常:{}", e.getMessage(), e);
json = null;
}
return json;
}
public static void main(String args[]) {
Map<String,String> paramMap = new HashMap<>();
paramMap.put("a", "1");
paramMap.put("b", "2");
paramMap.put("c", null);
String dataJson = JSON.toJSONString(paramMap, SerializerFeature.WriteNullStringAsEmpty);
String json = JSON.toJSONString(paramMap, SerializerFeature.WriteMapNullValue);
System.out.println(dataJson);
System.out.println(json);
}
}
| 1,066 | 0.645951 | 0.641243 | 41 | 24.902439 | 25.917133 | 96 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.682927 | false | false | 12 |
93fe48a68deb60b247af4f41bcfe8a1ad2460102 | 31,413,390,815,366 | 010bffb02c43f166dabbaefcf207e64068c70546 | /src/main/java/com/yudianbank/tms/dao/SmsContentStatisticsDao.java | 7880c94f3ac3f351cead77a9b7ae4824528a0c9a | [] | no_license | yanfei1819/report-statistics | https://github.com/yanfei1819/report-statistics | 9917bc4e75a03659f8fb816f88b1dad3a1283bba | 938fba919b7be951adcddb5f1f10797be5fa5cea | refs/heads/master | 2021-03-31T01:02:36.343000 | 2018-03-12T02:35:00 | 2018-03-12T02:35:00 | 124,819,994 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.yudianbank.tms.dao;
import com.yudianbank.tms.model.TmsSmsSettingModel;
import com.yudianbank.tms.model.vo.PayAmtStatisticsVO;
import com.yudianbank.tms.model.vo.SmsCarsAmountStatisticsVO;
import java.util.List;
/**
* Created by chengtianren on 2017/8/27.
*/
public interface SmsContentStatisticsDao {
// 按用车性质来查询
List<SmsCarsAmountStatisticsVO> listSendCarsAmount(String startDate, String endDate);
// 统计APP放款金额数据(按支付方式分组)
List<PayAmtStatisticsVO> listPayAmt(String startDate, String endDate);
// 加载短信配置信息
List<TmsSmsSettingModel> listSendSmsSetting();
// 更新配置表时间
int updateTmsSmsSetting(int smsSettingId);
} | UTF-8 | Java | 738 | java | SmsContentStatisticsDao.java | Java | [
{
"context": "ticsVO;\n\nimport java.util.List;\n\n/**\n * Created by chengtianren on 2017/8/27.\n */\npublic interface SmsContentStat",
"end": 257,
"score": 0.9996502995491028,
"start": 245,
"tag": "USERNAME",
"value": "chengtianren"
}
] | null | [] | package com.yudianbank.tms.dao;
import com.yudianbank.tms.model.TmsSmsSettingModel;
import com.yudianbank.tms.model.vo.PayAmtStatisticsVO;
import com.yudianbank.tms.model.vo.SmsCarsAmountStatisticsVO;
import java.util.List;
/**
* Created by chengtianren on 2017/8/27.
*/
public interface SmsContentStatisticsDao {
// 按用车性质来查询
List<SmsCarsAmountStatisticsVO> listSendCarsAmount(String startDate, String endDate);
// 统计APP放款金额数据(按支付方式分组)
List<PayAmtStatisticsVO> listPayAmt(String startDate, String endDate);
// 加载短信配置信息
List<TmsSmsSettingModel> listSendSmsSetting();
// 更新配置表时间
int updateTmsSmsSetting(int smsSettingId);
} | 738 | 0.771903 | 0.761329 | 25 | 25.52 | 26.208578 | 89 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.44 | false | false | 12 |
5cb3c3a253cf8f68b3bbbe53c61e22e617d4c960 | 13,039,520,727,507 | 1979f01cadfe4da009144bbdc476da3dd5dba65a | /src/main/java/com/wine/common/CommonException.java | c90f085f91237ce1f3d902873254ef211f06f582 | [] | no_license | admin88888888/Wine | https://github.com/admin88888888/Wine | b68888b74a2d1dd1caa1a2cf92c9620affae3c9e | d7def0ba8a0f0be89d7e991027d9e5854eaa1e89 | refs/heads/master | 2023-04-29T23:11:01.258000 | 2019-05-25T07:12:20 | 2019-05-25T07:12:20 | 188,045,824 | 0 | 0 | null | false | 2023-04-14T17:39:59 | 2019-05-22T13:35:24 | 2019-05-25T07:12:34 | 2023-04-14T17:39:59 | 360 | 0 | 0 | 3 | Java | false | false | package com.wine.common;
import com.wine.util.JsonUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
// 统一处理异常
// 控制器没有处理的异常,会被该类接收进行处理
@ControllerAdvice
@ResponseBody
public class CommonException {
@ExceptionHandler(Exception.class)
public JsonBean commonException(Exception e){
return JsonUtil.createJsonBean(0, e.getMessage(),null);
}
}
| UTF-8 | Java | 550 | java | CommonException.java | Java | [] | null | [] | package com.wine.common;
import com.wine.util.JsonUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
// 统一处理异常
// 控制器没有处理的异常,会被该类接收进行处理
@ControllerAdvice
@ResponseBody
public class CommonException {
@ExceptionHandler(Exception.class)
public JsonBean commonException(Exception e){
return JsonUtil.createJsonBean(0, e.getMessage(),null);
}
}
| 550 | 0.816532 | 0.814516 | 20 | 23.799999 | 22.966497 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.65 | false | false | 6 |
2a3dbc69bf6d2e3c0d432943ec9227961190d886 | 27,908,697,510,809 | eb5f5353f49ee558e497e5caded1f60f32f536b5 | /org/jcp/xml/dsig/internal/SignerOutputStream.java | cd68cafb14bfb8104ed1e9d21da7d91cf3196ade | [] | no_license | mohitrajvardhan17/java1.8.0_151 | https://github.com/mohitrajvardhan17/java1.8.0_151 | 6fc53e15354d88b53bd248c260c954807d612118 | 6eeab0c0fd20be34db653f4778f8828068c50c92 | refs/heads/master | 2020-03-18T09:44:14.769000 | 2018-05-23T14:28:24 | 2018-05-23T14:28:24 | 134,578,186 | 0 | 2 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.jcp.xml.dsig.internal;
import java.io.ByteArrayOutputStream;
import java.security.Signature;
import java.security.SignatureException;
public class SignerOutputStream
extends ByteArrayOutputStream
{
private final Signature sig;
public SignerOutputStream(Signature paramSignature)
{
sig = paramSignature;
}
public void write(int paramInt)
{
super.write(paramInt);
try
{
sig.update((byte)paramInt);
}
catch (SignatureException localSignatureException)
{
throw new RuntimeException(localSignatureException);
}
}
public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
super.write(paramArrayOfByte, paramInt1, paramInt2);
try
{
sig.update(paramArrayOfByte, paramInt1, paramInt2);
}
catch (SignatureException localSignatureException)
{
throw new RuntimeException(localSignatureException);
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\org\jcp\xml\dsig\internal\SignerOutputStream.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 1,139 | java | SignerOutputStream.java | Java | [] | null | [] | package org.jcp.xml.dsig.internal;
import java.io.ByteArrayOutputStream;
import java.security.Signature;
import java.security.SignatureException;
public class SignerOutputStream
extends ByteArrayOutputStream
{
private final Signature sig;
public SignerOutputStream(Signature paramSignature)
{
sig = paramSignature;
}
public void write(int paramInt)
{
super.write(paramInt);
try
{
sig.update((byte)paramInt);
}
catch (SignatureException localSignatureException)
{
throw new RuntimeException(localSignatureException);
}
}
public void write(byte[] paramArrayOfByte, int paramInt1, int paramInt2)
{
super.write(paramArrayOfByte, paramInt1, paramInt2);
try
{
sig.update(paramArrayOfByte, paramInt1, paramInt2);
}
catch (SignatureException localSignatureException)
{
throw new RuntimeException(localSignatureException);
}
}
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\org\jcp\xml\dsig\internal\SignerOutputStream.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | 1,139 | 0.702371 | 0.683933 | 48 | 22.75 | 26.183249 | 129 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 6 |
5ef903b71a716b5e853ff4a4049813297360c732 | 19,524,921,362,151 | d87deebc1dcee0072ac9a57ceb9a95087b1f0e20 | /Tester/src/ui/SignUp.java | a0a64bed9252ae40c617f726370e3ef2ede52d71 | [] | no_license | kurohashi/eclipse | https://github.com/kurohashi/eclipse | 08db082ea1aa458c2df486797883ba6d11a97108 | a9afc923e5dbd6ef7dc99ad4c3d643b8ae5d37f8 | refs/heads/master | 2020-08-09T00:15:57.609000 | 2019-10-09T15:47:02 | 2019-10-09T15:47:02 | 213,955,914 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ui;
import javax.swing.GroupLayout.Alignment;
import socket.Message;
import socket.SocketClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
public class SignUp extends SigningFrame {
private static final long serialVersionUID = -1004635773602792697L;
private JLabel labelConfirmPassword;
private JPasswordField textBoxConfirmPassword;
private JButton buttonSignUp;
private SocketClient socket;
public SignUp() {
labelConfirmPassword = new JLabel("Confirm Password");
textBoxConfirmPassword = new JPasswordField();
buttonSignUp = new JButton("Sign Up");
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGap(50)
.addGroup(layout.createParallelGroup()
.addComponent(labelUsername)
.addComponent(labelPassword)
.addComponent(labelConfirmPassword))
.addGap(30)
.addGroup(layout.createParallelGroup()
.addComponent(textBoxUsername)
.addComponent(textBoxPassword)
.addComponent(textBoxConfirmPassword))
.addGap(50))
.addComponent(buttonSignUp));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(labelUsername)
.addComponent(textBoxUsername))
.addGap(12)
.addGroup(layout.createParallelGroup()
.addComponent(labelPassword)
.addComponent(textBoxPassword))
.addGap(12)
.addGroup(layout.createParallelGroup()
.addComponent(labelConfirmPassword)
.addComponent(textBoxConfirmPassword))
.addGap(12)
.addComponent(buttonSignUp));
repaint();
buttonSignUp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
signUpActionPerformed();
}
});
}
private void signUpActionPerformed() {
socket.send(new Message("signup", labelUsername.getText(), labelPassword.getText(), "SERVER"));
setAccount();
}
}
| UTF-8 | Java | 2,095 | java | SignUp.java | Java | [] | null | [] | package ui;
import javax.swing.GroupLayout.Alignment;
import socket.Message;
import socket.SocketClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
public class SignUp extends SigningFrame {
private static final long serialVersionUID = -1004635773602792697L;
private JLabel labelConfirmPassword;
private JPasswordField textBoxConfirmPassword;
private JButton buttonSignUp;
private SocketClient socket;
public SignUp() {
labelConfirmPassword = new JLabel("Confirm Password");
textBoxConfirmPassword = new JPasswordField();
buttonSignUp = new JButton("Sign Up");
layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER)
.addGroup(layout.createSequentialGroup()
.addGap(50)
.addGroup(layout.createParallelGroup()
.addComponent(labelUsername)
.addComponent(labelPassword)
.addComponent(labelConfirmPassword))
.addGap(30)
.addGroup(layout.createParallelGroup()
.addComponent(textBoxUsername)
.addComponent(textBoxPassword)
.addComponent(textBoxConfirmPassword))
.addGap(50))
.addComponent(buttonSignUp));
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(labelUsername)
.addComponent(textBoxUsername))
.addGap(12)
.addGroup(layout.createParallelGroup()
.addComponent(labelPassword)
.addComponent(textBoxPassword))
.addGap(12)
.addGroup(layout.createParallelGroup()
.addComponent(labelConfirmPassword)
.addComponent(textBoxConfirmPassword))
.addGap(12)
.addComponent(buttonSignUp));
repaint();
buttonSignUp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
signUpActionPerformed();
}
});
}
private void signUpActionPerformed() {
socket.send(new Message("signup", labelUsername.getText(), labelPassword.getText(), "SERVER"));
setAccount();
}
}
| 2,095 | 0.741289 | 0.726014 | 71 | 28.507042 | 20.204498 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.28169 | false | false | 6 |
4081960f4a49029808517f9b75376b8653224b76 | 7,696,581,425,858 | 17415f650e8863f8d8fc5ac3a4a88b7696fa2cbc | /src/Hobbit.java | da9fec3091228c527f5b8c36887fa82b3405ec0d | [] | no_license | LuisAlejandroMendez/Se-orAnillos-IPC1-Vacas | https://github.com/LuisAlejandroMendez/Se-orAnillos-IPC1-Vacas | f503479a1b951e95a8d4fb7884b61cfd516eddac | 132edc42520571b03e5c518525775afcf1d5ad50 | refs/heads/main | 2023-06-03T02:09:45.771000 | 2021-06-23T22:07:07 | 2021-06-23T22:07:07 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | public class Hobbit extends Heroes {
private static int instanciaHobbit=0;
public Hobbit(String nombre){
super(200, 40, nombre);
Hobbit.instanciaHobbit++;
}
@Override
public void saludar(){
System.out.println("Hola soy un Heroe, mi nombre es: " + this.nombre+" y soy un Hobbit.");
}
@Override
public int getAtaque(Personaje defensor){
if(defensor instanceof Trasgo){
System.out.println("- Miedo de Hobbit (ataque disminuido -5 contra Trasgo) -");
return this.ataque -5;
}
return this.ataque;
}
public static int getInstancia(){
return Hobbit.instanciaHobbit;
}
}
| UTF-8 | Java | 691 | java | Hobbit.java | Java | [] | null | [] | public class Hobbit extends Heroes {
private static int instanciaHobbit=0;
public Hobbit(String nombre){
super(200, 40, nombre);
Hobbit.instanciaHobbit++;
}
@Override
public void saludar(){
System.out.println("Hola soy un Heroe, mi nombre es: " + this.nombre+" y soy un Hobbit.");
}
@Override
public int getAtaque(Personaje defensor){
if(defensor instanceof Trasgo){
System.out.println("- Miedo de Hobbit (ataque disminuido -5 contra Trasgo) -");
return this.ataque -5;
}
return this.ataque;
}
public static int getInstancia(){
return Hobbit.instanciaHobbit;
}
}
| 691 | 0.613603 | 0.602026 | 26 | 25.576923 | 25.139875 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.423077 | false | false | 6 |
12248424db074f0e03061d58ed13ce1496f92b4c | 15,212,774,186,810 | 19bfb1d138fd7a810ad4d99f571eb0a4866727ed | /Cribbage/src/cribbage/Logger.java | 92fa9615e28f5a9554f5c5a59c8dbb537c756686 | [] | no_license | is0xjh25/swen30006-project-2 | https://github.com/is0xjh25/swen30006-project-2 | eae67febf5024a04ea6bf9253f9c69c08fe88024 | 5b5970d98dcc6fe0ead444e1f05e22dc73c4d264 | refs/heads/main | 2023-05-06T13:43:45.356000 | 2021-08-24T16:26:02 | 2021-08-24T16:26:02 | 356,096,212 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cribbage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.*;
// Reference for File Class
// https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20java.lang.Iterable,%20java.nio.charset.Charset,%20java.nio.file.OpenOption...)
/* SWEN-30006-Project2
Created by Workshop16Team02, May 28th 2021
*/
public class Logger {
private static final Logger logger = new Logger();
private final Path filePath = Path.of("cribbage.log");
private Logger() {
try {
Files.deleteIfExists(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Logger getInstance() {
return logger;
}
// Logger the message output
public void log(String string) {
string = string + "\n";
byte[] logByte = string.getBytes();
try {
Files.write(filePath, logByte, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 1,120 | java | Logger.java | Java | [] | null | [] | package cribbage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.*;
// Reference for File Class
// https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#write(java.nio.file.Path,%20java.lang.Iterable,%20java.nio.charset.Charset,%20java.nio.file.OpenOption...)
/* SWEN-30006-Project2
Created by Workshop16Team02, May 28th 2021
*/
public class Logger {
private static final Logger logger = new Logger();
private final Path filePath = Path.of("cribbage.log");
private Logger() {
try {
Files.deleteIfExists(filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Logger getInstance() {
return logger;
}
// Logger the message output
public void log(String string) {
string = string + "\n";
byte[] logByte = string.getBytes();
try {
Files.write(filePath, logByte, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 1,120 | 0.634821 | 0.614286 | 45 | 23.888889 | 30.452311 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.466667 | false | false | 6 |
f6f50ec6a1a5df3254591150856ecbb8a6487069 | 10,823,317,629,869 | a67fa2dd162235371c914a68bb7c02a2a5b3db9e | /compiler/src/roxanne/quad/Quad.java | b594e842ea187136544a96f31aa5dc353fa9b3cf | [] | no_license | lostleaf/cpu | https://github.com/lostleaf/cpu | 4bdcbc2eb412ddb6bf59c397a39dd75fa4b61bdc | 14251933ed94cfb5779577b46af24cb513cf1bb7 | refs/heads/master | 2020-12-30T09:58:07.844000 | 2013-06-23T12:03:47 | 2013-06-23T12:03:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package roxanne.quad;
import roxanne.addr.Temp;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;
import roxanne.asm.*;
import roxanne.asm.Asm.Op;
import roxanne.addr.*;
import roxanne.ast.Expr.OpType;
import roxanne.error.Error;
import roxanne.translate.Level;
import roxanne.util.Constants;
public abstract class Quad implements Constants {
public LinkedHashSet<Temp> in = new LinkedHashSet<Temp> ();
public LinkedHashSet<Temp> out = new LinkedHashSet<Temp>();
public boolean isLeader = false;
//for DefReach
public int DRcount = 0;
public LinkedHashSet<Quad> DRin = new LinkedHashSet<Quad>();
public LinkedHashSet<Quad> DRout = new LinkedHashSet<Quad>();
public enum ConstMode {ALU, BR, LI, PCOFFSET};
public static Quad makeBiop(Temp dest, Addr l, OpType op, Addr r) {
if (l instanceof Temp && r instanceof Temp)
return new Biop(dest, (Temp)l, op, (Temp)r);
else if (op == OpType.PLUS || op == OpType.PLUS || op == OpType.BITAND
|| op == OpType.BITOR || op == OpType.BITXOR){
if (l instanceof Const)
return new BioprI(dest, (Temp) r, op, (Const)l);
else return new BioprI(dest, (Temp)l, op, (Const)r);
} else {
if (l instanceof Const)
return new BioplI(dest, (Const)l, op, (Temp)r);
else return new BioprI(dest, (Temp)l, op, (Const)r);
}
}
public static Quad makeMove(Temp dst, Addr src) {
if (src instanceof Const)
return new MoveI(dst, (Const)src);
else if (src instanceof Label)
return new MoveA(dst, (Label)src);
else return new Move(dst, (Temp)src);
}
public static Quad makeStore(Addr dst, Const index, Addr src) {
/*
* if addr of dst to store is const (unconsidered) although it wouldn't happen in my design now??
*/
if (index == null) index = new Const(0);
if (src instanceof Const)
return new StoreI((Temp)dst, index, (Const) src);
else return new Store((Temp)dst, index, (Temp)src);
}
public static Quad makeUop(Temp dst, OpType op, Addr src) {
return new Uop(dst, op, (Temp)src);
}
// temporary??
public abstract LinkedList<Asm> gen() throws Error;
public boolean isJump() { return false; }
public LABEL jumpLABEL() { return null; }
public LinkedHashSet<Temp> use() {
LinkedHashSet<Temp> set = new LinkedHashSet<Temp>();
return set;
}
public LinkedHashSet<Temp> def() {
LinkedHashSet<Temp> set = new LinkedHashSet<Temp>();
return set;
}
//for DefReach
public boolean isDef() {
return true;
}
public static void findAddr(Temp t, LinkedHashSet<Temp> set) {
/*
* for each temp find the register that temp used,
* each temp can use only one register, even if its addr is a temp other than fp, gp
* since if a temp is not spilled we find the register, whatever its addr is used, since we will not load from its addr once it's not spilled
* if it's spilled, the same applies to its register
*/
/*
* if not must be spilled, the address must be directly calculated before
* <=> if the address not calculated before, it must be spilled,since it must be a calculated temp of type pointer
*/
if (t!=null && t.addr instanceof Temp && t.addr != Temp.fp && t.addr != Temp.gp)
if (!((Temp)t.addr).mustBeSpilled())
set.add((Temp)t.addr);
else findAddr((Temp)t.addr, set);
if (t!=null && t.index instanceof Temp && t.index != Temp.fp && t.index != Temp.gp)
if (!((Temp)t.index).mustBeSpilled())
set.add((Temp)t.index);
else findAddr((Temp)t.index, set);
}
protected void addDef(LinkedHashSet<Temp> set, Addr t) {
if (t == null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled() || t == Temp.fp || t == Temp.gp)
return;
set.add((Temp)t);
}
protected void addDefToUse(LinkedHashSet<Temp> set, Addr t) {
if (t == null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled()) {
findAddr((Temp)t, set);
}
}
protected void addUse(LinkedHashSet<Temp> set, Addr t) {
if (t==null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled()) {
findAddr((Temp)t ,set);
} else if (t != Temp.fp && t != Temp.gp)
set.add((Temp)t);
}
/*protected int[] getMax(OpType op) {
switch (op) {
case MINUS: case PLUS: case TIMES: case ASSIGN:
}
}*/
// for codegen
protected static int[] getMinMax(ConstMode m) {
int min = 0, max = 0;
switch (m) {
case ALU: case PCOFFSET:
min = minInt;
max = maxInt;
break;
case LI:
min = minLiInt;
max = maxLiInt;
break;
case BR:
min = minBrInt;
max = maxBrInt;
break;
}
int ans[] = {min, max};
return ans;
}
protected static boolean outOfBound(int n, ConstMode m) {
int a[] = getMinMax(m);
int min = a[0], max = a[1];
if (min <= n && n <= max)
return false;
return true;
}
public static Temp genBeforeUse(LinkedList<Asm> strings, Temp t) {
if (!t.mustBeSpilled())
return t;
return t.genBeforeUse(strings);
}
public static Temp genBeforeDef(Temp t) {
if (!t.mustBeSpilled())
return t;
return t.level.newTemp(t.width);
}
public static Addr genBeforeUseConst(LinkedList<Asm> strings, Const num, Level lvl, ConstMode m) {
int a[] = getMinMax(m);
int min = a[0], max = a[1];
if (min <= num.value && num.value <= max)
return num;
int rest = 0;
Temp ans = lvl.newTemp();
if (num.value < min) {
rest = num.value - min;
strings.add(new Asm(Op.li, ans, new Const(min), null));
} else {
strings.add(new Asm(Op.li, ans, new Const(max), null));
rest = num.value - max;
}
strings.add(new Asm(Op.addi, ans, ans, new Const(rest)));
return ans;
}
protected static void genAfterDef(LinkedList<Asm> strings, Temp t, Temp storeDst) {
if (!t.mustBeSpilled())
return;
strings.addAll(t.genAfterDef(storeDst));
}
protected static Asm.Op getOp(OpType op) throws Error {
switch(op) {
case PLUS: return Op.add;
case MINUS: return Op.sub;
case TIMES: return Op.mul;
default: throw new Error("get illegal op: "+op);
}
}
public static Op getOpI(OpType op) throws Error{
switch(op) {
case PLUS: return Op.addi;
case MINUS: return Op.subi;
case TIMES: return Op.muli;
default:
throw new Error("get illegal op: "+op);
}
}
protected static Op getBranchOp(OpType op) throws Error{
switch(op) {
case GE: return Op.bge;
default: throw new Error("get illegal branch op: "+op);
}
}
/*protected static int[] getFirst2NotUsed(Temp t0, Temp t1, Temp t2) {
Integer reg0 = find(t0), reg1 = find(t1), reg2 = find(t2);
//System.out.println(((reg0==null)?null:regNames[reg0])+", "+((reg1 == null)? null:regNames[reg1])+", "+((reg2 == null)? reg2:regNames[reg2]));
int ans[] = new int[2], cnt = 0;
for (int i = baseOfSavedRegisters+numOfSavedRegisters-1; i>=baseOfSavedRegisters && cnt<2; --i) {
if ((reg0!=null && reg0 == i) || (reg1 != null && i==reg1) || (reg2 != null && i == reg2))
continue;
else {
ans[cnt++] = i;
}
}
//System.out.println("regs: "+regNames[ans[0]]+", "+regNames[ans[1]]);
return ans;
}*/
public static String genAddress(String addr, String index) {
return addr+", "+index;
}
/*public static String genAddress(LinkedList<String> strings, Const index, String addrName, int reg) {
if (index == null)
return addrName+", "+0;
String constName = genBeforeUseConst(strings, new Const(-index.value), reg, ConstMode.PCOFFSET);
return addrName+", "+constName;
}*/
public String toString() {
//StringBuffer str = new StringBuffer("\n");
/*str.append("\t\tin: "+in+"\n");
str.append("\t\tout: "+out+"\n");
str.append("\t\tDRin: "+DRin+"\n");
str.append("\t\tDRout: "+DRout+"\n");*/
//return str.toString();
return new String();
}
}
| UTF-8 | Java | 7,664 | java | Quad.java | Java | [] | null | [] | package roxanne.quad;
import roxanne.addr.Temp;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Set;
import roxanne.asm.*;
import roxanne.asm.Asm.Op;
import roxanne.addr.*;
import roxanne.ast.Expr.OpType;
import roxanne.error.Error;
import roxanne.translate.Level;
import roxanne.util.Constants;
public abstract class Quad implements Constants {
public LinkedHashSet<Temp> in = new LinkedHashSet<Temp> ();
public LinkedHashSet<Temp> out = new LinkedHashSet<Temp>();
public boolean isLeader = false;
//for DefReach
public int DRcount = 0;
public LinkedHashSet<Quad> DRin = new LinkedHashSet<Quad>();
public LinkedHashSet<Quad> DRout = new LinkedHashSet<Quad>();
public enum ConstMode {ALU, BR, LI, PCOFFSET};
public static Quad makeBiop(Temp dest, Addr l, OpType op, Addr r) {
if (l instanceof Temp && r instanceof Temp)
return new Biop(dest, (Temp)l, op, (Temp)r);
else if (op == OpType.PLUS || op == OpType.PLUS || op == OpType.BITAND
|| op == OpType.BITOR || op == OpType.BITXOR){
if (l instanceof Const)
return new BioprI(dest, (Temp) r, op, (Const)l);
else return new BioprI(dest, (Temp)l, op, (Const)r);
} else {
if (l instanceof Const)
return new BioplI(dest, (Const)l, op, (Temp)r);
else return new BioprI(dest, (Temp)l, op, (Const)r);
}
}
public static Quad makeMove(Temp dst, Addr src) {
if (src instanceof Const)
return new MoveI(dst, (Const)src);
else if (src instanceof Label)
return new MoveA(dst, (Label)src);
else return new Move(dst, (Temp)src);
}
public static Quad makeStore(Addr dst, Const index, Addr src) {
/*
* if addr of dst to store is const (unconsidered) although it wouldn't happen in my design now??
*/
if (index == null) index = new Const(0);
if (src instanceof Const)
return new StoreI((Temp)dst, index, (Const) src);
else return new Store((Temp)dst, index, (Temp)src);
}
public static Quad makeUop(Temp dst, OpType op, Addr src) {
return new Uop(dst, op, (Temp)src);
}
// temporary??
public abstract LinkedList<Asm> gen() throws Error;
public boolean isJump() { return false; }
public LABEL jumpLABEL() { return null; }
public LinkedHashSet<Temp> use() {
LinkedHashSet<Temp> set = new LinkedHashSet<Temp>();
return set;
}
public LinkedHashSet<Temp> def() {
LinkedHashSet<Temp> set = new LinkedHashSet<Temp>();
return set;
}
//for DefReach
public boolean isDef() {
return true;
}
public static void findAddr(Temp t, LinkedHashSet<Temp> set) {
/*
* for each temp find the register that temp used,
* each temp can use only one register, even if its addr is a temp other than fp, gp
* since if a temp is not spilled we find the register, whatever its addr is used, since we will not load from its addr once it's not spilled
* if it's spilled, the same applies to its register
*/
/*
* if not must be spilled, the address must be directly calculated before
* <=> if the address not calculated before, it must be spilled,since it must be a calculated temp of type pointer
*/
if (t!=null && t.addr instanceof Temp && t.addr != Temp.fp && t.addr != Temp.gp)
if (!((Temp)t.addr).mustBeSpilled())
set.add((Temp)t.addr);
else findAddr((Temp)t.addr, set);
if (t!=null && t.index instanceof Temp && t.index != Temp.fp && t.index != Temp.gp)
if (!((Temp)t.index).mustBeSpilled())
set.add((Temp)t.index);
else findAddr((Temp)t.index, set);
}
protected void addDef(LinkedHashSet<Temp> set, Addr t) {
if (t == null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled() || t == Temp.fp || t == Temp.gp)
return;
set.add((Temp)t);
}
protected void addDefToUse(LinkedHashSet<Temp> set, Addr t) {
if (t == null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled()) {
findAddr((Temp)t, set);
}
}
protected void addUse(LinkedHashSet<Temp> set, Addr t) {
if (t==null || t instanceof Const) return;
if (((Temp)t).mustBeSpilled()) {
findAddr((Temp)t ,set);
} else if (t != Temp.fp && t != Temp.gp)
set.add((Temp)t);
}
/*protected int[] getMax(OpType op) {
switch (op) {
case MINUS: case PLUS: case TIMES: case ASSIGN:
}
}*/
// for codegen
protected static int[] getMinMax(ConstMode m) {
int min = 0, max = 0;
switch (m) {
case ALU: case PCOFFSET:
min = minInt;
max = maxInt;
break;
case LI:
min = minLiInt;
max = maxLiInt;
break;
case BR:
min = minBrInt;
max = maxBrInt;
break;
}
int ans[] = {min, max};
return ans;
}
protected static boolean outOfBound(int n, ConstMode m) {
int a[] = getMinMax(m);
int min = a[0], max = a[1];
if (min <= n && n <= max)
return false;
return true;
}
public static Temp genBeforeUse(LinkedList<Asm> strings, Temp t) {
if (!t.mustBeSpilled())
return t;
return t.genBeforeUse(strings);
}
public static Temp genBeforeDef(Temp t) {
if (!t.mustBeSpilled())
return t;
return t.level.newTemp(t.width);
}
public static Addr genBeforeUseConst(LinkedList<Asm> strings, Const num, Level lvl, ConstMode m) {
int a[] = getMinMax(m);
int min = a[0], max = a[1];
if (min <= num.value && num.value <= max)
return num;
int rest = 0;
Temp ans = lvl.newTemp();
if (num.value < min) {
rest = num.value - min;
strings.add(new Asm(Op.li, ans, new Const(min), null));
} else {
strings.add(new Asm(Op.li, ans, new Const(max), null));
rest = num.value - max;
}
strings.add(new Asm(Op.addi, ans, ans, new Const(rest)));
return ans;
}
protected static void genAfterDef(LinkedList<Asm> strings, Temp t, Temp storeDst) {
if (!t.mustBeSpilled())
return;
strings.addAll(t.genAfterDef(storeDst));
}
protected static Asm.Op getOp(OpType op) throws Error {
switch(op) {
case PLUS: return Op.add;
case MINUS: return Op.sub;
case TIMES: return Op.mul;
default: throw new Error("get illegal op: "+op);
}
}
public static Op getOpI(OpType op) throws Error{
switch(op) {
case PLUS: return Op.addi;
case MINUS: return Op.subi;
case TIMES: return Op.muli;
default:
throw new Error("get illegal op: "+op);
}
}
protected static Op getBranchOp(OpType op) throws Error{
switch(op) {
case GE: return Op.bge;
default: throw new Error("get illegal branch op: "+op);
}
}
/*protected static int[] getFirst2NotUsed(Temp t0, Temp t1, Temp t2) {
Integer reg0 = find(t0), reg1 = find(t1), reg2 = find(t2);
//System.out.println(((reg0==null)?null:regNames[reg0])+", "+((reg1 == null)? null:regNames[reg1])+", "+((reg2 == null)? reg2:regNames[reg2]));
int ans[] = new int[2], cnt = 0;
for (int i = baseOfSavedRegisters+numOfSavedRegisters-1; i>=baseOfSavedRegisters && cnt<2; --i) {
if ((reg0!=null && reg0 == i) || (reg1 != null && i==reg1) || (reg2 != null && i == reg2))
continue;
else {
ans[cnt++] = i;
}
}
//System.out.println("regs: "+regNames[ans[0]]+", "+regNames[ans[1]]);
return ans;
}*/
public static String genAddress(String addr, String index) {
return addr+", "+index;
}
/*public static String genAddress(LinkedList<String> strings, Const index, String addrName, int reg) {
if (index == null)
return addrName+", "+0;
String constName = genBeforeUseConst(strings, new Const(-index.value), reg, ConstMode.PCOFFSET);
return addrName+", "+constName;
}*/
public String toString() {
//StringBuffer str = new StringBuffer("\n");
/*str.append("\t\tin: "+in+"\n");
str.append("\t\tout: "+out+"\n");
str.append("\t\tDRin: "+DRin+"\n");
str.append("\t\tDRout: "+DRout+"\n");*/
//return str.toString();
return new String();
}
}
| 7,664 | 0.648356 | 0.643267 | 268 | 27.597015 | 26.533594 | 145 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.567164 | false | false | 6 |
b69d3bb8b4d84eebe2da9659519cc00d6ee41b47 | 5,480,378,277,370 | 6d85f701ab4d656a98d72d1365a9e6a345caecb4 | /s3_ivanysusbambam-web/src/main/java/co/edu/uniandes/csw/ivanysusbambam/dtos/ClienteDTO.java | c6c4517c0aa4412570673e06acaaac7f226d1ce1 | [
"MIT"
] | permissive | IvanGarL/IvanySusBamBam | https://github.com/IvanGarL/IvanySusBamBam | 656d75858cdc48eb202c3c38c1ee774565096dd3 | 0414bfa8c9792f89ed215d7e3ec99926d69e534b | refs/heads/master | 2020-03-29T01:57:42.511000 | 2018-09-24T04:20:23 | 2018-09-24T04:20:23 | 149,415,365 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.edu.uniandes.csw.ivanysusbambam.dtos;
import co.edu.uniandes.csw.ivanysusbambam.entities.ClienteEntity;
/**
* Objeto de transferencia de datos del cliente.<br>
* Al serializarse como JSON esta clase implementa el siguiente modelo: <br>
* <pre>
* {
*
* "nombre": string,
* "cedula": number
* }
* </pre> Por ejemplo un cliente se representa así:<br>
*
* <pre>
*
* {
* "nombre": "Felipe Velasquez",
* "cedula": 1016609031
* }
*
* </pre>
*
*
* @author Felipe Velásquez Montoya <pre>
* Versiones:
* 10/02/2018
* -Creación de atributos
* -Creación de getters y setters
* 12/02/2018
* -Extendida documentacion.
* </pre>
*/
public class ClienteDTO {
/**
* Representa el nombre del cliente.
*/
private String nombre;
/**
* Representa el número de cédula del cliente.
*/
private Long cedula;
/**
* Representa la imagen del cliente
*/
private String imagen;
//Constructor vacío
/**
* Constructor por defecto.
*/
public ClienteDTO() {
//Constructor utilizado por JAX
}
/**
* Construye el DTO a partir de un entity correspondiente.
*
* @param ce entity al partir de que se construirá el DTO.
*/
public ClienteDTO(ClienteEntity ce) {
if (ce != null) {
this.nombre = ce.getNombre();
this.cedula = ce.getCedula();
this.imagen = ce.getImagen();
}
}
/**
* Contruye un Entity y le da la información del DTO.
*
* @return Entity construido a partir del DTO.
*/
public ClienteEntity toEntity() {
ClienteEntity ce = new ClienteEntity();
ce.setNombre(nombre);
ce.setCedula(cedula);
ce.setImagen(imagen);
return ce;
}
//----------------------GETTERS-----------------------------------------
/**
* @return el nombre del cliente.
*/
public String getNombre() {
return nombre;
}
/**
* @return la cédula del cliente.
*/
public Long getCedula() {
return cedula;
}
//---------------------SETTERS---------------------------
/**
* @param nombre nuevo nombre del cliente
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* Este método no debería ser llamado por nadie menos JAX.
*
* @param cedula del cliente
*/
public void setCedula(Long cedula) {
this.cedula = cedula;
}
/**
* @return retorna la imagen del cliente
*/
public String getImagen() {
return imagen;
}
/**
* Setea la imagen del cliente a la imagen dada por parametro
*
* @param imagen imagen del cliente
*/
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
| UTF-8 | Java | 3,019 | java | ClienteDTO.java | Java | [
{
"context": "br>\r\n *\r\n * <pre>\r\n *\r\n * {\r\n * \"nombre\": \"Felipe Velasquez\",\r\n * \"cedula\": 1016609031\r\n * }\r\n *\r\n * <",
"end": 459,
"score": 0.9998703002929688,
"start": 443,
"tag": "NAME",
"value": "Felipe Velasquez"
},
{
"context": "6609031\r\n ... | null | [] | package co.edu.uniandes.csw.ivanysusbambam.dtos;
import co.edu.uniandes.csw.ivanysusbambam.entities.ClienteEntity;
/**
* Objeto de transferencia de datos del cliente.<br>
* Al serializarse como JSON esta clase implementa el siguiente modelo: <br>
* <pre>
* {
*
* "nombre": string,
* "cedula": number
* }
* </pre> Por ejemplo un cliente se representa así:<br>
*
* <pre>
*
* {
* "nombre": "<NAME>",
* "cedula": 1016609031
* }
*
* </pre>
*
*
* @author <NAME> <pre>
* Versiones:
* 10/02/2018
* -Creación de atributos
* -Creación de getters y setters
* 12/02/2018
* -Extendida documentacion.
* </pre>
*/
public class ClienteDTO {
/**
* Representa el nombre del cliente.
*/
private String nombre;
/**
* Representa el número de cédula del cliente.
*/
private Long cedula;
/**
* Representa la imagen del cliente
*/
private String imagen;
//Constructor vacío
/**
* Constructor por defecto.
*/
public ClienteDTO() {
//Constructor utilizado por JAX
}
/**
* Construye el DTO a partir de un entity correspondiente.
*
* @param ce entity al partir de que se construirá el DTO.
*/
public ClienteDTO(ClienteEntity ce) {
if (ce != null) {
this.nombre = ce.getNombre();
this.cedula = ce.getCedula();
this.imagen = ce.getImagen();
}
}
/**
* Contruye un Entity y le da la información del DTO.
*
* @return Entity construido a partir del DTO.
*/
public ClienteEntity toEntity() {
ClienteEntity ce = new ClienteEntity();
ce.setNombre(nombre);
ce.setCedula(cedula);
ce.setImagen(imagen);
return ce;
}
//----------------------GETTERS-----------------------------------------
/**
* @return el nombre del cliente.
*/
public String getNombre() {
return nombre;
}
/**
* @return la cédula del cliente.
*/
public Long getCedula() {
return cedula;
}
//---------------------SETTERS---------------------------
/**
* @param nombre nuevo nombre del cliente
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* Este método no debería ser llamado por nadie menos JAX.
*
* @param cedula del cliente
*/
public void setCedula(Long cedula) {
this.cedula = cedula;
}
/**
* @return retorna la imagen del cliente
*/
public String getImagen() {
return imagen;
}
/**
* Setea la imagen del cliente a la imagen dada por parametro
*
* @param imagen imagen del cliente
*/
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
| 2,990 | 0.52012 | 0.511473 | 134 | 20.440298 | 19.49608 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.156716 | false | false | 6 |
0c8aa829559a8966adb4d4985d595ef585b02502 | 11,003,706,278,516 | cc92b17910d697d4e689cffdf5fab8333b2ff599 | /CampusCheckin/CampusCheckin/src/main/java/campusCheckin/CampusCheckinController.java | 615d2769a2f4567cae7c6bef2bdf1b76cebbaf9d | [] | no_license | abarnaks/4314 | https://github.com/abarnaks/4314 | 5dfb1fee4b5094de4e50e5877578910dca236a07 | d1bffa7c0dfe7caea7c4fc72abd1a7cc4f1fb230 | refs/heads/master | 2023-01-22T18:10:09.867000 | 2020-12-03T20:50:11 | 2020-12-03T20:50:11 | 298,328,975 | 0 | 1 | null | false | 2020-11-16T16:36:56 | 2020-09-24T16:04:35 | 2020-11-10T21:01:41 | 2020-11-16T16:36:55 | 430 | 0 | 1 | 0 | Java | false | false | package campusCheckin;
import org.springframework.hateoas.EntityModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class CampusCheckinController {
@RequestMapping({"/", "/login"})
public String index(@RequestParam(name="error_msg", required=false) String error_msg, Model model) {
model.addAttribute("error_msg", error_msg);
return "index";
}
// @RequestMapping({"/", "/login"})
// public String index() {
//
// return "index";
// }
//
@PostMapping("/hello")
public String sayHello(@RequestParam("name") String name, @RequestParam("studid") String studid, @RequestParam("em") String em, Model model) {
model.addAttribute("name", name);
model.addAttribute("studid", studid);
model.addAttribute("em", em);
return "hello";
}
@RequestMapping("/signup")
public String signupPage() {
// model.addAttribute("username", username);
// model.addAttribute("password", password);
return "createProfile";
}
@RequestMapping("/booking/{roomName}")
public String bookingPage(Model model, String[] params) {
model.addAttribute("buildingName", params[1]);
model.addAttribute("roomName", params[0]);
model.addAttribute("time_slot", params[2]);
model.addAttribute("currentCap", params[3]);
model.addAttribute("max_cap", params[4]);
return "booking";
}
// @RequestMapping("/login")
// public String login() {
// // model.addAttribute("username", username);
// // model.addAttribute("password", password);
// return "homelogin";
// }
// @RequestMapping("/welcome")
// public String available(Model model, String name,String building1,String building2,String building3,String building4, String building1_cap, String building2_cap,String building3_cap ,String building4_cap) {
//
// model.addAttribute("name", name);
// model.addAttribute("building1", building1);
// model.addAttribute("building2", building2);
// model.addAttribute("building3", building3);
// model.addAttribute("building4", building4);
// model.addAttribute("building1_cap", building1_cap);
// model.addAttribute("building2_cap", building2_cap);
// model.addAttribute("building3_cap", building3_cap);
// model.addAttribute("building4_cap", building4_cap);
// // model.addAttribute("username", username);
// // model
// return "welcome";
// }
@RequestMapping("/welcome")
public String available(Model model, String[] params) {
model.addAttribute("name", params[0]);
model.addAttribute("building1", params[1]);
model.addAttribute("building2", params[2]);
model.addAttribute("building3", params[3]);
model.addAttribute("building4", params[4]);
model.addAttribute("building1_cap", params[5]);
model.addAttribute("building2_cap", params[6]);
model.addAttribute("building3_cap", params[7]);
model.addAttribute("building4_cap", params[8]);
model.addAttribute("Booking1", params[9]);
model.addAttribute("Booking2", params[10]);
model.addAttribute("Booking3", params[11]);
// model.addAttribute("username", username);
// model
return "welcome";
}
@RequestMapping("rooms/{buildingName}")
public String book(Model model, String[] params) {
model.addAttribute("buildingName", params[0]);
model.addAttribute("Room1", params[1]);
model.addAttribute("Room2", params[2]);
model.addAttribute("Room3", params[3]);
model.addAttribute("Room4", params[4]);
model.addAttribute("Room1cap", params[5]);
model.addAttribute("Room2cap", params[6]);
model.addAttribute("Room3cap", params[7]);
model.addAttribute("Room4cap", params[8]);
model.addAttribute("time_h", params[9]);
model.addAttribute("date", params[10]);
model.addAttribute("CurrentCap1", params[11]);
model.addAttribute("CurrentCap2", params[12]);
model.addAttribute("CurrentCap3", params[13]);
model.addAttribute("CurrentCap4", params[14]);
// model
return "rooms";
}
@RequestMapping("/confirmation")
public String confirmation(Model model, String[] params) {
model.addAttribute("roomName", params[0]);
model.addAttribute("buildingName", params[1]);
model.addAttribute("time_slot", params[2]);
model.addAttribute("study_size", params[3]);
return "confirmation";
}
@GetMapping({"/greeting"})
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
| UTF-8 | Java | 5,046 | java | CampusCheckinController.java | Java | [
{
"context": "nupPage() {\n // model.addAttribute(\"username\", username);\n // model.addAttribute(\"password\", password",
"end": 1337,
"score": 0.9135862588882446,
"start": 1329,
"tag": "USERNAME",
"value": "username"
},
{
"context": " username);\n // model.addAttribute... | null | [] | package campusCheckin;
import org.springframework.hateoas.EntityModel;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Controller
public class CampusCheckinController {
@RequestMapping({"/", "/login"})
public String index(@RequestParam(name="error_msg", required=false) String error_msg, Model model) {
model.addAttribute("error_msg", error_msg);
return "index";
}
// @RequestMapping({"/", "/login"})
// public String index() {
//
// return "index";
// }
//
@PostMapping("/hello")
public String sayHello(@RequestParam("name") String name, @RequestParam("studid") String studid, @RequestParam("em") String em, Model model) {
model.addAttribute("name", name);
model.addAttribute("studid", studid);
model.addAttribute("em", em);
return "hello";
}
@RequestMapping("/signup")
public String signupPage() {
// model.addAttribute("username", username);
// model.addAttribute("password", <PASSWORD>);
return "createProfile";
}
@RequestMapping("/booking/{roomName}")
public String bookingPage(Model model, String[] params) {
model.addAttribute("buildingName", params[1]);
model.addAttribute("roomName", params[0]);
model.addAttribute("time_slot", params[2]);
model.addAttribute("currentCap", params[3]);
model.addAttribute("max_cap", params[4]);
return "booking";
}
// @RequestMapping("/login")
// public String login() {
// // model.addAttribute("username", username);
// // model.addAttribute("password", <PASSWORD>);
// return "homelogin";
// }
// @RequestMapping("/welcome")
// public String available(Model model, String name,String building1,String building2,String building3,String building4, String building1_cap, String building2_cap,String building3_cap ,String building4_cap) {
//
// model.addAttribute("name", name);
// model.addAttribute("building1", building1);
// model.addAttribute("building2", building2);
// model.addAttribute("building3", building3);
// model.addAttribute("building4", building4);
// model.addAttribute("building1_cap", building1_cap);
// model.addAttribute("building2_cap", building2_cap);
// model.addAttribute("building3_cap", building3_cap);
// model.addAttribute("building4_cap", building4_cap);
// // model.addAttribute("username", username);
// // model
// return "welcome";
// }
@RequestMapping("/welcome")
public String available(Model model, String[] params) {
model.addAttribute("name", params[0]);
model.addAttribute("building1", params[1]);
model.addAttribute("building2", params[2]);
model.addAttribute("building3", params[3]);
model.addAttribute("building4", params[4]);
model.addAttribute("building1_cap", params[5]);
model.addAttribute("building2_cap", params[6]);
model.addAttribute("building3_cap", params[7]);
model.addAttribute("building4_cap", params[8]);
model.addAttribute("Booking1", params[9]);
model.addAttribute("Booking2", params[10]);
model.addAttribute("Booking3", params[11]);
// model.addAttribute("username", username);
// model
return "welcome";
}
@RequestMapping("rooms/{buildingName}")
public String book(Model model, String[] params) {
model.addAttribute("buildingName", params[0]);
model.addAttribute("Room1", params[1]);
model.addAttribute("Room2", params[2]);
model.addAttribute("Room3", params[3]);
model.addAttribute("Room4", params[4]);
model.addAttribute("Room1cap", params[5]);
model.addAttribute("Room2cap", params[6]);
model.addAttribute("Room3cap", params[7]);
model.addAttribute("Room4cap", params[8]);
model.addAttribute("time_h", params[9]);
model.addAttribute("date", params[10]);
model.addAttribute("CurrentCap1", params[11]);
model.addAttribute("CurrentCap2", params[12]);
model.addAttribute("CurrentCap3", params[13]);
model.addAttribute("CurrentCap4", params[14]);
// model
return "rooms";
}
@RequestMapping("/confirmation")
public String confirmation(Model model, String[] params) {
model.addAttribute("roomName", params[0]);
model.addAttribute("buildingName", params[1]);
model.addAttribute("time_slot", params[2]);
model.addAttribute("study_size", params[3]);
return "confirmation";
}
@GetMapping({"/greeting"})
public String greeting(@RequestParam(name="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
| 5,050 | 0.676377 | 0.658145 | 138 | 35.565216 | 28.046793 | 211 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.384058 | false | false | 6 |
041380051b0c1e9bedb24fe169e90ddab0859b7c | 25,056,839,252,229 | 04197d80ffa37dedb017288d93cdc81590048ae2 | /tron/src/main/java/objects/Game.java | d081e3bec0f012b090b15ba15c0d18741df671b6 | [] | no_license | sybernatuz/codingame | https://github.com/sybernatuz/codingame | 6fd57f5646c15042521286cc55256362d0e80bba | aa6ffd738e9b3524a6c0ad159b9b1397a160b371 | refs/heads/master | 2023-06-22T20:17:24.784000 | 2023-06-07T15:32:53 | 2023-06-07T15:32:53 | 178,948,197 | 1 | 1 | null | false | 2023-06-05T16:42:26 | 2019-04-01T21:16:10 | 2021-11-13T11:35:36 | 2023-06-05T16:42:25 | 186 | 0 | 1 | 1 | Java | false | false | package objects;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Game {
public static int MAX_X = 30;
public static int MAX_Y = 20;
public static int MIN = 0;
public List<Moto> motos;
public ZoneType[][] grid = new ZoneType[MAX_Y][MAX_X];
private static final Game INSTANCE = new Game();
public static Game getInstance() {
return INSTANCE;
}
public Game() {
for (int y = 0; y < MAX_Y; y++) {
for (int x = 0; x < MAX_X; x++) {
grid[y][x] = ZoneType.FREE;
}
}
}
public void update(Scanner in) {
if (motos != null) {
for (Moto moto : motos) {
grid[moto.coordinate.y][moto.coordinate.x] = ZoneType.BLOCKED;
}
}
int playersNumber = in.nextInt();
int myNumber = in.nextInt();
motos = IntStream.range(0, playersNumber)
.mapToObj(playerNumber -> new Moto(in, playerNumber, myNumber))
.peek(this::updateGrid)
.collect(Collectors.toList());
}
private void updateGrid(Moto moto) {
ZoneType motoTeam = Team.ALLY.equals(moto.team) ? ZoneType.MY_MOTO : ZoneType.ENEMY_MOTO;
grid[moto.coordinate.y][moto.coordinate.x] = motoTeam;
}
public Moto getMyMoto() {
return motos.stream()
.filter(moto -> Team.ALLY.equals(moto.team))
.findFirst()
.orElseThrow(RuntimeException::new);
}
}
| UTF-8 | Java | 1,587 | java | Game.java | Java | [] | null | [] | package objects;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Game {
public static int MAX_X = 30;
public static int MAX_Y = 20;
public static int MIN = 0;
public List<Moto> motos;
public ZoneType[][] grid = new ZoneType[MAX_Y][MAX_X];
private static final Game INSTANCE = new Game();
public static Game getInstance() {
return INSTANCE;
}
public Game() {
for (int y = 0; y < MAX_Y; y++) {
for (int x = 0; x < MAX_X; x++) {
grid[y][x] = ZoneType.FREE;
}
}
}
public void update(Scanner in) {
if (motos != null) {
for (Moto moto : motos) {
grid[moto.coordinate.y][moto.coordinate.x] = ZoneType.BLOCKED;
}
}
int playersNumber = in.nextInt();
int myNumber = in.nextInt();
motos = IntStream.range(0, playersNumber)
.mapToObj(playerNumber -> new Moto(in, playerNumber, myNumber))
.peek(this::updateGrid)
.collect(Collectors.toList());
}
private void updateGrid(Moto moto) {
ZoneType motoTeam = Team.ALLY.equals(moto.team) ? ZoneType.MY_MOTO : ZoneType.ENEMY_MOTO;
grid[moto.coordinate.y][moto.coordinate.x] = motoTeam;
}
public Moto getMyMoto() {
return motos.stream()
.filter(moto -> Team.ALLY.equals(moto.team))
.findFirst()
.orElseThrow(RuntimeException::new);
}
}
| 1,587 | 0.563327 | 0.558286 | 56 | 27.339285 | 22.817034 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.482143 | false | false | 6 |
fd0f5ced5e3fb7912216f25001cc93d5d18c7f37 | 14,774,687,551,004 | 4d3ac47e689e10a934e3ecb079cba5c7acfe6215 | /core/src/pl/skempa/shader/ShaderWrapper.java | 742ce207d502493be3e5ea9ef01306e9d428ca8d | [] | no_license | kemp4/testLibgdx | https://github.com/kemp4/testLibgdx | 0b580b3c109894cd80c071dfc805678fe820dc35 | 529b1a86f2acb7edd13f22d5e7c45316837a335f | refs/heads/master | 2021-09-07T02:59:06.632000 | 2018-02-16T09:49:59 | 2018-02-16T09:49:59 | 104,484,929 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pl.skempa.shader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
/**
* Created by Mymon on 2017-10-08.
*/
public class ShaderWrapper {
private static final String vertexShader = "attribute vec4 a_position; \n" +
"attribute vec4 a_color;\n" +
"attribute vec2 a_texCoord0;\n" +
"uniform mat4 u_projTrans;\n" +
"varying vec4 v_color;" +
"varying vec2 v_texCoords;" +
"void main() \n" +
"{ \n" +
" v_color = vec4(1, 1, 1, 1); \n" +
" v_texCoords = a_texCoord0; \n" +
" gl_Position = u_projTrans * a_position; \n" +
"} \n" ;
private static final String fragmentShader = "#ifdef GL_ES\n" +
"precision mediump float;\n" +
"#endif\n" +
"varying vec4 v_color;\n" +
"varying vec2 v_texCoords;\n" +
"uniform sampler2D u_texture;\n" +
"void main() \n" +
"{ \n" +
" gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" +
"}";
ShaderProgram shaderProgram;
public ShaderWrapper() {
this.shaderProgram = new ShaderProgram(vertexShader,fragmentShader);
}
public ShaderProgram getShaderProgram() {
return shaderProgram;
}
}
| UTF-8 | Java | 1,491 | java | ShaderWrapper.java | Java | [
{
"context": "graphics.glutils.ShaderProgram;\n\n/**\n * Created by Mymon on 2017-10-08.\n */\n\npublic class ShaderWrapper {\n",
"end": 107,
"score": 0.9992638826370239,
"start": 102,
"tag": "USERNAME",
"value": "Mymon"
}
] | null | [] | package pl.skempa.shader;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
/**
* Created by Mymon on 2017-10-08.
*/
public class ShaderWrapper {
private static final String vertexShader = "attribute vec4 a_position; \n" +
"attribute vec4 a_color;\n" +
"attribute vec2 a_texCoord0;\n" +
"uniform mat4 u_projTrans;\n" +
"varying vec4 v_color;" +
"varying vec2 v_texCoords;" +
"void main() \n" +
"{ \n" +
" v_color = vec4(1, 1, 1, 1); \n" +
" v_texCoords = a_texCoord0; \n" +
" gl_Position = u_projTrans * a_position; \n" +
"} \n" ;
private static final String fragmentShader = "#ifdef GL_ES\n" +
"precision mediump float;\n" +
"#endif\n" +
"varying vec4 v_color;\n" +
"varying vec2 v_texCoords;\n" +
"uniform sampler2D u_texture;\n" +
"void main() \n" +
"{ \n" +
" gl_FragColor = v_color * texture2D(u_texture, v_texCoords);\n" +
"}";
ShaderProgram shaderProgram;
public ShaderWrapper() {
this.shaderProgram = new ShaderProgram(vertexShader,fragmentShader);
}
public ShaderProgram getShaderProgram() {
return shaderProgram;
}
}
| 1,491 | 0.476861 | 0.460094 | 44 | 32.886364 | 24.644026 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.590909 | false | false | 6 |
244836cd6661fa35725f978961d3433a68b6fead | 9,371,618,709,101 | 24dd5a4c2be73b5dab66a6157dd15ae68517e098 | /movieapp-service/src/main/java/upgrad/movieapp/service/movie/exception/ArtistErrorCode.java | 2baf446a009bb2328f95e771ef1c74afe510ac6d | [] | no_license | aditya8119/Movieapp-BackEnd | https://github.com/aditya8119/Movieapp-BackEnd | 313443ea409e229b1fa360859bb17b7368b382ed | 4035e3dc723405b344d5f401c5f08e21a715fd7c | refs/heads/master | 2022-12-02T15:24:37.567000 | 2020-08-20T14:46:06 | 2020-08-20T14:46:06 | 289,032,474 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* Copyright 2018-2019, https://beingtechie.io
*
* File: UserErrorCode.java
* Date: May 5, 2018
* Author: Thribhuvan Krishnamurthy
*/
package upgrad.movieapp.service.movie.exception;
import java.util.HashMap;
import java.util.Map;
import upgrad.movieapp.service.common.exception.ErrorCode;
/**
* Error code for MOVIE module.
*/
public enum ArtistErrorCode implements ErrorCode {
ART_001("ART-001", "Artist with identifier [{0}] does not exist"),
ART_002("ART-002", "[{0}] is not a valid artist role. Supported roles are [{1}]"),
;
private static final Map<String, ArtistErrorCode> LOOKUP = new HashMap<String, ArtistErrorCode>();
static {
for (final ArtistErrorCode enumeration : ArtistErrorCode.values()) {
LOOKUP.put(enumeration.getCode(), enumeration);
}
}
private final String code;
private final String defaultMessage;
private ArtistErrorCode(final String code, final String defaultMessage) {
this.code = code;
this.defaultMessage = defaultMessage;
}
@Override
public String getCode() {
return code;
}
@Override
public String getDefaultMessage() {
return defaultMessage;
}
} | UTF-8 | Java | 1,226 | java | ArtistErrorCode.java | Java | [
{
"context": "UserErrorCode.java\n * Date: May 5, 2018\n * Author: Thribhuvan Krishnamurthy\n */\npackage upgrad.movieapp.service.movie.excepti",
"end": 137,
"score": 0.9998804330825806,
"start": 113,
"tag": "NAME",
"value": "Thribhuvan Krishnamurthy"
}
] | null | [] | /*
* Copyright 2018-2019, https://beingtechie.io
*
* File: UserErrorCode.java
* Date: May 5, 2018
* Author: <NAME>
*/
package upgrad.movieapp.service.movie.exception;
import java.util.HashMap;
import java.util.Map;
import upgrad.movieapp.service.common.exception.ErrorCode;
/**
* Error code for MOVIE module.
*/
public enum ArtistErrorCode implements ErrorCode {
ART_001("ART-001", "Artist with identifier [{0}] does not exist"),
ART_002("ART-002", "[{0}] is not a valid artist role. Supported roles are [{1}]"),
;
private static final Map<String, ArtistErrorCode> LOOKUP = new HashMap<String, ArtistErrorCode>();
static {
for (final ArtistErrorCode enumeration : ArtistErrorCode.values()) {
LOOKUP.put(enumeration.getCode(), enumeration);
}
}
private final String code;
private final String defaultMessage;
private ArtistErrorCode(final String code, final String defaultMessage) {
this.code = code;
this.defaultMessage = defaultMessage;
}
@Override
public String getCode() {
return code;
}
@Override
public String getDefaultMessage() {
return defaultMessage;
}
} | 1,208 | 0.672104 | 0.649266 | 52 | 22.596153 | 26.141817 | 102 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.442308 | false | false | 6 |
70825016a9ada478030d4e557fec9ae8b3ee4df2 | 29,180,007,867,213 | 31e65f876940d08551330b87eb2a20a95c74ea78 | /src/main/java/com/example/demo/controller/UserController.java | bacd0da97b55707365a904666308b9b37365c80e | [] | no_license | XuRuiAngel/wxDemo_back | https://github.com/XuRuiAngel/wxDemo_back | b49265edd8a6c815df6dea075045364a64143039 | dad38fc4e6d266cb6453285f51719b5eb4e0912c | refs/heads/main | 2023-01-23T19:35:53.947000 | 2020-11-21T04:24:43 | 2020-11-21T04:24:43 | 314,416,280 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.demo.controller;
import com.example.demo.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
public class UserController {
@Autowired
UserService userService;
@GetMapping("/login")
@ResponseBody
public JSONObject getUnionid(@RequestParam("code") String code) {
String appid = "wx702333d2dea9331f";
String secret = "a6390821fa553ee10fa36ae4f68be7f3";
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
String result = restTemplate.getForObject(url, String.class);
net.sf.json.JSONObject re = JSONObject.fromObject(result);
String unionid = (String) re.get("openid");
return userService.findUserByunionid(unionid);
}
}
| UTF-8 | Java | 1,242 | java | UserController.java | Java | [
{
"context": " = \"wx702333d2dea9331f\";\n String secret = \"a6390821fa553ee10fa36ae4f68be7f3\";\n RestTemplate restTemplate = new RestTem",
"end": 768,
"score": 0.999383807182312,
"start": 736,
"tag": "KEY",
"value": "a6390821fa553ee10fa36ae4f68be7f3"
}
] | null | [] | package com.example.demo.controller;
import com.example.demo.service.UserService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
@Controller
public class UserController {
@Autowired
UserService userService;
@GetMapping("/login")
@ResponseBody
public JSONObject getUnionid(@RequestParam("code") String code) {
String appid = "wx702333d2dea9331f";
String secret = "a6390821fa553ee10fa36ae4f68be7f3";
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
String result = restTemplate.getForObject(url, String.class);
net.sf.json.JSONObject re = JSONObject.fromObject(result);
String unionid = (String) re.get("openid");
return userService.findUserByunionid(unionid);
}
}
| 1,242 | 0.743156 | 0.718196 | 34 | 35.529411 | 33.105213 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.558824 | false | false | 6 |
5ffaae7166a73e957b9945fd0b9e07d457bddfea | 16,776,142,266,754 | bc54a6ea4e5ae29b2aa7aa0b4f27ce6bc6acc557 | /Practica8-master/app/src/main/java/edu/tecii/android/practica8/MainActivity.java | 1a14e609b5813c888eb4d80cafecb0df9597cac9 | [] | no_license | chunel44/Proyecto-Android-SO | https://github.com/chunel44/Proyecto-Android-SO | 771b1525a598896c0c40c78b60e36d1a72a437ec | e9493578a09eb332a753bdc98aea298c32f27940 | refs/heads/master | 2021-01-12T08:47:08.741000 | 2016-12-16T23:04:07 | 2016-12-16T23:04:07 | 76,691,236 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package edu.tecii.android.practica8;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText txtCM, txtCP, txtRM, txtRMi, txtRP, txtRY;
Button btnSuma;
double cm, cp, rm, rmi, rp, ry, cantpulg, cantmet, aux;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtCM = (EditText)findViewById(R.id.txtCM);
txtCP = (EditText)findViewById(R.id.txtCP);
txtRM = (EditText)findViewById(R.id.txtRM);
txtRP = (EditText)findViewById(R.id.txtRP);
txtRY = (EditText)findViewById(R.id.txtRY);
txtRMi = (EditText)findViewById(R.id.txtRMi);
btnSuma = (Button)findViewById(R.id.btnSuma);
}
public void Sumar (View v){
cm = Double.parseDouble(txtCM.getText().toString());
cp = Double.parseDouble(txtCP.getText().toString());
cantpulg = cp * 12;
cantmet = cantpulg / 0.0254;
aux = cm / 0.0254;
rm = cm + cantmet;
rmi = 1609 * (cm + cantmet);
rp = aux + cantpulg;
ry = (cp + aux) * 3;
txtRY.setText(ry+"");
txtRP.setText(rp+"");
txtRM.setText(rm+"");
txtRMi.setText(rmi+"");
}
}
| UTF-8 | Java | 1,430 | java | MainActivity.java | Java | [] | null | [] | package edu.tecii.android.practica8;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText txtCM, txtCP, txtRM, txtRMi, txtRP, txtRY;
Button btnSuma;
double cm, cp, rm, rmi, rp, ry, cantpulg, cantmet, aux;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtCM = (EditText)findViewById(R.id.txtCM);
txtCP = (EditText)findViewById(R.id.txtCP);
txtRM = (EditText)findViewById(R.id.txtRM);
txtRP = (EditText)findViewById(R.id.txtRP);
txtRY = (EditText)findViewById(R.id.txtRY);
txtRMi = (EditText)findViewById(R.id.txtRMi);
btnSuma = (Button)findViewById(R.id.btnSuma);
}
public void Sumar (View v){
cm = Double.parseDouble(txtCM.getText().toString());
cp = Double.parseDouble(txtCP.getText().toString());
cantpulg = cp * 12;
cantmet = cantpulg / 0.0254;
aux = cm / 0.0254;
rm = cm + cantmet;
rmi = 1609 * (cm + cantmet);
rp = aux + cantpulg;
ry = (cp + aux) * 3;
txtRY.setText(ry+"");
txtRP.setText(rp+"");
txtRM.setText(rm+"");
txtRMi.setText(rmi+"");
}
}
| 1,430 | 0.63007 | 0.616783 | 43 | 32.255814 | 18.993382 | 60 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.023256 | false | false | 6 |
39a4cf7cb77d1af5a9869e0ad814557b45cc01ef | 20,031,727,485,857 | 94f1926e49d8609a932ba09e2cd9263be0f1c11f | /UWS-MTPP/src/guisanboot/datadup/ui/BrowseBakedFile.java | 0de1ffa0351855919724c10cedfde7dc8bdac0b4 | [] | no_license | zhbaics/UWS-MTPP | https://github.com/zhbaics/UWS-MTPP | a47dfe5e844b656c62c4b6255091d6c32446cef7 | 21f0d19cabb92a9763d3258fb494c11464c8caf7 | refs/heads/master | 2021-01-18T14:05:07.662000 | 2015-09-07T01:11:21 | 2015-09-07T01:11:21 | 42,024,137 | 5 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* BrowseBakedFile.java
*
* Created on 2008/7/28,�AM 10:24
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package guisanboot.datadup.ui;
/**
*
* @author zjj
*/
public interface BrowseBakedFile {
public void setEnabledTF1();
public void setWaitCursor();
public void resotreCursor();
public void saveRoots();
}
| UTF-8 | Java | 553 | java | BrowseBakedFile.java | Java | [
{
"context": "kage guisanboot.datadup.ui;\r\n\r\n/**\r\n *\r\n * @author zjj\r\n */\r\npublic interface BrowseBakedFile {\r\n pub",
"end": 373,
"score": 0.9995437860488892,
"start": 370,
"tag": "USERNAME",
"value": "zjj"
}
] | null | [] | /*
* BrowseBakedFile.java
*
* Created on 2008/7/28,�AM 10:24
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package guisanboot.datadup.ui;
/**
*
* @author zjj
*/
public interface BrowseBakedFile {
public void setEnabledTF1();
public void setWaitCursor();
public void resotreCursor();
public void saveRoots();
}
| 553 | 0.682396 | 0.660617 | 22 | 23.045454 | 25.145897 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.363636 | false | false | 6 |
43f352215e4ecc368a1161ff495f1fab8abbc7f7 | 28,750,511,144,000 | 7aaf2a0287672bf70d7a1c39663e47e0b3b2809e | /code/PayRoll.java | 43683c475ac264084d56931023c77d3f75cdbabe | [] | no_license | leungyukshing/javacode | https://github.com/leungyukshing/javacode | e4cdb234618e8d9c0bb1571045fe35d3539de38c | f5a6bb0f32c6bd3feea2120f122858996906faf5 | refs/heads/master | 2021-06-25T09:03:59.952000 | 2017-09-08T02:28:30 | 2017-09-08T02:28:30 | 102,364,303 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.Scanner;
public class PayRoll {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter employee's name: ");
String name = input.next();
System.out.print("Enter number of hours worked in a week: ");
int workedHours = input.nextInt();
System.out.print("Enter hourly pay rate: ");
double hourlyPayRate = input.nextDouble();
System.out.print("Enter federal tax withholding rate: ");
double federalTaxWithholdingRate = input.nextDouble();
System.out.print("Enter state tax withholding rate: ");
double stateTaxWithholdingRate = input.nextDouble();
// Calculation
double gross = workedHours * hourlyPayRate;
double federalWithholding = gross * federalTaxWithholdingRate;
double stateWithholding = gross * stateTaxWithholdingRate;
double totalDeduction = federalWithholding + stateWithholding;
double netPay = gross - totalDeduction;
// Formatting
gross = (int)(gross * 100) / 100.0;
federalWithholding = (int)(federalWithholding * 100) / 100.0;
stateWithholding = (int)(stateWithholding * 100) / 100.0;
totalDeduction = (int)(totalDeduction * 100) / 100.0;
netPay = (int)(netPay * 100) / 100.0;
// Output
System.out.println("Employee Name: " + name);
System.out.println("Hours Worked: " + workedHours * 1.0);
System.out.println("Pay Rate: $" + hourlyPayRate);
System.out.println("Gross Pay: $" + gross);
System.out.println("Deductions:");
System.out.println(" Federal Withholding (" + federalTaxWithholdingRate * 100 + "%): $" + federalWithholding);
System.out.println(" State Withholding (" + stateTaxWithholdingRate * 100 + "%): $" + stateWithholding);
System.out.println("Total Deduction: $" + totalDeduction);
System.out.println("Net Pay: $" + netPay);
}
} | UTF-8 | Java | 1,804 | java | PayRoll.java | Java | [] | null | [] | import java.util.Scanner;
public class PayRoll {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter employee's name: ");
String name = input.next();
System.out.print("Enter number of hours worked in a week: ");
int workedHours = input.nextInt();
System.out.print("Enter hourly pay rate: ");
double hourlyPayRate = input.nextDouble();
System.out.print("Enter federal tax withholding rate: ");
double federalTaxWithholdingRate = input.nextDouble();
System.out.print("Enter state tax withholding rate: ");
double stateTaxWithholdingRate = input.nextDouble();
// Calculation
double gross = workedHours * hourlyPayRate;
double federalWithholding = gross * federalTaxWithholdingRate;
double stateWithholding = gross * stateTaxWithholdingRate;
double totalDeduction = federalWithholding + stateWithholding;
double netPay = gross - totalDeduction;
// Formatting
gross = (int)(gross * 100) / 100.0;
federalWithholding = (int)(federalWithholding * 100) / 100.0;
stateWithholding = (int)(stateWithholding * 100) / 100.0;
totalDeduction = (int)(totalDeduction * 100) / 100.0;
netPay = (int)(netPay * 100) / 100.0;
// Output
System.out.println("Employee Name: " + name);
System.out.println("Hours Worked: " + workedHours * 1.0);
System.out.println("Pay Rate: $" + hourlyPayRate);
System.out.println("Gross Pay: $" + gross);
System.out.println("Deductions:");
System.out.println(" Federal Withholding (" + federalTaxWithholdingRate * 100 + "%): $" + federalWithholding);
System.out.println(" State Withholding (" + stateTaxWithholdingRate * 100 + "%): $" + stateWithholding);
System.out.println("Total Deduction: $" + totalDeduction);
System.out.println("Net Pay: $" + netPay);
}
} | 1,804 | 0.704545 | 0.68071 | 43 | 40.976746 | 26.115564 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.302325 | false | false | 6 |
1e1658307100feeb8f3760ce6704a39f17e0a2d8 | 7,962,869,421,047 | d5b2d3c760219864d322f6ced45e15a0d6a7898a | /src/java/com/proyecto/portalgarantias/menu/BeanMenu.java | 34fa9aca92c936f2980163a18a53c13306d6b02e | [] | no_license | seminarioumg20188102/FEEscuela | https://github.com/seminarioumg20188102/FEEscuela | 8c426be0cd53a1b6b3b7ef2e77d87f118d2361a5 | a9fd2bc36b19c35443c8d1da104c5d8c7c062a5c | refs/heads/master | 2020-03-24T16:12:26.896000 | 2018-07-30T02:54:52 | 2018-07-30T02:54:52 | 142,816,610 | 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 com.proyecto.portalgarantias.menu;
import com.proyecto.portalgarantias.lista.Lista;
import com.proyecto.portalgarantias.login.BeanLogin;
import com.proyecto.portalgarantias.webservice.Menu;
import com.proyecto.portalgarantias.webservice.Opciones;
import com.proyecto.portalgarantias.webservice.RespuestaMenu;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.faces.context.FacesContext;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;
//import org.primefaces.component.menuitem.MenuItem;
//import org.primefaces.component.submenu.Submenu;
//import org.primefaces.model.DefaultMenuModel;
//import org.primefaces.model.MenuModel;
/**
*
* @author AHERNANDEZ
*/
public class BeanMenu implements Serializable {
// static final long serialVersionUID = 42L;
private MenuModel modal;
private String SI = "S";
private String INICIOURL = "./../gestiones/inicio.xhtml";
private String INICIOLABEL = "Inicio";
List<String> principalUrl;
List<String> principalLabel;
List<Lista> listas;
// private Listas listas = new Listas();
/**
* Creates a new instance of BeanMenu
*/
public BeanMenu() {
FacesContext context = FacesContext.getCurrentInstance();
BeanLogin objLogin = (BeanLogin) context.getExternalContext().getSessionMap().get("beanLogin");
List<String> opciones = new LinkedList<String>();
opciones = objLogin.getOpciones();
modal = new DefaultMenuModel();
principalUrl = new LinkedList<String>();
principalLabel = new LinkedList<String>();
//
// opciones.add("AGREGAR");
// opciones.add("CONSULTAR");
// opciones.add("ELIMINAR");
// opciones.add("REPORTE");
Opciones op = new Opciones();
try {
op.getOpciones().addAll(opciones);
} catch (Exception e) {
System.out.println("no hay perfil en el cliente parametrizado");
}
// System.out.println("tamanio opciones es:" + op.getOpciones().size());
System.out.println("menu 1 " + new Date());
RespuestaMenu menuarbol = consultaMenuOpciones("test");
// System.out.println("tamanio menu:" + menuarbol.getMenus().size());
System.out.println("menu 2 " + new Date());
List<Menu> menus = menuarbol.getMenus();
for (Menu mi : menus) {
System.out.println("mi menuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy:" + mi.getDescripcion());
}
listas = new LinkedList<Lista>();
for (Menu menu : menus) {
// if (menu.getSubmenu().equals("N")) {
boolean existePadre = false;
for (Lista list : listas) {
if (list.getId().equals(menu.getPadre())) {
existePadre = true;
}
}
if (!existePadre) {
Lista lis = new Lista();
lis.setId(menu.getPadre());
listas.add(lis);
}
for (Lista list : listas) {
if (list.getId().equals(menu.getPadre())) {
list.getListasHijos().add(menu);
}
}
// }
}
for (Lista list : listas) {
System.out.println("NUEVA LISTA______________________");
System.out.println("Lista Id:" + list.getId());
System.out.println("Lista Hijos:" + list.getListasHijos().size());
System.out.println("FIN NUEVA LISTA______________________");
}
System.out.println("menu 3 " + new Date());
try {
principalUrl.add(INICIOURL);
principalLabel.add(INICIOLABEL);
principalUrl.add("./../gestiones/consultarguias.xhtml");
principalLabel.add("Consulta de Guias");
//agregando menus de INICIO
if (principalUrl.size() > 0) {
for (int b = 0; b < 1; b++) {
//menu inicial
DefaultMenuItem itemconsulta = new DefaultMenuItem();
itemconsulta.setValue(principalLabel.get(b));
itemconsulta.setUrl(principalUrl.get(b));
itemconsulta.setIcon("ui-icon-home");
//itemconsulta.setTransient(true);
modal.addElement(itemconsulta);
}
}
for (Lista list : listas) {
if (list.getId().equals("RAIZ")) {
List<Menu> menld = ordenaLista(list.getListasHijos());
for (Menu menu : menld) {
if (menu.getActivo().equals("S")) {
if (menu.getSubmenu().equals("S")) {
DefaultSubMenu submens = new DefaultSubMenu();
submens.setLabel(menu.getDescripcion());
modal.addElement(submens);
System.out.println("antes de agrega menu: " + menu.getDescripcion());
agregarMenu(listas, menu, submens);
System.out.println("DESPUES de agrega menu");
} else {
DefaultMenuItem item = new DefaultMenuItem();
item.setValue(menu.getDescripcion());
item.setUrl(menu.getUrl());
if (menu.getDescripcion() != null && menu.getDescripcion().equals("Modificar Servicios")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("Nuevo Existente")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("IMPRESION")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("IMPRESIONHIJAS")) {
item.setRendered(false);
}
// item.setTransient(true);
modal.addElement(item);
}
}
System.out.println("entra 2oooooooooooooooooo");
}
}
System.out.println("entra 1iiiiiiiiii");
}
System.out.println("saliendoooooo de ese fooooooooooooooooooooooooooooor!");
} catch (Exception e) {
System.out.println("error de menu");
e.printStackTrace();
}
System.out.println("menu 4 " + new Date());
}
boolean loagrego = false;
public void agregarMenu(List<Lista> listasox, Menu menu, DefaultSubMenu submens) {
System.out.println("entrando agregarMenu con menu:" + menu.getDescripcion());
System.out.println("listasox siza:" + listasox.size());
for (Lista list2 : listasox) {
if (!list2.getId().equals("RAIZ")) {
if (list2.getId().equals(menu.getCodigo())) {
System.out.println("entra a ordenar lista: " + list2.getListasHijos().size());
List<Menu> menld = ordenaLista(list2.getListasHijos());
System.out.println("sale de ordenar lista: " + list2.getListasHijos().size());
for (Menu hij : menld) {
if (hij.getActivo().equals("S")) {
if (hij.getSubmenu().equals("S")) {
DefaultSubMenu submens2 = new DefaultSubMenu();
submens2.setLabel(hij.getDescripcion());
submens.addElement(submens2);
agregarMenu(listasox, hij, submens2);
} else {
DefaultMenuItem item = new DefaultMenuItem();
item.setValue(hij.getDescripcion());
item.setUrl(hij.getUrl());
// item.setTransient(true);
submens.addElement(item);
if (!loagrego && submens.getLabel().equals("Consultas")) {
DefaultMenuItem itemx = new DefaultMenuItem();
itemx.setValue("Consulta de Guias");
itemx.setUrl("./../gestiones/consultarguias.xhtml");
// item.setTransient(true);
submens.addElement(itemx);
loagrego = true;
}
}
}
System.out.println("de aqui ya no salio:" + hij.getDescripcion());
}
}
}
System.out.println("no sale:" + list2.getId());
}
}
public String getINICIOLABEL() {
return INICIOLABEL;
}
public String getINICIOURL() {
return INICIOURL;
}
public String getSI() {
return SI;
}
public MenuModel getModal() {
return modal;
}
public List<String> getPrincipalLabel() {
return principalLabel;
}
public List<String> getPrincipalUrl() {
return principalUrl;
}
public void setINICIOLABEL(String INICIOLABEL) {
this.INICIOLABEL = INICIOLABEL;
}
public void setINICIOURL(String INICIOURL) {
this.INICIOURL = INICIOURL;
}
public void setSI(String SI) {
this.SI = SI;
}
public void setModal(MenuModel modal) {
this.modal = modal;
}
public void setPrincipalLabel(List<String> principalLabel) {
this.principalLabel = principalLabel;
}
public void setPrincipalUrl(List<String> principalUrl) {
this.principalUrl = principalUrl;
}
public void setListas(List<Lista> listas) {
this.listas = listas;
}
public List<Lista> getListas() {
return listas;
}
public List<Menu> ordenaLista(List<Menu> det) {
for (Menu mi : det) {
System.out.println("mi menuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy2:" + mi.getDescripcion());
}
List<Menu> detalles = new LinkedList<Menu>();
boolean lleno = false;
int cont = 0;
// for(Menu m : det){
// System.out.println("a ordenar:"+m.getDescripcion());
// }
while (!lleno) {
List<Menu> pasador = new LinkedList<Menu>();
for (Menu de : det) {
// System.out.println("encontrado de: "+de.isEncontrado());
boolean rechazado = false;
if (!de.isEncontrado()) {
for (Menu de2 : det) {
if (!de2.isEncontrado()) {
if (de.getPrioridad() > de2.getPrioridad()) {
rechazado = true;
}
}
}
if (!rechazado) {
de.setEncontrado(true);
detalles.add(de);
cont++;
}
}
pasador.add(de);
}
det = new LinkedList<Menu>();
for (Menu mde : pasador) {
det.add(mde);
}
// System.out.println("cont: " + cont + " det.size: " + det.size());
if (cont == det.size()) {
lleno = true;
}
// System.out.println("sigueeee cont:"+cont+" det.size:"+det.size());
}
return detalles;
}
private static RespuestaMenu consultaMenuOpciones(java.lang.String name) {
com.proyecto.portalgarantias.webservice.GarantiasWS_Service service = new com.proyecto.portalgarantias.webservice.GarantiasWS_Service();
com.proyecto.portalgarantias.webservice.GarantiasWS port = service.getGarantiasWSPort();
return port.consultaMenuOpciones(name);
}
}
| UTF-8 | Java | 12,782 | java | BeanMenu.java | Java | [
{
"context": " org.primefaces.model.MenuModel;\n/**\n *\n * @author AHERNANDEZ\n */\npublic class BeanMenu implements Serializable",
"end": 1065,
"score": 0.8496226072311401,
"start": 1055,
"tag": "USERNAME",
"value": "AHERNANDEZ"
},
{
"context": "targuias.xhtml\");\n prin... | 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 com.proyecto.portalgarantias.menu;
import com.proyecto.portalgarantias.lista.Lista;
import com.proyecto.portalgarantias.login.BeanLogin;
import com.proyecto.portalgarantias.webservice.Menu;
import com.proyecto.portalgarantias.webservice.Opciones;
import com.proyecto.portalgarantias.webservice.RespuestaMenu;
import java.io.Serializable;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import javax.faces.context.FacesContext;
import org.primefaces.model.menu.DefaultMenuItem;
import org.primefaces.model.menu.DefaultMenuModel;
import org.primefaces.model.menu.DefaultSubMenu;
import org.primefaces.model.menu.MenuModel;
//import org.primefaces.component.menuitem.MenuItem;
//import org.primefaces.component.submenu.Submenu;
//import org.primefaces.model.DefaultMenuModel;
//import org.primefaces.model.MenuModel;
/**
*
* @author AHERNANDEZ
*/
public class BeanMenu implements Serializable {
// static final long serialVersionUID = 42L;
private MenuModel modal;
private String SI = "S";
private String INICIOURL = "./../gestiones/inicio.xhtml";
private String INICIOLABEL = "Inicio";
List<String> principalUrl;
List<String> principalLabel;
List<Lista> listas;
// private Listas listas = new Listas();
/**
* Creates a new instance of BeanMenu
*/
public BeanMenu() {
FacesContext context = FacesContext.getCurrentInstance();
BeanLogin objLogin = (BeanLogin) context.getExternalContext().getSessionMap().get("beanLogin");
List<String> opciones = new LinkedList<String>();
opciones = objLogin.getOpciones();
modal = new DefaultMenuModel();
principalUrl = new LinkedList<String>();
principalLabel = new LinkedList<String>();
//
// opciones.add("AGREGAR");
// opciones.add("CONSULTAR");
// opciones.add("ELIMINAR");
// opciones.add("REPORTE");
Opciones op = new Opciones();
try {
op.getOpciones().addAll(opciones);
} catch (Exception e) {
System.out.println("no hay perfil en el cliente parametrizado");
}
// System.out.println("tamanio opciones es:" + op.getOpciones().size());
System.out.println("menu 1 " + new Date());
RespuestaMenu menuarbol = consultaMenuOpciones("test");
// System.out.println("tamanio menu:" + menuarbol.getMenus().size());
System.out.println("menu 2 " + new Date());
List<Menu> menus = menuarbol.getMenus();
for (Menu mi : menus) {
System.out.println("mi menuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy:" + mi.getDescripcion());
}
listas = new LinkedList<Lista>();
for (Menu menu : menus) {
// if (menu.getSubmenu().equals("N")) {
boolean existePadre = false;
for (Lista list : listas) {
if (list.getId().equals(menu.getPadre())) {
existePadre = true;
}
}
if (!existePadre) {
Lista lis = new Lista();
lis.setId(menu.getPadre());
listas.add(lis);
}
for (Lista list : listas) {
if (list.getId().equals(menu.getPadre())) {
list.getListasHijos().add(menu);
}
}
// }
}
for (Lista list : listas) {
System.out.println("NUEVA LISTA______________________");
System.out.println("Lista Id:" + list.getId());
System.out.println("Lista Hijos:" + list.getListasHijos().size());
System.out.println("FIN NUEVA LISTA______________________");
}
System.out.println("menu 3 " + new Date());
try {
principalUrl.add(INICIOURL);
principalLabel.add(INICIOLABEL);
principalUrl.add("./../gestiones/consultarguias.xhtml");
principalLabel.add("<NAME>");
//agregando menus de INICIO
if (principalUrl.size() > 0) {
for (int b = 0; b < 1; b++) {
//menu inicial
DefaultMenuItem itemconsulta = new DefaultMenuItem();
itemconsulta.setValue(principalLabel.get(b));
itemconsulta.setUrl(principalUrl.get(b));
itemconsulta.setIcon("ui-icon-home");
//itemconsulta.setTransient(true);
modal.addElement(itemconsulta);
}
}
for (Lista list : listas) {
if (list.getId().equals("RAIZ")) {
List<Menu> menld = ordenaLista(list.getListasHijos());
for (Menu menu : menld) {
if (menu.getActivo().equals("S")) {
if (menu.getSubmenu().equals("S")) {
DefaultSubMenu submens = new DefaultSubMenu();
submens.setLabel(menu.getDescripcion());
modal.addElement(submens);
System.out.println("antes de agrega menu: " + menu.getDescripcion());
agregarMenu(listas, menu, submens);
System.out.println("DESPUES de agrega menu");
} else {
DefaultMenuItem item = new DefaultMenuItem();
item.setValue(menu.getDescripcion());
item.setUrl(menu.getUrl());
if (menu.getDescripcion() != null && menu.getDescripcion().equals("Modificar Servicios")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("Nuevo Existente")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("IMPRESION")) {
item.setRendered(false);
} else if (menu.getDescripcion() != null && menu.getDescripcion().equals("IMPRESIONHIJAS")) {
item.setRendered(false);
}
// item.setTransient(true);
modal.addElement(item);
}
}
System.out.println("entra 2oooooooooooooooooo");
}
}
System.out.println("entra 1iiiiiiiiii");
}
System.out.println("saliendoooooo de ese fooooooooooooooooooooooooooooor!");
} catch (Exception e) {
System.out.println("error de menu");
e.printStackTrace();
}
System.out.println("menu 4 " + new Date());
}
boolean loagrego = false;
public void agregarMenu(List<Lista> listasox, Menu menu, DefaultSubMenu submens) {
System.out.println("entrando agregarMenu con menu:" + menu.getDescripcion());
System.out.println("listasox siza:" + listasox.size());
for (Lista list2 : listasox) {
if (!list2.getId().equals("RAIZ")) {
if (list2.getId().equals(menu.getCodigo())) {
System.out.println("entra a ordenar lista: " + list2.getListasHijos().size());
List<Menu> menld = ordenaLista(list2.getListasHijos());
System.out.println("sale de ordenar lista: " + list2.getListasHijos().size());
for (Menu hij : menld) {
if (hij.getActivo().equals("S")) {
if (hij.getSubmenu().equals("S")) {
DefaultSubMenu submens2 = new DefaultSubMenu();
submens2.setLabel(hij.getDescripcion());
submens.addElement(submens2);
agregarMenu(listasox, hij, submens2);
} else {
DefaultMenuItem item = new DefaultMenuItem();
item.setValue(hij.getDescripcion());
item.setUrl(hij.getUrl());
// item.setTransient(true);
submens.addElement(item);
if (!loagrego && submens.getLabel().equals("Consultas")) {
DefaultMenuItem itemx = new DefaultMenuItem();
itemx.setValue("Consulta de Guias");
itemx.setUrl("./../gestiones/consultarguias.xhtml");
// item.setTransient(true);
submens.addElement(itemx);
loagrego = true;
}
}
}
System.out.println("de aqui ya no salio:" + hij.getDescripcion());
}
}
}
System.out.println("no sale:" + list2.getId());
}
}
public String getINICIOLABEL() {
return INICIOLABEL;
}
public String getINICIOURL() {
return INICIOURL;
}
public String getSI() {
return SI;
}
public MenuModel getModal() {
return modal;
}
public List<String> getPrincipalLabel() {
return principalLabel;
}
public List<String> getPrincipalUrl() {
return principalUrl;
}
public void setINICIOLABEL(String INICIOLABEL) {
this.INICIOLABEL = INICIOLABEL;
}
public void setINICIOURL(String INICIOURL) {
this.INICIOURL = INICIOURL;
}
public void setSI(String SI) {
this.SI = SI;
}
public void setModal(MenuModel modal) {
this.modal = modal;
}
public void setPrincipalLabel(List<String> principalLabel) {
this.principalLabel = principalLabel;
}
public void setPrincipalUrl(List<String> principalUrl) {
this.principalUrl = principalUrl;
}
public void setListas(List<Lista> listas) {
this.listas = listas;
}
public List<Lista> getListas() {
return listas;
}
public List<Menu> ordenaLista(List<Menu> det) {
for (Menu mi : det) {
System.out.println("mi menuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy2:" + mi.getDescripcion());
}
List<Menu> detalles = new LinkedList<Menu>();
boolean lleno = false;
int cont = 0;
// for(Menu m : det){
// System.out.println("a ordenar:"+m.getDescripcion());
// }
while (!lleno) {
List<Menu> pasador = new LinkedList<Menu>();
for (Menu de : det) {
// System.out.println("encontrado de: "+de.isEncontrado());
boolean rechazado = false;
if (!de.isEncontrado()) {
for (Menu de2 : det) {
if (!de2.isEncontrado()) {
if (de.getPrioridad() > de2.getPrioridad()) {
rechazado = true;
}
}
}
if (!rechazado) {
de.setEncontrado(true);
detalles.add(de);
cont++;
}
}
pasador.add(de);
}
det = new LinkedList<Menu>();
for (Menu mde : pasador) {
det.add(mde);
}
// System.out.println("cont: " + cont + " det.size: " + det.size());
if (cont == det.size()) {
lleno = true;
}
// System.out.println("sigueeee cont:"+cont+" det.size:"+det.size());
}
return detalles;
}
private static RespuestaMenu consultaMenuOpciones(java.lang.String name) {
com.proyecto.portalgarantias.webservice.GarantiasWS_Service service = new com.proyecto.portalgarantias.webservice.GarantiasWS_Service();
com.proyecto.portalgarantias.webservice.GarantiasWS port = service.getGarantiasWSPort();
return port.consultaMenuOpciones(name);
}
}
| 12,771 | 0.509936 | 0.507824 | 370 | 33.543243 | 29.054089 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.440541 | false | false | 6 |
519a1f41c7500586e5e49e89d744536b42b8220b | 33,045,478,382,214 | 259be203835ac5ac4ec208872345aa07428f0f68 | /src/net/vincentpetry/nodereviver/LevelLoader.java | 5cec508055bce76768a0b8423aa8906a2c2afed3 | [] | no_license | PVince81/nodereviver-android | https://github.com/PVince81/nodereviver-android | 0f629aad8d0c0c2defe51d3c6cb8644f49ab958f | 0b477c72224c130ff41a15c731b1e47b7e1c3368 | refs/heads/master | 2021-01-01T05:30:56.578000 | 2013-06-05T19:33:10 | 2013-06-05T19:35:01 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package net.vincentpetry.nodereviver;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import net.vincentpetry.nodereviver.model.Edge;
import net.vincentpetry.nodereviver.model.Level;
import net.vincentpetry.nodereviver.model.Node;
public class LevelLoader {
public LevelLoader(){
}
private String fixNewlines(String s){
// it seems StaticLayout expects \r\n instead of \n
return s.replace("\\n", "\n");
}
public Level load(AssetManager assetManager, int levelNum) throws IOException{
InputStream input = assetManager.open("levels/level" + levelNum + ".json");
try{
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (input.read(buf) > 0) {
sb.append(new String(buf));
}
return load(sb.toString());
}
catch (JSONException e){
return null;
}
finally{
input.close();
}
}
private Level load(String jsonString) throws JSONException {
JSONObject root = new JSONObject(jsonString);
Level level = new Level();
level.setTitle(fixNewlines(root.optString("title")));
level.setSubtitle(fixNewlines(root.optString("subtitle")));
level.setEndtext(fixNewlines(root.optString("endtext")));
Map<Integer,Node> nodesMap = processNodes(level, root.getJSONArray("nodes"));
processEdges(level, nodesMap, root.getJSONArray("edges"));
processEntities(level, nodesMap, root.getJSONArray("entities"));
return level;
}
private Map<Integer,Node> processNodes(Level level, JSONArray jsonNodes) throws JSONException{
Map<Integer,Node> nodesMap = new HashMap<Integer,Node>(jsonNodes.length());
for ( int i = 0; i < jsonNodes.length(); i++ ){
JSONObject jsonNode = jsonNodes.getJSONObject(i);
String type = jsonNode.optString("type", "node");
if ( !"node".equals(type) && !"joint".equals(type) ){
continue;
}
int id = jsonNode.optInt("id", -1);
int x = jsonNode.getInt("x");
int y = jsonNode.getInt("y");
int nodeType = Node.TYPE_SQUARE;
if ("joint".equals(type)){
nodeType = Node.TYPE_JOINT;
}
Node node = level.createNode(x, y, nodeType);
if ( id != -1 ){
nodesMap.put(id, node);
}
}
return nodesMap;
}
private void processEdges(Level level, Map<Integer,Node> nodesMap, JSONArray jsonEdges) throws JSONException{
for ( int i = 0; i < jsonEdges.length(); i++ ){
JSONObject jsonEdge = jsonEdges.getJSONObject(i);
int sourceId = jsonEdge.getInt("source");
int targetId = jsonEdge.getInt("dest");
Node node1 = nodesMap.get(sourceId);
Node node2 = nodesMap.get(targetId);
if ( node1 == null || node2 == null ) {
continue;
}
boolean oneWay = jsonEdge.optBoolean("oneway", false);
Edge edge = level.connectNodes(node1, node2);
edge.setOneWay(oneWay);
}
}
private void processEntities(Level level, Map<Integer,Node> nodesMap, JSONArray jsonEntities) throws JSONException{
for ( int i = 0; i < jsonEntities.length(); i++ ){
JSONObject jsonEntity = jsonEntities.getJSONObject(i);
int startNodeId = jsonEntity.getInt("node");
String type = jsonEntity.getString("type");
Node startNode = nodesMap.get(startNodeId);
if ( startNode == null ){
continue;
}
if ("player".equals(type)){
level.setPlayerStartNode(startNode);
}
else if ("foe".equals(type)){
String foeType = jsonEntity.getString("foeType");
if ( "simple".equals(foeType) || "0".equals(foeType) ){
level.createSimpleFoe(startNode);
}
else{
level.createTrackingFoe(startNode);
}
}
}
}
}
| UTF-8 | Java | 4,401 | java | LevelLoader.java | Java | [] | null | [] | package net.vincentpetry.nodereviver;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.AssetManager;
import net.vincentpetry.nodereviver.model.Edge;
import net.vincentpetry.nodereviver.model.Level;
import net.vincentpetry.nodereviver.model.Node;
public class LevelLoader {
public LevelLoader(){
}
private String fixNewlines(String s){
// it seems StaticLayout expects \r\n instead of \n
return s.replace("\\n", "\n");
}
public Level load(AssetManager assetManager, int levelNum) throws IOException{
InputStream input = assetManager.open("levels/level" + levelNum + ".json");
try{
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (input.read(buf) > 0) {
sb.append(new String(buf));
}
return load(sb.toString());
}
catch (JSONException e){
return null;
}
finally{
input.close();
}
}
private Level load(String jsonString) throws JSONException {
JSONObject root = new JSONObject(jsonString);
Level level = new Level();
level.setTitle(fixNewlines(root.optString("title")));
level.setSubtitle(fixNewlines(root.optString("subtitle")));
level.setEndtext(fixNewlines(root.optString("endtext")));
Map<Integer,Node> nodesMap = processNodes(level, root.getJSONArray("nodes"));
processEdges(level, nodesMap, root.getJSONArray("edges"));
processEntities(level, nodesMap, root.getJSONArray("entities"));
return level;
}
private Map<Integer,Node> processNodes(Level level, JSONArray jsonNodes) throws JSONException{
Map<Integer,Node> nodesMap = new HashMap<Integer,Node>(jsonNodes.length());
for ( int i = 0; i < jsonNodes.length(); i++ ){
JSONObject jsonNode = jsonNodes.getJSONObject(i);
String type = jsonNode.optString("type", "node");
if ( !"node".equals(type) && !"joint".equals(type) ){
continue;
}
int id = jsonNode.optInt("id", -1);
int x = jsonNode.getInt("x");
int y = jsonNode.getInt("y");
int nodeType = Node.TYPE_SQUARE;
if ("joint".equals(type)){
nodeType = Node.TYPE_JOINT;
}
Node node = level.createNode(x, y, nodeType);
if ( id != -1 ){
nodesMap.put(id, node);
}
}
return nodesMap;
}
private void processEdges(Level level, Map<Integer,Node> nodesMap, JSONArray jsonEdges) throws JSONException{
for ( int i = 0; i < jsonEdges.length(); i++ ){
JSONObject jsonEdge = jsonEdges.getJSONObject(i);
int sourceId = jsonEdge.getInt("source");
int targetId = jsonEdge.getInt("dest");
Node node1 = nodesMap.get(sourceId);
Node node2 = nodesMap.get(targetId);
if ( node1 == null || node2 == null ) {
continue;
}
boolean oneWay = jsonEdge.optBoolean("oneway", false);
Edge edge = level.connectNodes(node1, node2);
edge.setOneWay(oneWay);
}
}
private void processEntities(Level level, Map<Integer,Node> nodesMap, JSONArray jsonEntities) throws JSONException{
for ( int i = 0; i < jsonEntities.length(); i++ ){
JSONObject jsonEntity = jsonEntities.getJSONObject(i);
int startNodeId = jsonEntity.getInt("node");
String type = jsonEntity.getString("type");
Node startNode = nodesMap.get(startNodeId);
if ( startNode == null ){
continue;
}
if ("player".equals(type)){
level.setPlayerStartNode(startNode);
}
else if ("foe".equals(type)){
String foeType = jsonEntity.getString("foeType");
if ( "simple".equals(foeType) || "0".equals(foeType) ){
level.createSimpleFoe(startNode);
}
else{
level.createTrackingFoe(startNode);
}
}
}
}
}
| 4,401 | 0.575324 | 0.571461 | 124 | 34.491936 | 26.27046 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.758065 | false | false | 6 |
2b9f83bbd7e6e50338af1a5be73d8170e0d43a06 | 27,453,430,982,043 | 323d233e1a0e301e8ab09c5190a00c47d5a9974d | /src/movieadvancedsearchtab/Fromto.java | f287346cfc47788d3e5afdf3c2747d6872da2a98 | [] | no_license | sieuthanh/FilmManagement | https://github.com/sieuthanh/FilmManagement | 1b05f38bae38e3b04a9677ee67c237ffb2653d17 | 9eb21306987e0ede5fec7336718370b25bd87bec | refs/heads/master | 2020-04-13T05:18:25.367000 | 2012-11-19T13:43:35 | 2012-11-19T13:43:35 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package movieadvancedsearchtab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Admin
*/
public class Fromto extends JPanel {
private JLabel From = new JLabel("From");
private JLabel To = new JLabel("To");
private JComboBox valuefrom = new JComboBox();
private JComboBox valueto = new JComboBox();
private int length;
public Fromto(String lb, String[] list){
setBackground(Color.white);
length = list.length;
JLabel label = new JLabel(lb);
label.setFont(new Font("Tahoma",Font.BOLD,12));
label.setPreferredSize(new Dimension(60,15));
setSize(new Dimension(200,25));
add(label);
add(From);
valuefrom = new JComboBox(list);
valuefrom.setSelectedIndex(0);
valuefrom.setPreferredSize(new Dimension(50,20));
add(valuefrom);
add(To);
valueto = new JComboBox(list);
valueto.setPreferredSize(new Dimension(50,20));
valueto.setSelectedIndex(length-1);
add(valueto);
}
public String valuefrom(){
return (String)valuefrom.getSelectedItem();
}
public String valueto(){
return (String)valueto.getSelectedItem();
}
public void clear(){
valuefrom.setSelectedIndex(0);
valueto.setSelectedIndex(length-1);
}
}
| UTF-8 | Java | 1,452 | java | Fromto.java | Java | [
{
"context": "bel;\nimport javax.swing.JPanel;\n\n/**\n *\n * @author Admin\n */\npublic class Fromto extends JPanel {\n priv",
"end": 215,
"score": 0.5367793440818787,
"start": 210,
"tag": "USERNAME",
"value": "Admin"
}
] | null | [] |
package movieadvancedsearchtab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* @author Admin
*/
public class Fromto extends JPanel {
private JLabel From = new JLabel("From");
private JLabel To = new JLabel("To");
private JComboBox valuefrom = new JComboBox();
private JComboBox valueto = new JComboBox();
private int length;
public Fromto(String lb, String[] list){
setBackground(Color.white);
length = list.length;
JLabel label = new JLabel(lb);
label.setFont(new Font("Tahoma",Font.BOLD,12));
label.setPreferredSize(new Dimension(60,15));
setSize(new Dimension(200,25));
add(label);
add(From);
valuefrom = new JComboBox(list);
valuefrom.setSelectedIndex(0);
valuefrom.setPreferredSize(new Dimension(50,20));
add(valuefrom);
add(To);
valueto = new JComboBox(list);
valueto.setPreferredSize(new Dimension(50,20));
valueto.setSelectedIndex(length-1);
add(valueto);
}
public String valuefrom(){
return (String)valuefrom.getSelectedItem();
}
public String valueto(){
return (String)valueto.getSelectedItem();
}
public void clear(){
valuefrom.setSelectedIndex(0);
valueto.setSelectedIndex(length-1);
}
}
| 1,452 | 0.643251 | 0.62741 | 58 | 24.017241 | 18.518854 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.689655 | false | false | 6 |
762bdc4d5310718b2749ab959d0f1e9294833bc7 | 3,779,571,251,509 | b1cb85373967ad218938d868f331fcaa7044f506 | /6-kyu/Vasya and Stairs/src/Stairs.java | 0416a903c7ce2f354efc6ba032d9defd7159e746 | [] | no_license | KamilCzerniak/Codewars-JAVA-katas | https://github.com/KamilCzerniak/Codewars-JAVA-katas | 7c20be1fd94bb9201345397d2af8def58b031f2f | 9f98f9630e4c812ac236e54052b3134067727d17 | refs/heads/master | 2020-04-02T03:10:46.344000 | 2019-08-13T23:27:39 | 2019-08-13T23:27:39 | 153,949,691 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.stream.IntStream;
public class Stairs {
public static int NumberOfSteps(int n, int m) {
return IntStream.rangeClosed((int) Math.ceil(n / 2.0), n)
.filter(i -> i % m == 0)
.findFirst()
.orElse(-1);
}
} | UTF-8 | Java | 282 | java | Stairs.java | Java | [] | null | [] | import java.util.stream.IntStream;
public class Stairs {
public static int NumberOfSteps(int n, int m) {
return IntStream.rangeClosed((int) Math.ceil(n / 2.0), n)
.filter(i -> i % m == 0)
.findFirst()
.orElse(-1);
}
} | 282 | 0.528369 | 0.514184 | 10 | 27.299999 | 20.406126 | 65 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 6 |
5f11260fac7bd0e189734c45da9a1a37e3ba77b2 | 11,106,785,483,400 | 75d37cb58d14449b16c716159ab63e3abed5203f | /baseJar/src/main/java/com/trading/service/impl/TradingGetDisputeImpl.java | c85569acc3df86bae0929af93ed29ed5b6ec51ea | [] | no_license | myothercode/tembin | https://github.com/myothercode/tembin | 880a10e58abfaa2c3c66fc14e604f8dd8e84a890 | e1bf828d112fe14b17b10afe11844109e1ae379d | refs/heads/master | 2021-01-10T06:58:37.017000 | 2015-01-30T10:07:54 | 2015-01-30T10:07:54 | 49,754,241 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.trading.service.impl;
import com.base.database.trading.mapper.TradingGetDisputeMapper;
import com.base.database.trading.model.TradingGetDispute;
import com.base.database.trading.model.TradingGetDisputeExample;
import com.base.utils.common.ObjectUtils;
import com.base.utils.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 退货政策
* Created by lq on 2014/7/29.
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TradingGetDisputeImpl implements com.trading.service.ITradingGetDispute {
@Autowired
private TradingGetDisputeMapper tradingGetDisputeMapper;
@Override
public void saveGetDispute(TradingGetDispute GetDispute) throws Exception {
if(GetDispute.getId()==null){
ObjectUtils.toInitPojoForInsert(GetDispute);
tradingGetDisputeMapper.insert(GetDispute);
}else{
TradingGetDispute t=tradingGetDisputeMapper.selectByPrimaryKey(GetDispute.getId());
Asserts.assertTrue(t != null && t.getCreateUser() != null, "没有找到记录或者记录创建者为空");
ObjectUtils.valiUpdate(t.getCreateUser(),TradingGetDisputeMapper.class,GetDispute.getId(),"Synchronize");
tradingGetDisputeMapper.updateByPrimaryKeySelective(GetDispute);
}
}
@Override
public List<TradingGetDispute> selectGetDisputeByTransactionId(String TransactionId) {
TradingGetDisputeExample example=new TradingGetDisputeExample();
TradingGetDisputeExample.Criteria cr=example.createCriteria();
cr.andTransactionidEqualTo(TransactionId);
List<TradingGetDispute> list=tradingGetDisputeMapper.selectByExample(example);
return list;
}
}
| UTF-8 | Java | 1,936 | java | TradingGetDisputeImpl.java | Java | [
{
"context": "ort java.util.List;\r\n\r\n/**\r\n * 退货政策\r\n * Created by lq on 2014/7/29.\r\n */\r\n@Service\r\n@Transactional(roll",
"end": 549,
"score": 0.9995970726013184,
"start": 547,
"tag": "USERNAME",
"value": "lq"
}
] | null | [] | package com.trading.service.impl;
import com.base.database.trading.mapper.TradingGetDisputeMapper;
import com.base.database.trading.model.TradingGetDispute;
import com.base.database.trading.model.TradingGetDisputeExample;
import com.base.utils.common.ObjectUtils;
import com.base.utils.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* 退货政策
* Created by lq on 2014/7/29.
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class TradingGetDisputeImpl implements com.trading.service.ITradingGetDispute {
@Autowired
private TradingGetDisputeMapper tradingGetDisputeMapper;
@Override
public void saveGetDispute(TradingGetDispute GetDispute) throws Exception {
if(GetDispute.getId()==null){
ObjectUtils.toInitPojoForInsert(GetDispute);
tradingGetDisputeMapper.insert(GetDispute);
}else{
TradingGetDispute t=tradingGetDisputeMapper.selectByPrimaryKey(GetDispute.getId());
Asserts.assertTrue(t != null && t.getCreateUser() != null, "没有找到记录或者记录创建者为空");
ObjectUtils.valiUpdate(t.getCreateUser(),TradingGetDisputeMapper.class,GetDispute.getId(),"Synchronize");
tradingGetDisputeMapper.updateByPrimaryKeySelective(GetDispute);
}
}
@Override
public List<TradingGetDispute> selectGetDisputeByTransactionId(String TransactionId) {
TradingGetDisputeExample example=new TradingGetDisputeExample();
TradingGetDisputeExample.Criteria cr=example.createCriteria();
cr.andTransactionidEqualTo(TransactionId);
List<TradingGetDispute> list=tradingGetDisputeMapper.selectByExample(example);
return list;
}
}
| 1,936 | 0.744468 | 0.74078 | 48 | 37.541668 | 33.058002 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 6 |
c81bcc0976e8675b4eda748e1cdf611b79213263 | 20,392,504,745,789 | 53dab80d52bbb3494c4aa9677fe03c0cbf36aa5d | /src/main/java/com/usa/zhiben/service/sysConfigService/SysConfigService.java | 990979a3218126caa9f9647558159100cc550324 | [] | no_license | yunlimengli/zhibenTest | https://github.com/yunlimengli/zhibenTest | f99fbf4581ad261ca96de37361b5379c80e74d58 | 1430c6a82b6efb8f37dd653331aaf77f7c90fbcf | refs/heads/master | 2020-05-25T01:24:16.122000 | 2019-05-20T02:31:02 | 2019-05-20T02:31:02 | 187,554,807 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.usa.zhiben.service.sysConfigService;
import java.util.Locale;
/**
* 系统配置表
*
* @author 胖花
* @create 2019-03-15 14:45
*/
public interface SysConfigService {
/**
* 获取当前的语言配置信息 是什么版本的语言
*
* @return
*/
Locale getSysLanguage();
/**
* 获取当前语言的配置信息
*
* @return
*/
public String getSysLanguageStr();
/**
* 更新当前系统的语言
*
* @param language
* @return
*/
int updateSysLanguage(String language);
/**
* 获取当前国际化的 KEY 对应的信息
*
* @param key
* @return
*/
public String getI18nMessageByKey(String key);
}
| UTF-8 | Java | 749 | java | SysConfigService.java | Java | [
{
"context": "ort java.util.Locale;\n\n/**\n * 系统配置表\n *\n * @author 胖花\n * @create 2019-03-15 14:45\n */\n\npublic interface",
"end": 105,
"score": 0.999079167842865,
"start": 103,
"tag": "NAME",
"value": "胖花"
}
] | null | [] | package com.usa.zhiben.service.sysConfigService;
import java.util.Locale;
/**
* 系统配置表
*
* @author 胖花
* @create 2019-03-15 14:45
*/
public interface SysConfigService {
/**
* 获取当前的语言配置信息 是什么版本的语言
*
* @return
*/
Locale getSysLanguage();
/**
* 获取当前语言的配置信息
*
* @return
*/
public String getSysLanguageStr();
/**
* 更新当前系统的语言
*
* @param language
* @return
*/
int updateSysLanguage(String language);
/**
* 获取当前国际化的 KEY 对应的信息
*
* @param key
* @return
*/
public String getI18nMessageByKey(String key);
}
| 749 | 0.549921 | 0.527734 | 46 | 12.717391 | 13.440145 | 50 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.130435 | false | false | 6 |
413f814f44fabe899229f0c8f5895d48d00ef2bf | 13,494,787,259,515 | 54baf1936afe8f77d1f4dc42268d8506d0218bb3 | /PowerProsRosterBuilder/src/PlayerBuilder/StatsRetriever.java | cfe47e04d8ec92f4f5734aead429ab160f2126fd | [] | no_license | CSho27/MLB_PowerPros_RosterBuilder | https://github.com/CSho27/MLB_PowerPros_RosterBuilder | b6360480a571b59709f8e591217cb453e02f8051 | 11364edf8634af6d5c1d5fa7ef5e58708e47546e | refs/heads/master | 2021-05-20T11:51:13.045000 | 2020-04-02T14:50:50 | 2020-04-02T14:50:50 | 252,283,298 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package PlayerBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class StatsRetriever {
public static String STATS_URL = "http://lookup-service-prod.mlb.com/json";
public static String SEARCH_ENDPOINT = "/named.search_player_all.bam?";
public static String INFO_ENDPOINT = "/named.player_info.bam?";
public static String HITTING_ENDPOINT = "/named.sport_hitting_tm.bam?";
public static String FIELDING_ENDPOINT = "/named.sport_fielding_tm.bam?";
public static String PITCHING_ENDPOINT = "/named.sport_pitching_tm.bam?";
// Public methods
public PlayerStatistics getPlayerStatistics(String firstName, String lastName, Integer year){
Long playerId = getPlayerId(firstName, lastName);
PlayerInfo playerInfo = getPlayerInfo(playerId);
PitchingStats pitchingStats = null;
HittingStats hittingStats = null;
if(playerInfo != null && playerInfo.getPrimary() == 1){
pitchingStats = getPitchingStats(playerId, year);
}
hittingStats = getHittingStats(playerId, year);
FieldingStats fieldingStats = getFieldingStats(playerId, year);
return new PlayerStatistics(playerInfo, hittingStats, fieldingStats, pitchingStats);
}
// Internal Methods
// Building Requests
private String createSearchRequest(String first, String last){
first = first.replaceAll(" ", "%20");
last = last.replaceAll(" ", "%20");
return STATS_URL+SEARCH_ENDPOINT+"sport_code='mlb'&name_part=%27"+first+"%20"+last+"%27";
}
private String createInfoRequest(Long playerId){
return STATS_URL+INFO_ENDPOINT+"sport_code='mlb'&player_id='"+playerId+"'";
}
private String createHittingRequest(Long playerId, Integer year){
return STATS_URL+HITTING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
private String createFieldingRequest(Long playerId, Integer year){
return STATS_URL+FIELDING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
private String createPitchingRequest(Long playerId, Integer year){
return STATS_URL+PITCHING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
// Initial Search
public long getPlayerId(String first, String last){
try {
URL url = new URL(createSearchRequest(first, last));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
SearchResults_Arr sr = gson.fromJson(content.toString(), SearchResults_Arr.class);
if(sr.getFirst() != null){
return sr.getFirst().player_id;
} else {
return -1;
}
}
catch (JsonSyntaxException jsE){
SearchResults_Obj sr = gson.fromJson(content.toString(), SearchResults_Obj.class);
return sr.getFirst().player_id;
}
} catch (IOException e) {
System.out.println("Could not find player "+first+" "+last);
e.printStackTrace();
return -1;
}
}
public PlayerInfo getPlayerInfo(long playerId){
try {
URL url = new URL(createInfoRequest(playerId));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
PlayerInformation info = gson.fromJson(content.toString(), PlayerInformation.class);
return info.player_info.queryResults.row;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Retrieving Stats
private HittingStats getHittingStats(long playerId, int year){
try {
URL url = new URL(createHittingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_hitting_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_hitting_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public FieldingStats getFieldingStats(long playerId, int year){
try {
URL url = new URL(createFieldingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_fielding_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_fielding_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public PitchingStats getPitchingStats(long playerId, int year){
try {
URL url = new URL(createPitchingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_pitching_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_pitching_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Internal Classes for Gson
// Search Query
public class SearchPlayer {
String name_display_first_last;
long player_id;
public String toString(){
return name_display_first_last+" : "+player_id;
}
}
public class PlayerInformation {
InfoObject player_info;
}
public class InfoObject {
String copyRight;
InfoQueryResult queryResults;
}
public class InfoQueryResult {
int total_size;
PlayerInfo row;
}
// Object
public class SearchResults_Obj {
Search_player_obj search_player_all;
public void print(){
search_player_all.print();
}
public SearchPlayer getFirst(){
if(search_player_all.queryResults.row != null){
return search_player_all.queryResults.row;
} else {
return null;
}
}
}
public class Search_player_obj {
String copyRight;
QueryResults_obj queryResults;
public void print(){
queryResults.print();
}
}
public class QueryResults_obj {
int total_size;
SearchPlayer row;
public void print(){
System.out.println(row.toString()); }
}
// Array
public class SearchResults_Arr {
Search_player_all search_player_all;
public void print(){
search_player_all.print();
}
public SearchPlayer getFirst(){
if(search_player_all.queryResults.row != null){
return search_player_all.queryResults.row[0];
} else {
return null;
}
}
}
public class Search_player_all {
String copyRight;
QueryResults queryResults;
public void print(){
queryResults.print();
}
}
public class QueryResults {
int total_size;
SearchPlayer[] row;
public void print(){
for(int i=0; i<row.length; i++){
System.out.println(row[i].toString());
}
}
}
// Statistics Query
public class StatsResults{
HittingStatsQuery sport_hitting_tm;
FieldingStatsQuery sport_fielding_tm;
PitchingStatsQuery sport_pitching_tm;
}
public class StatsResults_arr{
HittingStatsQuery_arr sport_hitting_tm;
FieldingStatsQuery_arr sport_fielding_tm;
PitchingStatsQuery_arr sport_pitching_tm;
}
// Hitting
// Regular
public class HittingStatsQuery {
String copyRight;
HSQueryResults queryResults;
}
public class HSQueryResults {
Integer totalSize;
HittingStats row;
}
// Array
public class HittingStatsQuery_arr {
String copyRight;
HSQueryResults_arr queryResults;
}
public class HSQueryResults_arr {
HittingStats[] row;
public HittingStats getCompiled(){
int at_bats = 0;
int hits = 0;
int hr = 0;
int sb = 0;
int cs = 0;
int rbi = 0;
int r = 0;
int totalBases = 0;
int go = 0;
int ao = 0;
for(int i=0; i<row.length; i++){
at_bats += row[i].getAtBats();
hits += row[i].getHits();
hr += row[i].getHomeruns();
sb += row[i].getStolenBases();
cs += row[i].getCaughtStealing();
r += row[i].getRuns();
totalBases += row[i].getTotalBases();
rbi += row[i].getRBI();
if(row[i].go.length() > 0 && row[i].ao.length() > 0){
go += Integer.parseInt(row[i].go);
ao += Integer.parseInt(row[i].ao);
}
}
return new HittingStats(hr, sb, at_bats, hits, totalBases, cs, r, go, ao, rbi);
}
}
// Fielding
//Regular
public class FieldingStatsQuery {
String copyRight;
FSQueryResults queryResults;
}
public class FSQueryResults {
FieldingStats row;
}
// Array
public class FieldingStatsQuery_arr {
String copyRight;
FSQueryResults_arr queryResults;
}
public class FSQueryResults_arr {
FieldingStats[] row;
public FieldingStats getCompiled(){
int tc = 0;
int e = 0;
for(int i=0; i<row.length; i++){
tc += row[i].getTotalChances();
e += row[i].getErrors();
}
return new FieldingStats(row[0].getPosition(), tc, e);
}
}
// Pitching
// Regular
public class PitchingStatsQuery {
String copyRight;
PSQueryResults queryResults;
}
public class PSQueryResults {
PitchingStats row;
}
// Array
public class PitchingStatsQuery_arr {
String copyRight;
PSQueryResults_arr queryResults;
}
public class PSQueryResults_arr {
PitchingStats[] row;
public PitchingStats getCompiled(){
Double ip = 0.0;
Double bb = 0.0;
Double er = 0.0;
Double g = 0.0;
Integer gs = 0;
Integer svo = 0;
for(int i=0; i<row.length; i++){
ip += row[i].getIP();
bb += row[i].getBB();
er += row[i].getER();
g += row[i].getGames();
gs += row[i].getStarts();
svo += row[i].getSVO();
}
return new PitchingStats(bb, er, ip, g, gs, svo);
}
}
}
| UTF-8 | Java | 11,217 | java | StatsRetriever.java | Java | [
{
"context": "public PlayerStatistics getPlayerStatistics(String firstName, String lastName, Integer year){\n\t\tLong playerId ",
"end": 798,
"score": 0.95284104347229,
"start": 789,
"tag": "NAME",
"value": "firstName"
},
{
"context": "stics getPlayerStatistics(String firstName, Stri... | null | [] | package PlayerBuilder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class StatsRetriever {
public static String STATS_URL = "http://lookup-service-prod.mlb.com/json";
public static String SEARCH_ENDPOINT = "/named.search_player_all.bam?";
public static String INFO_ENDPOINT = "/named.player_info.bam?";
public static String HITTING_ENDPOINT = "/named.sport_hitting_tm.bam?";
public static String FIELDING_ENDPOINT = "/named.sport_fielding_tm.bam?";
public static String PITCHING_ENDPOINT = "/named.sport_pitching_tm.bam?";
// Public methods
public PlayerStatistics getPlayerStatistics(String firstName, String lastName, Integer year){
Long playerId = getPlayerId(firstName, lastName);
PlayerInfo playerInfo = getPlayerInfo(playerId);
PitchingStats pitchingStats = null;
HittingStats hittingStats = null;
if(playerInfo != null && playerInfo.getPrimary() == 1){
pitchingStats = getPitchingStats(playerId, year);
}
hittingStats = getHittingStats(playerId, year);
FieldingStats fieldingStats = getFieldingStats(playerId, year);
return new PlayerStatistics(playerInfo, hittingStats, fieldingStats, pitchingStats);
}
// Internal Methods
// Building Requests
private String createSearchRequest(String first, String last){
first = first.replaceAll(" ", "%20");
last = last.replaceAll(" ", "%20");
return STATS_URL+SEARCH_ENDPOINT+"sport_code='mlb'&name_part=%27"+first+"%20"+last+"%27";
}
private String createInfoRequest(Long playerId){
return STATS_URL+INFO_ENDPOINT+"sport_code='mlb'&player_id='"+playerId+"'";
}
private String createHittingRequest(Long playerId, Integer year){
return STATS_URL+HITTING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
private String createFieldingRequest(Long playerId, Integer year){
return STATS_URL+FIELDING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
private String createPitchingRequest(Long playerId, Integer year){
return STATS_URL+PITCHING_ENDPOINT+"league_list_id='mlb'&game_type='R'&season='"+year+"'&player_id='"+playerId+"'";
}
// Initial Search
public long getPlayerId(String first, String last){
try {
URL url = new URL(createSearchRequest(first, last));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
SearchResults_Arr sr = gson.fromJson(content.toString(), SearchResults_Arr.class);
if(sr.getFirst() != null){
return sr.getFirst().player_id;
} else {
return -1;
}
}
catch (JsonSyntaxException jsE){
SearchResults_Obj sr = gson.fromJson(content.toString(), SearchResults_Obj.class);
return sr.getFirst().player_id;
}
} catch (IOException e) {
System.out.println("Could not find player "+first+" "+last);
e.printStackTrace();
return -1;
}
}
public PlayerInfo getPlayerInfo(long playerId){
try {
URL url = new URL(createInfoRequest(playerId));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
PlayerInformation info = gson.fromJson(content.toString(), PlayerInformation.class);
return info.player_info.queryResults.row;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Retrieving Stats
private HittingStats getHittingStats(long playerId, int year){
try {
URL url = new URL(createHittingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_hitting_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_hitting_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public FieldingStats getFieldingStats(long playerId, int year){
try {
URL url = new URL(createFieldingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_fielding_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_fielding_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public PitchingStats getPitchingStats(long playerId, int year){
try {
URL url = new URL(createPitchingRequest(playerId, year));
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
Gson gson = new Gson();
try{
StatsResults sr = gson.fromJson(content.toString(), StatsResults.class);
return sr.sport_pitching_tm.queryResults.row;
}
catch (JsonSyntaxException jsE){
StatsResults_arr sr = gson.fromJson(content.toString(),StatsResults_arr.class);
return sr.sport_pitching_tm.queryResults.getCompiled();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
// Internal Classes for Gson
// Search Query
public class SearchPlayer {
String name_display_first_last;
long player_id;
public String toString(){
return name_display_first_last+" : "+player_id;
}
}
public class PlayerInformation {
InfoObject player_info;
}
public class InfoObject {
String copyRight;
InfoQueryResult queryResults;
}
public class InfoQueryResult {
int total_size;
PlayerInfo row;
}
// Object
public class SearchResults_Obj {
Search_player_obj search_player_all;
public void print(){
search_player_all.print();
}
public SearchPlayer getFirst(){
if(search_player_all.queryResults.row != null){
return search_player_all.queryResults.row;
} else {
return null;
}
}
}
public class Search_player_obj {
String copyRight;
QueryResults_obj queryResults;
public void print(){
queryResults.print();
}
}
public class QueryResults_obj {
int total_size;
SearchPlayer row;
public void print(){
System.out.println(row.toString()); }
}
// Array
public class SearchResults_Arr {
Search_player_all search_player_all;
public void print(){
search_player_all.print();
}
public SearchPlayer getFirst(){
if(search_player_all.queryResults.row != null){
return search_player_all.queryResults.row[0];
} else {
return null;
}
}
}
public class Search_player_all {
String copyRight;
QueryResults queryResults;
public void print(){
queryResults.print();
}
}
public class QueryResults {
int total_size;
SearchPlayer[] row;
public void print(){
for(int i=0; i<row.length; i++){
System.out.println(row[i].toString());
}
}
}
// Statistics Query
public class StatsResults{
HittingStatsQuery sport_hitting_tm;
FieldingStatsQuery sport_fielding_tm;
PitchingStatsQuery sport_pitching_tm;
}
public class StatsResults_arr{
HittingStatsQuery_arr sport_hitting_tm;
FieldingStatsQuery_arr sport_fielding_tm;
PitchingStatsQuery_arr sport_pitching_tm;
}
// Hitting
// Regular
public class HittingStatsQuery {
String copyRight;
HSQueryResults queryResults;
}
public class HSQueryResults {
Integer totalSize;
HittingStats row;
}
// Array
public class HittingStatsQuery_arr {
String copyRight;
HSQueryResults_arr queryResults;
}
public class HSQueryResults_arr {
HittingStats[] row;
public HittingStats getCompiled(){
int at_bats = 0;
int hits = 0;
int hr = 0;
int sb = 0;
int cs = 0;
int rbi = 0;
int r = 0;
int totalBases = 0;
int go = 0;
int ao = 0;
for(int i=0; i<row.length; i++){
at_bats += row[i].getAtBats();
hits += row[i].getHits();
hr += row[i].getHomeruns();
sb += row[i].getStolenBases();
cs += row[i].getCaughtStealing();
r += row[i].getRuns();
totalBases += row[i].getTotalBases();
rbi += row[i].getRBI();
if(row[i].go.length() > 0 && row[i].ao.length() > 0){
go += Integer.parseInt(row[i].go);
ao += Integer.parseInt(row[i].ao);
}
}
return new HittingStats(hr, sb, at_bats, hits, totalBases, cs, r, go, ao, rbi);
}
}
// Fielding
//Regular
public class FieldingStatsQuery {
String copyRight;
FSQueryResults queryResults;
}
public class FSQueryResults {
FieldingStats row;
}
// Array
public class FieldingStatsQuery_arr {
String copyRight;
FSQueryResults_arr queryResults;
}
public class FSQueryResults_arr {
FieldingStats[] row;
public FieldingStats getCompiled(){
int tc = 0;
int e = 0;
for(int i=0; i<row.length; i++){
tc += row[i].getTotalChances();
e += row[i].getErrors();
}
return new FieldingStats(row[0].getPosition(), tc, e);
}
}
// Pitching
// Regular
public class PitchingStatsQuery {
String copyRight;
PSQueryResults queryResults;
}
public class PSQueryResults {
PitchingStats row;
}
// Array
public class PitchingStatsQuery_arr {
String copyRight;
PSQueryResults_arr queryResults;
}
public class PSQueryResults_arr {
PitchingStats[] row;
public PitchingStats getCompiled(){
Double ip = 0.0;
Double bb = 0.0;
Double er = 0.0;
Double g = 0.0;
Integer gs = 0;
Integer svo = 0;
for(int i=0; i<row.length; i++){
ip += row[i].getIP();
bb += row[i].getBB();
er += row[i].getER();
g += row[i].getGames();
gs += row[i].getStarts();
svo += row[i].getSVO();
}
return new PitchingStats(bb, er, ip, g, gs, svo);
}
}
}
| 11,217 | 0.683784 | 0.67995 | 431 | 25.025522 | 23.892971 | 117 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.74942 | false | false | 6 |
eb89a9b6a20b1ff3a5d55e99da61c1ee8e1b8247 | 180,388,677,417 | 9dacef32a3c95a5d653de9cca4f56b56788cbbeb | /044-microversices-sprboot2/user-sevice/src/main/java/com/demien/services/user/repository/UserRepository.java | 643a1ee4b0e8863813a06112c8f0aafba9867f49 | [] | no_license | demien666/dev-blog | https://github.com/demien666/dev-blog | 46a219b95a60fc54fd0e5842137f51bef3c6d669 | 8d0efafea4b9857c2772de9b583e1e133f412376 | refs/heads/master | 2023-06-08T16:05:36.066000 | 2023-05-28T15:49:02 | 2023-05-28T15:49:02 | 94,076,043 | 0 | 0 | null | false | 2022-12-16T15:45:11 | 2017-06-12T09:00:40 | 2022-07-28T20:06:17 | 2022-12-16T15:45:11 | 10,502 | 0 | 0 | 39 | JavaScript | false | false | package com.demien.services.user.repository;
import com.demien.services.user.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface UserRepository extends JpaRepository<User, String> {
}
| UTF-8 | Java | 286 | java | UserRepository.java | Java | [] | null | [] | package com.demien.services.user.repository;
import com.demien.services.user.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
@Component
public interface UserRepository extends JpaRepository<User, String> {
}
| 286 | 0.839161 | 0.839161 | 9 | 30.777779 | 26.317623 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.555556 | false | false | 6 |
8c09a407b024ee65f4afccd90e31c006406cd6d1 | 9,552,007,315,092 | 78608de074512471fc7551eaea9c1f0579eb8664 | /class-basicplatform/src/main/java/com/school/dao/TeacherDAO.java | 7dc83e1136db1b1644ebb4a6016029680122d08a | [] | no_license | qihasihi/RollStone | https://github.com/qihasihi/RollStone | 312e53c60f9c36ebc41886704d7d99590ce5bd93 | 754c2eefbbc91a7d2aa7dbd6d7bf6e46ba98a228 | refs/heads/master | 2021-01-16T20:57:18.178000 | 2015-02-16T03:05:12 | 2015-02-16T03:05:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.school.dao;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.school.dao.base.CommonDAO;
import com.school.dao.inter.ITeacherDAO;
import com.school.entity.TeacherInfo;
import com.school.util.PageResult;
import com.school.util.UtilTool;
import com.school.util.UtilTool.DateType;
@Component
public class TeacherDAO extends CommonDAO<TeacherInfo> implements ITeacherDAO {
public Boolean doDelete(TeacherInfo obj) {
StringBuilder sqlbuilder=new StringBuilder();
List<Object> objList=getDeleteSql(obj, sqlbuilder);
Object afficeObj=this.executeSacle_PROC(sqlbuilder.toString(), objList.toArray());
if(afficeObj!=null&&afficeObj.toString().trim().length()>0&&Integer.parseInt(afficeObj.toString())>0){
return true;
}return false;
}
public Boolean doExcetueArrayProc(List<String> sqlArrayList,
List<List<Object>> objArrayList) {
return this.executeArrayQuery_PROC(sqlArrayList, objArrayList);
}
public Boolean doSave(TeacherInfo obj) {
if (obj == null)
return false;
StringBuilder sqlbuilder = new StringBuilder();
List<Object> objList = this.getSaveSql(obj, sqlbuilder);
Object afficeObj = this.executeSacle_PROC(sqlbuilder.toString(),
objList.toArray());
if (afficeObj != null && afficeObj.toString().trim().length() > 0
&& Integer.parseInt(afficeObj.toString()) > 0) {
return true;
}
return false;
}
public Boolean doUpdate(TeacherInfo obj) {
if (obj == null)
return false;
StringBuilder sqlbuilder = new StringBuilder();
List<Object> objList = this.getUpdateSql(obj, sqlbuilder);
Object afficeObj = this.executeSacle_PROC(sqlbuilder.toString(),
objList.toArray());
if (afficeObj != null && afficeObj.toString().trim().length() > 0
&& Integer.parseInt(afficeObj.toString()) > 0) {
return true;
}
return false;
}
public List<Object> getDeleteSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||sqlbuilder==null)
return null;
sqlbuilder.append("{call teacher_proc_delete(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<TeacherInfo> getList(TeacherInfo obj, PageResult presult) {
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_search_split(");
List<Object> objList=new ArrayList<Object>();
if(obj==null)
sqlbuilder.append("NULL,NULL,NULL,NULL,NULL,NULL,");
else{
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTuserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTuserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getUsername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getUsername());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getRealname()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getRealname());
}else
sqlbuilder.append("NULL,");
}
if(presult!=null&&presult.getPageNo()>0&&presult.getPageSize()>0){
sqlbuilder.append("?,?,");
objList.add(presult.getPageNo());
objList.add(presult.getPageSize());
}else{
sqlbuilder.append("NULL,NULL,");
}
if(presult!=null&&presult.getOrderBy()!=null&&presult.getOrderBy().trim().length()>0){
sqlbuilder.append("?,");
objList.add(presult.getOrderBy());
}else{
sqlbuilder.append("NULL,");
}
sqlbuilder.append("?)}");
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(presult!=null&&objArray[0]!=null&&objArray[0].toString().trim().length()>0)
presult.setRecTotal(Integer.parseInt(objArray[0].toString().trim()));
return teacherList;
}
public List<TeacherInfo> getListByTchnameOrUsername(TeacherInfo obj, PageResult presult) {
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_search_by_tnorun(");
List<Object> objList=new ArrayList<Object>();
if(obj==null)
sqlbuilder.append("NULL,NULL,NULL,NULL,NULL,NULL,");
else{
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTuserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTuserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getUsername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getUsername());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getRealname()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getRealname());
}else
sqlbuilder.append("NULL,");
}
if(presult!=null&&presult.getPageNo()>0&&presult.getPageSize()>0){
sqlbuilder.append("?,?,");
objList.add(presult.getPageNo());
objList.add(presult.getPageSize());
}else{
sqlbuilder.append("NULL,NULL,");
}
if(presult!=null&&presult.getOrderBy()!=null&&presult.getOrderBy().trim().length()>0){
sqlbuilder.append("?,");
objList.add(presult.getOrderBy());
}else{
sqlbuilder.append("NULL,");
}
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getDcschoolid());
sqlbuilder.append("?)}");
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(presult!=null&&objArray[0]!=null&&objArray[0].toString().trim().length()>0)
presult.setRecTotal(Integer.parseInt(objArray[0].toString().trim()));
return teacherList;
}
public List<Object> getSaveSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||sqlbuilder==null)
return null;
sqlbuilder.append("{call teacher_proc_add(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacheraddress()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacheraddress());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherphone()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherphone());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachercardid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachercardid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherpost()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherpost());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getPassword()!=null){
sqlbuilder.append("?,");
objList.add(obj.getPassword());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherlevel()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherlevel());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherbirth()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getTeacherbirth(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getEntrytime()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getEntrytime(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getImgheardsrc()!=null){
sqlbuilder.append("?,");
objList.add(obj.getImgheardsrc());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<Object> getUpdateSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||obj.getUserid()==null)
return null;
sqlbuilder.append("{call teacher_proc_update(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacheraddress()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacheraddress());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherphone()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherphone());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachercardid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachercardid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherpost()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherpost());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getPassword()!=null){
sqlbuilder.append("?,");
objList.add(obj.getPassword());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherlevel()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherlevel());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherbirth()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getTeacherbirth(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getEntrytime()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getEntrytime(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getImgheardsrc()!=null){
sqlbuilder.append("?,");
objList.add(obj.getImgheardsrc());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<TeacherInfo> getTeacherListByUserId(String userid,String year) {
// TODO Auto-generated method stub
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_getlistby_stuid(?,?,?)}");
List<Object> objList=new ArrayList<Object>();
objList.add(userid);
objList.add(year);
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(objArray[0]!=null&&Integer.parseInt(objArray[0].toString())>0)
return teacherList;
else
return null;
}
}
| UTF-8 | Java | 12,362 | java | TeacherDAO.java | Java | [] | null | [] | package com.school.dao;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.school.dao.base.CommonDAO;
import com.school.dao.inter.ITeacherDAO;
import com.school.entity.TeacherInfo;
import com.school.util.PageResult;
import com.school.util.UtilTool;
import com.school.util.UtilTool.DateType;
@Component
public class TeacherDAO extends CommonDAO<TeacherInfo> implements ITeacherDAO {
public Boolean doDelete(TeacherInfo obj) {
StringBuilder sqlbuilder=new StringBuilder();
List<Object> objList=getDeleteSql(obj, sqlbuilder);
Object afficeObj=this.executeSacle_PROC(sqlbuilder.toString(), objList.toArray());
if(afficeObj!=null&&afficeObj.toString().trim().length()>0&&Integer.parseInt(afficeObj.toString())>0){
return true;
}return false;
}
public Boolean doExcetueArrayProc(List<String> sqlArrayList,
List<List<Object>> objArrayList) {
return this.executeArrayQuery_PROC(sqlArrayList, objArrayList);
}
public Boolean doSave(TeacherInfo obj) {
if (obj == null)
return false;
StringBuilder sqlbuilder = new StringBuilder();
List<Object> objList = this.getSaveSql(obj, sqlbuilder);
Object afficeObj = this.executeSacle_PROC(sqlbuilder.toString(),
objList.toArray());
if (afficeObj != null && afficeObj.toString().trim().length() > 0
&& Integer.parseInt(afficeObj.toString()) > 0) {
return true;
}
return false;
}
public Boolean doUpdate(TeacherInfo obj) {
if (obj == null)
return false;
StringBuilder sqlbuilder = new StringBuilder();
List<Object> objList = this.getUpdateSql(obj, sqlbuilder);
Object afficeObj = this.executeSacle_PROC(sqlbuilder.toString(),
objList.toArray());
if (afficeObj != null && afficeObj.toString().trim().length() > 0
&& Integer.parseInt(afficeObj.toString()) > 0) {
return true;
}
return false;
}
public List<Object> getDeleteSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||sqlbuilder==null)
return null;
sqlbuilder.append("{call teacher_proc_delete(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<TeacherInfo> getList(TeacherInfo obj, PageResult presult) {
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_search_split(");
List<Object> objList=new ArrayList<Object>();
if(obj==null)
sqlbuilder.append("NULL,NULL,NULL,NULL,NULL,NULL,");
else{
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTuserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTuserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getUsername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getUsername());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getRealname()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getRealname());
}else
sqlbuilder.append("NULL,");
}
if(presult!=null&&presult.getPageNo()>0&&presult.getPageSize()>0){
sqlbuilder.append("?,?,");
objList.add(presult.getPageNo());
objList.add(presult.getPageSize());
}else{
sqlbuilder.append("NULL,NULL,");
}
if(presult!=null&&presult.getOrderBy()!=null&&presult.getOrderBy().trim().length()>0){
sqlbuilder.append("?,");
objList.add(presult.getOrderBy());
}else{
sqlbuilder.append("NULL,");
}
sqlbuilder.append("?)}");
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(presult!=null&&objArray[0]!=null&&objArray[0].toString().trim().length()>0)
presult.setRecTotal(Integer.parseInt(objArray[0].toString().trim()));
return teacherList;
}
public List<TeacherInfo> getListByTchnameOrUsername(TeacherInfo obj, PageResult presult) {
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_search_by_tnorun(");
List<Object> objList=new ArrayList<Object>();
if(obj==null)
sqlbuilder.append("NULL,NULL,NULL,NULL,NULL,NULL,");
else{
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTuserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTuserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getUsername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getUsername());
}else
sqlbuilder.append("NULL,");
if(obj.getUserinfo().getRealname()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getRealname());
}else
sqlbuilder.append("NULL,");
}
if(presult!=null&&presult.getPageNo()>0&&presult.getPageSize()>0){
sqlbuilder.append("?,?,");
objList.add(presult.getPageNo());
objList.add(presult.getPageSize());
}else{
sqlbuilder.append("NULL,NULL,");
}
if(presult!=null&&presult.getOrderBy()!=null&&presult.getOrderBy().trim().length()>0){
sqlbuilder.append("?,");
objList.add(presult.getOrderBy());
}else{
sqlbuilder.append("NULL,");
}
sqlbuilder.append("?,");
objList.add(obj.getUserinfo().getDcschoolid());
sqlbuilder.append("?)}");
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(presult!=null&&objArray[0]!=null&&objArray[0].toString().trim().length()>0)
presult.setRecTotal(Integer.parseInt(objArray[0].toString().trim()));
return teacherList;
}
public List<Object> getSaveSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||sqlbuilder==null)
return null;
sqlbuilder.append("{call teacher_proc_add(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacheraddress()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacheraddress());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherphone()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherphone());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachercardid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachercardid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherpost()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherpost());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getPassword()!=null){
sqlbuilder.append("?,");
objList.add(obj.getPassword());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherlevel()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherlevel());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherbirth()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getTeacherbirth(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getEntrytime()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getEntrytime(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getImgheardsrc()!=null){
sqlbuilder.append("?,");
objList.add(obj.getImgheardsrc());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<Object> getUpdateSql(TeacherInfo obj, StringBuilder sqlbuilder) {
if(obj==null||obj.getUserid()==null)
return null;
sqlbuilder.append("{call teacher_proc_update(");
List<Object>objList = new ArrayList<Object>();
if(obj.getTeacherid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachername()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachername());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachersex()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachersex());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacheraddress()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacheraddress());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherphone()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherphone());
}else
sqlbuilder.append("NULL,");
if(obj.getTeachercardid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeachercardid());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherpost()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherpost());
}else
sqlbuilder.append("NULL,");
if(obj.getUserid()!=null){
sqlbuilder.append("?,");
objList.add(obj.getUserid());
}else
sqlbuilder.append("NULL,");
if(obj.getPassword()!=null){
sqlbuilder.append("?,");
objList.add(obj.getPassword());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherlevel()!=null){
sqlbuilder.append("?,");
objList.add(obj.getTeacherlevel());
}else
sqlbuilder.append("NULL,");
if(obj.getTeacherbirth()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getTeacherbirth(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getEntrytime()!=null){
sqlbuilder.append("?,");
objList.add(UtilTool.DateConvertToString(obj.getEntrytime(), DateType.type1));
}else
sqlbuilder.append("NULL,");
if(obj.getImgheardsrc()!=null){
sqlbuilder.append("?,");
objList.add(obj.getImgheardsrc());
}else
sqlbuilder.append("NULL,");
sqlbuilder.append("?)}");
return objList;
}
public List<TeacherInfo> getTeacherListByUserId(String userid,String year) {
// TODO Auto-generated method stub
StringBuilder sqlbuilder=new StringBuilder("{CALL teacher_proc_getlistby_stuid(?,?,?)}");
List<Object> objList=new ArrayList<Object>();
objList.add(userid);
objList.add(year);
List<Integer> types=new ArrayList<Integer>();
types.add(Types.INTEGER);
Object[] objArray=new Object[1];
List<TeacherInfo> teacherList=this.executeResult_PROC(sqlbuilder.toString(), objList, types, TeacherInfo.class, objArray);
if(objArray[0]!=null&&Integer.parseInt(objArray[0].toString())>0)
return teacherList;
else
return null;
}
}
| 12,362 | 0.655396 | 0.652969 | 380 | 30.531578 | 21.615822 | 124 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 3.384211 | false | false | 6 |
c06e0d45f9b2fd60e7d19da53cbc49579547fdb2 | 26,121,991,126,384 | aaf936565d8d4262db560b53a564db62ee936daf | /backend/src/main/java/com/davivasconcelos/teste/services/SemestreService.java | ccf3d00d0fd41d0e52f0e315c7b11c1145468e16 | [] | no_license | davimelovasc/teste-nati | https://github.com/davimelovasc/teste-nati | 177ed8a1f1a0c30111cad51012a13e00dbaef82d | 13c2185ac4d437f2df4c7034302b59f54eab3318 | refs/heads/master | 2020-08-29T09:40:46.093000 | 2019-10-28T17:01:12 | 2019-10-28T17:01:12 | 217,996,000 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.davivasconcelos.teste.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.davivasconcelos.teste.domain.Curso;
import com.davivasconcelos.teste.domain.Disciplina;
import com.davivasconcelos.teste.domain.Semestre;
import com.davivasconcelos.teste.dto.SemestreDTO;
import com.davivasconcelos.teste.repositories.CursoRepository;
import com.davivasconcelos.teste.repositories.DisciplinaRepository;
import com.davivasconcelos.teste.repositories.SemestreRepository;
@Service
public class SemestreService {
@Autowired
private SemestreRepository repository;
@Autowired
private CursoRepository cursoRepository;
@Autowired
private DisciplinaRepository disciplinaRepository;
public Semestre find(Integer id) {
Semestre semestre = repository.findById(id).orElse(null);
if(semestre == null) {
throw new IllegalArgumentException("Não foi possivel encontrar o recurso.");
}
return semestre;
}
public Semestre insert(SemestreDTO s) {
s.setId(null);
Semestre semestre = this.fromDTO(s);
semestre = repository.save(semestre);
return semestre;
}
public Semestre fromDTO(SemestreDTO semestreDTO) {
Semestre s = new Semestre();
Curso c = cursoRepository.findById(semestreDTO.getCurso_id()).orElse(null);
s.setCurso(c);
s.setOrdem(semestreDTO.getOrdem());
s.setId(semestreDTO.getId());
return s;
}
public void delete(Integer id) {
repository.deleteById(id);
}
public Semestre addDisciplina(Integer semestre_id, Integer disciplina_id) {
Semestre semestre = find(semestre_id);
Disciplina disciplina = disciplinaRepository.findById(disciplina_id).orElse(null);
semestre.addDisciplina(disciplina);
return repository.save(semestre);
}
public Semestre removeDisciplina(Integer semestre_id, Integer disciplina_id) {
Semestre semestre = find(semestre_id);
Disciplina disciplina = disciplinaRepository.findById(disciplina_id).orElse(null);
semestre.removeDisciplina(disciplina);
return repository.save(semestre);
}
}
| UTF-8 | Java | 2,142 | java | SemestreService.java | Java | [] | null | [] | package com.davivasconcelos.teste.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.davivasconcelos.teste.domain.Curso;
import com.davivasconcelos.teste.domain.Disciplina;
import com.davivasconcelos.teste.domain.Semestre;
import com.davivasconcelos.teste.dto.SemestreDTO;
import com.davivasconcelos.teste.repositories.CursoRepository;
import com.davivasconcelos.teste.repositories.DisciplinaRepository;
import com.davivasconcelos.teste.repositories.SemestreRepository;
@Service
public class SemestreService {
@Autowired
private SemestreRepository repository;
@Autowired
private CursoRepository cursoRepository;
@Autowired
private DisciplinaRepository disciplinaRepository;
public Semestre find(Integer id) {
Semestre semestre = repository.findById(id).orElse(null);
if(semestre == null) {
throw new IllegalArgumentException("Não foi possivel encontrar o recurso.");
}
return semestre;
}
public Semestre insert(SemestreDTO s) {
s.setId(null);
Semestre semestre = this.fromDTO(s);
semestre = repository.save(semestre);
return semestre;
}
public Semestre fromDTO(SemestreDTO semestreDTO) {
Semestre s = new Semestre();
Curso c = cursoRepository.findById(semestreDTO.getCurso_id()).orElse(null);
s.setCurso(c);
s.setOrdem(semestreDTO.getOrdem());
s.setId(semestreDTO.getId());
return s;
}
public void delete(Integer id) {
repository.deleteById(id);
}
public Semestre addDisciplina(Integer semestre_id, Integer disciplina_id) {
Semestre semestre = find(semestre_id);
Disciplina disciplina = disciplinaRepository.findById(disciplina_id).orElse(null);
semestre.addDisciplina(disciplina);
return repository.save(semestre);
}
public Semestre removeDisciplina(Integer semestre_id, Integer disciplina_id) {
Semestre semestre = find(semestre_id);
Disciplina disciplina = disciplinaRepository.findById(disciplina_id).orElse(null);
semestre.removeDisciplina(disciplina);
return repository.save(semestre);
}
}
| 2,142 | 0.758991 | 0.758991 | 70 | 28.585714 | 25.527851 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.671429 | false | false | 6 |
b41fb6fc2e1c74d778b24dd724055b225b421510 | 6,081,673,751,409 | f941ac16d056595ac58da4f52f4df9ec1fa60533 | /src/Day24/Cat/Dog.java | e2f3ad5c2781f0e63072f27d8a8f82ff18c48890 | [] | no_license | seamisssun/zly | https://github.com/seamisssun/zly | 6bde9307e53b532d3247cc92fdfb0d9290ffba6d | a7fd4bc182bb7ad628e757929d3007a5a5758c72 | refs/heads/master | 2020-12-02T22:47:42.122000 | 2017-07-01T05:18:34 | 2017-07-01T05:18:34 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package Day24.Cat;
/**
* Created by Administrator on 2017/6/23.
*/
public class Dog implements CanCry {
public void cry(){
System.out.println("我是狗,我的叫声是汪汪汪");
}
}
| UTF-8 | Java | 207 | java | Dog.java | Java | [
{
"context": "package Day24.Cat;\n\n/**\n * Created by Administrator on 2017/6/23.\n */\npublic class Dog implements Can",
"end": 51,
"score": 0.6069868206977844,
"start": 38,
"tag": "USERNAME",
"value": "Administrator"
}
] | null | [] | package Day24.Cat;
/**
* Created by Administrator on 2017/6/23.
*/
public class Dog implements CanCry {
public void cry(){
System.out.println("我是狗,我的叫声是汪汪汪");
}
}
| 207 | 0.63388 | 0.584699 | 11 | 15.636364 | 16.482899 | 43 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.181818 | false | false | 6 |
b0940d219d608a41ec59a92d39a543f4ae6b2f1c | 6,081,673,751,340 | 872ad65013258a0511a61ad3d936862046125f22 | /src/apiCalls/TweetReposter.java | 8da8cbbb3026e504a787a492c5f6d906d0c70aa6 | [] | no_license | izzykid/TwitterBot | https://github.com/izzykid/TwitterBot | dea54fc0eff677101ea6b6d19e327d1cc002da32 | 513ae247a1d14888e449d60e2716c6fc91966f5e | refs/heads/master | 2020-04-19T19:30:13.973000 | 2019-05-10T04:10:01 | 2019-05-10T04:10:01 | 168,390,480 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package apiCalls;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import core.Launcher;
import twitter4j.MediaEntity;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;
public class TweetReposter extends APICall {
/**
*
* @param numOfInfluencers - number of influencers the user wants to search for tweets from
* @param numOfTweets
* @throws TwitterException
* @throws IOException
* @throws ParseException
*/
public TweetReposter(int numOfInfluencers, int numOfTweets) throws TwitterException, IOException, ParseException {
// Sets number of tweets per influencer and grabs "numOfInfluencers" influencers
ArrayList<String> targetedInfluencers = chooseRandomInfluencers(numOfInfluencers);
ArrayList<Status> bestTweets = grab(targetedInfluencers, numOfTweets);
if(bestTweets.size() < 1) {
throw new IOException();
}
boolean posted = false;
Status chosenTweet = bestTweets.get(bestTweets.size() - 1);
posted = postTweet(chosenTweet);
if(!posted) {
for(int i = bestTweets.size() - 2; i >= 0; i--) {
chosenTweet = bestTweets.get(i);
posted = postTweet(chosenTweet);
if(posted) {
break;
}
}
if(!posted) {
throw new IOException("Post failed");
}
}
else {
Launcher.setWarningLabel("Posted");
}
}
/**
* Grabs a list of influencers at random, based on how many influencers the user wants
* to be selected
* @param numOfInfluencers - the amount of influencers that tweets will be grabbed from
* @return targetedInfluencers - the randomly selected influencers
* @throws ParseException
* @throws IOException
* @throws FileNotFoundException
*/
private static ArrayList<String> chooseRandomInfluencers(int numOfInfluencers) throws FileNotFoundException, IOException, ParseException {
// Initialize variables needed to grab "numOfInfluencers" influencers
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("res/Influencers.json"));
JSONObject targetUsers = (JSONObject) obj;
Iterator<?> it = targetUsers.entrySet().iterator();
ArrayList<String> allInfluencers = new ArrayList<String>();
ArrayList<String> targetedInfluencers = new ArrayList<String>();
// Add all influencers to an ArrayList
while(it.hasNext()) {
@SuppressWarnings("unchecked")
Entry<String, String> pair = (Entry<String, String>) it.next();
allInfluencers.add(pair.getKey());
}
// If the amount of desired influencers is more than what is stored, return null
if(numOfInfluencers > allInfluencers.size())
return null;
// Randomly add numOfInfluencers to targetedInfluencers
for(int i = 0; i < numOfInfluencers; i++) {
int randIndex = (int) Math.round(Math.random() * allInfluencers.size());
targetedInfluencers.add(allInfluencers.get(randIndex));
allInfluencers.remove(randIndex);
}
return targetedInfluencers;
}
/**
* Pulls the most recent 100 tweets from each person's timeline and grades them all against eachother for most engagement.
* @param usersToPullFrom
* @return The tweet with the most engagement
* @throws TwitterException
* @throws IOException
*/
public ArrayList<Status> grab(List<String> usersToPullFrom, int numOfTweets) throws TwitterException, IOException {
if(usersToPullFrom.size() < 1) {
throw new IOException();
}
ArrayList<Status> tweets = new ArrayList<Status>();
int maxGrade = 0;
Status bestTweet = null;
//Iterates though each user and gets the 100 most recent posts from each user
Paging paging = new Paging(1, numOfTweets);
for(String user: usersToPullFrom) {
Launcher.setWarningLabel("Scraping " + user + "'s tweets");
ResponseList<Status> results = twitter.getUserTimeline(user, paging);
//Grades the results
for(Status tweet: results) {
int grade = gradeTweet(tweet);
//Stores the better result between the current best and current tweet
if(grade >= maxGrade) {
tweets.add(tweet);
maxGrade = grade;
bestTweet = tweet;
}
}
}
return tweets;
}
/**
* @param tweet
* @return A grade based on the engagement of that tweet
*/
private int gradeTweet(Status tweet) {
if(tweet.getMediaEntities().length < 1) {
return 0;
}
int grade = tweet.getFavoriteCount();
grade += tweet.getRetweetCount() * 2;
//Adding an element of oldness to help prevent us being caught for reposting
//Each day since today adds a point to the grade
Date date = new Date();
grade += (int)((date.getTime() - tweet.getCreatedAt().getTime()) / (long)(86400000));
return grade;
}
/**
* Returns whether or not twitterbot was able to post the tweet
* @param tweet
* @return
* @throws TwitterException
* @throws FileNotFoundException
*/
private boolean postTweet(Status tweet){
MediaEntity[] images = tweet.getMediaEntities();
String post = tweet.getText();
for(int i = 0; i < images.length; i++) {
post += images[i].getMediaURL() + " ";
}
StatusUpdate statusUpdate = new StatusUpdate(tweet.getText());
//statusUpdate.setMediaIds(mediaIDs);
try {
Status status = twitter.updateStatus(statusUpdate);
return true;
} catch (TwitterException e) {
return false;
}
}
} | UTF-8 | Java | 5,747 | java | TweetReposter.java | Java | [] | null | [] | package apiCalls;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import core.Launcher;
import twitter4j.MediaEntity;
import twitter4j.Paging;
import twitter4j.ResponseList;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;
public class TweetReposter extends APICall {
/**
*
* @param numOfInfluencers - number of influencers the user wants to search for tweets from
* @param numOfTweets
* @throws TwitterException
* @throws IOException
* @throws ParseException
*/
public TweetReposter(int numOfInfluencers, int numOfTweets) throws TwitterException, IOException, ParseException {
// Sets number of tweets per influencer and grabs "numOfInfluencers" influencers
ArrayList<String> targetedInfluencers = chooseRandomInfluencers(numOfInfluencers);
ArrayList<Status> bestTweets = grab(targetedInfluencers, numOfTweets);
if(bestTweets.size() < 1) {
throw new IOException();
}
boolean posted = false;
Status chosenTweet = bestTweets.get(bestTweets.size() - 1);
posted = postTweet(chosenTweet);
if(!posted) {
for(int i = bestTweets.size() - 2; i >= 0; i--) {
chosenTweet = bestTweets.get(i);
posted = postTweet(chosenTweet);
if(posted) {
break;
}
}
if(!posted) {
throw new IOException("Post failed");
}
}
else {
Launcher.setWarningLabel("Posted");
}
}
/**
* Grabs a list of influencers at random, based on how many influencers the user wants
* to be selected
* @param numOfInfluencers - the amount of influencers that tweets will be grabbed from
* @return targetedInfluencers - the randomly selected influencers
* @throws ParseException
* @throws IOException
* @throws FileNotFoundException
*/
private static ArrayList<String> chooseRandomInfluencers(int numOfInfluencers) throws FileNotFoundException, IOException, ParseException {
// Initialize variables needed to grab "numOfInfluencers" influencers
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("res/Influencers.json"));
JSONObject targetUsers = (JSONObject) obj;
Iterator<?> it = targetUsers.entrySet().iterator();
ArrayList<String> allInfluencers = new ArrayList<String>();
ArrayList<String> targetedInfluencers = new ArrayList<String>();
// Add all influencers to an ArrayList
while(it.hasNext()) {
@SuppressWarnings("unchecked")
Entry<String, String> pair = (Entry<String, String>) it.next();
allInfluencers.add(pair.getKey());
}
// If the amount of desired influencers is more than what is stored, return null
if(numOfInfluencers > allInfluencers.size())
return null;
// Randomly add numOfInfluencers to targetedInfluencers
for(int i = 0; i < numOfInfluencers; i++) {
int randIndex = (int) Math.round(Math.random() * allInfluencers.size());
targetedInfluencers.add(allInfluencers.get(randIndex));
allInfluencers.remove(randIndex);
}
return targetedInfluencers;
}
/**
* Pulls the most recent 100 tweets from each person's timeline and grades them all against eachother for most engagement.
* @param usersToPullFrom
* @return The tweet with the most engagement
* @throws TwitterException
* @throws IOException
*/
public ArrayList<Status> grab(List<String> usersToPullFrom, int numOfTweets) throws TwitterException, IOException {
if(usersToPullFrom.size() < 1) {
throw new IOException();
}
ArrayList<Status> tweets = new ArrayList<Status>();
int maxGrade = 0;
Status bestTweet = null;
//Iterates though each user and gets the 100 most recent posts from each user
Paging paging = new Paging(1, numOfTweets);
for(String user: usersToPullFrom) {
Launcher.setWarningLabel("Scraping " + user + "'s tweets");
ResponseList<Status> results = twitter.getUserTimeline(user, paging);
//Grades the results
for(Status tweet: results) {
int grade = gradeTweet(tweet);
//Stores the better result between the current best and current tweet
if(grade >= maxGrade) {
tweets.add(tweet);
maxGrade = grade;
bestTweet = tweet;
}
}
}
return tweets;
}
/**
* @param tweet
* @return A grade based on the engagement of that tweet
*/
private int gradeTweet(Status tweet) {
if(tweet.getMediaEntities().length < 1) {
return 0;
}
int grade = tweet.getFavoriteCount();
grade += tweet.getRetweetCount() * 2;
//Adding an element of oldness to help prevent us being caught for reposting
//Each day since today adds a point to the grade
Date date = new Date();
grade += (int)((date.getTime() - tweet.getCreatedAt().getTime()) / (long)(86400000));
return grade;
}
/**
* Returns whether or not twitterbot was able to post the tweet
* @param tweet
* @return
* @throws TwitterException
* @throws FileNotFoundException
*/
private boolean postTweet(Status tweet){
MediaEntity[] images = tweet.getMediaEntities();
String post = tweet.getText();
for(int i = 0; i < images.length; i++) {
post += images[i].getMediaURL() + " ";
}
StatusUpdate statusUpdate = new StatusUpdate(tweet.getText());
//statusUpdate.setMediaIds(mediaIDs);
try {
Status status = twitter.updateStatus(statusUpdate);
return true;
} catch (TwitterException e) {
return false;
}
}
} | 5,747 | 0.697581 | 0.692013 | 173 | 31.231215 | 27.373962 | 139 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.271676 | false | false | 6 |
0332bc79ccf19bb0e1e41075f80708c80cee945a | 4,784,593,596,212 | a56ad3924ebf3c76dcf5e2d68c3d0942e0659071 | /src/main/java/com/codecool/shop/model/Order.java | 5324e7b81f71907a09cb20741caa7996ee5cbce7 | [] | no_license | CodecoolBPoop/oop-java-codecool-shop-the-narwhals | https://github.com/CodecoolBPoop/oop-java-codecool-shop-the-narwhals | 4f28e0927d8d4415294ba4d2a7bd8def8be13b96 | 59a315581f4aa46d10221e0991eb03a36dde72c7 | refs/heads/develop | 2020-04-15T11:07:53.860000 | 2019-04-08T11:07:58 | 2019-04-08T11:07:58 | 164,615,441 | 1 | 3 | null | false | 2019-01-25T09:05:17 | 2019-01-08T09:40:34 | 2019-01-24T18:08:19 | 2019-01-25T09:05:17 | 8,371 | 0 | 1 | 0 | Java | false | null | package com.codecool.shop.model;
import com.codecool.shop.personal.Address;
import com.codecool.shop.personal.ContactInfo;
import java.util.ArrayList;
import java.util.List;
public class Order extends BaseModel{
private static Order instance = null;
private List<LineItem> items = new ArrayList<>();
private int totalSum;
private final String CURRENCY = "Credits";
private ContactInfo contactInfo;
public ContactInfo getContactInfo() {
return contactInfo;
}
public Order(String orderName, String orderDescription) {
super(orderName, orderDescription);
}
public Order(int id, String name, String description, int totalSum, String currency, ContactInfo contactInfo, List<LineItem> lineItems) {
super(name, description);
this.id = id;
this.totalSum = totalSum;
this.contactInfo = contactInfo;
}
public static Order getInstance() {
if (instance == null) {
String orderName = "Current order";
String description = "The only active order for now";
instance = new Order(orderName, description);
}
return instance;
}
public List<LineItem> getItems() {
return items;
}
public void addProduct(Product product) {
LineItem lineItem = getLineItemByProductId(product.getId());
if (lineItem == null) {
String lineItemName = "Line item " + product.getName();
String lineItemDescription = "Some " + product.getName() + "s";
LineItem newLineItem = new LineItem(product, lineItemName, lineItemDescription);
items.add(newLineItem);
} else {
lineItem.add(product);
}
totalSum += product.getDefaultPrice();
}
public void removeProduct(Product product) {
LineItem lineItem = getLineItemByProductId(product.getId());
lineItem.remove(product);
totalSum -= product.getDefaultPrice();
if (lineItem.isEmpty()) {
items.remove(lineItem);
}
}
public LineItem getLineItemByProductId(int productId) {
return items.stream()
.filter(item -> item.getProductId() == productId)
.findFirst()
.orElse(null);
}
public int getTotalNumberOfOrderedProducts() {
int numberOfOrderedProducts = 0;
for (int i = 0; i < items.size(); i++) {
numberOfOrderedProducts += items.get(i).getNumberOfProducts();
}
return numberOfOrderedProducts;
}
public float getTotalSum(){
return totalSum;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("id: " + this.id + "," )
.append("name: " + this.name + ",")
.append("description: " + this.description + ",")
.append("items: " + this.items + ",")
.append("total sum: " + this.totalSum + ",")
.append("currency: " + this.CURRENCY);
return builder.toString();
}
public void addContactInfo(String name, String email, String phoneNumber, Address billingAddress, Address shippingAddress) {
this.contactInfo = new ContactInfo(name, email, phoneNumber, billingAddress, shippingAddress);
}
public String getCurrency() {
return CURRENCY;
}
public int getContactInfoId() {
return contactInfo.getId();
}
public void setContactInfoId(int id) {
contactInfo.setId(id);
}
public void resetInstance(){
instance =null;
}
}
| UTF-8 | Java | 3,648 | java | Order.java | Java | [] | null | [] | package com.codecool.shop.model;
import com.codecool.shop.personal.Address;
import com.codecool.shop.personal.ContactInfo;
import java.util.ArrayList;
import java.util.List;
public class Order extends BaseModel{
private static Order instance = null;
private List<LineItem> items = new ArrayList<>();
private int totalSum;
private final String CURRENCY = "Credits";
private ContactInfo contactInfo;
public ContactInfo getContactInfo() {
return contactInfo;
}
public Order(String orderName, String orderDescription) {
super(orderName, orderDescription);
}
public Order(int id, String name, String description, int totalSum, String currency, ContactInfo contactInfo, List<LineItem> lineItems) {
super(name, description);
this.id = id;
this.totalSum = totalSum;
this.contactInfo = contactInfo;
}
public static Order getInstance() {
if (instance == null) {
String orderName = "Current order";
String description = "The only active order for now";
instance = new Order(orderName, description);
}
return instance;
}
public List<LineItem> getItems() {
return items;
}
public void addProduct(Product product) {
LineItem lineItem = getLineItemByProductId(product.getId());
if (lineItem == null) {
String lineItemName = "Line item " + product.getName();
String lineItemDescription = "Some " + product.getName() + "s";
LineItem newLineItem = new LineItem(product, lineItemName, lineItemDescription);
items.add(newLineItem);
} else {
lineItem.add(product);
}
totalSum += product.getDefaultPrice();
}
public void removeProduct(Product product) {
LineItem lineItem = getLineItemByProductId(product.getId());
lineItem.remove(product);
totalSum -= product.getDefaultPrice();
if (lineItem.isEmpty()) {
items.remove(lineItem);
}
}
public LineItem getLineItemByProductId(int productId) {
return items.stream()
.filter(item -> item.getProductId() == productId)
.findFirst()
.orElse(null);
}
public int getTotalNumberOfOrderedProducts() {
int numberOfOrderedProducts = 0;
for (int i = 0; i < items.size(); i++) {
numberOfOrderedProducts += items.get(i).getNumberOfProducts();
}
return numberOfOrderedProducts;
}
public float getTotalSum(){
return totalSum;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("id: " + this.id + "," )
.append("name: " + this.name + ",")
.append("description: " + this.description + ",")
.append("items: " + this.items + ",")
.append("total sum: " + this.totalSum + ",")
.append("currency: " + this.CURRENCY);
return builder.toString();
}
public void addContactInfo(String name, String email, String phoneNumber, Address billingAddress, Address shippingAddress) {
this.contactInfo = new ContactInfo(name, email, phoneNumber, billingAddress, shippingAddress);
}
public String getCurrency() {
return CURRENCY;
}
public int getContactInfoId() {
return contactInfo.getId();
}
public void setContactInfoId(int id) {
contactInfo.setId(id);
}
public void resetInstance(){
instance =null;
}
}
| 3,648 | 0.609923 | 0.609375 | 119 | 29.655462 | 26.993444 | 141 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.605042 | false | false | 6 |
aaa21781aff08449ad44802793c8faf7d4732cad | 21,423,296,908,622 | a1dad241023a54c47b19ef60366cab36ee354bab | /covid19-tracker/src/main/java/com/springboot/covid19/covid19tracker/controller/HomeController.java | 0f7c30f94acf2d1f2186804c02eeec5d56fc1733 | [] | no_license | venkatesangb54/Covid19Tracker | https://github.com/venkatesangb54/Covid19Tracker | 60fae607393da81c8143111b85bfc7eca3b2cb85 | 596dd42059b0d54bcdbdc66f6c3d0141ff5a5fa2 | refs/heads/master | 2022-04-23T15:45:07.600000 | 2020-04-25T05:39:47 | 2020-04-25T05:39:47 | 258,692,904 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springboot.covid19.covid19tracker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.springboot.covid19.covid19tracker.models.LocationStats;
import com.springboot.covid19.covid19tracker.services.CovidServiceData;
@Controller
public class HomeController {
@Autowired
CovidServiceData covidServiceData;
@GetMapping("/")
public String home(Model model) {
List<LocationStats> allStats = covidServiceData.getAllStats();
int totalCases = allStats.stream().mapToInt(stat -> stat.getLatestTotalCases()).sum();
int totalNewCases = allStats.stream().mapToInt(stat -> stat.getDiffCasesPrevDay()).sum();
model.addAttribute("appName", "Covid19 Tracker");
model.addAttribute("locationStats",allStats);
model.addAttribute("totalNumberOfCases",totalCases);
model.addAttribute("totalNumberOfNewCases",totalNewCases);
return "home1";
}
}
| UTF-8 | Java | 1,098 | java | HomeController.java | Java | [] | null | [] | package com.springboot.covid19.covid19tracker.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import com.springboot.covid19.covid19tracker.models.LocationStats;
import com.springboot.covid19.covid19tracker.services.CovidServiceData;
@Controller
public class HomeController {
@Autowired
CovidServiceData covidServiceData;
@GetMapping("/")
public String home(Model model) {
List<LocationStats> allStats = covidServiceData.getAllStats();
int totalCases = allStats.stream().mapToInt(stat -> stat.getLatestTotalCases()).sum();
int totalNewCases = allStats.stream().mapToInt(stat -> stat.getDiffCasesPrevDay()).sum();
model.addAttribute("appName", "Covid19 Tracker");
model.addAttribute("locationStats",allStats);
model.addAttribute("totalNumberOfCases",totalCases);
model.addAttribute("totalNumberOfNewCases",totalNewCases);
return "home1";
}
}
| 1,098 | 0.776867 | 0.763206 | 31 | 33.419353 | 28.347811 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.451613 | false | false | 6 |
8fa74b44dde3431d88a40032713d09c6db076a55 | 21,423,296,908,167 | 6d09a2af96afe5e87b11d7161c474aa6fd745199 | /springboot/spring-boot-concepts/src/main/java/com/example/springbootconcepts/annotation/components/TestComponentClass.java | 847a42e45d5248860fe2f0aee951c998a4a98af6 | [] | no_license | umeshwale/code-playarea | https://github.com/umeshwale/code-playarea | 5228698a4ea93c4656becdf6a90d0fb6ab1fc72a | 7de3835d9213ee51f693f55e2a7b11b85c1d542b | refs/heads/master | 2023-08-03T18:13:18.460000 | 2021-09-27T06:21:32 | 2021-09-27T06:21:32 | 297,268,862 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.springbootconcepts.annotation.components;
import org.springframework.stereotype.Component;
@Component
public class TestComponentClass {
public TestComponentClass() {
System.out.println("No args constructor in component");
}
public int add(int x, int y) {
System.out.println("In the add method");
return x + y;
}
}
| UTF-8 | Java | 377 | java | TestComponentClass.java | Java | [] | null | [] | package com.example.springbootconcepts.annotation.components;
import org.springframework.stereotype.Component;
@Component
public class TestComponentClass {
public TestComponentClass() {
System.out.println("No args constructor in component");
}
public int add(int x, int y) {
System.out.println("In the add method");
return x + y;
}
}
| 377 | 0.69496 | 0.69496 | 15 | 24.133333 | 22.342386 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 6 |
aecca44dbdf7312b901cb5dbcd77ed891e7f1e91 | 6,622,839,608,629 | 06c26a0a8ced8c727aed905a7a3ddd1db58fb7c9 | /customimageloader/src/main/java/me/daixin/customimageloader/ui2/DiskCacheAdvance.java | f0d97e7fa8254f50552d9b65a0e4e95189d94fc5 | [] | no_license | ishidai/DailyPracticeDemos | https://github.com/ishidai/DailyPracticeDemos | 490312fc1a172f941da314c68e8f60e0e4db44ff | c15dac39dfd5e7872ccbfeb443cc96ba44914ddf | refs/heads/master | 2017-04-23T16:07:56.241000 | 2016-09-07T14:38:04 | 2016-09-07T14:38:04 | 60,274,347 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.daixin.customimageloader.ui2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import me.daixin.customimageloader.interfaces.CommonImageCache;
/**
* Created by shidai on 2016/7/15.
*/
public class DiskCacheAdvance implements CommonImageCache{
static String cacheFilePath = "sdcard/cache/";
@Override
public void put(String url, Bitmap bitmap) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(cacheFilePath + url);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public Bitmap get(String url) {
return BitmapFactory.decodeFile(cacheFilePath + url);
}
}
| UTF-8 | Java | 1,134 | java | DiskCacheAdvance.java | Java | [
{
"context": "interfaces.CommonImageCache;\r\n\r\n/**\r\n * Created by shidai on 2016/7/15.\r\n */\r\npublic class DiskCacheAdvance",
"end": 315,
"score": 0.9995427131652832,
"start": 309,
"tag": "USERNAME",
"value": "shidai"
}
] | null | [] | package me.daixin.customimageloader.ui2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import me.daixin.customimageloader.interfaces.CommonImageCache;
/**
* Created by shidai on 2016/7/15.
*/
public class DiskCacheAdvance implements CommonImageCache{
static String cacheFilePath = "sdcard/cache/";
@Override
public void put(String url, Bitmap bitmap) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(cacheFilePath + url);
bitmap.compress(Bitmap.CompressFormat.PNG,100,fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public Bitmap get(String url) {
return BitmapFactory.decodeFile(cacheFilePath + url);
}
}
| 1,134 | 0.636684 | 0.626984 | 40 | 26.35 | 22.22448 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.45 | false | false | 6 |
4bfdd71531155c24fc48713b5a5fc646138dbac0 | 8,495,445,370,902 | d9dee1cd7040d4a7d2d8661dfdc2e1e65d4345e8 | /assignment/WS1-4/Ex3/MusicTitle.java | b9c8c051ed9cf62bc8e630447136bfd90e110c3c | [] | no_license | Fury-Feng/SoftwareWorkshop | https://github.com/Fury-Feng/SoftwareWorkshop | 49a1bc183b9cc95bcbc927806847e96a6e21438f | 9d14024419db405e5e439dfa31466eaf4e40e5f7 | refs/heads/master | 2020-08-06T22:33:23.449000 | 2020-02-18T14:32:20 | 2020-02-18T14:32:20 | 213,183,393 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* The program is a class named MusicTitle implements interface MusicTitleInterface.
* The class has three field variables: title with String type, artist with String type, price with int type.
* The class has a constructor, getters and toString method.
*
* @author: Fuwei Feng
* @version: 2019/11/16
*/
public class MusicTitle implements MusicTitleInterface {
private String title;
private String artist;
private int price;
/**
* The constructor is used to create a musicTitle object.
* @param title The title of the music.
* @param artist The artist of the music.
* @param price The price of the music.
*/
public MusicTitle(String title, String artist, int price) {
this.title = title;
this.artist = artist;
this.price = price;
}
/**
* Override the getter for the title.
* @return title The title of the music.
*/
@Override
public String getTitle() {
return title;
}
/**
* Override the getter for the artist.
* @return artist The artist of the music.
*/
@Override
public String getArtist() {
return artist;
}
/**
* Override the getter for the price.
* @return price The price of the music.
*/
@Override
public int getPrice() {
return price;
}
/**
* Override the toString method.
* @return a human readable description of the musictitle in form of the three field variables specifying in.
*/
@Override
public String toString() {
return "MusicTitle[Title: " + title + ", Artist: " + artist + ", Price: " + price;
}
}
| UTF-8 | Java | 1,693 | java | MusicTitle.java | Java | [
{
"context": "uctor, getters and toString method.\n *\n * @author: Fuwei Feng\n * @version: 2019/11/16\n */\npublic class MusicTit",
"end": 285,
"score": 0.9998528361320496,
"start": 275,
"tag": "NAME",
"value": "Fuwei Feng"
}
] | null | [] | /**
* The program is a class named MusicTitle implements interface MusicTitleInterface.
* The class has three field variables: title with String type, artist with String type, price with int type.
* The class has a constructor, getters and toString method.
*
* @author: <NAME>
* @version: 2019/11/16
*/
public class MusicTitle implements MusicTitleInterface {
private String title;
private String artist;
private int price;
/**
* The constructor is used to create a musicTitle object.
* @param title The title of the music.
* @param artist The artist of the music.
* @param price The price of the music.
*/
public MusicTitle(String title, String artist, int price) {
this.title = title;
this.artist = artist;
this.price = price;
}
/**
* Override the getter for the title.
* @return title The title of the music.
*/
@Override
public String getTitle() {
return title;
}
/**
* Override the getter for the artist.
* @return artist The artist of the music.
*/
@Override
public String getArtist() {
return artist;
}
/**
* Override the getter for the price.
* @return price The price of the music.
*/
@Override
public int getPrice() {
return price;
}
/**
* Override the toString method.
* @return a human readable description of the musictitle in form of the three field variables specifying in.
*/
@Override
public String toString() {
return "MusicTitle[Title: " + title + ", Artist: " + artist + ", Price: " + price;
}
}
| 1,689 | 0.611932 | 0.607206 | 62 | 26.306452 | 26.531532 | 113 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.274194 | false | false | 6 |
d97769c7c318ad9a4293daf3a29a6c422160e886 | 14,800,457,348,928 | 7d83f66fcd4f07343e59b4cc2d911fe4de34a4bb | /src/main/java/com/springbook/biz/board/BoardVO.java | 530cc234b0b9eddeb4c9fc6510946fa22210e885 | [] | no_license | songmjj/Java_Mybatis-Oracle_Board | https://github.com/songmjj/Java_Mybatis-Oracle_Board | 6fef9671eaed0026cad41add8018d5a51d2f91c6 | b49e03fcf156de9f491651bacb6d413a40d3703e | refs/heads/master | 2023-05-29T09:38:16.770000 | 2021-06-13T13:26:09 | 2021-06-13T13:26:09 | 376,550,097 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.springbook.biz.board;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BoardVO {
private int boardNo; //게시글번호
private String userCode; //유저코드
private String grade; //유저등급
private String boardTitle; //게시판본문제목
private String boardContents; //게시글내용
private String boardDate; //게시글작성일자
private int boardHits; //게시글조회수
private String boardRatingLike; //게시글좋아요
private String boardRatingHate; //게시글싫어요
private String searchCondition; //검색 조건
private String searchKeyword; //검색 키워드
} | UTF-8 | Java | 683 | java | BoardVO.java | Java | [] | null | [] | package com.springbook.biz.board;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class BoardVO {
private int boardNo; //게시글번호
private String userCode; //유저코드
private String grade; //유저등급
private String boardTitle; //게시판본문제목
private String boardContents; //게시글내용
private String boardDate; //게시글작성일자
private int boardHits; //게시글조회수
private String boardRatingLike; //게시글좋아요
private String boardRatingHate; //게시글싫어요
private String searchCondition; //검색 조건
private String searchKeyword; //검색 키워드
} | 683 | 0.723894 | 0.723894 | 21 | 25.952381 | 16.214268 | 42 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.380952 | false | false | 6 |
03e26718129544b235d4cb4c5224a1fa9174ad9b | 35,845,797,091,010 | fdd419607ffb7417871006e97b7b581ad406da3e | /src/main/java/com/drawdream/app/admin/service/AdminUserService.java | 2a86dd882ea3ea595bb7e0f8b5087c05f52654c9 | [] | no_license | coolxiaohao/drawDream | https://github.com/coolxiaohao/drawDream | a4f35cde998f182f6346f459d6d52bfe73da1910 | 449dc34d264f12f8eb48b2c3a25812a0c9718080 | refs/heads/master | 2022-08-02T16:38:45.354000 | 2020-05-25T02:13:06 | 2020-05-25T02:13:06 | 250,277,902 | 2 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.drawdream.app.admin.service;
import com.drawdream.app.admin.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface AdminUserService {
int addAdminUser(@Param("User") User user);
}
| UTF-8 | Java | 215 | java | AdminUserService.java | Java | [] | null | [] | package com.drawdream.app.admin.service;
import com.drawdream.app.admin.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface AdminUserService {
int addAdminUser(@Param("User") User user);
}
| 215 | 0.781395 | 0.781395 | 8 | 25.875 | 20.027716 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 6 |
53c68fdba24d925fe452fe0b0921edeeb9e8f909 | 38,551,626,474,482 | 0ddea631b34386a2b1cb361160cd6a0347783dbe | /Goryachev.Denys/src/HomeTask_19/Book.java | 4e73a45d03327c0c4ef8333ac9f496dc75f7068a | [] | no_license | OldRetorta/OldRetorta.github.io | https://github.com/OldRetorta/OldRetorta.github.io | 37e691554995f16ffed3d699d7ce4814fb0dde2e | 87c249266916c99508da45ef372bca1910cf1d42 | refs/heads/master | 2021-01-01T16:15:14.923000 | 2017-09-18T08:06:13 | 2017-09-18T08:06:13 | 97,796,795 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package homeTask_19;
public class Book implements Comparable {
private String autor;
private String name;
private double cost;
public Book() {
}
public Book(String autor, String name, double cost) {
this.autor = autor;
this.name = name;
this.cost = cost;
}
/* public String getName() {
return name;
}
public String getAutor() {
return autor;
}
public double getCost() {
return cost;
}
public void setName(String name) {
this.name = name;
}
public void setAutor(String autor) {
this.autor = autor;
}
public void setCost(double cost) {
this.cost = cost;
}
*/
@Override
public int compareTo(Object prime) {
if (!(prime instanceof Book)) {
System.exit(-10);
}
Book book = (Book) prime;
return autor.compareToIgnoreCase(book.autor);
}
public static Book copyBook(Book book) {
Book newBook = new Book();
newBook.name = book.name;
newBook.autor = book.autor;
newBook.cost = book.cost;
return newBook;
}
@Override
public String toString() {
return "Autor: " + autor + " - " + name + " " + cost + "$";
}
public boolean equals(Book book) {
if (!name.equalsIgnoreCase(book.name) || !autor.equalsIgnoreCase(book.autor) || cost != book.cost) {
return false;
}
return true;
}
}
| UTF-8 | Java | 1,508 | java | Book.java | Java | [] | null | [] | package homeTask_19;
public class Book implements Comparable {
private String autor;
private String name;
private double cost;
public Book() {
}
public Book(String autor, String name, double cost) {
this.autor = autor;
this.name = name;
this.cost = cost;
}
/* public String getName() {
return name;
}
public String getAutor() {
return autor;
}
public double getCost() {
return cost;
}
public void setName(String name) {
this.name = name;
}
public void setAutor(String autor) {
this.autor = autor;
}
public void setCost(double cost) {
this.cost = cost;
}
*/
@Override
public int compareTo(Object prime) {
if (!(prime instanceof Book)) {
System.exit(-10);
}
Book book = (Book) prime;
return autor.compareToIgnoreCase(book.autor);
}
public static Book copyBook(Book book) {
Book newBook = new Book();
newBook.name = book.name;
newBook.autor = book.autor;
newBook.cost = book.cost;
return newBook;
}
@Override
public String toString() {
return "Autor: " + autor + " - " + name + " " + cost + "$";
}
public boolean equals(Book book) {
if (!name.equalsIgnoreCase(book.name) || !autor.equalsIgnoreCase(book.autor) || cost != book.cost) {
return false;
}
return true;
}
}
| 1,508 | 0.545756 | 0.543103 | 85 | 16.741177 | 19.174219 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 6 |
ee152d7122f23cf80117ae42ab8fc8485d8b9493 | 35,261,681,550,944 | 3cd91e8cd858156b9a3448e134d171e66dfae116 | /src/main/java/org/dflow/msg/DDocument.java | e2964e4e3b61003066ef111dfec0d47dd1da92bf | [] | no_license | Williee/dflow | https://github.com/Williee/dflow | 649a68647d09d5df3428fa7a558fba4645c4367e | 0279bced5ee417d8589a953b4648f5eb6e1f4047 | refs/heads/master | 2020-06-02T08:47:16.527000 | 2014-09-04T21:42:03 | 2014-09-04T21:42:03 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.dflow.msg;
public class DDocument {
}
| UTF-8 | Java | 52 | java | DDocument.java | Java | [] | null | [] | package org.dflow.msg;
public class DDocument {
}
| 52 | 0.730769 | 0.730769 | 5 | 9.4 | 11.128343 | 24 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 6 |
455711487f55124e24c1c63fab2e0bcbd7d236c9 | 34,875,134,499,110 | 00531f4a4055bd1b04109f410de058ee2a260814 | /src/main/java/repository/MongodbAPIRepo.java | 710a4fc83162326d7167a02aff4d398642d93d14 | [] | no_license | pmckenna25/mongodbCRUD | https://github.com/pmckenna25/mongodbCRUD | 34a859840004247ef1bcf8e4b80266bf6aba5e7e | 7c2b53de3cbaa0e5e144e360a8b02b4b048bbf4c | refs/heads/master | 2020-05-04T18:23:34.972000 | 2019-04-09T12:00:36 | 2019-04-09T12:00:36 | 179,351,091 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package repository;
import com.mongodb.client.MongoCollection;
import model.API_Key;
import javax.ws.rs.NotFoundException;
import java.util.LinkedList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
public class MongodbAPIRepo {
private static MongoCollection<API_Key> collection;
public MongodbAPIRepo(String dbName, String collectionName){
MongoConnect connection = new MongoConnect(dbName);
connection.connect();
collection = connection.getDatabase().getCollection(collectionName, API_Key.class);
}
public List<API_Key> getAll(){
List<API_Key> fullList = collection.find().into(new LinkedList<>());
if(fullList.size() == 0){
throw new NotFoundException();
}else{
return fullList;
}
}
public API_Key findOne(String email){
List<API_Key> apikeys = getAll();
for(API_Key key: apikeys){
if(key.getEmail().equals(email)){
return key;
}
}
throw new NotFoundException();
}
public void addOne(API_Key key){
collection.insertOne(key);
}
public void delete(API_Key key){
if(collection.find(eq("email", key.getEmail())).into(new LinkedList<>()).size() == 0){
throw new NotFoundException();
}else {
collection.deleteOne(eq("email", key.getEmail()));
}
}
public void updateOne(API_Key key){
if(collection.find(eq("email", key.getEmail())).into(new LinkedList<>()).size() == 0){
throw new NotFoundException();
}else {
collection.replaceOne(eq("email", key.getEmail()), key);
}
}
}
| UTF-8 | Java | 1,722 | java | MongodbAPIRepo.java | Java | [] | null | [] | package repository;
import com.mongodb.client.MongoCollection;
import model.API_Key;
import javax.ws.rs.NotFoundException;
import java.util.LinkedList;
import java.util.List;
import static com.mongodb.client.model.Filters.eq;
public class MongodbAPIRepo {
private static MongoCollection<API_Key> collection;
public MongodbAPIRepo(String dbName, String collectionName){
MongoConnect connection = new MongoConnect(dbName);
connection.connect();
collection = connection.getDatabase().getCollection(collectionName, API_Key.class);
}
public List<API_Key> getAll(){
List<API_Key> fullList = collection.find().into(new LinkedList<>());
if(fullList.size() == 0){
throw new NotFoundException();
}else{
return fullList;
}
}
public API_Key findOne(String email){
List<API_Key> apikeys = getAll();
for(API_Key key: apikeys){
if(key.getEmail().equals(email)){
return key;
}
}
throw new NotFoundException();
}
public void addOne(API_Key key){
collection.insertOne(key);
}
public void delete(API_Key key){
if(collection.find(eq("email", key.getEmail())).into(new LinkedList<>()).size() == 0){
throw new NotFoundException();
}else {
collection.deleteOne(eq("email", key.getEmail()));
}
}
public void updateOne(API_Key key){
if(collection.find(eq("email", key.getEmail())).into(new LinkedList<>()).size() == 0){
throw new NotFoundException();
}else {
collection.replaceOne(eq("email", key.getEmail()), key);
}
}
}
| 1,722 | 0.606272 | 0.60453 | 66 | 25.09091 | 25.295063 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.439394 | false | false | 6 |
a24e7d6f1050cb5531a9d6689283d8c78bdfeb00 | 36,481,452,259,038 | 518590750686c5c5bd5b9a58bee3c0705922ad61 | /ap-item-validation/src/main/java/org/opentestsystem/ap/item/validator/repository/ItemTabulationDataRepository.java | 9706493fc2eef90a66a0aec1bd03a63c03aa2896 | [
"ECL-2.0"
] | permissive | SmarterApp/AP_ItemTabulator | https://github.com/SmarterApp/AP_ItemTabulator | 5c8a83436a297f21da2f3324419c1febd434c6ed | b13bc7a3ef38d6dc7289f4c1cb1ad69dc0fc4d61 | refs/heads/develop | 2020-07-02T11:54:41.177000 | 2019-12-17T23:46:16 | 2019-12-17T23:46:16 | 201,519,809 | 0 | 0 | NOASSERTION | false | 2019-12-16T18:43:47 | 2019-08-09T18:19:23 | 2019-12-12T17:47:04 | 2019-12-16T18:43:45 | 11,202 | 0 | 0 | 0 | Java | false | false | package org.opentestsystem.ap.item.validator.repository;
import org.opentestsystem.ap.common.model.Item;
import org.opentestsystem.ap.common.saaif.item.ItemRelease;
import org.opentestsystem.ap.common.saaif.metadata.SmarterAppMetadata;
import org.opentestsystem.ap.item.validator.exceptions.ItemDataParseException;
import java.io.File;
import java.nio.file.Path;
import java.util.Optional;
/**
* Handles finding data for tabulation
*/
public interface ItemTabulationDataRepository {
/**
* Find the TIMS item data (item.json)
*
* @param itemContentLocation the directory containing all of the
* @param bankKey bank key for the items
* @param itemId the item id
* @return the item if found and parsed
* @throws ItemDataParseException if the data found cannot be parsed for any reason
*/
Optional<Item> findItem(Path itemContentLocation, String bankKey, String itemId) throws ItemDataParseException;
/**
* Finds the {@link ItemRelease}
*
* @param itemContentLocation the base item content directory
* @param bankKey the bank key to use for look up
* @param itemId the item id
* @return the Item Release if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<ItemRelease> findItemRelease(Path itemContentLocation,
String bankKey,
String itemId) throws ItemDataParseException;
/**
* Finds the {@link SmarterAppMetadata}
*
* @param itemContentLocation the base item content directory
* @param bankKey the bank key to use for look up
* @param itemId the item id
* @return the Metadata object if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<SmarterAppMetadata> findMetadata(Path itemContentLocation,
String bankKey,
String itemId) throws ItemDataParseException;
/**
* Finds the {@link Item}
*
* @param itemContentLocation the base item content directory
* @param itemId the item id
* @return the Metadata object if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<File> findItemDirectory(Path itemContentLocation, String itemId);
}
| UTF-8 | Java | 2,646 | java | ItemTabulationDataRepository.java | Java | [] | null | [] | package org.opentestsystem.ap.item.validator.repository;
import org.opentestsystem.ap.common.model.Item;
import org.opentestsystem.ap.common.saaif.item.ItemRelease;
import org.opentestsystem.ap.common.saaif.metadata.SmarterAppMetadata;
import org.opentestsystem.ap.item.validator.exceptions.ItemDataParseException;
import java.io.File;
import java.nio.file.Path;
import java.util.Optional;
/**
* Handles finding data for tabulation
*/
public interface ItemTabulationDataRepository {
/**
* Find the TIMS item data (item.json)
*
* @param itemContentLocation the directory containing all of the
* @param bankKey bank key for the items
* @param itemId the item id
* @return the item if found and parsed
* @throws ItemDataParseException if the data found cannot be parsed for any reason
*/
Optional<Item> findItem(Path itemContentLocation, String bankKey, String itemId) throws ItemDataParseException;
/**
* Finds the {@link ItemRelease}
*
* @param itemContentLocation the base item content directory
* @param bankKey the bank key to use for look up
* @param itemId the item id
* @return the Item Release if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<ItemRelease> findItemRelease(Path itemContentLocation,
String bankKey,
String itemId) throws ItemDataParseException;
/**
* Finds the {@link SmarterAppMetadata}
*
* @param itemContentLocation the base item content directory
* @param bankKey the bank key to use for look up
* @param itemId the item id
* @return the Metadata object if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<SmarterAppMetadata> findMetadata(Path itemContentLocation,
String bankKey,
String itemId) throws ItemDataParseException;
/**
* Finds the {@link Item}
*
* @param itemContentLocation the base item content directory
* @param itemId the item id
* @return the Metadata object if found otherwise empty
* @throws ItemDataParseException thrown if there is a parse error mapping the XML to the object model
*/
Optional<File> findItemDirectory(Path itemContentLocation, String itemId);
}
| 2,646 | 0.660998 | 0.660998 | 63 | 41 | 32.762249 | 115 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.301587 | false | false | 6 |
d9d38a3e6b7d723fb728095da1c05c982d839239 | 39,659,728,020,372 | eeafa6d26fe049c2abc8aa49dcfd897364e50ad7 | /app/src/main/java/yuyi/com/zhihuiyuyi/Main/HomeFragment.java | 39d0b1f43c06312bc87b5fd09e936af879a8b1b3 | [] | no_license | RookieExaminer/yuyixinxi | https://github.com/RookieExaminer/yuyixinxi | 164033a506174e5058403ad46f5cc325de3b55ec | 7650e9318f0bac811f73558e6cf9413b92770d2e | refs/heads/master | 2017-04-23T23:55:29.588000 | 2017-02-08T08:19:02 | 2017-02-08T08:19:02 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package yuyi.com.zhihuiyuyi.Main;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import yuyi.com.zhihuiyuyi.Beans.API.LuanBoPicAPI;
import yuyi.com.zhihuiyuyi.Beans.LuanBoPic;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.CompanyIntroduction;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.ContactUs;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.JoinUs;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.MainBuiness;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.MoreActivity;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.Patener;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.Weixin;
import yuyi.com.zhihuiyuyi.Main.homeadapter.HomePageAdapter;
import yuyi.com.zhihuiyuyi.R;
import yuyi.com.zhihuiyuyi.Utils.Constant;
import yuyi.com.zhihuiyuyi.Utils.DensityUtil;
import yuyi.com.zhihuiyuyi.Utils.LoadHtml;
import yuyi.com.zhihuiyuyi.Utils.LogUtils;
import yuyi.com.zhihuiyuyi.ZiXun.Tools.CircleImageView;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
//顶部的头像标志
public static CircleImageView circleImageView_home = null;
//下面是中间六个按钮
private TextView companyIntroduction, mainBuiness, contactUs, weixin, patener, keFu;
//viewpager的三个状态
public static final int PAGER_START = 1;
public static final int PAGER_STOP = 2;
public static final int PAGER_RESTART = 3;
//viewpager下面提示的栏目
private LinearLayout mHomeIndicator;
//顶部的viewpager
private ViewPager mViewPager;
private int mPosition = 100;
private int lastIndex = 100;
//存贮数据源
private List<ImageView> mImageViews = new ArrayList<>();
//handler为了操控viewpager的轮播的
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (this.hasMessages(PAGER_START)) {
this.removeMessages(PAGER_START);
}
switch (msg.what) {
case PAGER_START:
mPosition++;
mViewPager.setCurrentItem(mPosition, true);
this.sendEmptyMessageDelayed(PAGER_START, 3000);
break;
case PAGER_STOP:
if (this.hasMessages(PAGER_START)) {
this.removeMessages(PAGER_START);
}
break;
case PAGER_RESTART:
mPosition = msg.arg1;
this.sendEmptyMessageDelayed(PAGER_START, 3000);
break;
}
}
};
private HomePageAdapter homePageAdapter;
private SharedPreferences homeSharedPreferences;
private SharedPreferences.Editor homeEdit;
private RelativeLayout mMore;
private String mPicUrl;
private int indicatorNum;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);//填充视图
//初始化控件
init(view);
SharedPreferences userInfo = getContext().getSharedPreferences("UserInfo", MODE_PRIVATE);
Glide.with(this).load(userInfo.getString("userIcon", "null")).error(R.mipmap.bn_geren).into(circleImageView_home);
//初始化viewpager
initViewPager();
//获取数据源
initdata();
return view;
}
//一般是联网获取数据,
private void initdata() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.BASEURL)
.addConverterFactory(GsonConverterFactory.create()).build();
LuanBoPicAPI luanBoPicAPI = retrofit.create(LuanBoPicAPI.class);
Call<LuanBoPic> call = luanBoPicAPI.getLuanBoPic();
call.enqueue(new Callback<LuanBoPic>() {
@Override
public void onResponse(Call<LuanBoPic> call, Response<LuanBoPic> response) {
LuanBoPic luanBoPic = response.body();
if (luanBoPic != null) {
LuanBoPic.InfoBean info = luanBoPic.getInfo();
String prefix = info.getPrefix();
List<LuanBoPic.InfoBean.ContentBean> content = info.getContent();
indicatorNum = content.size();
for (int i = 0; i < content.size(); i++) {
ImageView imageView = new ImageView(getActivity());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
LuanBoPic.InfoBean.ContentBean contentBean = content.get(i);
String picture = contentBean.getPicture();
mPicUrl = LoadHtml.zhuangyi(prefix + picture);
LogUtils.d("HomeFragment", mPicUrl);
Glide.with(HomeFragment.this).load(mPicUrl).into(imageView);
homePageAdapter.notifyDataSetChanged();
mImageViews.add(imageView);
}
initIndicator();
}
}
@Override
public void onFailure(Call<LuanBoPic> call, Throwable t) {
}
});
homePageAdapter.setDate(mImageViews);
}
private void initIndicator() {
for (int i = 0; i < indicatorNum; i++) {
ImageView indicator = new ImageView(getActivity());
indicator.setImageResource(getActivity().getResources().getIdentifier("icon_lunbo", "drawable", getActivity().getPackageName()));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtil.getpx(getContext(), 10), DensityUtil.getpx(getContext(), 10));
layoutParams.rightMargin = DensityUtil.getdp(getContext(), 30);
indicator.setLayoutParams(layoutParams);
mHomeIndicator.addView(indicator);
}
// mHomeIndicator.getChildAt(0).setEnabled(false);
//通知改变后,再去根据数据源展示决定不同的indicator的孩子
//设置监听
initListener();
}
private void initListener() {
mHandler.sendEmptyMessage(PAGER_START);
mViewPager.addOnPageChangeListener(this);
}
private void initViewPager() {
homePageAdapter = new HomePageAdapter(getActivity());
mViewPager.setAdapter(homePageAdapter);
}
//companyIntroduction,mainBuiness,contactUs,weixin,patener,keFu,
private void init(View view) {
mHomeIndicator = (LinearLayout) view.findViewById(R.id.linearlayout_indicator_home);
mViewPager = (ViewPager) view.findViewById(R.id.viewPager_HomeFragment);
//下面是进行初始化中间的六个按钮
companyIntroduction = (TextView) view.findViewById(R.id.textView_CompanyIntroduction);
mainBuiness = (TextView) view.findViewById(R.id.textView_mainBuiness);
contactUs = (TextView) view.findViewById(R.id.textView_contactUs);
weixin = (TextView) view.findViewById(R.id.textView_weixin);
patener = (TextView) view.findViewById(R.id.textView_panter);
keFu = (TextView) view.findViewById(R.id.textView_KeFu);
//头部的头像
circleImageView_home = (CircleImageView) view.findViewById(R.id.circleImageView_home);
mMore = (RelativeLayout) view.findViewById(R.id.home_qiyedongtai);
//设置监听
initviewListener();
}
//控件的点击事件
private void initviewListener() {
//中部六个按钮的监听事件
companyIntroduction.setOnClickListener(this);
mainBuiness.setOnClickListener(this);
contactUs.setOnClickListener(this);
weixin.setOnClickListener(this);
patener.setOnClickListener(this);
keFu.setOnClickListener(this);
mMore.setOnClickListener(this);
//顶部的头像标志
// circleImageView_home.setOnClickListener(this);
getInfo();
}
//下面是viewpager监听的三个重写的方法---开始
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (indicatorNum != 0) {
mHomeIndicator.getChildAt(lastIndex % indicatorNum).setEnabled(true);
mHomeIndicator.getChildAt(position % indicatorNum).setEnabled(false);
lastIndex = position;
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
Message msg = Message.obtain();
msg.what = PAGER_RESTART;
msg.arg1 = lastIndex;
mHandler.sendMessage(msg);
}
}
//这是viewpager监听的三个方法---结束
//开始中部点击按钮
// companyIntroduction,mainBuiness,contactUs,weixin,patener,keFu,
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.textView_CompanyIntroduction:
Intent companyIntroductionIntent = new Intent(getContext(), CompanyIntroduction.class);
startActivity(companyIntroductionIntent);
break;
case R.id.textView_mainBuiness:
Intent maniBuinessintent = new Intent(getContext(), MainBuiness.class);
startActivity(maniBuinessintent);
break;
case R.id.textView_contactUs:
Intent contactUsIntent = new Intent(getContext(), ContactUs.class);
startActivity(contactUsIntent);
break;
case R.id.textView_weixin:
//表示跳转e运河网
Intent WeixinIntent = new Intent(getContext(), Weixin.class);
startActivity(WeixinIntent);
break;
case R.id.textView_panter:
Intent panterIntent = new Intent(getContext(), Patener.class);
startActivity(panterIntent);
break;
case R.id.textView_KeFu:
Intent kefuIntent = new Intent(getContext(), JoinUs.class);
startActivity(kefuIntent);
break;
case R.id.home_qiyedongtai://跳转到企业动态那一栏目里面
Intent moreIntent = new Intent(getContext(), MoreActivity.class);
startActivity(moreIntent);
break;
}
}
public void getInfo() {
homeSharedPreferences = getContext().getSharedPreferences("UserInfo", MODE_PRIVATE);
// homeEdit = homeSharedPreferences.edit();
//开始就读取
String userInfo = homeSharedPreferences.getString("userIcon", "www");
// Picasso.with(getContext()).load(userInfo).resize(50, 50).into(circleImageView_home);
}
public void setIcon(String icon) {
Glide.with(this).load(icon).error(R.mipmap.bn_geren).into(circleImageView_home);
}
}
| UTF-8 | Java | 11,982 | java | HomeFragment.java | Java | [] | null | [] | package yuyi.com.zhihuiyuyi.Main;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import yuyi.com.zhihuiyuyi.Beans.API.LuanBoPicAPI;
import yuyi.com.zhihuiyuyi.Beans.LuanBoPic;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.CompanyIntroduction;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.ContactUs;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.JoinUs;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.MainBuiness;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.MoreActivity;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.Patener;
import yuyi.com.zhihuiyuyi.Main.HomeActivity.Weixin;
import yuyi.com.zhihuiyuyi.Main.homeadapter.HomePageAdapter;
import yuyi.com.zhihuiyuyi.R;
import yuyi.com.zhihuiyuyi.Utils.Constant;
import yuyi.com.zhihuiyuyi.Utils.DensityUtil;
import yuyi.com.zhihuiyuyi.Utils.LoadHtml;
import yuyi.com.zhihuiyuyi.Utils.LogUtils;
import yuyi.com.zhihuiyuyi.ZiXun.Tools.CircleImageView;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {@link Fragment} subclass.
*/
public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
//顶部的头像标志
public static CircleImageView circleImageView_home = null;
//下面是中间六个按钮
private TextView companyIntroduction, mainBuiness, contactUs, weixin, patener, keFu;
//viewpager的三个状态
public static final int PAGER_START = 1;
public static final int PAGER_STOP = 2;
public static final int PAGER_RESTART = 3;
//viewpager下面提示的栏目
private LinearLayout mHomeIndicator;
//顶部的viewpager
private ViewPager mViewPager;
private int mPosition = 100;
private int lastIndex = 100;
//存贮数据源
private List<ImageView> mImageViews = new ArrayList<>();
//handler为了操控viewpager的轮播的
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (this.hasMessages(PAGER_START)) {
this.removeMessages(PAGER_START);
}
switch (msg.what) {
case PAGER_START:
mPosition++;
mViewPager.setCurrentItem(mPosition, true);
this.sendEmptyMessageDelayed(PAGER_START, 3000);
break;
case PAGER_STOP:
if (this.hasMessages(PAGER_START)) {
this.removeMessages(PAGER_START);
}
break;
case PAGER_RESTART:
mPosition = msg.arg1;
this.sendEmptyMessageDelayed(PAGER_START, 3000);
break;
}
}
};
private HomePageAdapter homePageAdapter;
private SharedPreferences homeSharedPreferences;
private SharedPreferences.Editor homeEdit;
private RelativeLayout mMore;
private String mPicUrl;
private int indicatorNum;
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);//填充视图
//初始化控件
init(view);
SharedPreferences userInfo = getContext().getSharedPreferences("UserInfo", MODE_PRIVATE);
Glide.with(this).load(userInfo.getString("userIcon", "null")).error(R.mipmap.bn_geren).into(circleImageView_home);
//初始化viewpager
initViewPager();
//获取数据源
initdata();
return view;
}
//一般是联网获取数据,
private void initdata() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.BASEURL)
.addConverterFactory(GsonConverterFactory.create()).build();
LuanBoPicAPI luanBoPicAPI = retrofit.create(LuanBoPicAPI.class);
Call<LuanBoPic> call = luanBoPicAPI.getLuanBoPic();
call.enqueue(new Callback<LuanBoPic>() {
@Override
public void onResponse(Call<LuanBoPic> call, Response<LuanBoPic> response) {
LuanBoPic luanBoPic = response.body();
if (luanBoPic != null) {
LuanBoPic.InfoBean info = luanBoPic.getInfo();
String prefix = info.getPrefix();
List<LuanBoPic.InfoBean.ContentBean> content = info.getContent();
indicatorNum = content.size();
for (int i = 0; i < content.size(); i++) {
ImageView imageView = new ImageView(getActivity());
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
LuanBoPic.InfoBean.ContentBean contentBean = content.get(i);
String picture = contentBean.getPicture();
mPicUrl = LoadHtml.zhuangyi(prefix + picture);
LogUtils.d("HomeFragment", mPicUrl);
Glide.with(HomeFragment.this).load(mPicUrl).into(imageView);
homePageAdapter.notifyDataSetChanged();
mImageViews.add(imageView);
}
initIndicator();
}
}
@Override
public void onFailure(Call<LuanBoPic> call, Throwable t) {
}
});
homePageAdapter.setDate(mImageViews);
}
private void initIndicator() {
for (int i = 0; i < indicatorNum; i++) {
ImageView indicator = new ImageView(getActivity());
indicator.setImageResource(getActivity().getResources().getIdentifier("icon_lunbo", "drawable", getActivity().getPackageName()));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(DensityUtil.getpx(getContext(), 10), DensityUtil.getpx(getContext(), 10));
layoutParams.rightMargin = DensityUtil.getdp(getContext(), 30);
indicator.setLayoutParams(layoutParams);
mHomeIndicator.addView(indicator);
}
// mHomeIndicator.getChildAt(0).setEnabled(false);
//通知改变后,再去根据数据源展示决定不同的indicator的孩子
//设置监听
initListener();
}
private void initListener() {
mHandler.sendEmptyMessage(PAGER_START);
mViewPager.addOnPageChangeListener(this);
}
private void initViewPager() {
homePageAdapter = new HomePageAdapter(getActivity());
mViewPager.setAdapter(homePageAdapter);
}
//companyIntroduction,mainBuiness,contactUs,weixin,patener,keFu,
private void init(View view) {
mHomeIndicator = (LinearLayout) view.findViewById(R.id.linearlayout_indicator_home);
mViewPager = (ViewPager) view.findViewById(R.id.viewPager_HomeFragment);
//下面是进行初始化中间的六个按钮
companyIntroduction = (TextView) view.findViewById(R.id.textView_CompanyIntroduction);
mainBuiness = (TextView) view.findViewById(R.id.textView_mainBuiness);
contactUs = (TextView) view.findViewById(R.id.textView_contactUs);
weixin = (TextView) view.findViewById(R.id.textView_weixin);
patener = (TextView) view.findViewById(R.id.textView_panter);
keFu = (TextView) view.findViewById(R.id.textView_KeFu);
//头部的头像
circleImageView_home = (CircleImageView) view.findViewById(R.id.circleImageView_home);
mMore = (RelativeLayout) view.findViewById(R.id.home_qiyedongtai);
//设置监听
initviewListener();
}
//控件的点击事件
private void initviewListener() {
//中部六个按钮的监听事件
companyIntroduction.setOnClickListener(this);
mainBuiness.setOnClickListener(this);
contactUs.setOnClickListener(this);
weixin.setOnClickListener(this);
patener.setOnClickListener(this);
keFu.setOnClickListener(this);
mMore.setOnClickListener(this);
//顶部的头像标志
// circleImageView_home.setOnClickListener(this);
getInfo();
}
//下面是viewpager监听的三个重写的方法---开始
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if (indicatorNum != 0) {
mHomeIndicator.getChildAt(lastIndex % indicatorNum).setEnabled(true);
mHomeIndicator.getChildAt(position % indicatorNum).setEnabled(false);
lastIndex = position;
}
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
Message msg = Message.obtain();
msg.what = PAGER_RESTART;
msg.arg1 = lastIndex;
mHandler.sendMessage(msg);
}
}
//这是viewpager监听的三个方法---结束
//开始中部点击按钮
// companyIntroduction,mainBuiness,contactUs,weixin,patener,keFu,
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.textView_CompanyIntroduction:
Intent companyIntroductionIntent = new Intent(getContext(), CompanyIntroduction.class);
startActivity(companyIntroductionIntent);
break;
case R.id.textView_mainBuiness:
Intent maniBuinessintent = new Intent(getContext(), MainBuiness.class);
startActivity(maniBuinessintent);
break;
case R.id.textView_contactUs:
Intent contactUsIntent = new Intent(getContext(), ContactUs.class);
startActivity(contactUsIntent);
break;
case R.id.textView_weixin:
//表示跳转e运河网
Intent WeixinIntent = new Intent(getContext(), Weixin.class);
startActivity(WeixinIntent);
break;
case R.id.textView_panter:
Intent panterIntent = new Intent(getContext(), Patener.class);
startActivity(panterIntent);
break;
case R.id.textView_KeFu:
Intent kefuIntent = new Intent(getContext(), JoinUs.class);
startActivity(kefuIntent);
break;
case R.id.home_qiyedongtai://跳转到企业动态那一栏目里面
Intent moreIntent = new Intent(getContext(), MoreActivity.class);
startActivity(moreIntent);
break;
}
}
public void getInfo() {
homeSharedPreferences = getContext().getSharedPreferences("UserInfo", MODE_PRIVATE);
// homeEdit = homeSharedPreferences.edit();
//开始就读取
String userInfo = homeSharedPreferences.getString("userIcon", "www");
// Picasso.with(getContext()).load(userInfo).resize(50, 50).into(circleImageView_home);
}
public void setIcon(String icon) {
Glide.with(this).load(icon).error(R.mipmap.bn_geren).into(circleImageView_home);
}
}
| 11,982 | 0.641227 | 0.63777 | 319 | 35.269592 | 28.396698 | 157 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664577 | false | false | 6 |
928f0db522e6ab5b467c856c8bdcc66793554fe4 | 34,737,695,549,167 | 9b6085595ab7943409247a0b365aa406992264be | /src/main/java/com/webdatabase/dgz/controller/Member_typeController.java | 3a835ec2fff988f104a419fb80406e92f7cf0c35 | [] | no_license | buddzbuddy/dgz | https://github.com/buddzbuddy/dgz | bf381f0a9e82b04979965607e6f9031535d07477 | 1f3cd054fb866618db76f2cb7e3306310e92717b | refs/heads/master | 2023-03-31T13:08:35.698000 | 2021-04-08T05:17:24 | 2021-04-08T05:17:24 | 317,546,083 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.webdatabase.dgz.controller;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.webdatabase.dgz.excelExport.Member_typeExcelExporter;
import com.webdatabase.dgz.excelUpload.Member_typeExcelUpload;
import com.webdatabase.dgz.exception.ResourceNotFoundException;
import com.webdatabase.dgz.message.ResponseMessage;
import com.webdatabase.dgz.model.Member_type;
import com.webdatabase.dgz.repository.Member_typeRepository;
import com.webdatabase.dgz.service.Member_typeService;
@RestController
public class Member_typeController {
@Autowired
private Member_typeRepository member_typeRepository;
@GetMapping("/member_types")
public Page<Member_type> getAll(Pageable pageable) {
return member_typeRepository.findAll(pageable);
}
@GetMapping("/member_types/{member_typeId}")
public Optional<Member_type> getOne(@PathVariable Long member_typeId) {
return member_typeRepository.findById(member_typeId);
}
@PostMapping("/member_types")
public Member_type create(@Valid @RequestBody Member_type member_type) {
return member_typeRepository.save(member_type);
}
@PutMapping("/member_types/{member_typeId}")
public Member_type update(@PathVariable Long member_typeId,
@Valid @RequestBody Member_type member_typeRequest) {
return member_typeRepository.findById(member_typeId)
.map(member_type -> {
member_type.setName(member_typeRequest.getName());
return member_typeRepository.save(member_type);
}).orElseThrow(() -> new ResourceNotFoundException("Member type not found with id " + member_typeId));
}
@DeleteMapping("/member_types/{member_typeId}")
public ResponseEntity<?> delete(@PathVariable Long member_typeId) {
return member_typeRepository.findById(member_typeId)
.map(member_type -> {
member_typeRepository.delete(member_type);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Member type not found with id " + member_typeId));
}
//export to Excel
@Autowired
private Member_typeService member_typeService;
@GetMapping("/member_types/export/excel")
public void exportToExcel(HttpServletResponse response) throws IOException{
response.setContentType("application.octet-stream");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDate = dateFormat.format(new Date());
String headerKey = "Content-Dispostion";
String headerValue = "attachment; filename=member_type_"+currentDate + ".xlsx";
response.setHeader(headerKey, headerValue);
List<Member_type> listMember_types = member_typeService.listAll();
Member_typeExcelExporter excelExport = new Member_typeExcelExporter(listMember_types);
excelExport.export(response);
}
//upload from Excel
@PostMapping("/member_types/upload/excel")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) {
String message = "";
if (Member_typeExcelUpload.hasExcelFormat(file)) {
try {
member_typeService.save(file);
message = "Файл успешно загружен: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Не удалось загрузить файл: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
message = "Загрузите файл в формате Excel!";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}
@GetMapping("/member_types/excel")
public ResponseEntity<List<Member_type>> getAllMember_types() {
try {
List<Member_type> member_types = member_typeService.listAll();
if (member_types.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(member_types, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| UTF-8 | Java | 5,464 | java | Member_typeController.java | Java | [
{
"context": "ew Date());\n \t\n \tString headerKey = \"Content-Dispostion\";\n \tString headerValue = \"attachment; filename",
"end": 3616,
"score": 0.6536009907722473,
"start": 3606,
"tag": "KEY",
"value": "Dispostion"
}
] | null | [] | package com.webdatabase.dgz.controller;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.webdatabase.dgz.excelExport.Member_typeExcelExporter;
import com.webdatabase.dgz.excelUpload.Member_typeExcelUpload;
import com.webdatabase.dgz.exception.ResourceNotFoundException;
import com.webdatabase.dgz.message.ResponseMessage;
import com.webdatabase.dgz.model.Member_type;
import com.webdatabase.dgz.repository.Member_typeRepository;
import com.webdatabase.dgz.service.Member_typeService;
@RestController
public class Member_typeController {
@Autowired
private Member_typeRepository member_typeRepository;
@GetMapping("/member_types")
public Page<Member_type> getAll(Pageable pageable) {
return member_typeRepository.findAll(pageable);
}
@GetMapping("/member_types/{member_typeId}")
public Optional<Member_type> getOne(@PathVariable Long member_typeId) {
return member_typeRepository.findById(member_typeId);
}
@PostMapping("/member_types")
public Member_type create(@Valid @RequestBody Member_type member_type) {
return member_typeRepository.save(member_type);
}
@PutMapping("/member_types/{member_typeId}")
public Member_type update(@PathVariable Long member_typeId,
@Valid @RequestBody Member_type member_typeRequest) {
return member_typeRepository.findById(member_typeId)
.map(member_type -> {
member_type.setName(member_typeRequest.getName());
return member_typeRepository.save(member_type);
}).orElseThrow(() -> new ResourceNotFoundException("Member type not found with id " + member_typeId));
}
@DeleteMapping("/member_types/{member_typeId}")
public ResponseEntity<?> delete(@PathVariable Long member_typeId) {
return member_typeRepository.findById(member_typeId)
.map(member_type -> {
member_typeRepository.delete(member_type);
return ResponseEntity.ok().build();
}).orElseThrow(() -> new ResourceNotFoundException("Member type not found with id " + member_typeId));
}
//export to Excel
@Autowired
private Member_typeService member_typeService;
@GetMapping("/member_types/export/excel")
public void exportToExcel(HttpServletResponse response) throws IOException{
response.setContentType("application.octet-stream");
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
String currentDate = dateFormat.format(new Date());
String headerKey = "Content-Dispostion";
String headerValue = "attachment; filename=member_type_"+currentDate + ".xlsx";
response.setHeader(headerKey, headerValue);
List<Member_type> listMember_types = member_typeService.listAll();
Member_typeExcelExporter excelExport = new Member_typeExcelExporter(listMember_types);
excelExport.export(response);
}
//upload from Excel
@PostMapping("/member_types/upload/excel")
public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) {
String message = "";
if (Member_typeExcelUpload.hasExcelFormat(file)) {
try {
member_typeService.save(file);
message = "Файл успешно загружен: " + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = "Не удалось загрузить файл: " + file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
message = "Загрузите файл в формате Excel!";
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}
@GetMapping("/member_types/excel")
public ResponseEntity<List<Member_type>> getAllMember_types() {
try {
List<Member_type> member_types = member_typeService.listAll();
if (member_types.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(member_types, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| 5,464 | 0.709552 | 0.709552 | 139 | 37.863308 | 30.117563 | 118 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.633094 | false | false | 6 |
ce5bb24eafa73ce05799bcae2fa8c700c8d35a3d | 38,104,949,883,870 | 65d46556fba1545c06594a1434de92feb3515520 | /src/project/actions/ConcertService.java | e2eee4497bc551cb5a8cfc9e2c4815c85c4f4899 | [] | no_license | ioanapintilie07/E-TicketingPlatform | https://github.com/ioanapintilie07/E-TicketingPlatform | cae9812c3e25f1dae07fdf982b5d2461a1cd4bec | 8edf578e2f4e61837f8c0435468f5ba5a7204f22 | refs/heads/main | 2023-04-30T06:28:36.998000 | 2021-05-25T19:05:37 | 2021-05-25T19:05:37 | 352,174,926 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package project.actions;
import project.DB.ConcertRepository;
import project.events.Concert;
import project.events.Event;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class ConcertService {
static ConcertRepository concertRepository= new ConcertRepository();
public void listConcerts() {
List<Event> concerts = new ArrayList<>(concertRepository.findAllConcerts());
if (concerts.size() == 0) {
System.out.println("Sorry, there are no concerts registered in the database");
}
else {
for (Event concert : concerts) {
System.out.println(concert);
System.out.println("Tickets: " + concert.getParticipantsLimit() + "\n");
}
}
}
public void updateConcertTickets() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("Please enter the concert id:");
int id = scanner.nextInt();
System.out.println("Updated number of max tickets:");
int newParticipantsLimit = scanner.nextInt();
int updated = concertRepository.updateConcert(id, newParticipantsLimit);
if (updated == 0) {
System.out.println("Sorry, there is no concert with this id in the database");
}
else {
System.out.println("\nConcert updated successfully!\n");
}
}
public void lookForConcert() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("What's the name of the artist you're interested in?");
String musician = scanner.next();
List<Event> concerts = new ArrayList<>(concertRepository.findConcert(musician));
if (concerts.size() == 0) {
System.out.println("Sorry, this artist has no upcoming concerts.");
}
else {
System.out.println("Check these out!");
for (Event concert : concerts) {
System.out.println(concert);
}
}
}
public void deleteConcert() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("Please enter the concert's id:");
int id = scanner.nextInt();
int deleted = concertRepository.deleteConcert(id);
if (deleted == 0) {
System.out.println("Sorry, couldn't find the concert you were looking for");
}
else {
System.out.println("\nConcert deleted successfully!\n");
}
}
public void addConcertDB() {
Random rand = new Random();
String[] names = {"Night Out", "The Colors Show", "Let's talk about things!", "Amazing Skies", "Look Beyond"};
String[] dates = {"1/04/2021", "5/04/2021", "9/04/2021", "1/07/2021", "10/07/2021"};
String[] descriptions = {"Check out this cool event", "Come have a great time", "We're waiting for you",
"Buy a ticket, buy an experience", "Makes you want to come back every time"};
String[] musicians = {"Halsey", "The New York Philharmonic", "Gorillaz", "Nothing But Thieves", "Beyonce"};
String[] musicGenres = {"pop", "rock", "classical", "indie", "alternative"};
String name = names[rand.nextInt(names.length)];
String date = dates[rand.nextInt(dates.length)];
String description = descriptions[rand.nextInt(descriptions.length)];
String musician = musicians[rand.nextInt(musicians.length)];
String musicGenre = musicGenres[rand.nextInt(musicGenres.length)];
int durationInHours = rand.nextInt(25);
int locationId = rand.nextInt(11);
int participantsLimit = rand.nextInt(1000);
Event concert = new Concert(name, date, description, durationInHours, locationId, participantsLimit, musician, musicGenre);
concertRepository.createConcert(concert);
System.out.println("\nConcert added successfully!\n");
}
}
| UTF-8 | Java | 3,986 | java | ConcertService.java | Java | [
{
"context": "back every time\"};\n String[] musicians = {\"Halsey\", \"The New York Philharmonic\", \"Gorillaz\", \"Nothi",
"end": 3089,
"score": 0.9977588653564453,
"start": 3083,
"tag": "NAME",
"value": "Halsey"
},
{
"context": "icians = {\"Halsey\", \"The New York Philharm... | null | [] | package project.actions;
import project.DB.ConcertRepository;
import project.events.Concert;
import project.events.Event;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class ConcertService {
static ConcertRepository concertRepository= new ConcertRepository();
public void listConcerts() {
List<Event> concerts = new ArrayList<>(concertRepository.findAllConcerts());
if (concerts.size() == 0) {
System.out.println("Sorry, there are no concerts registered in the database");
}
else {
for (Event concert : concerts) {
System.out.println(concert);
System.out.println("Tickets: " + concert.getParticipantsLimit() + "\n");
}
}
}
public void updateConcertTickets() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("Please enter the concert id:");
int id = scanner.nextInt();
System.out.println("Updated number of max tickets:");
int newParticipantsLimit = scanner.nextInt();
int updated = concertRepository.updateConcert(id, newParticipantsLimit);
if (updated == 0) {
System.out.println("Sorry, there is no concert with this id in the database");
}
else {
System.out.println("\nConcert updated successfully!\n");
}
}
public void lookForConcert() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("What's the name of the artist you're interested in?");
String musician = scanner.next();
List<Event> concerts = new ArrayList<>(concertRepository.findConcert(musician));
if (concerts.size() == 0) {
System.out.println("Sorry, this artist has no upcoming concerts.");
}
else {
System.out.println("Check these out!");
for (Event concert : concerts) {
System.out.println(concert);
}
}
}
public void deleteConcert() {
Scanner scanner = new Scanner(System.in).useDelimiter("\n");
System.out.println("Please enter the concert's id:");
int id = scanner.nextInt();
int deleted = concertRepository.deleteConcert(id);
if (deleted == 0) {
System.out.println("Sorry, couldn't find the concert you were looking for");
}
else {
System.out.println("\nConcert deleted successfully!\n");
}
}
public void addConcertDB() {
Random rand = new Random();
String[] names = {"Night Out", "The Colors Show", "Let's talk about things!", "Amazing Skies", "Look Beyond"};
String[] dates = {"1/04/2021", "5/04/2021", "9/04/2021", "1/07/2021", "10/07/2021"};
String[] descriptions = {"Check out this cool event", "Come have a great time", "We're waiting for you",
"Buy a ticket, buy an experience", "Makes you want to come back every time"};
String[] musicians = {"Halsey", "The New York Philharmonic", "Gorillaz", "Nothing But Thieves", "Beyonce"};
String[] musicGenres = {"pop", "rock", "classical", "indie", "alternative"};
String name = names[rand.nextInt(names.length)];
String date = dates[rand.nextInt(dates.length)];
String description = descriptions[rand.nextInt(descriptions.length)];
String musician = musicians[rand.nextInt(musicians.length)];
String musicGenre = musicGenres[rand.nextInt(musicGenres.length)];
int durationInHours = rand.nextInt(25);
int locationId = rand.nextInt(11);
int participantsLimit = rand.nextInt(1000);
Event concert = new Concert(name, date, description, durationInHours, locationId, participantsLimit, musician, musicGenre);
concertRepository.createConcert(concert);
System.out.println("\nConcert added successfully!\n");
}
}
| 3,986 | 0.625188 | 0.613146 | 93 | 41.860214 | 32.568073 | 131 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.903226 | false | false | 6 |
28a4e2d084bfb452d446513ca0afac76cf1de23c | 35,966,056,184,126 | 86a9b24d3ed2ee98a7d97cee3c6cb153a6f4a6fd | /app/src/main/java/com/falconssoft/app_pos/models/Branches.java | 3b444a10db8e692d869cf66bd49e79f2ec6f68a3 | [] | no_license | SundosAlTamimi/PosFalconsAPP_ | https://github.com/SundosAlTamimi/PosFalconsAPP_ | 5d11323f1b80df9a72766accd49f63bc2ab3559e | a120866037f8b258f1597b04d3c9b2bfb1105bb1 | refs/heads/master | 2021-07-25T05:26:44.135000 | 2020-09-22T08:44:12 | 2020-09-22T08:44:12 | 219,726,706 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.falconssoft.app_pos.models;
public class Branches {
private String name;
private String adress;
private String time_work;
private String telephone;
private String latitude;
private String longtude;
public Branches(String name, String adress, String time_work, String telephone, String latitude, String longtude) {
this.name = name;
this.adress = adress;
this.time_work = time_work;
this.telephone = telephone;
this.latitude = latitude;
this.longtude = longtude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getTime_work() {
return time_work;
}
public void setTime_work(String time_work) {
this.time_work = time_work;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongtude() {
return longtude;
}
public void setLongtude(String longtude) {
this.longtude = longtude;
}
}
| UTF-8 | Java | 1,466 | java | Branches.java | Java | [] | null | [] | package com.falconssoft.app_pos.models;
public class Branches {
private String name;
private String adress;
private String time_work;
private String telephone;
private String latitude;
private String longtude;
public Branches(String name, String adress, String time_work, String telephone, String latitude, String longtude) {
this.name = name;
this.adress = adress;
this.time_work = time_work;
this.telephone = telephone;
this.latitude = latitude;
this.longtude = longtude;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public String getTime_work() {
return time_work;
}
public void setTime_work(String time_work) {
this.time_work = time_work;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongtude() {
return longtude;
}
public void setLongtude(String longtude) {
this.longtude = longtude;
}
}
| 1,466 | 0.612551 | 0.612551 | 67 | 20.880596 | 19.689775 | 119 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.447761 | false | false | 6 |
169eaea8ece291dd72bced25c4a9d17e41621f42 | 24,575,802,905,206 | 5e5c311ca4885dc583a21f864ae22ac2083e8ddd | /java/com/bytesw/platform/eis/mapper/RegistroPersonasMapper.java | 0ca93bc1c6eb84fcc73cb74729f07ad9cf0260b6 | [] | no_license | LudwingCuxil/bacc | https://github.com/LudwingCuxil/bacc | a001a768598d8447056d6dca86bf548cc197dbff | e2f4c142abacee368ca13cfe3e1936f81ff8c72d | refs/heads/master | 2021-08-28T16:34:25.813000 | 2017-12-12T19:14:12 | 2017-12-12T19:14:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bytesw.platform.eis.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.springframework.jdbc.core.RowMapper;
import com.bytesw.platform.eis.bo.clientes.dominio.Genero;
import com.bytesw.platform.eis.dto.clientes.ClienteResumenDTO;
public class RegistroPersonasMapper implements RowMapper<ClienteResumenDTO> {
private static final String DIA_NACIMIENTO = "DIA_NACIMIENTO";
private static final String MES_NACIMIENTO = "MES_NACIMIENTO";
private static final String ANO_NACIMIENTO = "ANO_NACIMIENTO";
private static final String M = "M";
private static final String GENERO2 = "GENERO";
private static final String APELLIDO_DE_CASADA = "APELLIDO_DE_CASADA";
private static final String SEGUNDO_APELLIDO = "SEGUNDO_APELLIDO";
private static final String PRIMER_APELLIDO = "PRIMER_APELLIDO";
private static final String SEGUNDO_NOMBRE = "SEGUNDO_NOMBRE";
private static final String PRIMER_NOMBRE = "PRIMER_NOMBRE";
private static final String ID_PERSONA = "ID_PERSONA";
public ClienteResumenDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
ClienteResumenDTO dto = new ClienteResumenDTO();
dto.setIdentificacion(rs.getString(ID_PERSONA));
dto.setPrimerNombre(rs.getString(PRIMER_NOMBRE));
dto.setSegundoNombre(rs.getString(SEGUNDO_NOMBRE));
dto.setPrimerApellido(rs.getString(PRIMER_APELLIDO));
dto.setSegundoApellido(rs.getString(SEGUNDO_APELLIDO));
dto.setApellidoCasada(rs.getString(APELLIDO_DE_CASADA));
String genero = rs.getString(GENERO2);
if (M.equals(genero)) {
dto.setGenero(Genero.M);
} else {
dto.setGenero(Genero.F);
}
Integer anio = rs.getInt(ANO_NACIMIENTO);
Integer mes = rs.getInt(MES_NACIMIENTO);
Integer dia = rs.getInt(DIA_NACIMIENTO);
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, anio);
calendar.set(Calendar.MONTH, mes);
calendar.set(Calendar.DATE, dia);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
dto.setFecha(calendar.getTime());
return dto;
}
} | UTF-8 | Java | 2,172 | java | RegistroPersonasMapper.java | Java | [] | null | [] | package com.bytesw.platform.eis.mapper;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.springframework.jdbc.core.RowMapper;
import com.bytesw.platform.eis.bo.clientes.dominio.Genero;
import com.bytesw.platform.eis.dto.clientes.ClienteResumenDTO;
public class RegistroPersonasMapper implements RowMapper<ClienteResumenDTO> {
private static final String DIA_NACIMIENTO = "DIA_NACIMIENTO";
private static final String MES_NACIMIENTO = "MES_NACIMIENTO";
private static final String ANO_NACIMIENTO = "ANO_NACIMIENTO";
private static final String M = "M";
private static final String GENERO2 = "GENERO";
private static final String APELLIDO_DE_CASADA = "APELLIDO_DE_CASADA";
private static final String SEGUNDO_APELLIDO = "SEGUNDO_APELLIDO";
private static final String PRIMER_APELLIDO = "PRIMER_APELLIDO";
private static final String SEGUNDO_NOMBRE = "SEGUNDO_NOMBRE";
private static final String PRIMER_NOMBRE = "PRIMER_NOMBRE";
private static final String ID_PERSONA = "ID_PERSONA";
public ClienteResumenDTO mapRow(ResultSet rs, int rowNum) throws SQLException {
ClienteResumenDTO dto = new ClienteResumenDTO();
dto.setIdentificacion(rs.getString(ID_PERSONA));
dto.setPrimerNombre(rs.getString(PRIMER_NOMBRE));
dto.setSegundoNombre(rs.getString(SEGUNDO_NOMBRE));
dto.setPrimerApellido(rs.getString(PRIMER_APELLIDO));
dto.setSegundoApellido(rs.getString(SEGUNDO_APELLIDO));
dto.setApellidoCasada(rs.getString(APELLIDO_DE_CASADA));
String genero = rs.getString(GENERO2);
if (M.equals(genero)) {
dto.setGenero(Genero.M);
} else {
dto.setGenero(Genero.F);
}
Integer anio = rs.getInt(ANO_NACIMIENTO);
Integer mes = rs.getInt(MES_NACIMIENTO);
Integer dia = rs.getInt(DIA_NACIMIENTO);
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, anio);
calendar.set(Calendar.MONTH, mes);
calendar.set(Calendar.DATE, dia);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
dto.setFecha(calendar.getTime());
return dto;
}
} | 2,172 | 0.768877 | 0.766114 | 58 | 36.465519 | 23.229897 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.017241 | false | false | 6 |
9dc4da97218fe30057b08e417d7098df4770ec32 | 16,252,156,290,603 | 7646e3668a8ef3f6168d6d66556477e53f14fb1a | /java/src/Problem19.java | 91984167e23fd6f6b4f047e204d9de429b69e674 | [] | no_license | aweis/Project-euler | https://github.com/aweis/Project-euler | 1d374a65dadc3c0b4ed9955d6e8d10ac03fd67f8 | 8ac25256a8efcac1b016ff57ae2e13b2cba287b2 | refs/heads/master | 2023-06-11T14:52:13.600000 | 2023-05-27T21:48:48 | 2023-05-27T21:48:48 | 3,072,361 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by adam on 2/16/14.
*/
public class Problem19 implements Euler {
@Override
public String answer() throws Exception {
int count = 0;
for(int year = 1901; year <= 2000; year++) {
for(int month = 1; month <= 12; month++) {
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd/M/yyyy").parse("01/"+month+"/"+year));
if(cal.get(cal.DAY_OF_WEEK) == 1) {
count++;
}
}
}
return Integer.toString(count);
}
}
| UTF-8 | Java | 712 | java | Problem19.java | Java | [
{
"context": "rt java.util.GregorianCalendar;\n\n/**\n * Created by adam on 2/16/14.\n */\npublic class Problem19 implements",
"end": 144,
"score": 0.9619500637054443,
"start": 140,
"tag": "USERNAME",
"value": "adam"
}
] | null | [] | import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by adam on 2/16/14.
*/
public class Problem19 implements Euler {
@Override
public String answer() throws Exception {
int count = 0;
for(int year = 1901; year <= 2000; year++) {
for(int month = 1; month <= 12; month++) {
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd/M/yyyy").parse("01/"+month+"/"+year));
if(cal.get(cal.DAY_OF_WEEK) == 1) {
count++;
}
}
}
return Integer.toString(count);
}
}
| 712 | 0.547753 | 0.516854 | 24 | 28.666666 | 21.778557 | 91 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.541667 | false | false | 6 |
1547513c639148d3dfd180762412037b82eb943b | 4,930,622,505,051 | df33222c9d2abfd50f1ff454d28ae429135d04e1 | /modules/rescuecore2/src/rescuecore2/worldmodel/AbstractEntity.java | 6535bbf6ae9e0efa1f11b078e6f53bb093452497 | [
"BSD-3-Clause"
] | permissive | roborescue/rcrs-server | https://github.com/roborescue/rcrs-server | 40039fae44b171d4beec12c320bba55f51122c3d | 0cfa042db2c36e14a918395139cd73124413c299 | refs/heads/master | 2023-06-09T16:57:25.813000 | 2023-06-02T06:44:13 | 2023-06-02T06:44:13 | 99,498,612 | 39 | 43 | BSD-3-Clause | false | 2023-02-06T13:46:34 | 2017-08-06T16:18:45 | 2023-02-03T07:37:05 | 2023-02-06T13:46:31 | 75,659 | 25 | 34 | 3 | Java | false | false | package rescuecore2.worldmodel;
import static rescuecore2.misc.EncodingTools.readInt32;
import static rescuecore2.misc.EncodingTools.readProperty;
import static rescuecore2.misc.EncodingTools.writeInt32;
import static rescuecore2.misc.EncodingTools.writeProperty;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import rescuecore2.messages.protobuf.MsgProtoBuf;
import rescuecore2.messages.protobuf.RCRSProto.EntityProto;
import rescuecore2.messages.protobuf.RCRSProto.PropertyProto;
/**
* Abstract base class for concrete Entity implementations.
*/
public abstract class AbstractEntity implements Entity {
private final EntityID id;
private final Set<EntityListener> listeners;
private final Set<Property> properties;
/**
* Construct an AbstractEntity with a set of properties.
*
* @param id The ID of this entity.
*/
protected AbstractEntity(EntityID id) {
this.id = id;
listeners = new HashSet<EntityListener>();
properties = new HashSet<Property>();
}
/**
* AbstractEntity copy constructor.
*
* @param other The AbstractEntity to copy.
*/
protected AbstractEntity(AbstractEntity other) {
this(other.getID());
}
@Override
public void addEntityListener(EntityListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
@Override
public void removeEntityListener(EntityListener l) {
synchronized (listeners) {
listeners.remove(l);
}
}
@Override
public Entity copy() {
Entity result = copyImpl();
for (Property original : getProperties()) {
Property copy = result.getProperty(original.getURN());
copy.takeValue(original);
}
return result;
}
/**
* Create a copy of this entity. Property values do not need to be copied.
*
* @return A new Entity of the same type as this and with the same ID.
*/
protected abstract Entity copyImpl();
@Override
public final Set<Property> getProperties() {
return properties;
}
@Override
public Property getProperty(int propertyURN) {
return null;
}
@Override
public EntityID getID() {
return id;
}
@Override
public void write(OutputStream out) throws IOException {
int count = 0;
for (Property next : getProperties()) {
if (next.isDefined()) {
++count;
}
}
writeInt32(count, out);
for (Property next : getProperties()) {
if (next.isDefined()) {
writeProperty(next, out);
}
}
}
@Override
public void read(InputStream in) throws IOException {
int count = readInt32(in);
for (int i = 0; i < count; ++i) {
Property prop = readProperty(in);
if (prop == null) {
continue;
}
Property existing = getProperty(prop.getURN());
existing.takeValue(prop);
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getEntityName());
result.append(" (");
result.append(id);
result.append(")");
return result.toString();
}
/**
* Get the full description of this object.
*
* @return The full description.
*/
public String getFullDescription() {
StringBuilder result = new StringBuilder();
String name = getEntityName();
int urn = getURN();
result.append(name);
result.append(" [");
result.append(urn);
result.append("]");
result.append(" (");
result.append(id);
result.append(") [");
for (Iterator<Property> it = getProperties().iterator(); it.hasNext();) {
result.append(it.next().toString());
if (it.hasNext()) {
result.append(", ");
}
}
result.append("]");
return result.toString();
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof AbstractEntity) {
AbstractEntity a = (AbstractEntity) o;
return this.id.equals(a.id);
}
return false;
}
/**
* Get the name of this entity. Default implementation returns the entity URN.
*
* @return The name of this entity.
*/
protected String getEntityName() {
return this.getClass().getSimpleName();
}
/**
* Register a set of properties.
*
* @param props The properties to register.
*/
protected void registerProperties(Property... props) {
for (Property p : props) {
properties.add(p);
if (p instanceof AbstractProperty) {
((AbstractProperty) p).setEntity(this);
}
}
}
/**
* Notify all listeners that a property has changed.
*
* @param p The changed property.
* @param oldValue The old value.
* @param newValue The new value.
*/
protected void firePropertyChanged(Property p, Object oldValue, Object newValue) {
Collection<EntityListener> copy;
synchronized (listeners) {
copy = new HashSet<EntityListener>(listeners);
}
for (EntityListener next : copy) {
next.propertyChanged(this, p, oldValue, newValue);
}
}
@Override
public EntityProto toEntityProto() {
EntityProto.Builder builder = EntityProto.newBuilder().setEntityID(id.getValue()).setUrn(getURN());
for (Property next : getProperties()) {
if (next.isDefined()) {
builder.addProperties(next.toPropertyProto());
}
}
return builder.build();
}
@Override
public void fromEntityProto(EntityProto proto) {
for (PropertyProto propertyProto : proto.getPropertiesList()) {
Property prop = MsgProtoBuf.propertyProto2Property(propertyProto);
if (prop == null) {
continue;
}
Property existing = getProperty(prop.getURN());
existing.takeValue(prop);
}
}
} | UTF-8 | Java | 5,839 | java | AbstractEntity.java | Java | [] | null | [] | package rescuecore2.worldmodel;
import static rescuecore2.misc.EncodingTools.readInt32;
import static rescuecore2.misc.EncodingTools.readProperty;
import static rescuecore2.misc.EncodingTools.writeInt32;
import static rescuecore2.misc.EncodingTools.writeProperty;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import rescuecore2.messages.protobuf.MsgProtoBuf;
import rescuecore2.messages.protobuf.RCRSProto.EntityProto;
import rescuecore2.messages.protobuf.RCRSProto.PropertyProto;
/**
* Abstract base class for concrete Entity implementations.
*/
public abstract class AbstractEntity implements Entity {
private final EntityID id;
private final Set<EntityListener> listeners;
private final Set<Property> properties;
/**
* Construct an AbstractEntity with a set of properties.
*
* @param id The ID of this entity.
*/
protected AbstractEntity(EntityID id) {
this.id = id;
listeners = new HashSet<EntityListener>();
properties = new HashSet<Property>();
}
/**
* AbstractEntity copy constructor.
*
* @param other The AbstractEntity to copy.
*/
protected AbstractEntity(AbstractEntity other) {
this(other.getID());
}
@Override
public void addEntityListener(EntityListener l) {
synchronized (listeners) {
listeners.add(l);
}
}
@Override
public void removeEntityListener(EntityListener l) {
synchronized (listeners) {
listeners.remove(l);
}
}
@Override
public Entity copy() {
Entity result = copyImpl();
for (Property original : getProperties()) {
Property copy = result.getProperty(original.getURN());
copy.takeValue(original);
}
return result;
}
/**
* Create a copy of this entity. Property values do not need to be copied.
*
* @return A new Entity of the same type as this and with the same ID.
*/
protected abstract Entity copyImpl();
@Override
public final Set<Property> getProperties() {
return properties;
}
@Override
public Property getProperty(int propertyURN) {
return null;
}
@Override
public EntityID getID() {
return id;
}
@Override
public void write(OutputStream out) throws IOException {
int count = 0;
for (Property next : getProperties()) {
if (next.isDefined()) {
++count;
}
}
writeInt32(count, out);
for (Property next : getProperties()) {
if (next.isDefined()) {
writeProperty(next, out);
}
}
}
@Override
public void read(InputStream in) throws IOException {
int count = readInt32(in);
for (int i = 0; i < count; ++i) {
Property prop = readProperty(in);
if (prop == null) {
continue;
}
Property existing = getProperty(prop.getURN());
existing.takeValue(prop);
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getEntityName());
result.append(" (");
result.append(id);
result.append(")");
return result.toString();
}
/**
* Get the full description of this object.
*
* @return The full description.
*/
public String getFullDescription() {
StringBuilder result = new StringBuilder();
String name = getEntityName();
int urn = getURN();
result.append(name);
result.append(" [");
result.append(urn);
result.append("]");
result.append(" (");
result.append(id);
result.append(") [");
for (Iterator<Property> it = getProperties().iterator(); it.hasNext();) {
result.append(it.next().toString());
if (it.hasNext()) {
result.append(", ");
}
}
result.append("]");
return result.toString();
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof AbstractEntity) {
AbstractEntity a = (AbstractEntity) o;
return this.id.equals(a.id);
}
return false;
}
/**
* Get the name of this entity. Default implementation returns the entity URN.
*
* @return The name of this entity.
*/
protected String getEntityName() {
return this.getClass().getSimpleName();
}
/**
* Register a set of properties.
*
* @param props The properties to register.
*/
protected void registerProperties(Property... props) {
for (Property p : props) {
properties.add(p);
if (p instanceof AbstractProperty) {
((AbstractProperty) p).setEntity(this);
}
}
}
/**
* Notify all listeners that a property has changed.
*
* @param p The changed property.
* @param oldValue The old value.
* @param newValue The new value.
*/
protected void firePropertyChanged(Property p, Object oldValue, Object newValue) {
Collection<EntityListener> copy;
synchronized (listeners) {
copy = new HashSet<EntityListener>(listeners);
}
for (EntityListener next : copy) {
next.propertyChanged(this, p, oldValue, newValue);
}
}
@Override
public EntityProto toEntityProto() {
EntityProto.Builder builder = EntityProto.newBuilder().setEntityID(id.getValue()).setUrn(getURN());
for (Property next : getProperties()) {
if (next.isDefined()) {
builder.addProperties(next.toPropertyProto());
}
}
return builder.build();
}
@Override
public void fromEntityProto(EntityProto proto) {
for (PropertyProto propertyProto : proto.getPropertiesList()) {
Property prop = MsgProtoBuf.propertyProto2Property(propertyProto);
if (prop == null) {
continue;
}
Property existing = getProperty(prop.getURN());
existing.takeValue(prop);
}
}
} | 5,839 | 0.65542 | 0.652166 | 236 | 23.745762 | 20.902594 | 103 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.381356 | false | false | 6 |
4e21f93779439bf82d34f8876cf2fa8628560dc3 | 4,930,622,506,057 | 98651afefefaa343e169ef44a569cee202795ff1 | /gamerPong/src/pong/Comentario.java | 5154cdc0a2010c60cb9ae857f36aa441137a00c7 | [] | no_license | Tonyfilho/Atec | https://github.com/Tonyfilho/Atec | 5afe1a43ba47ad1001e9554c5e2c69be14210d28 | eb9e333d811409de3f3c1f5f7303de3d154681c7 | refs/heads/master | 2020-06-15T08:14:04.874000 | 2020-06-07T13:32:06 | 2020-06-07T13:32:06 | 195,245,720 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package pong;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Comentario {
/*
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyListener; implementa os eventos do teclado
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;*/
/**public class Game extends Canvas implements Runnable, KeyListener {
* public class Game extends Canvas implements Runnable , como estamos usando
* mais de um THREAD, precisamos usar o EXTEND RUNNABLE do JAVA
private static final long serialVersionUID = 1L;
public static int WIDTH = 240; // largura da janela
public static int HEIGHT = 120; // altura da janela
public static int SCALE = 3; // a escala do jogo
public BufferedImage layer = new BufferedImage(WIDTH*SCALE, HEIGHT*SCALE, BufferedImage.TYPE_INT_RGB);
cria a nossa LAYER para renderizamos.
public Player player; // instanciando o nosso objeto player da classe Player
public Game() { NOsso construtor
this.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
player = new Player(); // iniciando no objeto Player dentro do Construtor
}// fim do construtor
public static void main(String[] args) {
Game game = new Game(); instanciando a classe game
JFrame frame = new JFrame("Jogo Pong"); é o OBJETO do java para criar JANELAS
frame.setResizable(false); é para quando fecharmos o programa no X, eele párar o jogo
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Faz parte para fechar o programa
frame.add(game);
frame.pack();
frame.setVisible(true); o Metodo de janela, por padrão é FALSE, e por isto ele não aparece
frame.setLocationRelativeTo(null); para janela ficar no CENTRO da TELA
new Thread(game).start(); // chamando nossa THREAD que fica dentro dentro do GAME
}// fim do main
public void tick () {
}// fim do metodo tick
public void render() {
BufferStrategy bs = this.getBufferStrategy(); fazendo com que seja checado se há um BufferStrategy
if (bs == null) { // temos que criar o BufferStrategy, checar se EXITE e somente, depois ....
this.createBufferStrategy(3); darmos um RETURN no nosso metodo, é assim que funciona
return;
}// fim do if // depois de feito, ele passa a funcionar.
Graphics g = layer.getGraphics();instaciando nosso grafica, instanciando nosso objeto grafico, da nossa LAYER
player.render(g); mostrando o jogador
g = bs.getDrawGraphics();
g.drawImage(layer, 0, 0, WIDTH*SCALE, HEIGHT*SCALE, null); // chamando nossa layer
bs.show();// serve para MOSTRAR na tela o que foi redenrizado
}// fim do metodo render
public void run() { inicio do nosso GAMER LOOPING simples
while (true) {
tick(); // chamando o metodo tick
render();// chamando o metoso render
try { try /catch é obrigadorio em caso de erro de execução
Thread.sleep(1000/ 60); // colocando um time na redenrização 60FPS
} catch (InterruptedException e) {
e.printStackTrace();
}
}// fim do construtor run
}
@Override
public void keyTyped(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
}// fimd a classe
////////////******************************************//////////////////////////////
/** na classe GAMER
*
*
public class Player {
public void tick() {
Este metodo serve para cuidar da logica do jogo
}// fim da classe tick
public void render(Graphics g) {
este metodo serve para manipular o render
o Objeto Graphics é da classe AWT, é para controlarmos o nosso Grafico, e o g é a varriável
public int x, y; // são o eixos X e Y
public boolean right, left; // variaveis booleanas
public void tick() {
if(right) {
x++;
}// fim do if
else if(left) {
x--;
}// fim do else if
}// fim da classe tick
public void render(Graphics g) {
g.setColor(Color.blue); caracteristicas de cor do nosso jogador
g.fillRect(200, 120-10, 40, 10); caracteristicas de localização do nosso jogador
}// fim da cclasse render
* */
} | ISO-8859-1 | Java | 4,552 | java | Comentario.java | Java | [] | null | [] | package pong;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Comentario {
/*
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyListener; implementa os eventos do teclado
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;*/
/**public class Game extends Canvas implements Runnable, KeyListener {
* public class Game extends Canvas implements Runnable , como estamos usando
* mais de um THREAD, precisamos usar o EXTEND RUNNABLE do JAVA
private static final long serialVersionUID = 1L;
public static int WIDTH = 240; // largura da janela
public static int HEIGHT = 120; // altura da janela
public static int SCALE = 3; // a escala do jogo
public BufferedImage layer = new BufferedImage(WIDTH*SCALE, HEIGHT*SCALE, BufferedImage.TYPE_INT_RGB);
cria a nossa LAYER para renderizamos.
public Player player; // instanciando o nosso objeto player da classe Player
public Game() { NOsso construtor
this.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
player = new Player(); // iniciando no objeto Player dentro do Construtor
}// fim do construtor
public static void main(String[] args) {
Game game = new Game(); instanciando a classe game
JFrame frame = new JFrame("Jogo Pong"); é o OBJETO do java para criar JANELAS
frame.setResizable(false); é para quando fecharmos o programa no X, eele párar o jogo
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Faz parte para fechar o programa
frame.add(game);
frame.pack();
frame.setVisible(true); o Metodo de janela, por padrão é FALSE, e por isto ele não aparece
frame.setLocationRelativeTo(null); para janela ficar no CENTRO da TELA
new Thread(game).start(); // chamando nossa THREAD que fica dentro dentro do GAME
}// fim do main
public void tick () {
}// fim do metodo tick
public void render() {
BufferStrategy bs = this.getBufferStrategy(); fazendo com que seja checado se há um BufferStrategy
if (bs == null) { // temos que criar o BufferStrategy, checar se EXITE e somente, depois ....
this.createBufferStrategy(3); darmos um RETURN no nosso metodo, é assim que funciona
return;
}// fim do if // depois de feito, ele passa a funcionar.
Graphics g = layer.getGraphics();instaciando nosso grafica, instanciando nosso objeto grafico, da nossa LAYER
player.render(g); mostrando o jogador
g = bs.getDrawGraphics();
g.drawImage(layer, 0, 0, WIDTH*SCALE, HEIGHT*SCALE, null); // chamando nossa layer
bs.show();// serve para MOSTRAR na tela o que foi redenrizado
}// fim do metodo render
public void run() { inicio do nosso GAMER LOOPING simples
while (true) {
tick(); // chamando o metodo tick
render();// chamando o metoso render
try { try /catch é obrigadorio em caso de erro de execução
Thread.sleep(1000/ 60); // colocando um time na redenrização 60FPS
} catch (InterruptedException e) {
e.printStackTrace();
}
}// fim do construtor run
}
@Override
public void keyTyped(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) { // metodo implementados pelo KEYLISTENERS
// TODO Auto-generated method stub
}
}// fimd a classe
////////////******************************************//////////////////////////////
/** na classe GAMER
*
*
public class Player {
public void tick() {
Este metodo serve para cuidar da logica do jogo
}// fim da classe tick
public void render(Graphics g) {
este metodo serve para manipular o render
o Objeto Graphics é da classe AWT, é para controlarmos o nosso Grafico, e o g é a varriável
public int x, y; // são o eixos X e Y
public boolean right, left; // variaveis booleanas
public void tick() {
if(right) {
x++;
}// fim do if
else if(left) {
x--;
}// fim do else if
}// fim da classe tick
public void render(Graphics g) {
g.setColor(Color.blue); caracteristicas de cor do nosso jogador
g.fillRect(200, 120-10, 40, 10); caracteristicas de localização do nosso jogador
}// fim da cclasse render
* */
} | 4,552 | 0.70256 | 0.695719 | 148 | 29.628378 | 29.785786 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.858108 | false | false | 6 |
6b0d5805d3cf23b46193c5274ce21ba94c690887 | 15,857,019,288,463 | fea372e23fe13e6c9fdc696e65a5f55852db8202 | /aMediatorMechine/src/aMediatorMechine/Valve.java | 23adec2c97775f5d62fd3566ffadaeda4cd7c91d | [] | no_license | mbohekale/JavaDesignPattern | https://github.com/mbohekale/JavaDesignPattern | 72e61a5c65ace71ed9cc090db6e4325daa205482 | 14e64dcc0a70449c23e5b50e233cdf2fc45952c6 | refs/heads/main | 2023-02-20T05:10:20.309000 | 2021-01-21T17:39:18 | 2021-01-21T17:39:18 | 325,646,146 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aMediatorMechine;
public class Valve implements Colleague{
private MechineMediator mediator;
//public Valve() {}
@Override
public void setMediator(MechineMediator mediator) {
this.mediator=mediator;
}
public void open() {
System.out.println("Valve is opened......");
System.out.println("Filling in water......");
mediator.closed();
}
public void closed() {
System.out.println("Valve is closed......");
mediator.on();
}
}
| UTF-8 | Java | 478 | java | Valve.java | Java | [] | null | [] | package aMediatorMechine;
public class Valve implements Colleague{
private MechineMediator mediator;
//public Valve() {}
@Override
public void setMediator(MechineMediator mediator) {
this.mediator=mediator;
}
public void open() {
System.out.println("Valve is opened......");
System.out.println("Filling in water......");
mediator.closed();
}
public void closed() {
System.out.println("Valve is closed......");
mediator.on();
}
}
| 478 | 0.654812 | 0.654812 | 22 | 19.727272 | 17.493328 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.409091 | false | false | 6 |
b44dcbd135c6c34d151d8bb5730efe1b35f99923 | 19,816,979,140,989 | b42fd38fd3b0faac98a0c641847559858f742b22 | /HomeWAV/Source Code/Android App Version 2005007/sources/com/thoughtbot/expandablerecyclerview/listeners/GroupExpandCollapseListener.java | 3378bc4b71819781944e4b54a0a6a81ca13bd137 | [] | no_license | zuiaixiaobai/twilio-prison-video-visitation | https://github.com/zuiaixiaobai/twilio-prison-video-visitation | c8b300be9001c8b846ac4d1c1a46b3a720ee4f8a | c172ba4679b14e28d1922847309c3a86388c9957 | refs/heads/main | 2023-04-20T18:14:11.035000 | 2021-05-14T13:47:39 | 2021-05-14T13:47:39 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.thoughtbot.expandablerecyclerview.listeners;
import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup;
public interface GroupExpandCollapseListener {
void onGroupCollapsed(ExpandableGroup expandableGroup);
void onGroupExpanded(ExpandableGroup expandableGroup);
}
| UTF-8 | Java | 297 | java | GroupExpandCollapseListener.java | Java | [] | null | [] | package com.thoughtbot.expandablerecyclerview.listeners;
import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup;
public interface GroupExpandCollapseListener {
void onGroupCollapsed(ExpandableGroup expandableGroup);
void onGroupExpanded(ExpandableGroup expandableGroup);
}
| 297 | 0.855219 | 0.855219 | 9 | 32 | 28.879059 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 6 |
9eeb9a909c460ebabad7addb69b87e4420a4695b | 22,497,038,754,817 | 8979aaf20062a650b1be113689474de62aeb4285 | /src/main/java/nonapi/io/github/classgraph/fileslice/FileSlice.java | 11d8f0dd40c71a3ce0f67a0c2f7c6858d4072484 | [
"MIT"
] | permissive | liuyuanOUC/classgraph | https://github.com/liuyuanOUC/classgraph | 2812863ad55ed1351407b6e0f19f399ee38dcb48 | 876ddc04b0f7932c755bfd2738297da6a772fe7e | refs/heads/master | 2021-01-04T04:19:51.829000 | 2020-02-13T16:22:22 | 2020-02-13T16:22:22 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2020 Luke Hutchison
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nonapi.io.github.classgraph.fileslice;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessFileReader;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessReader;
import nonapi.io.github.classgraph.utils.FileUtils;
/** A {@link File} slice. */
public class FileSlice extends Slice {
/** The {@link File}. */
public final File file;
/** The {@link RandomAccessFile} opened on the {@link File}. */
public final RandomAccessFile raf;
private final FileChannel fileChannel;
private final long fileLength;
/** Constructor. */
private FileSlice(final FileSlice parentSlice, final long offset, final long length,
final boolean isDeflatedZipEntry, final long inflatedLengthHint,
final NestedJarHandler nestedJarHandler) {
super(parentSlice, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
this.file = parentSlice.file;
this.raf = parentSlice.raf;
this.fileChannel = parentSlice.fileChannel;
this.fileLength = parentSlice.fileLength;
}
/**
* Constructor.
*
* @throws IOException
* if the file cannot be opened.
*/
public FileSlice(final File file, final boolean isDeflatedZipEntry, final long inflatedLengthHint,
final NestedJarHandler nestedJarHandler) throws IOException {
super(file.length(), isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
this.file = file;
this.raf = nestedJarHandler.openFile(file);
this.fileChannel = raf.getChannel();
this.fileLength = file.length();
}
/**
* Constructor.
*
* @throws IOException
* if the file cannot be opened.
*/
public FileSlice(final File file, final NestedJarHandler nestedJarHandler) throws IOException {
this(file, /* isDeflatedZipEntry = */ false, /* inflatedSizeHint = */ 0L, nestedJarHandler);
}
@Override
public Slice slice(final long offset, final long length, final boolean isDeflatedZipEntry,
final long inflatedLengthHint) {
if (this.isDeflatedZipEntry) {
throw new IllegalArgumentException("Cannot slice a deflated zip entry");
}
return new FileSlice(this, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
}
/** Read directly from FileChannel (slow path, but handles >2GB). */
@Override
public RandomAccessReader randomAccessReader() {
return new RandomAccessFileReader(fileChannel, sliceStartPos, sliceLength);
}
@Override
public byte[] load() throws IOException {
if (isDeflatedZipEntry) {
// Deflate into RAM if necessary
try (InputStream inputStream = open()) {
return NestedJarHandler.readAllBytesAsArray(inputStream, inflatedLengthHint);
}
} else {
if (sliceLength > FileUtils.MAX_BUFFER_SIZE) {
throw new IOException("File is larger than 2GB");
}
final RandomAccessReader reader = randomAccessReader();
final byte[] content = new byte[(int) sliceLength];
if (reader.read(sliceStartPos, content, 0, content.length) < content.length) {
// Should not happen
throw new IOException("File is truncated");
}
return content;
}
}
// TODO: could make load() and read() mmap the file to MappedByteBuffers
}
| UTF-8 | Java | 5,019 | java | FileSlice.java | Java | [
{
"context": "\n * This file is part of ClassGraph.\n *\n * Author: Luke Hutchison\n *\n * Hosted at: https://github.com/classgraph/cl",
"end": 67,
"score": 0.9998648762702942,
"start": 53,
"tag": "NAME",
"value": "Luke Hutchison"
},
{
"context": "\n * The MIT License (MIT)\n *\n * C... | null | [] | /*
* This file is part of ClassGraph.
*
* Author: <NAME>
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
* EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
package nonapi.io.github.classgraph.fileslice;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import nonapi.io.github.classgraph.fastzipfilereader.NestedJarHandler;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessFileReader;
import nonapi.io.github.classgraph.fileslice.reader.RandomAccessReader;
import nonapi.io.github.classgraph.utils.FileUtils;
/** A {@link File} slice. */
public class FileSlice extends Slice {
/** The {@link File}. */
public final File file;
/** The {@link RandomAccessFile} opened on the {@link File}. */
public final RandomAccessFile raf;
private final FileChannel fileChannel;
private final long fileLength;
/** Constructor. */
private FileSlice(final FileSlice parentSlice, final long offset, final long length,
final boolean isDeflatedZipEntry, final long inflatedLengthHint,
final NestedJarHandler nestedJarHandler) {
super(parentSlice, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
this.file = parentSlice.file;
this.raf = parentSlice.raf;
this.fileChannel = parentSlice.fileChannel;
this.fileLength = parentSlice.fileLength;
}
/**
* Constructor.
*
* @throws IOException
* if the file cannot be opened.
*/
public FileSlice(final File file, final boolean isDeflatedZipEntry, final long inflatedLengthHint,
final NestedJarHandler nestedJarHandler) throws IOException {
super(file.length(), isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
this.file = file;
this.raf = nestedJarHandler.openFile(file);
this.fileChannel = raf.getChannel();
this.fileLength = file.length();
}
/**
* Constructor.
*
* @throws IOException
* if the file cannot be opened.
*/
public FileSlice(final File file, final NestedJarHandler nestedJarHandler) throws IOException {
this(file, /* isDeflatedZipEntry = */ false, /* inflatedSizeHint = */ 0L, nestedJarHandler);
}
@Override
public Slice slice(final long offset, final long length, final boolean isDeflatedZipEntry,
final long inflatedLengthHint) {
if (this.isDeflatedZipEntry) {
throw new IllegalArgumentException("Cannot slice a deflated zip entry");
}
return new FileSlice(this, offset, length, isDeflatedZipEntry, inflatedLengthHint, nestedJarHandler);
}
/** Read directly from FileChannel (slow path, but handles >2GB). */
@Override
public RandomAccessReader randomAccessReader() {
return new RandomAccessFileReader(fileChannel, sliceStartPos, sliceLength);
}
@Override
public byte[] load() throws IOException {
if (isDeflatedZipEntry) {
// Deflate into RAM if necessary
try (InputStream inputStream = open()) {
return NestedJarHandler.readAllBytesAsArray(inputStream, inflatedLengthHint);
}
} else {
if (sliceLength > FileUtils.MAX_BUFFER_SIZE) {
throw new IOException("File is larger than 2GB");
}
final RandomAccessReader reader = randomAccessReader();
final byte[] content = new byte[(int) sliceLength];
if (reader.read(sliceStartPos, content, 0, content.length) < content.length) {
// Should not happen
throw new IOException("File is truncated");
}
return content;
}
}
// TODO: could make load() and read() mmap the file to MappedByteBuffers
}
| 5,003 | 0.687986 | 0.686392 | 126 | 38.833332 | 34.606117 | 111 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.722222 | false | false | 6 |
f089d15eda01fc13905c8bcefb4e381b1d3c7bf3 | 3,882,650,477,494 | 947419735f3360227115c632c17ff7f495bed701 | /Project-7/SportStacker2Test.java | f98f6d3e90fc7eaa54c57e7e02c0930c037dcf97 | [] | no_license | WalterConway/COMP-1210 | https://github.com/WalterConway/COMP-1210 | af27b4bb2b5b9664d4b09f2f379af502ba3a6066 | 19a700d94f962b2fdb0ef482e3ddac11214d7b0b | refs/heads/master | 2016-09-10T23:08:30.050000 | 2015-01-02T03:13:35 | 2015-01-02T03:13:35 | 28,702,137 | 7 | 5 | null | null | null | null | null | null | null | null | null | null | null | null | null | import org.junit.Assert;
import org.junit.Test;
/**
* Test the SportStacker2 class for bugs.
* @author Walter James Conway
* @version 10/19/2012
*/
public class SportStacker2Test {
/**
getName, getTimes, getNumTimesRecorded,
toString, addTime, increaseSize, removeSlowestTime, findFastestTime
computeAvgTime, computeMedianTime, findSlowestTime.
*/
/** Test for the return of the correct name. **/
@Test public void nameTest()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals("Sami", s1.getName());
}
/** Test to see if the two arrays have the same values. **/
@Test public void timesTest()
{
double[] testArray = {4.5, 6.5, 6.0, 7.2, 6.3};
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(java.util.Arrays.toString(testArray),
java.util.Arrays.toString(s1.getTimes()));
}
/** Test to see if the array length matches.**/
@Test public void howManyInList()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(5, s1.getNumTimesRecorded());
}
/** makes sure the toString method is correct.**/
@Test public void toStringTest()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean out1 = s1.toString().contains("Sport Stacker Name: Sami");
boolean out2 = s1.toString().contains("Times: 4.5 6.5 6.0 7.2 6.3");
boolean out3 = s1.toString().contains("Average Time: 6.10");
boolean out4 = s1.toString().contains("Median Time: 6.30");
boolean out5 = s1.toString().contains("Fastest Time: 4.50");
boolean out6 = s1.toString().contains("Slowest Time: 7.20");
boolean out7 = s1.toString().contains("Player Count:");
Assert.assertTrue(out1
&& out2 && out3 && out4 && out5 && out6 && out7);
}
/** test to see if the array list increased by one element. **/
@Test public void addATime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
s1.addTime(5.9);
Assert.assertEquals(6, s1.getNumTimesRecorded());
}
/** Test to see if a empty element existed. **/
@Test public void increaseTheSize()
{
SportStacker2 s1 = new
SportStacker2("Sami", 1, 4.5);
s1.increaseSize();
boolean zeroElement = java.util.Arrays.toString(s1.getTimes())
.contains("0.0");
Assert.assertTrue(zeroElement);
}
/**
* checks to see if the result is correct
* and if the array contains the slowest time.
**/
@Test public void removeTheSlowestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean check = (7.2 == s1.removeSlowestTime()
&& !(java.util.Arrays.toString(s1.getTimes()).contains("7.2")));
Assert.assertTrue(check);
}
/**
* checks to see if the result is correct
* and if the array contains the slowest time.
**/
@Test public void removeTheSlowestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.removeSlowestTime()
&& !(java.util.Arrays.toString(s1.getTimes()).contains("0.0")));
Assert.assertTrue(check);
}
/** checks to see if the result is the fastest. **/
@Test public void findTheFastestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 2, 0.0, 0.0, 6.0, 7.2, 0.0);
boolean check = (6.0 == s1.findFastestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is Zero. **/
@Test public void findTheFastestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.findFastestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is the slowest. **/
@Test public void findTheSlowestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean check = (7.2 == s1.findSlowestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is the zero. **/
@Test public void findTheSlowestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.findSlowestTime());
Assert.assertTrue(check);
}
/** checks to see the average is correct. **/
@Test public void computeTheAvgTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 4, 4.5, 6.5, 6.0, 7.2, 0.0);
Assert.assertEquals(6.05, s1.computeAvgTime(), 0.01);
}
/** checks to see the average is correct. **/
@Test public void computeTheAvgTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
Assert.assertEquals(0.0, s1.computeAvgTime(), 0.01);
}
/** checks to see if the median is right for the zero list. **/
@Test public void computeTheMedianTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
Assert.assertEquals(0.0, s1.computeMedianTime(), 0.01);
}
/** checks to see if the median is right for the odd number. **/
@Test public void computeTheMedianTimeOdd()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(6.30, s1.computeMedianTime(), 0.01);
}
/** checks to see if the median is right for the even number. **/
@Test public void computeTheMedianTimeEven()
{
SportStacker2 s1 = new
SportStacker2("Sami", 6, 4.5, 6.5, 6.0, 7.2, 6.3, 2.2);
Assert.assertEquals(6.15, s1.computeMedianTime(), 0.01);
}
/** checks to see if the count is set to 0. **/
@Test public void setCount()
{
SportStacker2 s1 = new SportStacker2("Sami", 5, 4.5, 6.5,
6.0, 7.2, 6.3);
s1.resetPlayerCount();
Assert.assertEquals(0, s1.getPlayerCount());
}
/**
* checks to see if the count of how many sport
* stackers have been created is correct.
**/
@Test public void getCount()
{
SportStacker2 s1 = new SportStacker2("Sami", 5, 4.5, 6.5,
6.0, 7.2, 6.3);
Assert.assertEquals(1, s1.getPlayerCount());
}
}
| UTF-8 | Java | 7,104 | java | SportStacker2Test.java | Java | [
{
"context": "\tTest the SportStacker2 class for bugs.\n*\t@author\tWalter James Conway\n*\t@version 10/19/2012\n*/\n public class SportSta",
"end": 129,
"score": 0.9998246431350708,
"start": 110,
"tag": "NAME",
"value": "Walter James Conway"
},
{
"context": "SportStacker2 s1 = new... | null | [] | import org.junit.Assert;
import org.junit.Test;
/**
* Test the SportStacker2 class for bugs.
* @author <NAME>
* @version 10/19/2012
*/
public class SportStacker2Test {
/**
getName, getTimes, getNumTimesRecorded,
toString, addTime, increaseSize, removeSlowestTime, findFastestTime
computeAvgTime, computeMedianTime, findSlowestTime.
*/
/** Test for the return of the correct name. **/
@Test public void nameTest()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals("Sami", s1.getName());
}
/** Test to see if the two arrays have the same values. **/
@Test public void timesTest()
{
double[] testArray = {4.5, 6.5, 6.0, 7.2, 6.3};
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(java.util.Arrays.toString(testArray),
java.util.Arrays.toString(s1.getTimes()));
}
/** Test to see if the array length matches.**/
@Test public void howManyInList()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(5, s1.getNumTimesRecorded());
}
/** makes sure the toString method is correct.**/
@Test public void toStringTest()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean out1 = s1.toString().contains("Sport Stacker Name: Sami");
boolean out2 = s1.toString().contains("Times: 4.5 6.5 6.0 7.2 6.3");
boolean out3 = s1.toString().contains("Average Time: 6.10");
boolean out4 = s1.toString().contains("Median Time: 6.30");
boolean out5 = s1.toString().contains("Fastest Time: 4.50");
boolean out6 = s1.toString().contains("Slowest Time: 7.20");
boolean out7 = s1.toString().contains("Player Count:");
Assert.assertTrue(out1
&& out2 && out3 && out4 && out5 && out6 && out7);
}
/** test to see if the array list increased by one element. **/
@Test public void addATime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
s1.addTime(5.9);
Assert.assertEquals(6, s1.getNumTimesRecorded());
}
/** Test to see if a empty element existed. **/
@Test public void increaseTheSize()
{
SportStacker2 s1 = new
SportStacker2("Sami", 1, 4.5);
s1.increaseSize();
boolean zeroElement = java.util.Arrays.toString(s1.getTimes())
.contains("0.0");
Assert.assertTrue(zeroElement);
}
/**
* checks to see if the result is correct
* and if the array contains the slowest time.
**/
@Test public void removeTheSlowestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean check = (7.2 == s1.removeSlowestTime()
&& !(java.util.Arrays.toString(s1.getTimes()).contains("7.2")));
Assert.assertTrue(check);
}
/**
* checks to see if the result is correct
* and if the array contains the slowest time.
**/
@Test public void removeTheSlowestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.removeSlowestTime()
&& !(java.util.Arrays.toString(s1.getTimes()).contains("0.0")));
Assert.assertTrue(check);
}
/** checks to see if the result is the fastest. **/
@Test public void findTheFastestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 2, 0.0, 0.0, 6.0, 7.2, 0.0);
boolean check = (6.0 == s1.findFastestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is Zero. **/
@Test public void findTheFastestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.findFastestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is the slowest. **/
@Test public void findTheSlowestTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
boolean check = (7.2 == s1.findSlowestTime());
Assert.assertTrue(check);
}
/** checks to see if the result is the zero. **/
@Test public void findTheSlowestTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
boolean check = (0.0 == s1.findSlowestTime());
Assert.assertTrue(check);
}
/** checks to see the average is correct. **/
@Test public void computeTheAvgTime()
{
SportStacker2 s1 = new
SportStacker2("Sami", 4, 4.5, 6.5, 6.0, 7.2, 0.0);
Assert.assertEquals(6.05, s1.computeAvgTime(), 0.01);
}
/** checks to see the average is correct. **/
@Test public void computeTheAvgTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
Assert.assertEquals(0.0, s1.computeAvgTime(), 0.01);
}
/** checks to see if the median is right for the zero list. **/
@Test public void computeTheMedianTimeZero()
{
double[] timesInList = {};
SportStacker2 s1 = new SportStacker2("Sami", 0, timesInList);
Assert.assertEquals(0.0, s1.computeMedianTime(), 0.01);
}
/** checks to see if the median is right for the odd number. **/
@Test public void computeTheMedianTimeOdd()
{
SportStacker2 s1 = new
SportStacker2("Sami", 5, 4.5, 6.5, 6.0, 7.2, 6.3);
Assert.assertEquals(6.30, s1.computeMedianTime(), 0.01);
}
/** checks to see if the median is right for the even number. **/
@Test public void computeTheMedianTimeEven()
{
SportStacker2 s1 = new
SportStacker2("Sami", 6, 4.5, 6.5, 6.0, 7.2, 6.3, 2.2);
Assert.assertEquals(6.15, s1.computeMedianTime(), 0.01);
}
/** checks to see if the count is set to 0. **/
@Test public void setCount()
{
SportStacker2 s1 = new SportStacker2("Sami", 5, 4.5, 6.5,
6.0, 7.2, 6.3);
s1.resetPlayerCount();
Assert.assertEquals(0, s1.getPlayerCount());
}
/**
* checks to see if the count of how many sport
* stackers have been created is correct.
**/
@Test public void getCount()
{
SportStacker2 s1 = new SportStacker2("Sami", 5, 4.5, 6.5,
6.0, 7.2, 6.3);
Assert.assertEquals(1, s1.getPlayerCount());
}
}
| 7,091 | 0.555462 | 0.506334 | 204 | 33.808823 | 23.958046 | 77 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.142157 | false | false | 6 |
c03e6d0680c4ba425d85a60e92ca07838e8ede93 | 11,046,655,936,215 | 3345dc3d0c2860c07d06e8dd09b4a571c2fb23a1 | /src/main/java/springmvc/java/domain/Product.java | 1627d6f402fb8567aeba4ecd2fd3cf9289ec195e | [] | no_license | anirudhreddy18/springmvc-java-config | https://github.com/anirudhreddy18/springmvc-java-config | f1e5d34bf07bb4d35c39b112c7535d9d1966390f | af84c4b4fbc63358de0a3edcce6692cc6c0afe7c | refs/heads/master | 2020-04-03T18:47:11.385000 | 2018-11-05T01:00:45 | 2018-11-05T01:00:45 | 155,497,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package springmvc.java.domain;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "product")
public class Product {
@Id
@Column(name = "productId" , nullable = false)
private Long productId;
@Column(name = "productName", nullable = false)
private String productName;
@Column(name = "productCost", nullable = false)
private double productCost;
@Column(name = "productDescription")
private String productDescription;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "categoryId", nullable = false)
private Category category;
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getProductCost() {
return productCost;
}
public void setProductCost(double productCost) {
this.productCost = productCost;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
}
| UTF-8 | Java | 1,385 | java | Product.java | Java | [] | null | [] | package springmvc.java.domain;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "product")
public class Product {
@Id
@Column(name = "productId" , nullable = false)
private Long productId;
@Column(name = "productName", nullable = false)
private String productName;
@Column(name = "productCost", nullable = false)
private double productCost;
@Column(name = "productDescription")
private String productDescription;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "categoryId", nullable = false)
private Category category;
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public double getProductCost() {
return productCost;
}
public void setProductCost(double productCost) {
this.productCost = productCost;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
}
| 1,385 | 0.761011 | 0.761011 | 64 | 20.640625 | 18.24432 | 63 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.15625 | false | false | 6 |
3685cc2ba01aeada94e0b2f88a4ee81d9807c3b3 | 17,334,488,054,854 | d17d6c0208591622e5d76082604b249a2943a3dd | /src/main/java/io/pivotal/cfapp/controller/DbmsOnlyPoliciesController.java | 95cbac678aee3517eeceeec17ebd52175059434a | [
"Apache-2.0"
] | permissive | pacphi/cf-butler | https://github.com/pacphi/cf-butler | a9ca8a1520dc417c12a6447b67eaed96561c96b4 | 0b7afe39ca8f1a26b20293fb9082d6f469020260 | refs/heads/main | 2023-08-22T13:30:54.507000 | 2023-08-21T15:27:08 | 2023-08-21T15:27:08 | 164,013,366 | 37 | 21 | Apache-2.0 | false | 2023-09-08T12:44:39 | 2019-01-03T19:18:15 | 2023-07-25T13:31:30 | 2023-09-08T12:44:38 | 1,358 | 33 | 14 | 5 | Java | false | false | package io.pivotal.cfapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.pivotal.cfapp.domain.Policies;
import io.pivotal.cfapp.service.PoliciesService;
import io.pivotal.cfapp.util.DbmsOnlyCondition;
import reactor.core.publisher.Mono;
@RestController
@Conditional(DbmsOnlyCondition.class)
public class DbmsOnlyPoliciesController {
private final PoliciesService policiesService;
@Autowired
public DbmsOnlyPoliciesController(
PoliciesService policiesService) {
this.policiesService = policiesService;
}
@DeleteMapping("/policies")
public Mono<ResponseEntity<Void>> deleteAllPolicies() {
return policiesService.deleteAll()
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/application/{id}")
public Mono<ResponseEntity<Void>> deleteApplicationPolicy(@PathVariable String id) {
return policiesService.deleteApplicationPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/endpoint/{id}")
public Mono<ResponseEntity<Void>> deleteEndpointPolicy(@PathVariable String id) {
return policiesService.deleteEndpointPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/hygiene/{id}")
public Mono<ResponseEntity<Void>> deleteHygienePolicy(@PathVariable String id) {
return policiesService.deleteHygienePolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/resourcenotification/{id}")
public Mono<ResponseEntity<Void>> deleteResourceNotificationPolicy(@PathVariable String id) {
return policiesService.deleteResourceNotificationPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/legacy/{id}")
public Mono<ResponseEntity<Void>> deleteLegacyPolicy(@PathVariable String id) {
return policiesService.deleteLegacyPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/query/{id}")
public Mono<ResponseEntity<Void>> deleteQueryPolicy(@PathVariable String id) {
return policiesService.deleteQueryPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/serviceInstance/{id}")
public Mono<ResponseEntity<Void>> deleteServiceInstancePolicy(@PathVariable String id) {
return policiesService.deleteServiceInstancePolicyById(id)
.map(ResponseEntity::ok);
}
@PostMapping("/policies")
public Mono<ResponseEntity<Policies>> establishPolicies(@RequestBody Policies policies) {
return policiesService.save(policies)
.map(ResponseEntity::ok);
}
}
| UTF-8 | Java | 3,135 | java | DbmsOnlyPoliciesController.java | Java | [] | null | [] | package io.pivotal.cfapp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Conditional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.pivotal.cfapp.domain.Policies;
import io.pivotal.cfapp.service.PoliciesService;
import io.pivotal.cfapp.util.DbmsOnlyCondition;
import reactor.core.publisher.Mono;
@RestController
@Conditional(DbmsOnlyCondition.class)
public class DbmsOnlyPoliciesController {
private final PoliciesService policiesService;
@Autowired
public DbmsOnlyPoliciesController(
PoliciesService policiesService) {
this.policiesService = policiesService;
}
@DeleteMapping("/policies")
public Mono<ResponseEntity<Void>> deleteAllPolicies() {
return policiesService.deleteAll()
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/application/{id}")
public Mono<ResponseEntity<Void>> deleteApplicationPolicy(@PathVariable String id) {
return policiesService.deleteApplicationPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/endpoint/{id}")
public Mono<ResponseEntity<Void>> deleteEndpointPolicy(@PathVariable String id) {
return policiesService.deleteEndpointPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/hygiene/{id}")
public Mono<ResponseEntity<Void>> deleteHygienePolicy(@PathVariable String id) {
return policiesService.deleteHygienePolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/resourcenotification/{id}")
public Mono<ResponseEntity<Void>> deleteResourceNotificationPolicy(@PathVariable String id) {
return policiesService.deleteResourceNotificationPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/legacy/{id}")
public Mono<ResponseEntity<Void>> deleteLegacyPolicy(@PathVariable String id) {
return policiesService.deleteLegacyPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/query/{id}")
public Mono<ResponseEntity<Void>> deleteQueryPolicy(@PathVariable String id) {
return policiesService.deleteQueryPolicyById(id)
.map(ResponseEntity::ok);
}
@DeleteMapping("/policies/serviceInstance/{id}")
public Mono<ResponseEntity<Void>> deleteServiceInstancePolicy(@PathVariable String id) {
return policiesService.deleteServiceInstancePolicyById(id)
.map(ResponseEntity::ok);
}
@PostMapping("/policies")
public Mono<ResponseEntity<Policies>> establishPolicies(@RequestBody Policies policies) {
return policiesService.save(policies)
.map(ResponseEntity::ok);
}
}
| 3,135 | 0.730144 | 0.730144 | 83 | 36.771084 | 27.899702 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.289157 | false | false | 6 |
de17a75a3ef8e321df13af4dcf5c0863923c2bec | 1,975,685,012,212 | 26ca189d7454920c74e99a0fc806666be2cb0af5 | /spring/src/test/java/spring/condition/MagicBeanCoditionTest.java | 683b9836de50d7f1058153b5b66d75be1c49566e | [
"Apache-2.0"
] | permissive | codemonkeykings/study | https://github.com/codemonkeykings/study | d319a45a121fadc17b551373238d9a51339d5642 | a024692920339507bdd78b79e4cff8553a644f59 | refs/heads/master | 2021-01-22T18:58:56.825000 | 2017-05-29T13:32:59 | 2017-05-29T13:32:59 | 85,146,389 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package spring.condition;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import spring.config.MagicBeanConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MagicBeanConfig.class)
public class MagicBeanCoditionTest {
@Autowired
private MagicBean bean;
//MagicExistsCondition.class 中mantch方法返回false时
@Test
public void beanCouldBeNull() {
assertNotNull(bean);
}
@Test
public void beanCouldNotNull() {
assertNotNull(bean);
}
}
| GB18030 | Java | 756 | java | MagicBeanCoditionTest.java | Java | [] | null | [] | package spring.condition;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import spring.config.MagicBeanConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MagicBeanConfig.class)
public class MagicBeanCoditionTest {
@Autowired
private MagicBean bean;
//MagicExistsCondition.class 中mantch方法返回false时
@Test
public void beanCouldBeNull() {
assertNotNull(bean);
}
@Test
public void beanCouldNotNull() {
assertNotNull(bean);
}
}
| 756 | 0.776882 | 0.772849 | 31 | 22 | 21.24815 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.83871 | false | false | 6 |
2355300474ced795888a86af87840b1e955a9367 | 1,125,281,488,675 | 95c9ef2afa0ac4fcd545c226c37bbc89890b588c | /beca/lib/src/main/java/beca/TareaArrays.java | 5ab1392cce3f5fb09ad55b01d332e1527acab9f0 | [] | no_license | cjofrevi/CursoIntensivoJava | https://github.com/cjofrevi/CursoIntensivoJava | ba0f5dcda4a27c9ee4e76dc551527045d80ae5e2 | d2d5081fde452bf7c56a83cc305234e18712299a | refs/heads/main | 2023-06-03T16:14:12.151000 | 2021-06-21T15:32:37 | 2021-06-21T15:32:37 | 377,663,034 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package beca;
public class TareaArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("lista del 1 al 100: ");
for (int i : arregloCien()) {
System.out.println(i);
}
System.out.println("lista de los primeros 100 pares: ");
int[] array = arregloPares();
for (int i = 0; i < 10; i++) {
System.out.println(array[i]);
}
System.out.println("piramide de n lineas: ");
arregloPiramide(8);
}
public static int[] arregloCien() {
int[] array = new int[100];
for (int i = 0; i < 100; i++) {
array[i] = i + 1;
}
return array;
}
public static int[] arregloPares() {
int[] array = new int[100];
int indice = 0;
int numero = 0;
while (indice < array.length) {
if (numero % 2 == 0) {
array[indice] = numero;
indice++;
}
numero++;
}
return array;
}
public static void arregloPiramide(int lineas) {
String[] array = new String[lineas];
int count = 1;
for (int i = 0; i < array.length; i++) {
int ini = 0;
String linea = "";
while (ini <= i) {
linea = linea + ", " + count;
count++;
ini++;
}
linea = linea.substring(2);
linea = "[" + i + "]: " + linea;
array[i] = linea;
}
for (String linea : array) {
System.out.println(linea);
}
}
}
| UTF-8 | Java | 1,306 | java | TareaArrays.java | Java | [] | null | [] | package beca;
public class TareaArrays {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("lista del 1 al 100: ");
for (int i : arregloCien()) {
System.out.println(i);
}
System.out.println("lista de los primeros 100 pares: ");
int[] array = arregloPares();
for (int i = 0; i < 10; i++) {
System.out.println(array[i]);
}
System.out.println("piramide de n lineas: ");
arregloPiramide(8);
}
public static int[] arregloCien() {
int[] array = new int[100];
for (int i = 0; i < 100; i++) {
array[i] = i + 1;
}
return array;
}
public static int[] arregloPares() {
int[] array = new int[100];
int indice = 0;
int numero = 0;
while (indice < array.length) {
if (numero % 2 == 0) {
array[indice] = numero;
indice++;
}
numero++;
}
return array;
}
public static void arregloPiramide(int lineas) {
String[] array = new String[lineas];
int count = 1;
for (int i = 0; i < array.length; i++) {
int ini = 0;
String linea = "";
while (ini <= i) {
linea = linea + ", " + count;
count++;
ini++;
}
linea = linea.substring(2);
linea = "[" + i + "]: " + linea;
array[i] = linea;
}
for (String linea : array) {
System.out.println(linea);
}
}
}
| 1,306 | 0.56585 | 0.542879 | 74 | 16.648649 | 15.6994 | 58 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.135135 | false | false | 6 |
3bb0e752431b0afc5a5ae2d0ff0802e4f8c62d45 | 30,416,958,457,363 | 68327a264a1d53f3ca7169de00777c8dadcf9776 | /test/src/main/java/org/axonframework/test/aggregate/ResultValidator.java | 84ed448cf09c7f6e8b31f01cf65ed5cd2d526f92 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-unknown"
] | permissive | nagyist/AxonFramework | https://github.com/nagyist/AxonFramework | 03c0f9d4f059b3f7cd50323bfe85fbd33765f46b | d92f72af86e6a6304a46b229bb83cc67225ca32d | refs/heads/master | 2023-09-01T02:22:50.326000 | 2023-08-28T03:02:07 | 2023-08-28T03:02:07 | 21,167,278 | 0 | 0 | Apache-2.0 | true | 2023-09-11T19:36:58 | 2014-06-24T14:14:25 | 2022-12-17T05:48:02 | 2023-09-11T19:36:57 | 41,002 | 0 | 0 | 1 | Java | false | false | /*
* Copyright (c) 2010-2022. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.test.aggregate;
import org.axonframework.commandhandling.CommandResultMessage;
import org.axonframework.deadline.DeadlineMessage;
import org.axonframework.eventhandling.EventMessage;
import org.hamcrest.Matcher;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.function.Consumer;
/**
* Interface describing the operations available on the "validate result" (a.k.a. "then") stage of the test execution.
* The underlying fixture expects a test to have been executed successfully using a {@link TestExecutor}.
* <p>
* There are several things to validate:<ul><li>the published events,<li>the stored events, and<li>the command handler's
* execution result, which is one of <ul><li>a regular return value,<li>a {@code void} return value, or<li>an
* exception.</ul></ul>
*
* @param <T> The type of Aggregate under test
* @author Allard Buijze
* @since 0.6
*/
public interface ResultValidator<T> {
/**
* Expect the given set of events to have been published.
* <p>
* All events are compared for equality using a shallow equals comparison on all the fields of the events. This
* means that all assigned values on the events' fields should have a proper equals implementation.
* <p>
* Note that the event identifier is ignored in the comparison.
*
* @param expectedEvents The expected events, in the exact order they are expected to be dispatched and stored.
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEvents(Object... expectedEvents);
/**
* Expect the given set of events to have been published.
* <p>
* All events are compared for equality using a shallow equals comparison on all the fields of the events. This
* means that all assigned values on the events' fields should have a proper equals implementation.<br/>
* Additionally the metadata will be compared too.
* <p>
* Note that the event identifier is ignored in the comparison.
*
* @param expectedEvents The expected events, in the exact order they are expected to be dispatched and stored.
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEvents(EventMessage<?>... expectedEvents);
/**
* Expect no events to have been published from the command.
*
* @return the current ResultValidator, for fluent interfacing
*/
default ResultValidator<T> expectNoEvents() {
return expectEvents();
}
/**
* Expect the published events to match the given {@code matcher}.
* <p>
* Note: if no events were published, the matcher receives an empty List.
*
* @param matcher The matcher to match with the actually published events
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEventsMatching(Matcher<? extends List<? super EventMessage<?>>> matcher);
/**
* Expect the command handler to return the given {@code expectedPayload} after execution. The actual and expected
* values are compared using their equals methods.
*
* @param expectedPayload The expected result message payload of the command execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessagePayload(Object expectedPayload);
/**
* Expect the command handler to return a payload that matches the given {@code matcher} after execution.
*
* @param matcher The matcher to verify the actual return value against
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessagePayloadMatching(Matcher<?> matcher);
/**
* Expect the command handler to return the given {@code expectedResultMessage} after execution. The actual and
* expected values are compared using their equals methods.
* <p>
* Comparison is done on message payload and meta data.
* </p>
*
* @param expectedResultMessage The expected result message of the command execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessage(CommandResultMessage<?> expectedResultMessage);
/**
* Expect the command handler to return a value that matches the given {@code matcher} after execution.
*
* @param matcher The matcher to verify the actual result message against
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessageMatching(Matcher<? super CommandResultMessage<?>> matcher);
/**
* Expect an exception message to occur during command handler execution that matches with the given {@code
* matcher}.
*
* @param matcher The matcher to validate the actual exception message
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionMessage(Matcher<?> matcher);
/**
* Expect the given {@code exceptionMessage} to occur during command handler execution. The actual exception message
* should be exactly the same as {@code exceptionMessage}.
*
* @param exceptionMessage The exception message expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionMessage(String exceptionMessage);
/**
* Expect the given {@code expectedException} to occur during command handler execution. The actual exception should
* be exactly of that type, subclasses are not accepted.
*
* @param expectedException The type of exception expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectException(Class<? extends Throwable> expectedException);
/**
* Expect an exception to occur during command handler execution that matches with the given {@code matcher}.
*
* @param matcher The matcher to validate the actual exception
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectException(Matcher<?> matcher);
/**
* Expect the given {@code exceptionDetails} to occur during command handler execution. The actual exception details
* should be exactly the same as {@code exceptionDetails}.
*
* @param exceptionDetails The exception details expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Object exceptionDetails);
/**
* Expect the given {@code exceptionDetails} type to occur during command handler execution. The actual exception details
* should be exactly of that type, subclasses are not accepted.
*
* @param exceptionDetails The type of exception details expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Class<?> exceptionDetails);
/**
* Expect exception details to occur during command handler execution that matches with the given {@code
* matcher}.
*
* @param matcher The matcher to validate the actual exception details
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Matcher<?> matcher);
/**
* Expect a successful execution of the given command handler, regardless of the actual return value.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectSuccessfulHandlerExecution();
/**
* Provides access the the state of the Aggregate as it was stored in the repository, allowing for validation of the
* state of the aggregate, as it was left in the repository.
* <p>
* Note that validating state on Event Sourced Aggregate is highly discouraged. Event Sourced aggregates should
* measure behavior exclusively by measuring emitted events.
*
* @param aggregateStateValidator a consumer that is provided with the aggregate instance, allowing it to make
* assertions based on the aggregate's state.
* @return the current ResultValidator, for fluent interfacing
* @throws IllegalStateException when an error in Command execution caused the Unit of Work to be rolled back.
*/
ResultValidator<T> expectState(Consumer<T> aggregateStateValidator);
/**
* Asserts that a deadline scheduled after given {@code duration} matches the given {@code matcher}.
*
* @param duration the delay expected before the deadline is met
* @param matcher the matcher that must match with the deadline scheduled at the given time
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineMatching(Duration duration, Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that a deadline equal to the given {@code deadline} has been scheduled after the given {@code duration}.
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param duration the time to wait before the deadline should be met
* @param deadline the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadline(Duration duration, Object deadline);
/**
* Asserts that a deadline of the given {@code deadlineType} has been scheduled after the given {@code duration}.
*
* @param duration the time to wait before the deadline is met
* @param deadlineType the type of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineOfType(Duration duration, Class<?> deadlineType);
/**
* Asserts that a deadline with the given {@code deadlineName} has been scheduled after the given {@code duration}.
*
* @param duration the time to wait before the deadline is met
* @param deadlineName the name of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineWithName(Duration duration, String deadlineName);
/**
* Asserts that a deadline matching the given {@code matcher} has been scheduled at the given {@code
* scheduledTime}.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
*
* @param scheduledTime the time at which the deadline should be met
* @param matcher the matcher defining the deadline expected
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineMatching(Instant scheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that a deadline equal to the given {@code deadline} has been scheduled at the given {@code
* scheduledTime}.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadline the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadline(Instant scheduledTime, Object deadline);
/**
* Asserts that a deadline of the given {@code deadlineType} has been scheduled at the given {@code scheduledTime}.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadlineType the type of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineOfType(Instant scheduledTime, Class<?> deadlineType);
/**
* Asserts that a deadline with the given {@code deadlineName} has been scheduled at the given {@code
* scheduledTime}.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadlineName the name of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineWithName(Instant scheduledTime, String deadlineName);
/**
* Asserts that no deadlines are scheduled. This means that either no deadlines were scheduled at all, all schedules
* have been cancelled or all scheduled deadlines have been met already.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlines();
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} is scheduled. Can be used to validate if a
* deadline has never been set or has been canceled.
*
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} should be scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Duration durationToScheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Duration durationToScheduledTime, Object deadline);
/**
* Asserts that <b>no</b> deadline of the given {@code deadlineType} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Duration durationToScheduledTime, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Duration durationToScheduledTime, String deadlineName);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
*
* @param scheduledTime the time at which no deadline matching the given {@code matcher} should be scheduled
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Instant scheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param scheduledTime the time at which no deadline equal to the given {@code deadline} should be scheduled
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Instant scheduledTime, Object deadline);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineType} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
*
* @param scheduledTime the time at which no deadline of {@code deadlineType} should be scheduled
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Instant scheduledTime, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
*
* @param scheduledTime the time at which no deadline of {@code deadlineName} should be scheduled
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Instant scheduledTime, String deadlineName);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} has been scheduled between the {@code to} and {@code from} times, where {@code to} and
* {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Instant from, Instant to, Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Instant from, Instant to, Object deadline);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineType} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Instant from, Instant to, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Instant from, Instant to, String deadlineName);
/**
* Asserts that deadlines matching the given {@code matcher} have been met (which have passed in time) on this aggregate.
*
* @param matcher The matcher that defines the expected list of deadlines
* @return the current ResultValidator, for fluent interfacing
* @deprecated in favor of {@link #expectTriggeredDeadlinesMatching(Matcher)}
*/
@Deprecated
ResultValidator<T> expectDeadlinesMetMatching(Matcher<? extends List<? super DeadlineMessage<?>>> matcher);
/**
* Asserts that deadlines matching the given {@code matcher} have been triggered for this aggregate.
*
* @param matcher the matcher that defines the expected list of deadlines
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesMatching(Matcher<? extends List<? super DeadlineMessage<?>>> matcher);
/**
* Asserts that given {@code expected} deadlines have been met (which have passed in time). Deadlines are compared
* comparing their type and fields using "equals".
*
* @param expected The sequence of deadlines expected to be met
* @return the current ResultValidator, for fluent interfacing
* @deprecated in favor of {@link #expectTriggeredDeadlines(Object...)}
*/
@Deprecated
ResultValidator<T> expectDeadlinesMet(Object... expected);
/**
* Asserts that given {@code expected} deadlines have been triggered. Deadlines are compared by their type
* and fields using "equals".
*
* @param expected the sequence of deadlines expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlines(Object... expected);
/**
* Asserts that the given {@code expectedDeadlineNames} have been triggered. Matches that the given names are
* complete, in the same order and match the triggered deadlines by validating with {@link
* DeadlineMessage#getDeadlineName()}.
*
* @param expectedDeadlineNames the sequence of deadline names expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesWithName(String... expectedDeadlineNames);
/**
* Asserts that the given {@code expectedDeadlineTypes} have been triggered. Matches that the given types are
* complete, in the same order and match the triggered deadlines by validating with {@link
* DeadlineMessage#getPayloadType()}.
*
* @param expectedDeadlineTypes the sequence of deadline types expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesOfType(Class<?>... expectedDeadlineTypes);
/**
* Asserts that the Aggregate has been marked for deletion.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectMarkedDeleted();
/**
* Asserts that the Aggregate has NOT been marked for deletion.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNotMarkedDeleted();
}
| UTF-8 | Java | 27,355 | java | ResultValidator.java | Java | [
{
"context": "am <T> The type of Aggregate under test\n * @author Allard Buijze\n * @since 0.6\n */\npublic interface ResultValidato",
"end": 1526,
"score": 0.9998903274536133,
"start": 1513,
"tag": "NAME",
"value": "Allard Buijze"
}
] | null | [] | /*
* Copyright (c) 2010-2022. Axon Framework
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.axonframework.test.aggregate;
import org.axonframework.commandhandling.CommandResultMessage;
import org.axonframework.deadline.DeadlineMessage;
import org.axonframework.eventhandling.EventMessage;
import org.hamcrest.Matcher;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
import java.util.function.Consumer;
/**
* Interface describing the operations available on the "validate result" (a.k.a. "then") stage of the test execution.
* The underlying fixture expects a test to have been executed successfully using a {@link TestExecutor}.
* <p>
* There are several things to validate:<ul><li>the published events,<li>the stored events, and<li>the command handler's
* execution result, which is one of <ul><li>a regular return value,<li>a {@code void} return value, or<li>an
* exception.</ul></ul>
*
* @param <T> The type of Aggregate under test
* @author <NAME>
* @since 0.6
*/
public interface ResultValidator<T> {
/**
* Expect the given set of events to have been published.
* <p>
* All events are compared for equality using a shallow equals comparison on all the fields of the events. This
* means that all assigned values on the events' fields should have a proper equals implementation.
* <p>
* Note that the event identifier is ignored in the comparison.
*
* @param expectedEvents The expected events, in the exact order they are expected to be dispatched and stored.
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEvents(Object... expectedEvents);
/**
* Expect the given set of events to have been published.
* <p>
* All events are compared for equality using a shallow equals comparison on all the fields of the events. This
* means that all assigned values on the events' fields should have a proper equals implementation.<br/>
* Additionally the metadata will be compared too.
* <p>
* Note that the event identifier is ignored in the comparison.
*
* @param expectedEvents The expected events, in the exact order they are expected to be dispatched and stored.
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEvents(EventMessage<?>... expectedEvents);
/**
* Expect no events to have been published from the command.
*
* @return the current ResultValidator, for fluent interfacing
*/
default ResultValidator<T> expectNoEvents() {
return expectEvents();
}
/**
* Expect the published events to match the given {@code matcher}.
* <p>
* Note: if no events were published, the matcher receives an empty List.
*
* @param matcher The matcher to match with the actually published events
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectEventsMatching(Matcher<? extends List<? super EventMessage<?>>> matcher);
/**
* Expect the command handler to return the given {@code expectedPayload} after execution. The actual and expected
* values are compared using their equals methods.
*
* @param expectedPayload The expected result message payload of the command execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessagePayload(Object expectedPayload);
/**
* Expect the command handler to return a payload that matches the given {@code matcher} after execution.
*
* @param matcher The matcher to verify the actual return value against
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessagePayloadMatching(Matcher<?> matcher);
/**
* Expect the command handler to return the given {@code expectedResultMessage} after execution. The actual and
* expected values are compared using their equals methods.
* <p>
* Comparison is done on message payload and meta data.
* </p>
*
* @param expectedResultMessage The expected result message of the command execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessage(CommandResultMessage<?> expectedResultMessage);
/**
* Expect the command handler to return a value that matches the given {@code matcher} after execution.
*
* @param matcher The matcher to verify the actual result message against
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectResultMessageMatching(Matcher<? super CommandResultMessage<?>> matcher);
/**
* Expect an exception message to occur during command handler execution that matches with the given {@code
* matcher}.
*
* @param matcher The matcher to validate the actual exception message
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionMessage(Matcher<?> matcher);
/**
* Expect the given {@code exceptionMessage} to occur during command handler execution. The actual exception message
* should be exactly the same as {@code exceptionMessage}.
*
* @param exceptionMessage The exception message expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionMessage(String exceptionMessage);
/**
* Expect the given {@code expectedException} to occur during command handler execution. The actual exception should
* be exactly of that type, subclasses are not accepted.
*
* @param expectedException The type of exception expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectException(Class<? extends Throwable> expectedException);
/**
* Expect an exception to occur during command handler execution that matches with the given {@code matcher}.
*
* @param matcher The matcher to validate the actual exception
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectException(Matcher<?> matcher);
/**
* Expect the given {@code exceptionDetails} to occur during command handler execution. The actual exception details
* should be exactly the same as {@code exceptionDetails}.
*
* @param exceptionDetails The exception details expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Object exceptionDetails);
/**
* Expect the given {@code exceptionDetails} type to occur during command handler execution. The actual exception details
* should be exactly of that type, subclasses are not accepted.
*
* @param exceptionDetails The type of exception details expected from the command handler execution
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Class<?> exceptionDetails);
/**
* Expect exception details to occur during command handler execution that matches with the given {@code
* matcher}.
*
* @param matcher The matcher to validate the actual exception details
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectExceptionDetails(Matcher<?> matcher);
/**
* Expect a successful execution of the given command handler, regardless of the actual return value.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectSuccessfulHandlerExecution();
/**
* Provides access the the state of the Aggregate as it was stored in the repository, allowing for validation of the
* state of the aggregate, as it was left in the repository.
* <p>
* Note that validating state on Event Sourced Aggregate is highly discouraged. Event Sourced aggregates should
* measure behavior exclusively by measuring emitted events.
*
* @param aggregateStateValidator a consumer that is provided with the aggregate instance, allowing it to make
* assertions based on the aggregate's state.
* @return the current ResultValidator, for fluent interfacing
* @throws IllegalStateException when an error in Command execution caused the Unit of Work to be rolled back.
*/
ResultValidator<T> expectState(Consumer<T> aggregateStateValidator);
/**
* Asserts that a deadline scheduled after given {@code duration} matches the given {@code matcher}.
*
* @param duration the delay expected before the deadline is met
* @param matcher the matcher that must match with the deadline scheduled at the given time
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineMatching(Duration duration, Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that a deadline equal to the given {@code deadline} has been scheduled after the given {@code duration}.
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param duration the time to wait before the deadline should be met
* @param deadline the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadline(Duration duration, Object deadline);
/**
* Asserts that a deadline of the given {@code deadlineType} has been scheduled after the given {@code duration}.
*
* @param duration the time to wait before the deadline is met
* @param deadlineType the type of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineOfType(Duration duration, Class<?> deadlineType);
/**
* Asserts that a deadline with the given {@code deadlineName} has been scheduled after the given {@code duration}.
*
* @param duration the time to wait before the deadline is met
* @param deadlineName the name of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineWithName(Duration duration, String deadlineName);
/**
* Asserts that a deadline matching the given {@code matcher} has been scheduled at the given {@code
* scheduledTime}.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
*
* @param scheduledTime the time at which the deadline should be met
* @param matcher the matcher defining the deadline expected
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineMatching(Instant scheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that a deadline equal to the given {@code deadline} has been scheduled at the given {@code
* scheduledTime}.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadline the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadline(Instant scheduledTime, Object deadline);
/**
* Asserts that a deadline of the given {@code deadlineType} has been scheduled at the given {@code scheduledTime}.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadlineType the type of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineOfType(Instant scheduledTime, Class<?> deadlineType);
/**
* Asserts that a deadline with the given {@code deadlineName} has been scheduled at the given {@code
* scheduledTime}.
*
* @param scheduledTime the time at which the deadline is scheduled
* @param deadlineName the name of the expected deadline
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectScheduledDeadlineWithName(Instant scheduledTime, String deadlineName);
/**
* Asserts that no deadlines are scheduled. This means that either no deadlines were scheduled at all, all schedules
* have been cancelled or all scheduled deadlines have been met already.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlines();
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} is scheduled. Can be used to validate if a
* deadline has never been set or has been canceled.
*
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} should be scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Duration durationToScheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Duration durationToScheduledTime, Object deadline);
/**
* Asserts that <b>no</b> deadline of the given {@code deadlineType} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Duration durationToScheduledTime, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled after the given {@code
* durationToScheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an
* <b>exact</b> moment in time.
*
* @param durationToScheduledTime the time to wait until the trigger point of the deadline which should not be
* scheduled
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Duration durationToScheduledTime, String deadlineName);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
*
* @param scheduledTime the time at which no deadline matching the given {@code matcher} should be scheduled
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Instant scheduledTime,
Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
* <p/>
* If the {@code scheduledTime} is calculated based on the "current time", use the {@link
* TestExecutor#currentTime()} to get the time to use as "current time".
* <p/>
* Note that the source attribute of the deadline is ignored when comparing deadlines. Deadlines are compared using
* an "equals" check on all fields in the deadlines.
*
* @param scheduledTime the time at which no deadline equal to the given {@code deadline} should be scheduled
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Instant scheduledTime, Object deadline);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineType} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
*
* @param scheduledTime the time at which no deadline of {@code deadlineType} should be scheduled
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Instant scheduledTime, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled at the given {@code
* scheduledTime}. Can be used to validate if a deadline has never been set or has been canceled at an exact moment
* in time.
*
* @param scheduledTime the time at which no deadline of {@code deadlineName} should be scheduled
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Instant scheduledTime, String deadlineName);
/**
* Asserts that <b>no</b> deadline matching the given {@code matcher} has been scheduled between the {@code to} and {@code from} times, where {@code to} and
* {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param matcher the matcher defining the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineMatching(Instant from, Instant to, Matcher<? super DeadlineMessage<?>> matcher);
/**
* Asserts that <b>no</b> deadline equal to the given {@code deadline} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadline the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadline(Instant from, Instant to, Object deadline);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineType} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadlineType the type of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineOfType(Instant from, Instant to, Class<?> deadlineType);
/**
* Asserts that <b>no</b> deadline with the given {@code deadlineName} has been scheduled between the {@code to} and {@code from} times, where {@code to}
* and {@code from} are inclusive. Can be used to validate if a deadline has never been set or has been canceled within a given timeframe.
*
* @param from the time from which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param to the time until which no deadline equal to the given {@code deadline} should be scheduled (inclusive)
* @param deadlineName the name of the deadline which should not be scheduled
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNoScheduledDeadlineWithName(Instant from, Instant to, String deadlineName);
/**
* Asserts that deadlines matching the given {@code matcher} have been met (which have passed in time) on this aggregate.
*
* @param matcher The matcher that defines the expected list of deadlines
* @return the current ResultValidator, for fluent interfacing
* @deprecated in favor of {@link #expectTriggeredDeadlinesMatching(Matcher)}
*/
@Deprecated
ResultValidator<T> expectDeadlinesMetMatching(Matcher<? extends List<? super DeadlineMessage<?>>> matcher);
/**
* Asserts that deadlines matching the given {@code matcher} have been triggered for this aggregate.
*
* @param matcher the matcher that defines the expected list of deadlines
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesMatching(Matcher<? extends List<? super DeadlineMessage<?>>> matcher);
/**
* Asserts that given {@code expected} deadlines have been met (which have passed in time). Deadlines are compared
* comparing their type and fields using "equals".
*
* @param expected The sequence of deadlines expected to be met
* @return the current ResultValidator, for fluent interfacing
* @deprecated in favor of {@link #expectTriggeredDeadlines(Object...)}
*/
@Deprecated
ResultValidator<T> expectDeadlinesMet(Object... expected);
/**
* Asserts that given {@code expected} deadlines have been triggered. Deadlines are compared by their type
* and fields using "equals".
*
* @param expected the sequence of deadlines expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlines(Object... expected);
/**
* Asserts that the given {@code expectedDeadlineNames} have been triggered. Matches that the given names are
* complete, in the same order and match the triggered deadlines by validating with {@link
* DeadlineMessage#getDeadlineName()}.
*
* @param expectedDeadlineNames the sequence of deadline names expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesWithName(String... expectedDeadlineNames);
/**
* Asserts that the given {@code expectedDeadlineTypes} have been triggered. Matches that the given types are
* complete, in the same order and match the triggered deadlines by validating with {@link
* DeadlineMessage#getPayloadType()}.
*
* @param expectedDeadlineTypes the sequence of deadline types expected to have been triggered
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectTriggeredDeadlinesOfType(Class<?>... expectedDeadlineTypes);
/**
* Asserts that the Aggregate has been marked for deletion.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectMarkedDeleted();
/**
* Asserts that the Aggregate has NOT been marked for deletion.
*
* @return the current ResultValidator, for fluent interfacing
*/
ResultValidator<T> expectNotMarkedDeleted();
}
| 27,348 | 0.70594 | 0.705429 | 535 | 50.13084 | 44.092911 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.293458 | false | false | 6 |
f2b8a77e8cabe61fd38facc187b9f2502e188e05 | 24,799,141,232,848 | 437855198d140e7b45a1f1e453d856bc54ab8b45 | /app/src/main/java/cav/pdst/ui/activity/SportsmanDetailActivity.java | b6496fcde1c9780d561f166818e3b2e025026339 | [
"Apache-2.0"
] | permissive | CavInc/PDANDSt | https://github.com/CavInc/PDANDSt | 3abe2182de29bac9050c24a38eccf2f2f7cf59f5 | 17da5d94e1c81f5c85aa56a110863be8ee241fcb | refs/heads/master | 2021-01-01T04:38:36.815000 | 2018-03-29T09:03:19 | 2018-03-29T09:03:19 | 97,217,790 | 0 | 0 | Apache-2.0 | false | 2018-03-28T09:46:46 | 2017-07-14T09:34:19 | 2017-07-14T09:35:27 | 2018-03-28T09:46:45 | 973 | 0 | 0 | 0 | Java | false | null | package cav.pdst.ui.activity;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import cav.pdst.R;
import cav.pdst.data.managers.DataManager;
import cav.pdst.data.models.AbonementModel;
import cav.pdst.data.models.SportsmanModel;
import cav.pdst.ui.fragments.SpAbonementFragment;
import cav.pdst.ui.fragments.SpInfoFragment;
import cav.pdst.ui.fragments.SpTrainingFragment;
import cav.pdst.utils.ConstantManager;
public class SportsmanDetailActivity extends AppCompatActivity implements SpInfoFragment.Callbacks,
SpAbonementFragment.AbonementCallback {
private static final String TAG = "SPDETAIL";
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private SportsmanModel mSportsmanModel;
private AbonementModel mAbonementModel;
private int mode;
private DataManager mDataManager;
private int sp_id = -1;
private Menu mMenu;
private boolean return_flg = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sportsman_detail);
mDataManager = DataManager.getInstance();
mode = getIntent().getIntExtra(ConstantManager.MODE_SP_DETAIL,ConstantManager.NEW_SPORTSMAN);
if ((mode == ConstantManager.EDIT_SPORTSMAN) || (mode == ConstantManager.VIEW_SPORTSMAN)) {
mSportsmanModel = getIntent().getParcelableExtra(ConstantManager.SP_DETAIL_DATA);
sp_id = mSportsmanModel.getId();
}
if (mode == ConstantManager.ALARM_SPORTSMAN){
return_flg = true;
if (getIntent().getIntExtra(ConstantManager.MODE_RETURN_SP,0)==ConstantManager.RETURN_IN_BACK) {
return_flg = false;
}
mSportsmanModel = mDataManager.getSportsman(getIntent().getIntExtra(ConstantManager.ALARM_ID,-1));
sp_id = mSportsmanModel.getId();
mode = ConstantManager.VIEW_SPORTSMAN;
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
setupToolBar();
}
private void setupToolBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar!=null && mode != ConstantManager.NEW_SPORTSMAN){
toolbar.setTitle(mSportsmanModel.getName());
}
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.all_save_menu, menu);
if (mode == ConstantManager.VIEW_SPORTSMAN) {
mMenu.findItem(R.id.save_item).setVisible(false);
mMenu.findItem(R.id.edit_tr_item).setVisible(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home){
mDataManager.getDB().delAbonement();
onBackPressed();
}
if (item.getItemId() == R.id.save_item) {
saveData();
setResult(RESULT_OK,null);
onBackPressed();
}
if (item.getItemId() == R.id.edit_tr_item) {
mMenu.findItem(R.id.save_item).setVisible(true);
mMenu.findItem(R.id.edit_tr_item).setVisible(false);
mode = ConstantManager.EDIT_SPORTSMAN;
switch (mViewPager.getCurrentItem()){
case 0:
//((SpInfoFragment) mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem())).setMode(mode);
break;
case 2:
break;
}
return false;
}
return true;
}
@Override
public void onBackPressed() {
//saveData();
super.onBackPressed();
if (return_flg) {
Intent intent = new Intent(this,SportsmanActivity.class);
startActivity(intent);
}
}
@Override
public void updateData(SportsmanModel model) {
mSportsmanModel=model;
}
private void saveData(){
if (mode == ConstantManager.VIEW_SPORTSMAN) return;
if (mSportsmanModel.getName().length()!=0){
if (mode == ConstantManager.NEW_SPORTSMAN) {
mDataManager.addSportsman(mSportsmanModel);
} else if (mode == ConstantManager.EDIT_SPORTSMAN) {
mDataManager.updateSportsman(mSportsmanModel);
}
}else{
mDataManager.getDB().delAbonement();
}
}
@Override
public void updateData(AbonementModel model) {
mAbonementModel = model;
}
//
// FragmentPagerAdapter FragmentStatePagerAdapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return SpInfoFragment.newInstance(mSportsmanModel,mode);
case 1:
return SpTrainingFragment.newInstanse(sp_id);
case 2:
return SpAbonementFragment.newInstance(mSportsmanModel,mode);
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Инфо";
case 1:
return "Тренировки";
case 2:
return "Абонементы";
}
return null;
}
}
}
| UTF-8 | Java | 6,722 | java | SportsmanDetailActivity.java | Java | [] | null | [] | package cav.pdst.ui.activity;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import cav.pdst.R;
import cav.pdst.data.managers.DataManager;
import cav.pdst.data.models.AbonementModel;
import cav.pdst.data.models.SportsmanModel;
import cav.pdst.ui.fragments.SpAbonementFragment;
import cav.pdst.ui.fragments.SpInfoFragment;
import cav.pdst.ui.fragments.SpTrainingFragment;
import cav.pdst.utils.ConstantManager;
public class SportsmanDetailActivity extends AppCompatActivity implements SpInfoFragment.Callbacks,
SpAbonementFragment.AbonementCallback {
private static final String TAG = "SPDETAIL";
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
private SportsmanModel mSportsmanModel;
private AbonementModel mAbonementModel;
private int mode;
private DataManager mDataManager;
private int sp_id = -1;
private Menu mMenu;
private boolean return_flg = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sportsman_detail);
mDataManager = DataManager.getInstance();
mode = getIntent().getIntExtra(ConstantManager.MODE_SP_DETAIL,ConstantManager.NEW_SPORTSMAN);
if ((mode == ConstantManager.EDIT_SPORTSMAN) || (mode == ConstantManager.VIEW_SPORTSMAN)) {
mSportsmanModel = getIntent().getParcelableExtra(ConstantManager.SP_DETAIL_DATA);
sp_id = mSportsmanModel.getId();
}
if (mode == ConstantManager.ALARM_SPORTSMAN){
return_flg = true;
if (getIntent().getIntExtra(ConstantManager.MODE_RETURN_SP,0)==ConstantManager.RETURN_IN_BACK) {
return_flg = false;
}
mSportsmanModel = mDataManager.getSportsman(getIntent().getIntExtra(ConstantManager.ALARM_ID,-1));
sp_id = mSportsmanModel.getId();
mode = ConstantManager.VIEW_SPORTSMAN;
}
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
setupToolBar();
}
private void setupToolBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar!=null && mode != ConstantManager.NEW_SPORTSMAN){
toolbar.setTitle(mSportsmanModel.getName());
}
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar!=null){
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
mMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.all_save_menu, menu);
if (mode == ConstantManager.VIEW_SPORTSMAN) {
mMenu.findItem(R.id.save_item).setVisible(false);
mMenu.findItem(R.id.edit_tr_item).setVisible(true);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home){
mDataManager.getDB().delAbonement();
onBackPressed();
}
if (item.getItemId() == R.id.save_item) {
saveData();
setResult(RESULT_OK,null);
onBackPressed();
}
if (item.getItemId() == R.id.edit_tr_item) {
mMenu.findItem(R.id.save_item).setVisible(true);
mMenu.findItem(R.id.edit_tr_item).setVisible(false);
mode = ConstantManager.EDIT_SPORTSMAN;
switch (mViewPager.getCurrentItem()){
case 0:
//((SpInfoFragment) mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem())).setMode(mode);
break;
case 2:
break;
}
return false;
}
return true;
}
@Override
public void onBackPressed() {
//saveData();
super.onBackPressed();
if (return_flg) {
Intent intent = new Intent(this,SportsmanActivity.class);
startActivity(intent);
}
}
@Override
public void updateData(SportsmanModel model) {
mSportsmanModel=model;
}
private void saveData(){
if (mode == ConstantManager.VIEW_SPORTSMAN) return;
if (mSportsmanModel.getName().length()!=0){
if (mode == ConstantManager.NEW_SPORTSMAN) {
mDataManager.addSportsman(mSportsmanModel);
} else if (mode == ConstantManager.EDIT_SPORTSMAN) {
mDataManager.updateSportsman(mSportsmanModel);
}
}else{
mDataManager.getDB().delAbonement();
}
}
@Override
public void updateData(AbonementModel model) {
mAbonementModel = model;
}
//
// FragmentPagerAdapter FragmentStatePagerAdapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return SpInfoFragment.newInstance(mSportsmanModel,mode);
case 1:
return SpTrainingFragment.newInstanse(sp_id);
case 2:
return SpAbonementFragment.newInstance(mSportsmanModel,mode);
}
return null;
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Инфо";
case 1:
return "Тренировки";
case 2:
return "Абонементы";
}
return null;
}
}
}
| 6,722 | 0.625411 | 0.622425 | 209 | 31.047848 | 25.429472 | 114 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.497608 | false | false | 6 |
becf55be4f27ed8803a05f6031cf449abebd86b2 | 19,361,712,630,167 | eedf6bb19ee4c42872ff422a8132db227a9eafa5 | /Assignment4/src/com/main/OopExercise.java | 9e3aa75cde72cc551d2ace9053a92befa8ef6aeb | [] | no_license | Nmahimaraj/day1 | https://github.com/Nmahimaraj/day1 | 05a2ba5b65108dc559909954ee660d699feb2ea8 | c7f1a4f652020c274156e459f76fa3e0d72a6738 | refs/heads/master | 2023-03-22T11:24:03.516000 | 2021-02-20T13:00:06 | 2021-02-20T13:00:06 | 340,639,007 | 1 | 1 | null | false | 2021-03-11T04:39:05 | 2021-02-20T11:33:57 | 2021-02-20T13:00:22 | 2021-02-20T13:00:20 | 17 | 0 | 1 | 1 | Java | false | false | package com.main;
import com.model.A;
public class OopExercise {
public static void main(String[] args) {
A objA = new A();
System.out.println("in main():");
System.out.println("objA.a = "+objA.getA());
objA.setA(222);
}
}
| UTF-8 | Java | 279 | java | OopExercise.java | Java | [] | null | [] | package com.main;
import com.model.A;
public class OopExercise {
public static void main(String[] args) {
A objA = new A();
System.out.println("in main():");
System.out.println("objA.a = "+objA.getA());
objA.setA(222);
}
}
| 279 | 0.544803 | 0.53405 | 17 | 15.411765 | 17.667048 | 54 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.705882 | false | false | 6 |
5345e3fa6bd2cc1b0f040cf76cdc758ec46badeb | 18,056,042,575,401 | 6334cf242d6207b066a97f56a35d442e5920fe32 | /Mensaje.java | e0aaffeda55390f020b811ef3d8fd67726908958 | [] | no_license | dubanortiz/Mensajeria-Android- | https://github.com/dubanortiz/Mensajeria-Android- | 666193dbbce74d59974d152436c7c50e261b33d8 | 158f226569b98589743d49468be226d2481a7d3d | refs/heads/master | 2019-02-02T09:37:12.714000 | 2017-08-06T02:45:29 | 2017-08-06T02:45:29 | 99,455,095 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package com.example.dubanortiz.mensajeriaudla;
import org.ksoap2.serialization.SoapObject;
import java.util.ArrayList;
/**
* Created by dubanortiz on 30/11/2016.
*/
public class Mensaje {
public int codigo_mensaje;
public String msg;
public Persona usuario;
Deserilization obj=new Deserilization();
public ArrayList<Mensaje> children;
public Mensaje(SoapObject object){
obj.SoapDeserilize(this,object);
}
public Mensaje(){
}
public Mensaje(int codigo_mensaje, Persona usuario, String msg) {
this.codigo_mensaje = codigo_mensaje;
this.msg = msg;
this.usuario = usuario;
}
}
| UTF-8 | Java | 670 | java | Mensaje.java | Java | [
{
"context": "t;\n\nimport java.util.ArrayList;\n\n/**\n * Created by dubanortiz on 30/11/2016.\n */\n\npublic class Mensaje {\n\n\n\n ",
"end": 152,
"score": 0.9996957778930664,
"start": 142,
"tag": "USERNAME",
"value": "dubanortiz"
}
] | null | [] |
package com.example.dubanortiz.mensajeriaudla;
import org.ksoap2.serialization.SoapObject;
import java.util.ArrayList;
/**
* Created by dubanortiz on 30/11/2016.
*/
public class Mensaje {
public int codigo_mensaje;
public String msg;
public Persona usuario;
Deserilization obj=new Deserilization();
public ArrayList<Mensaje> children;
public Mensaje(SoapObject object){
obj.SoapDeserilize(this,object);
}
public Mensaje(){
}
public Mensaje(int codigo_mensaje, Persona usuario, String msg) {
this.codigo_mensaje = codigo_mensaje;
this.msg = msg;
this.usuario = usuario;
}
}
| 670 | 0.670149 | 0.656716 | 38 | 16.552631 | 19.034176 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.394737 | false | false | 6 |
0596bc2d6c704b4de18fe8e3c0678e6c1d275d94 | 12,824,772,402,468 | fa9a8a850fe4d1f76d09d9bdaacd97dcb004731e | /pofu-admin/src/main/java/cn/jixunsoft/taoke/service/impl/MImagesServiceImpl.java | 0d667d1220eaca2ae23163d81401f4528a41e2a5 | [] | no_license | shinobi-x/common-business-backend-RESTful | https://github.com/shinobi-x/common-business-backend-RESTful | 3c3af847e1f5ee972c75152d502c711a0dff7b34 | f727bb69ce0451c611bab9a1271894891dd870c5 | refs/heads/master | 2020-02-06T02:03:26.953000 | 2017-08-07T02:07:10 | 2017-08-07T02:07:10 | 98,142,511 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cn.jixunsoft.taoke.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.print.attribute.standard.RequestingUserName;
import org.springframework.stereotype.Service;
import cn.jixunsoft.taoke.dao.MImagesMapper;
import cn.jixunsoft.taoke.model.MImages;
import cn.jixunsoft.taoke.service.MImagesService;
/**
* MImages Service 实现类
*
* @author CodeGenerator
*
* @date 2017-04-19 11:24:43
*/
@Service("mImagesService")
public class MImagesServiceImpl implements MImagesService {
@Resource
private MImagesMapper mImagesMapper;
@Override
public Integer getMImageCountByMId(Long mId) {
return mImagesMapper.getMImageCountByMId(mId);
}
@Override
public void saveBatch(List<MImages> mImageList) {
mImagesMapper.saveBatch(mImageList);
}
@Override
public List<MImages> deleteByMId(Long mId) {
return mImagesMapper.deleteByMId(mId);
}
@Override
public List<MImages> getMImageListByMId(Long mId) {
return mImagesMapper.getMImageListByMId(mId);
}
}
| UTF-8 | Java | 1,088 | java | MImagesServiceImpl.java | Java | [
{
"context": "ervice;\n\n/**\n * MImages Service 实现类\n * \n * @author CodeGenerator\n * \n * @date 2017-04-19 11:24:43\n */\n@Service(\"mI",
"end": 399,
"score": 0.9992122054100037,
"start": 386,
"tag": "USERNAME",
"value": "CodeGenerator"
}
] | null | [] | package cn.jixunsoft.taoke.service.impl;
import java.util.List;
import javax.annotation.Resource;
import javax.print.attribute.standard.RequestingUserName;
import org.springframework.stereotype.Service;
import cn.jixunsoft.taoke.dao.MImagesMapper;
import cn.jixunsoft.taoke.model.MImages;
import cn.jixunsoft.taoke.service.MImagesService;
/**
* MImages Service 实现类
*
* @author CodeGenerator
*
* @date 2017-04-19 11:24:43
*/
@Service("mImagesService")
public class MImagesServiceImpl implements MImagesService {
@Resource
private MImagesMapper mImagesMapper;
@Override
public Integer getMImageCountByMId(Long mId) {
return mImagesMapper.getMImageCountByMId(mId);
}
@Override
public void saveBatch(List<MImages> mImageList) {
mImagesMapper.saveBatch(mImageList);
}
@Override
public List<MImages> deleteByMId(Long mId) {
return mImagesMapper.deleteByMId(mId);
}
@Override
public List<MImages> getMImageListByMId(Long mId) {
return mImagesMapper.getMImageListByMId(mId);
}
}
| 1,088 | 0.731054 | 0.718115 | 47 | 22.021276 | 20.984787 | 59 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.276596 | false | false | 6 |
3a81ab4e806f6840d5857d6a879c04d14996148b | 12,163,347,449,650 | 2a50916b4fc905454f66628115c0033ff2471954 | /app/src/main/java/com/bidex/app/MainActivity.java | 81ac92769953c6cb39c11efd7ab8c324b4388a21 | [] | no_license | jihopark/bidex-android | https://github.com/jihopark/bidex-android | d0aab2f998834a8d23cf50302428a75a503d20ea | 27e38e4d699682f1e37b808bc98faf2f28cd1420 | refs/heads/master | 2020-04-05T23:44:25.541000 | 2015-03-28T06:50:13 | 2015-03-28T06:50:13 | 32,621,026 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bidex.app;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public static ParseObject currentUser = null;
private static boolean parseIsNotInitialized = true;
private ParseObject deal;
private int currentBid;
private RelativeLayout bidButton;
private ListView _commentListView;
private CommentListAdapter commentListAdapter;
private TextView dealTitle,totalBidder,topBidNumber, topBidUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_commentListView = (ListView) findViewById(R.id.comments_list);
commentListAdapter = new CommentListAdapter(MainActivity.this, getSampleComments());
_commentListView.setAdapter(commentListAdapter);
bidButton = (RelativeLayout) findViewById(R.id.bid_button);
dealTitle = (TextView) findViewById(R.id.deal_title);
totalBidder = (TextView) findViewById(R.id.total_bidder_number);
topBidNumber = (TextView) findViewById(R.id.top_bid_number);
topBidUser = (TextView) findViewById(R.id.top_bidder_id);
setBidButton();
// setTimer(null);
setDB();
}
private void setDB(){
Log.d("MainActivity/setDB","Set DB");
if (parseIsNotInitialized) {
Parse.enableLocalDatastore(this);
Parse.initialize(this, "8y2Ma1EO394oPIoyEqVIBXFhtBmGjMQYjXfDm9od", "ftK0rwjfMgai0KxoXBvsbr9GYgr952Kq8TndWi0o");
parseIsNotInitialized = false;
}
ParseQuery<ParseObject> query = ParseQuery.getQuery("Deal");
query.getInBackground("z17eDDD5bc", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
Log.d("MainActivity/done","parse "+ object.getString("title"));
deal = object;
setTimer(deal.getDate("dealEndTime"));
dealTitle.setText(object.getString("title"));
setUpBid();
// setUpInitialBids(deal);
} else {
// something went wrong
}
}
});
}
private void setUpBid(){
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Bid");
query2.whereEqualTo("bid_for", deal);
query2.addDescendingOrder("amount");
query2.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> bidList, ParseException e) {
if (e == null) {
Log.d("MainActivity/done", "Total Bidder " + bidList.size());
totalBidder.setText(""+bidList.size());
if (bidList.size()!=0) {
currentBid = bidList.get(0).getInt("amount");
topBidNumber.setText("$" + bidList.get(0).getInt("amount"));
bidList.get(0).getParseObject("bid_by").fetchInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject parseObject, ParseException e) {
topBidUser.setText("" + parseObject.getString("userid"));
}
});
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
private void setUpInitialBids(ParseObject deal){
if (currentUser == null)
return ;
Log.d("MainActivity/setUpInitialBids", currentUser.get("userid")+"");
ParseObject bid = new ParseObject("Bid");
bid.put("amount",100);
bid.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid.put("bid_for",deal);
bid.put("bid_by",currentUser);
ParseObject bid2 = new ParseObject("Bid");
bid2.put("amount",150);
bid2.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid2.put("bid_for",deal);
bid2.put("bid_by",currentUser);
bid.saveInBackground();
bid2.saveInBackground();
}
private void setBidButton(){
final DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (currentUser ==null){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.login_please_title)
.setMessage(R.string.login_please_message)
.setPositiveButton(R.string.bid_confirm_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
builder.create().show();
}
else
placeBid();
}
};
bidButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.bid_confirm_title)
.setMessage(R.string.bid_confirm_message)
.setPositiveButton(R.string.bid_confirm_yes, positiveListener)
.setNegativeButton(R.string.bid_confirm_no, null);
builder.create().show();
}
});
}
private void placeBid(){
int bidAmount = currentBid + 100;
ParseObject bid = new ParseObject("Bid");
bid.put("amount",bidAmount);
bid.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid.put("bid_for",deal);
bid.put("bid_by",currentUser);
commentListAdapter.addItem(new Comment(currentUser.getString("userid"), bidAmount, "I am bidding $" +bidAmount));
bid.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
setUpBid();
}
});
}
private void setTimer(Date date){
if (date==null){
date = new Date(Calendar.getInstance().getTimeInMillis() + 1000*60*60);
}
final Date fDate = date;
final TextView timeLeft = (TextView) findViewById(R.id.time_left_number);
long timeLeftDate = fDate.getTime() - Calendar.getInstance().getTimeInMillis();
new CountDownTimer(timeLeftDate, 1000) {
public void onTick(long millisUntilFinished) {
long timeLeftDate = fDate.getTime() - Calendar.getInstance().getTimeInMillis();
timeLeft.setText((timeLeftDate / (60 * 60 * 1000) % 24) + ":" + (timeLeftDate/(60 * 1000) % 60) + ":" + (timeLeftDate/1000%60));
}
public void onFinish() {
timeLeft.setText("ENDED");
}
}
.start();
}
private LinkedList<Comment> getSampleComments(){
LinkedList<Comment> list = new LinkedList<Comment>();
list.add(new Comment("bidder123",0,"I am getting this deal"));
list.add(new Comment("bidder4",0,"Hey this is cool"));
list.add(new Comment("bidder3",0,"Hello world"));
list.add(new Comment("bidder2",0,"yeah this is quite awesome"));
list.add(new Comment("first1",0,"First"));
return list;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id==R.id.action_login){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| UTF-8 | Java | 9,615 | java | MainActivity.java | Java | [] | null | [] | package com.bidex.app;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
public static ParseObject currentUser = null;
private static boolean parseIsNotInitialized = true;
private ParseObject deal;
private int currentBid;
private RelativeLayout bidButton;
private ListView _commentListView;
private CommentListAdapter commentListAdapter;
private TextView dealTitle,totalBidder,topBidNumber, topBidUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_commentListView = (ListView) findViewById(R.id.comments_list);
commentListAdapter = new CommentListAdapter(MainActivity.this, getSampleComments());
_commentListView.setAdapter(commentListAdapter);
bidButton = (RelativeLayout) findViewById(R.id.bid_button);
dealTitle = (TextView) findViewById(R.id.deal_title);
totalBidder = (TextView) findViewById(R.id.total_bidder_number);
topBidNumber = (TextView) findViewById(R.id.top_bid_number);
topBidUser = (TextView) findViewById(R.id.top_bidder_id);
setBidButton();
// setTimer(null);
setDB();
}
private void setDB(){
Log.d("MainActivity/setDB","Set DB");
if (parseIsNotInitialized) {
Parse.enableLocalDatastore(this);
Parse.initialize(this, "8y2Ma1EO394oPIoyEqVIBXFhtBmGjMQYjXfDm9od", "ftK0rwjfMgai0KxoXBvsbr9GYgr952Kq8TndWi0o");
parseIsNotInitialized = false;
}
ParseQuery<ParseObject> query = ParseQuery.getQuery("Deal");
query.getInBackground("z17eDDD5bc", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
Log.d("MainActivity/done","parse "+ object.getString("title"));
deal = object;
setTimer(deal.getDate("dealEndTime"));
dealTitle.setText(object.getString("title"));
setUpBid();
// setUpInitialBids(deal);
} else {
// something went wrong
}
}
});
}
private void setUpBid(){
ParseQuery<ParseObject> query2 = ParseQuery.getQuery("Bid");
query2.whereEqualTo("bid_for", deal);
query2.addDescendingOrder("amount");
query2.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> bidList, ParseException e) {
if (e == null) {
Log.d("MainActivity/done", "Total Bidder " + bidList.size());
totalBidder.setText(""+bidList.size());
if (bidList.size()!=0) {
currentBid = bidList.get(0).getInt("amount");
topBidNumber.setText("$" + bidList.get(0).getInt("amount"));
bidList.get(0).getParseObject("bid_by").fetchInBackground(new GetCallback<ParseObject>() {
@Override
public void done(ParseObject parseObject, ParseException e) {
topBidUser.setText("" + parseObject.getString("userid"));
}
});
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
private void setUpInitialBids(ParseObject deal){
if (currentUser == null)
return ;
Log.d("MainActivity/setUpInitialBids", currentUser.get("userid")+"");
ParseObject bid = new ParseObject("Bid");
bid.put("amount",100);
bid.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid.put("bid_for",deal);
bid.put("bid_by",currentUser);
ParseObject bid2 = new ParseObject("Bid");
bid2.put("amount",150);
bid2.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid2.put("bid_for",deal);
bid2.put("bid_by",currentUser);
bid.saveInBackground();
bid2.saveInBackground();
}
private void setBidButton(){
final DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (currentUser ==null){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.login_please_title)
.setMessage(R.string.login_please_message)
.setPositiveButton(R.string.bid_confirm_yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
builder.create().show();
}
else
placeBid();
}
};
bidButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.bid_confirm_title)
.setMessage(R.string.bid_confirm_message)
.setPositiveButton(R.string.bid_confirm_yes, positiveListener)
.setNegativeButton(R.string.bid_confirm_no, null);
builder.create().show();
}
});
}
private void placeBid(){
int bidAmount = currentBid + 100;
ParseObject bid = new ParseObject("Bid");
bid.put("amount",bidAmount);
bid.put("bidTime", new Date(Calendar.getInstance().getTimeInMillis()));
bid.put("bid_for",deal);
bid.put("bid_by",currentUser);
commentListAdapter.addItem(new Comment(currentUser.getString("userid"), bidAmount, "I am bidding $" +bidAmount));
bid.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
setUpBid();
}
});
}
private void setTimer(Date date){
if (date==null){
date = new Date(Calendar.getInstance().getTimeInMillis() + 1000*60*60);
}
final Date fDate = date;
final TextView timeLeft = (TextView) findViewById(R.id.time_left_number);
long timeLeftDate = fDate.getTime() - Calendar.getInstance().getTimeInMillis();
new CountDownTimer(timeLeftDate, 1000) {
public void onTick(long millisUntilFinished) {
long timeLeftDate = fDate.getTime() - Calendar.getInstance().getTimeInMillis();
timeLeft.setText((timeLeftDate / (60 * 60 * 1000) % 24) + ":" + (timeLeftDate/(60 * 1000) % 60) + ":" + (timeLeftDate/1000%60));
}
public void onFinish() {
timeLeft.setText("ENDED");
}
}
.start();
}
private LinkedList<Comment> getSampleComments(){
LinkedList<Comment> list = new LinkedList<Comment>();
list.add(new Comment("bidder123",0,"I am getting this deal"));
list.add(new Comment("bidder4",0,"Hey this is cool"));
list.add(new Comment("bidder3",0,"Hello world"));
list.add(new Comment("bidder2",0,"yeah this is quite awesome"));
list.add(new Comment("first1",0,"First"));
return list;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id==R.id.action_login){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
return true;
}
else if (id == R.id.action_settings) {
Intent intent = new Intent(MainActivity.this, PaymentActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 9,615 | 0.590952 | 0.581591 | 244 | 38.405739 | 28.876846 | 144 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.737705 | false | false | 6 |
00e61018ad115a258748f07ca788a5faaf0ac969 | 27,642,409,583,159 | a58d33ae3573859b68af8c24c2857a7f5ad90fb3 | /src/main/java/org/dai/thread/concurrent/Volatile.java | 36c4fdccfaa2578e4391a0011ba5776c1d1a3e7b | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | permissive | daishicheng/java-tutorial | https://github.com/daishicheng/java-tutorial | 332888c4197fa0e52e5b21219a00994125ec62e6 | 36ea936a5a3c5f18b59c0152e5dfe9d89f35b503 | refs/heads/master | 2020-03-27T08:43:52.793000 | 2019-11-14T09:42:38 | 2019-11-14T09:42:38 | 146,282,319 | 1 | 0 | Apache-2.0 | false | 2020-03-04T21:59:21 | 2018-08-27T10:25:53 | 2019-11-14T09:42:41 | 2020-03-04T21:59:19 | 783 | 0 | 0 | 1 | Java | false | false | package org.dai.thread.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author dai
* @date 2019/9/20
*/
public class Volatile {
private volatile static boolean keepA = true;
private static boolean keepB = true;
private static ExecutorService executor = new ThreadPoolExecutor(3,
3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1) );
public static void main(String[] args) {
executor.execute(() -> {
while (keepA) {
System.out.println("keepA running...");
}
System.out.println("keepA stop!!!!!!");
});
executor.execute(() -> {
while (keepB) {
System.out.println("keepB running...");
}
System.out.println("keepB stop!!!!!!");
});
executor.execute(() -> {
keepA = false;
keepB = false;
});
while (true) {
}
}
}
| UTF-8 | Java | 1,098 | java | Volatile.java | Java | [
{
"context": "ort java.util.concurrent.TimeUnit;\n\n/**\n * @author dai\n * @date 2019/9/20\n */\npublic class Volatile {\n\n ",
"end": 235,
"score": 0.9754424691200256,
"start": 232,
"tag": "USERNAME",
"value": "dai"
}
] | null | [] | package org.dai.thread.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author dai
* @date 2019/9/20
*/
public class Volatile {
private volatile static boolean keepA = true;
private static boolean keepB = true;
private static ExecutorService executor = new ThreadPoolExecutor(3,
3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1) );
public static void main(String[] args) {
executor.execute(() -> {
while (keepA) {
System.out.println("keepA running...");
}
System.out.println("keepA stop!!!!!!");
});
executor.execute(() -> {
while (keepB) {
System.out.println("keepB running...");
}
System.out.println("keepB stop!!!!!!");
});
executor.execute(() -> {
keepA = false;
keepB = false;
});
while (true) {
}
}
}
| 1,098 | 0.568306 | 0.558288 | 40 | 26.450001 | 20.48774 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.525 | false | false | 6 |
cf212f2a1853dc872dcafe1da5b9a29029da7204 | 32,031,866,093,653 | d56517efc7ac0bca494ff3d7d9e7e1a36813db9a | /itheima11_gyl/src/main/java/com/isoftstone/gyl/business/xsgl/dao/XsyddzhubDao.java | 3c53a9710979794127b358a327d983da9cdce9d5 | [] | no_license | Henray0607/itheima | https://github.com/Henray0607/itheima | 03be78aa73271d80a22cb0d9e115f2c8f4980b13 | 4e9514a2b8ac001aae5e2cb132389aa5e7b40bc2 | refs/heads/master | 2021-03-06T12:14:08.808000 | 2016-11-13T10:37:49 | 2016-11-13T10:37:49 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.isoftstone.gyl.business.xsgl.dao;
import com.isoftstone.gyl.base.dao.BaseDao;
import com.isoftstone.gyl.domain.business.xsgl.Xsyddzhub;
public interface XsyddzhubDao extends BaseDao<Xsyddzhub>{
}
| UTF-8 | Java | 212 | java | XsyddzhubDao.java | Java | [] | null | [] | package com.isoftstone.gyl.business.xsgl.dao;
import com.isoftstone.gyl.base.dao.BaseDao;
import com.isoftstone.gyl.domain.business.xsgl.Xsyddzhub;
public interface XsyddzhubDao extends BaseDao<Xsyddzhub>{
}
| 212 | 0.816038 | 0.816038 | 8 | 25.5 | 25.426365 | 57 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 6 |
6c84fa7473cacb7b165a7b7fd497e614df22d532 | 25,649,544,717,375 | f3312e09d5c7c4281af4165de9840cedbedf9a25 | /设计模式All/java设计模式/策略模式-demo/src/main/java/com/radis/RedisUtil.java | bdf49c7685ce5f0df1c8a1ce517025444f45df30 | [] | no_license | purgeyao/springboot-related | https://github.com/purgeyao/springboot-related | c9c6a7eb335f150dc3f0dba381ef0839f5493ded | 3a9caf4d480316fb2cf44cd6a3b5ef0607656d0e | refs/heads/master | 2020-04-17T17:56:13.869000 | 2019-09-02T08:32:47 | 2019-09-02T08:32:47 | 166,805,241 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.radis;
import com.radis.error.RedisException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* redis工具类
*
* @author wxy
* @date 2018-08-30 下午8:00
*/
@Component
public class RedisUtil {
private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
// @Resource
private JedisPool jedisPool;
public void setJedisPool(JedisPool jedisPool){
this.jedisPool = jedisPool;
}
/**
* set value
*
* @param key
* @param value
*/
public void set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
} catch (Exception e) {
logger.error("RedisUtil set exception. key:{},value:{}", key, value, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* get value
*
* @param key
* @return
*/
public String get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.get(key);
} catch (Exception e) {
logger.error("RedisUtil get exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 设置key的过期时间
*
* @param key
* @param seconds
* @return
*/
public void expire(String key, int seconds) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.expire(key, seconds);
} catch (Exception e) {
logger.error("RedisUtil expire exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 判断是否存在
*
* @param key
* @return
*/
public boolean exists(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
logger.error("RedisUtil exists exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param keys
* @return
*/
public void del(String... keys) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(keys);
} catch (Exception e) {
logger.error("RedisUtil del exception. keys:{}", keys, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set if not exists,若key已存在,则setnx不做任何操作
*
* @param key
* @param value
* @return
*/
public boolean setnx(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.setnx(key, value) > 0;
} catch (Exception e) {
logger.error("RedisUtil setnx exception. key:{},value:{}", key, value, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 在列表key的头部插入元素
*
* @param key
* @param values
* @return
*/
public Long lpush(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lpush(key, values);
} catch (Exception e) {
logger.error("RedisUtil lpush exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 在列表key的尾部插入元素
*
* @param key
* @param values
* @return
*/
public Long rpush(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.rpush(key, values);
} catch (Exception e) {
logger.error("RedisUtil rpush exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 返回列表中从索引start至end的元素
* @param key
* @param start
* @param end
* @return
*/
public List<String> lrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lrange(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil lrange exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set 集合
* @param key 键
* @param values 值
* @return 成功1 失败0
*/
public Long sadd(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.sadd(key, values);
} catch (Exception e) {
logger.error("RedisUtil sadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 显示set集合中的元素内容
*
* @param key 键
* @return set集合
*/
public Set<String> smembers(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.smembers(key);
} catch (Exception e) {
logger.error("RedisUtil smembers exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 列表中元素个数
* @param key
* @return
*/
public Long llen(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.llen(key);
} catch (Exception e) {
logger.error("RedisUtil llen exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 移除等于value的元素<br/><br/> 当count>0时,从表头开始查找,移除count个;<br/> 当count=0时,从表头开始查找,移除所有等于value的;<br/>
* 当count<0时,从表尾开始查找,移除count个
*
* @param key
* @param count
* @param value
*/
public Long lrem(String key, long count, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lrem(key, count, value);
} catch (Exception e) {
logger.error("RedisUtil lrem exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 对列表进行修剪
*
* @param key
* @param start
* @param end
*/
public String ltrim(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.ltrim(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil ltrim exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 缓存Map赋值
*
* @param key
* @param field
* @param value
*/
public Long hset(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hset(key, field, value);
} catch (Exception e) {
logger.error("RedisUtil hset exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hget(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public boolean hexists(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hexists(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public Long hdel(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hdel(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @return
*/
public Map<String, String> hgetAll(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hgetAll(key);
} catch (Exception e) {
logger.error("RedisUtil hgetAll exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zadd
*
* @param key
* @param score
* @param member
* @return
*/
public Long zadd(String key, double score, String member) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zadd(key, score, member);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zrevrange
*
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zrevrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrevrange(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zrank
*
* @param key
* @param member
* @return
*/
public Long zrank(String key, String member) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrank(key, member);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 分布式自增数
*
* @param key
* @return
*/
public Long incr(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.incr(key);
} catch (Exception e) {
logger.error("RedisUtil incr exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 分布式自减数
*
* @param key
* @return
*/
public Long decr(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.decr(key);
} catch (Exception e) {
logger.error("RedisUtil incr exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
| UTF-8 | Java | 13,715 | java | RedisUtil.java | Java | [
{
"context": "port java.util.Set;\n\n/**\n * redis工具类\n *\n * @author wxy\n * @date 2018-08-30 下午8:00\n */\n@Component\npublic ",
"end": 339,
"score": 0.9996041059494019,
"start": 336,
"tag": "USERNAME",
"value": "wxy"
}
] | null | [] | package com.radis;
import com.radis.error.RedisException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* redis工具类
*
* @author wxy
* @date 2018-08-30 下午8:00
*/
@Component
public class RedisUtil {
private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
// @Resource
private JedisPool jedisPool;
public void setJedisPool(JedisPool jedisPool){
this.jedisPool = jedisPool;
}
/**
* set value
*
* @param key
* @param value
*/
public void set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.set(key, value);
} catch (Exception e) {
logger.error("RedisUtil set exception. key:{},value:{}", key, value, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* get value
*
* @param key
* @return
*/
public String get(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.get(key);
} catch (Exception e) {
logger.error("RedisUtil get exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 设置key的过期时间
*
* @param key
* @param seconds
* @return
*/
public void expire(String key, int seconds) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.expire(key, seconds);
} catch (Exception e) {
logger.error("RedisUtil expire exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 判断是否存在
*
* @param key
* @return
*/
public boolean exists(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
logger.error("RedisUtil exists exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param keys
* @return
*/
public void del(String... keys) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
jedis.del(keys);
} catch (Exception e) {
logger.error("RedisUtil del exception. keys:{}", keys, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set if not exists,若key已存在,则setnx不做任何操作
*
* @param key
* @param value
* @return
*/
public boolean setnx(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.setnx(key, value) > 0;
} catch (Exception e) {
logger.error("RedisUtil setnx exception. key:{},value:{}", key, value, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 在列表key的头部插入元素
*
* @param key
* @param values
* @return
*/
public Long lpush(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lpush(key, values);
} catch (Exception e) {
logger.error("RedisUtil lpush exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 在列表key的尾部插入元素
*
* @param key
* @param values
* @return
*/
public Long rpush(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.rpush(key, values);
} catch (Exception e) {
logger.error("RedisUtil rpush exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 返回列表中从索引start至end的元素
* @param key
* @param start
* @param end
* @return
*/
public List<String> lrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lrange(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil lrange exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set 集合
* @param key 键
* @param values 值
* @return 成功1 失败0
*/
public Long sadd(String key, String... values) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.sadd(key, values);
} catch (Exception e) {
logger.error("RedisUtil sadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 显示set集合中的元素内容
*
* @param key 键
* @return set集合
*/
public Set<String> smembers(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.smembers(key);
} catch (Exception e) {
logger.error("RedisUtil smembers exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 列表中元素个数
* @param key
* @return
*/
public Long llen(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.llen(key);
} catch (Exception e) {
logger.error("RedisUtil llen exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 移除等于value的元素<br/><br/> 当count>0时,从表头开始查找,移除count个;<br/> 当count=0时,从表头开始查找,移除所有等于value的;<br/>
* 当count<0时,从表尾开始查找,移除count个
*
* @param key
* @param count
* @param value
*/
public Long lrem(String key, long count, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.lrem(key, count, value);
} catch (Exception e) {
logger.error("RedisUtil lrem exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 对列表进行修剪
*
* @param key
* @param start
* @param end
*/
public String ltrim(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.ltrim(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil ltrim exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 缓存Map赋值
*
* @param key
* @param field
* @param value
*/
public Long hset(String key, String field, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hset(key, field, value);
} catch (Exception e) {
logger.error("RedisUtil hset exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hget(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public boolean hexists(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hexists(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @param field
* @return
*/
public Long hdel(String key, String field) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hdel(key, field);
} catch (Exception e) {
logger.error("RedisUtil hget exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param key
* @return
*/
public Map<String, String> hgetAll(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.hgetAll(key);
} catch (Exception e) {
logger.error("RedisUtil hgetAll exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zadd
*
* @param key
* @param score
* @param member
* @return
*/
public Long zadd(String key, double score, String member) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zadd(key, score, member);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zrevrange
*
* @param key
* @param start
* @param end
* @return
*/
public Set<String> zrevrange(String key, long start, long end) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrevrange(key, start, end);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* zrank
*
* @param key
* @param member
* @return
*/
public Long zrank(String key, String member) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.zrank(key, member);
} catch (Exception e) {
logger.error("RedisUtil zadd exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 分布式自增数
*
* @param key
* @return
*/
public Long incr(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.incr(key);
} catch (Exception e) {
logger.error("RedisUtil incr exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 分布式自减数
*
* @param key
* @return
*/
public Long decr(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.decr(key);
} catch (Exception e) {
logger.error("RedisUtil incr exception. key:{}", key, e);
throw new RedisException(e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
}
| 13,715 | 0.469238 | 0.467818 | 551 | 23.277678 | 18.145435 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.46098 | false | false | 6 |
8c25766004fa2930d6c5a4946aeccf013c8b82e6 | 7,911,329,785,620 | 63b889e2f87d8562178f210b9109b6d586738d5d | /src/com/parking/ParkingLot.java | 3dbbde31cde1afb0a612830e7cd6868f710fbf0b | [] | no_license | naresh-coder/parkinglot | https://github.com/naresh-coder/parkinglot | 6816f9e723e2dc9fd4a3883686e71888aeb7c8dd | 516367a59f22a477c9ad90e78f33692445684e31 | refs/heads/master | 2020-12-21T12:04:53.254000 | 2020-01-27T05:25:34 | 2020-01-27T05:25:34 | 236,424,863 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.parking;
import java.util.PriorityQueue;
/**
* Class to avail total no parking slots
*/
public class ParkingLot {
private Level[] levels = new Level[1];
public ParkingLot(int noOfSpot) {
this(0, noOfSpot);
}
public ParkingLot(int no, int noOfSpot) {
levels[no] = new Level(noOfSpot);
}
public Level[] getLevels() {
return levels;
}
}
| UTF-8 | Java | 407 | java | ParkingLot.java | Java | [] | null | [] | package com.parking;
import java.util.PriorityQueue;
/**
* Class to avail total no parking slots
*/
public class ParkingLot {
private Level[] levels = new Level[1];
public ParkingLot(int noOfSpot) {
this(0, noOfSpot);
}
public ParkingLot(int no, int noOfSpot) {
levels[no] = new Level(noOfSpot);
}
public Level[] getLevels() {
return levels;
}
}
| 407 | 0.616708 | 0.611794 | 23 | 16.695652 | 16.64576 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.347826 | false | false | 6 |
6df04752c80db657af08a4fe41b2a57400ba0b0c | 24,730,421,711,412 | df0a60038f56b6a0997f79ca90c7e4d6cc7ca19c | /src/test/java/io/github/asanovs/autobot/service/MessageServiceTest.java | 6b3f1bc2aeca8657b94e93c9ab3e112bbaff1105 | [] | no_license | ASanovS/autobot | https://github.com/ASanovS/autobot | d62e5ae7562d1df48127ded9e9b53feeb268f0b0 | 583d6f4f7eca3edbff568b864cedbb6787cded9f | refs/heads/master | 2023-03-15T06:53:55.745000 | 2021-03-26T19:46:49 | 2021-03-26T19:46:49 | 350,868,011 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.github.asanovs.autobot.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.asanovs.autobot.config.Mapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = {TelegramBot.class, Mapper.class, MessageService.class})
class MessageServiceTest {
@Autowired
TelegramBot telegramBot;
@Autowired
ObjectMapper objectMapper;
@Autowired
MessageService messageService;
@Test
void onUpdateReceived() throws IOException {
Update update = objectMapper.readValue(new File("src/test/resources/update.json"), Update.class);
String actualResult = messageService.onUpdateReceived(update);
String expectedResult = "Hello!";
assertEquals(expectedResult, actualResult);
}
} | UTF-8 | Java | 1,093 | java | MessageServiceTest.java | Java | [
{
"context": "package io.github.asanovs.autobot.service;\n\nimport com.fasterxml.jackson.da",
"end": 25,
"score": 0.9936538338661194,
"start": 18,
"tag": "USERNAME",
"value": "asanovs"
},
{
"context": "l.jackson.databind.ObjectMapper;\nimport io.github.asanovs.autobot.config.Mapper;\... | null | [] | package io.github.asanovs.autobot.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.asanovs.autobot.config.Mapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.telegram.telegrambots.meta.api.objects.Update;
import java.io.File;
import java.io.IOException;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(classes = {TelegramBot.class, Mapper.class, MessageService.class})
class MessageServiceTest {
@Autowired
TelegramBot telegramBot;
@Autowired
ObjectMapper objectMapper;
@Autowired
MessageService messageService;
@Test
void onUpdateReceived() throws IOException {
Update update = objectMapper.readValue(new File("src/test/resources/update.json"), Update.class);
String actualResult = messageService.onUpdateReceived(update);
String expectedResult = "Hello!";
assertEquals(expectedResult, actualResult);
}
} | 1,093 | 0.773102 | 0.773102 | 33 | 32.151516 | 26.334816 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.666667 | false | false | 6 |
484feb228d1fb0744b3db964e1b40c5139efb97d | 24,309,514,920,212 | 533ff159f125813460432c8d43956788e6da045f | /Chintha/ChinthaApp/app/src/main/java/com/suhi_chintha/DataDB1.java | 207d93537955a291c683bf6ae008d4de3d0dd225 | [] | no_license | AitoApps/AndroidWorks | https://github.com/AitoApps/AndroidWorks | 7747b084e84b8ad769f4552e8b2691d9cdec3f06 | 3c6c7d17f085ee3aa714e66f13fec2a4d8663ca3 | refs/heads/master | 2022-03-14T10:57:59.215000 | 2019-12-06T17:03:24 | 2019-12-06T17:03:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.suhi_chintha;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class DataDB1 extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =102;
private static final String DATABASE_NAME = "chinathdb1";
private static final String table1 = "bststaus";
private static final String table2 = "staus";
private static final String table4 = "cmntVisible";
private static final String table6 = "ogcomment";
private static final String table7 = "statusnoti";
private static final String table8 = "likenoti";
private static final String table9 = "commentnoti";
private static final String table10 = "notilist";
private static final String table11 = "noticount";
private static final String table12 = "adminmessgae";
private static final String table13 = "legalnotice";
private static final String table14 = "refreshhost";
private static final String table15 = "commentdetails";
private static final String table17 = "cmntpost";
private static final String table18 = "fvrtcounts";
private static final String userid = "userid";
private static final String name = "name";
private static final String mobile = "mobile";
private static final String statusid = "statusid";
private static final String status= "status";
private static final String showmobile = "showmobile";
private static final String varified = "varified";
private static final String isread = "isread";
private static final String fvrts = "fvrts";
private static final String pkey= "pkey";
private static final String statusdate = "statusdate";
private static final String notification = "notification";
private static final String notiogid = "notiogid";
private static final String noti_type = "noti_type";
private static final String noti_lastname = "noti_lastname";
private static final String noti_count = "noti_count";
private static final String noti_text = "noti_text";
private static final String date_created="date_created";
private static final String noti_userid = "noti_userid";
private static final String adminmsg= "adminmsg";
private static final String adminmsg_type = "adminmsg_type"; // 0- text 1-imageadvt
private static final String cmnt_photodim = "cmnt_photodim";
private static final String status_imgsigid = "status_imgsigid";
private static final String status_id = "status_id";
private static final String status_name = "status_name";
private static final String status_status = "status_status";
private static final String status_userid= "status_userid";
private static final String status_username = "status_username";
private static final String cmnt_statusid = "cmnt_statusid";
private static final String cmnt_userid = "cmnt_userid";
private static final String cmnt_username = "cmnt_username";
private static final String cmnt_status = "cmnt_status";
private static final String cmnt_imgsigid = "cmnt_imgsigid";
private static final String cmnt_statustype = "cmnt_statustype";
private static final String cmnt_photourl = "cmnt_photourl";
public static String fvrstatus="fvrstatus";
public static String fvrstatususerid="statususerid";
public static String dvrt_userid ="fvruserid";
public static String fvrusername="fvrusername";
public static String fvrstatustext="fvrstatustext";
public static String fvrstatusimgsig="fvrstatusimgsig";
public DataDB1(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static String CREATE_videoid_TABLE1 = "CREATE TABLE " + table1 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+statusid +" TEXT,"+userid +" TEXT,"+name +" TEXT,"+mobile+" TEXT,"+status +" TEXT,"+fvrts +" TEXT,"+showmobile +" TEXT,"+varified+" TEXT"+")";
private static String CREATE_videoid_TABLE2 = "CREATE TABLE " + table2 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+statusid +" TEXT,"+userid +" TEXT,"+name +" TEXT,"+mobile+" TEXT,"+status +" TEXT,"+fvrts +" TEXT,"+showmobile +" TEXT,"+varified +" TEXT,"+statusdate+" TEXT"+")";
private static String CREATE_videoid_TABLE4 = "CREATE TABLE " + table4 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE10 = "CREATE TABLE " + table10 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+notiogid +" TEXT,"+noti_type +" TEXT,"+noti_lastname +" TEXT,"+noti_count+" TEXT,"+noti_text+" TEXT,"+date_created+" DATETIME,"+noti_userid+" TEXT,"+isread+" TEXT,"+status_userid+" TEXT,"+status_username+" TEXT,"+status_imgsigid+" TEXT,"+cmnt_statustype+" TEXT,"+cmnt_photourl+" TEXT,"+cmnt_photodim+" TEXT"+")";
private static String CREATE_videoid_TABLE11 = "CREATE TABLE " + table11 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE12 = "CREATE TABLE " + table12 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+adminmsg+" TEXT,"+adminmsg_type+" TEXT"+")";
private static String CREATE_videoid_TABLE13 = "CREATE TABLE " + table13 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE14 = "CREATE TABLE " + table14 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE15 = "CREATE TABLE " + table15 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+cmnt_statusid +" TEXT,"+cmnt_userid +" TEXT,"+cmnt_username +" TEXT,"+cmnt_status +" TEXT,"+cmnt_imgsigid +" TEXT,"+cmnt_statustype +" TEXT,"+cmnt_photourl +" TEXT,"+cmnt_photodim+" TEXT"+")";
private static String CREATE_videoid_TABLE17 = "CREATE TABLE " + table17 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+status_id +" TEXT,"+status_status+" TEXT"+")";
private static String CREATE_videoid_TABLE18 = "CREATE TABLE " + table18 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+ dvrt_userid +" TEXT,"+fvrstatus +" TEXT,"+fvrstatususerid +" TEXT,"+fvrusername +" TEXT,"+fvrstatustext+" TEXT,"+fvrstatusimgsig+" TEXT"+")";
private static String CREATE_videoid_TABLE6 = "CREATE TABLE " + table6 + "("+statusid+" TEXT"+")";
private static String CREATE_videoid_TABLE7 = "CREATE TABLE " + table7 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE8 = "CREATE TABLE " + table8 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE9 = "CREATE TABLE " + table9 + "("+notification+" TEXT"+")";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_videoid_TABLE1);
db.execSQL(CREATE_videoid_TABLE2);
db.execSQL(CREATE_videoid_TABLE4);
db.execSQL(CREATE_videoid_TABLE6);
db.execSQL(CREATE_videoid_TABLE7);
db.execSQL(CREATE_videoid_TABLE12);
db.execSQL(CREATE_videoid_TABLE13);
db.execSQL(CREATE_videoid_TABLE14);
db.execSQL(CREATE_videoid_TABLE15);
db.execSQL(CREATE_videoid_TABLE17);
db.execSQL(CREATE_videoid_TABLE18);
db.execSQL(CREATE_videoid_TABLE8);
db.execSQL(CREATE_videoid_TABLE9);
db.execSQL(CREATE_videoid_TABLE10);
db.execSQL(CREATE_videoid_TABLE11);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table1);
db.execSQL("DROP TABLE IF EXISTS " + table2);
db.execSQL("DROP TABLE IF EXISTS " + table4);
db.execSQL("DROP TABLE IF EXISTS " + table12);
db.execSQL("DROP TABLE IF EXISTS " + table13);
db.execSQL("DROP TABLE IF EXISTS " + table14);
db.execSQL("DROP TABLE IF EXISTS " + table15);
db.execSQL("DROP TABLE IF EXISTS " + table17);
db.execSQL("DROP TABLE IF EXISTS " + table18);
db.execSQL("DROP TABLE IF EXISTS " + table6);
db.execSQL("DROP TABLE IF EXISTS " + table7);
db.execSQL("DROP TABLE IF EXISTS " + table8);
db.execSQL("DROP TABLE IF EXISTS " + table9);
db.execSQL("DROP TABLE IF EXISTS " + table10);
db.execSQL("DROP TABLE IF EXISTS " + table11);
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table1);
db.execSQL("DROP TABLE IF EXISTS " + table2);
db.execSQL("DROP TABLE IF EXISTS " + table4);
db.execSQL("DROP TABLE IF EXISTS " + table6);
db.execSQL("DROP TABLE IF EXISTS " + table13);
db.execSQL("DROP TABLE IF EXISTS " + table14);
db.execSQL("DROP TABLE IF EXISTS " + table15);
db.execSQL("DROP TABLE IF EXISTS " + table18);
db.execSQL("DROP TABLE IF EXISTS " + table17);
db.execSQL("DROP TABLE IF EXISTS " + table7);
db.execSQL("DROP TABLE IF EXISTS " + table8);
db.execSQL("DROP TABLE IF EXISTS " + table9);
db.execSQL("DROP TABLE IF EXISTS " + table10);
db.execSQL("DROP TABLE IF EXISTS " + table11);
db.execSQL("DROP TABLE IF EXISTS " + table12);
onCreate(db);
}
public void add_cmntdetails(String status_id1, String status_status1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(status_id,status_id1);
values.put(status_status,status_status1);
db.insert(table17,null, values);
db.close();
}
public String get_commntdtls(String status_id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table17 +" WHERE status_id="+status_id;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public ArrayList<String> getcommentdetails(String status_id){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table17 +" WHERE status_id="+status_id;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
}
c.close();
return arraylist;
}
public void dropcmntdetails()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table17);
}
public void dropcmntdetails(String status_id)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table17, status_id+"="+status_id, null);
}
public void add_cmntdtails(String cmnt_statusid1, String cmnt_userid1, String cmnt_username1, String cmnt_status1, String cmnt_imgsigid1, String cmnt_statustype1, String cmnt_photourl1, String cmnt_photodim1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(cmnt_statusid,cmnt_statusid1);
values.put(cmnt_userid,cmnt_userid1);
values.put(cmnt_username,cmnt_username1);
values.put(cmnt_status,cmnt_status1);
values.put(cmnt_imgsigid,cmnt_imgsigid1);
values.put(cmnt_statustype,cmnt_statustype1);
values.put(cmnt_photourl,cmnt_photourl1);
values.put(cmnt_photodim,cmnt_photodim1);
db.insert(table15,null, values);
db.close();
}
public ArrayList<String> getcmntdetails(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table15;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
arraylist.add(c.getString(7));
arraylist.add(c.getString(8));
}
c.close();
return arraylist;
}
public void deletecmntdetails()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table15);
}
public void add_privacynoti(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table13,null, values);
db.close();
}
public String get_privacynoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table13;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void deletelegalnotice()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table13);
}
void add_message(String adminmsg1, String adminmsg_type1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(adminmsg,adminmsg1);
values.put(adminmsg_type,adminmsg_type1);
db.insert(table12,null, values);
db.close();
}
public ArrayList<String> get_message(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table12;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
}
c.close();
return arraylist;
}
void drop_message()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table12);
}
public String get_noticount(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT count(pkey) FROM " + table10 +" where isread=0";
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void add_cmtnnoti(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table9,null, values);
db.close();
}
public String get_cmntnoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table9;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_cmntnoti()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table9);
}
public void add_notilike(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table8,null, values);
db.close();
}
public String get_likenoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table8;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_notilike()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table8);
}
public void add_notistatus(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table7,null, values);
db.close();
}
public String get_notistatus(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table7;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_statusnoti()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table7);
}
public void add_cmntvisible(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table4,null, values);
db.close();
}
public String get_cmntvisible(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table4;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void deletecmntvisible()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table4);
}
void add_notilist(String notiogid1, String noti_type1, String noti_lastname1, String noti_count1, String noti_text1, String noti_userid1, String isread1, String status_userid1, String status_username1, String status_imgsigid1, String cmnt_statustype1, String cmnt_photourl1, String cmnt_photodim1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notiogid,notiogid1);
values.put(noti_type,noti_type1);
values.put(noti_lastname,noti_lastname1);
values.put(noti_count,noti_count1);
values.put(noti_text,noti_text1);
values.put(date_created,getDateTime());
values.put(noti_userid,noti_userid1);
values.put(isread,isread1);
values.put(status_userid,status_userid1);
values.put(status_username,status_username1);
values.put(status_imgsigid,status_imgsigid1);
values.put(cmnt_statustype,cmnt_statustype1);
values.put(cmnt_photourl,cmnt_photourl1);
values.put(cmnt_photodim,cmnt_photodim1);
db.insert(table10,null, values);
db.close();
}
public ArrayList<String> get_notilist(String limit){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table10 +" ORDER BY date_created desc LIMIT "+limit+",30";
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
arraylist.add(c.getString(7));
arraylist.add(c.getString(8));
arraylist.add(c.getString(0));
arraylist.add(c.getString(9));
arraylist.add(c.getString(10));
arraylist.add(c.getString(11));
arraylist.add(c.getString(12));
arraylist.add(c.getString(13));
arraylist.add(c.getString(14));
}
c.close();
return arraylist;
}
void deletenotilist()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table10);
}
public String getlikes(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='0' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getcomments(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='1' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getcomments_bld(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='3' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String get_reply(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='2' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getreplay_bld(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='4' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String get_comments1(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='1' and noti_userid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(5);
}
c.close();
return link;
}
public String getreply1(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='2' and noti_userid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(5);
}
c.close();
return link;
}
public void updatereadstatus(String pkey1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(isread,"1");
db.update(table10, newValues, pkey + " = ?",new String[]{pkey1});
}
public void updatereadstatusall()
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(isread,"1");
db.update(table10, newValues, null,null);
}
public void update_likes(String id, String lastname, String userid1, String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(getlikes(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_userid,userid1);
newValues.put(status_imgsigid,status_imgsigid1);
newValues.put(isread,"0");
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "0"});
}
public void update_cmnts(String id, String lastname, String noti_text1, String userid1, String status_userid1, String status_username1, String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(getcomments(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(noti_userid,userid1);
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
newValues.put(isread,"0");
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "1"});
}
public void updatecomments1(String id,String lastname,String noti_text1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(isread,"0");
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "1"});
}
public void updatereplay(String id,String lastname,String noti_text1,String userid1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(get_reply(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(noti_userid,userid1);
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(isread,"0");
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "2"});
}
public void updatereplay1(String id,String lastname,String noti_text1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(isread,"0");
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "2"});
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
public void add_fvrtstaus(String userid1, String fvrstatusid1, String fvrstatususerid1, String fvrusername1, String fvrstatustext1, String fvrstatusimgsig1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dvrt_userid,userid1);
values.put(fvrstatus,fvrstatusid1);
values.put(fvrstatususerid,fvrstatususerid1);
values.put(fvrusername,fvrusername1);
values.put(fvrstatustext,fvrstatustext1);
values.put(fvrstatusimgsig,fvrstatusimgsig1);
db.insert(table18,null, values);
db.close();
}
public ArrayList<String> get_fvrtstaus(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table18;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(0));
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
}
c.close();
return arraylist;
}
public void deletefvrtcoloum(String pkey1)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table18, pkey+"="+pkey1, null);
}
} | UTF-8 | Java | 26,315 | java | DataDB1.java | Java | [
{
"context": "\r\n\tprivate static final String status_username = \"status_username\";\r\n\tprivate static final String cmnt_statusid = \"",
"end": 2905,
"score": 0.9992702007293701,
"start": 2890,
"tag": "USERNAME",
"value": "status_username"
},
{
"context": "\";\r\n\tprivate static... | null | [] | package com.suhi_chintha;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class DataDB1 extends SQLiteOpenHelper {
private static final int DATABASE_VERSION =102;
private static final String DATABASE_NAME = "chinathdb1";
private static final String table1 = "bststaus";
private static final String table2 = "staus";
private static final String table4 = "cmntVisible";
private static final String table6 = "ogcomment";
private static final String table7 = "statusnoti";
private static final String table8 = "likenoti";
private static final String table9 = "commentnoti";
private static final String table10 = "notilist";
private static final String table11 = "noticount";
private static final String table12 = "adminmessgae";
private static final String table13 = "legalnotice";
private static final String table14 = "refreshhost";
private static final String table15 = "commentdetails";
private static final String table17 = "cmntpost";
private static final String table18 = "fvrtcounts";
private static final String userid = "userid";
private static final String name = "name";
private static final String mobile = "mobile";
private static final String statusid = "statusid";
private static final String status= "status";
private static final String showmobile = "showmobile";
private static final String varified = "varified";
private static final String isread = "isread";
private static final String fvrts = "fvrts";
private static final String pkey= "pkey";
private static final String statusdate = "statusdate";
private static final String notification = "notification";
private static final String notiogid = "notiogid";
private static final String noti_type = "noti_type";
private static final String noti_lastname = "noti_lastname";
private static final String noti_count = "noti_count";
private static final String noti_text = "noti_text";
private static final String date_created="date_created";
private static final String noti_userid = "noti_userid";
private static final String adminmsg= "adminmsg";
private static final String adminmsg_type = "adminmsg_type"; // 0- text 1-imageadvt
private static final String cmnt_photodim = "cmnt_photodim";
private static final String status_imgsigid = "status_imgsigid";
private static final String status_id = "status_id";
private static final String status_name = "status_name";
private static final String status_status = "status_status";
private static final String status_userid= "status_userid";
private static final String status_username = "status_username";
private static final String cmnt_statusid = "cmnt_statusid";
private static final String cmnt_userid = "cmnt_userid";
private static final String cmnt_username = "cmnt_username";
private static final String cmnt_status = "cmnt_status";
private static final String cmnt_imgsigid = "cmnt_imgsigid";
private static final String cmnt_statustype = "cmnt_statustype";
private static final String cmnt_photourl = "cmnt_photourl";
public static String fvrstatus="fvrstatus";
public static String fvrstatususerid="statususerid";
public static String dvrt_userid ="fvruserid";
public static String fvrusername="fvrusername";
public static String fvrstatustext="fvrstatustext";
public static String fvrstatusimgsig="fvrstatusimgsig";
public DataDB1(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static String CREATE_videoid_TABLE1 = "CREATE TABLE " + table1 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+statusid +" TEXT,"+userid +" TEXT,"+name +" TEXT,"+mobile+" TEXT,"+status +" TEXT,"+fvrts +" TEXT,"+showmobile +" TEXT,"+varified+" TEXT"+")";
private static String CREATE_videoid_TABLE2 = "CREATE TABLE " + table2 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+statusid +" TEXT,"+userid +" TEXT,"+name +" TEXT,"+mobile+" TEXT,"+status +" TEXT,"+fvrts +" TEXT,"+showmobile +" TEXT,"+varified +" TEXT,"+statusdate+" TEXT"+")";
private static String CREATE_videoid_TABLE4 = "CREATE TABLE " + table4 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE10 = "CREATE TABLE " + table10 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+notiogid +" TEXT,"+noti_type +" TEXT,"+noti_lastname +" TEXT,"+noti_count+" TEXT,"+noti_text+" TEXT,"+date_created+" DATETIME,"+noti_userid+" TEXT,"+isread+" TEXT,"+status_userid+" TEXT,"+status_username+" TEXT,"+status_imgsigid+" TEXT,"+cmnt_statustype+" TEXT,"+cmnt_photourl+" TEXT,"+cmnt_photodim+" TEXT"+")";
private static String CREATE_videoid_TABLE11 = "CREATE TABLE " + table11 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE12 = "CREATE TABLE " + table12 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+adminmsg+" TEXT,"+adminmsg_type+" TEXT"+")";
private static String CREATE_videoid_TABLE13 = "CREATE TABLE " + table13 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE14 = "CREATE TABLE " + table14 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE15 = "CREATE TABLE " + table15 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+cmnt_statusid +" TEXT,"+cmnt_userid +" TEXT,"+cmnt_username +" TEXT,"+cmnt_status +" TEXT,"+cmnt_imgsigid +" TEXT,"+cmnt_statustype +" TEXT,"+cmnt_photourl +" TEXT,"+cmnt_photodim+" TEXT"+")";
private static String CREATE_videoid_TABLE17 = "CREATE TABLE " + table17 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+status_id +" TEXT,"+status_status+" TEXT"+")";
private static String CREATE_videoid_TABLE18 = "CREATE TABLE " + table18 + "("+pkey +" INTEGER PRIMARY KEY AUTOINCREMENT,"+ dvrt_userid +" TEXT,"+fvrstatus +" TEXT,"+fvrstatususerid +" TEXT,"+fvrusername +" TEXT,"+fvrstatustext+" TEXT,"+fvrstatusimgsig+" TEXT"+")";
private static String CREATE_videoid_TABLE6 = "CREATE TABLE " + table6 + "("+statusid+" TEXT"+")";
private static String CREATE_videoid_TABLE7 = "CREATE TABLE " + table7 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE8 = "CREATE TABLE " + table8 + "("+notification+" TEXT"+")";
private static String CREATE_videoid_TABLE9 = "CREATE TABLE " + table9 + "("+notification+" TEXT"+")";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_videoid_TABLE1);
db.execSQL(CREATE_videoid_TABLE2);
db.execSQL(CREATE_videoid_TABLE4);
db.execSQL(CREATE_videoid_TABLE6);
db.execSQL(CREATE_videoid_TABLE7);
db.execSQL(CREATE_videoid_TABLE12);
db.execSQL(CREATE_videoid_TABLE13);
db.execSQL(CREATE_videoid_TABLE14);
db.execSQL(CREATE_videoid_TABLE15);
db.execSQL(CREATE_videoid_TABLE17);
db.execSQL(CREATE_videoid_TABLE18);
db.execSQL(CREATE_videoid_TABLE8);
db.execSQL(CREATE_videoid_TABLE9);
db.execSQL(CREATE_videoid_TABLE10);
db.execSQL(CREATE_videoid_TABLE11);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table1);
db.execSQL("DROP TABLE IF EXISTS " + table2);
db.execSQL("DROP TABLE IF EXISTS " + table4);
db.execSQL("DROP TABLE IF EXISTS " + table12);
db.execSQL("DROP TABLE IF EXISTS " + table13);
db.execSQL("DROP TABLE IF EXISTS " + table14);
db.execSQL("DROP TABLE IF EXISTS " + table15);
db.execSQL("DROP TABLE IF EXISTS " + table17);
db.execSQL("DROP TABLE IF EXISTS " + table18);
db.execSQL("DROP TABLE IF EXISTS " + table6);
db.execSQL("DROP TABLE IF EXISTS " + table7);
db.execSQL("DROP TABLE IF EXISTS " + table8);
db.execSQL("DROP TABLE IF EXISTS " + table9);
db.execSQL("DROP TABLE IF EXISTS " + table10);
db.execSQL("DROP TABLE IF EXISTS " + table11);
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + table1);
db.execSQL("DROP TABLE IF EXISTS " + table2);
db.execSQL("DROP TABLE IF EXISTS " + table4);
db.execSQL("DROP TABLE IF EXISTS " + table6);
db.execSQL("DROP TABLE IF EXISTS " + table13);
db.execSQL("DROP TABLE IF EXISTS " + table14);
db.execSQL("DROP TABLE IF EXISTS " + table15);
db.execSQL("DROP TABLE IF EXISTS " + table18);
db.execSQL("DROP TABLE IF EXISTS " + table17);
db.execSQL("DROP TABLE IF EXISTS " + table7);
db.execSQL("DROP TABLE IF EXISTS " + table8);
db.execSQL("DROP TABLE IF EXISTS " + table9);
db.execSQL("DROP TABLE IF EXISTS " + table10);
db.execSQL("DROP TABLE IF EXISTS " + table11);
db.execSQL("DROP TABLE IF EXISTS " + table12);
onCreate(db);
}
public void add_cmntdetails(String status_id1, String status_status1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(status_id,status_id1);
values.put(status_status,status_status1);
db.insert(table17,null, values);
db.close();
}
public String get_commntdtls(String status_id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table17 +" WHERE status_id="+status_id;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public ArrayList<String> getcommentdetails(String status_id){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table17 +" WHERE status_id="+status_id;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
}
c.close();
return arraylist;
}
public void dropcmntdetails()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table17);
}
public void dropcmntdetails(String status_id)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table17, status_id+"="+status_id, null);
}
public void add_cmntdtails(String cmnt_statusid1, String cmnt_userid1, String cmnt_username1, String cmnt_status1, String cmnt_imgsigid1, String cmnt_statustype1, String cmnt_photourl1, String cmnt_photodim1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(cmnt_statusid,cmnt_statusid1);
values.put(cmnt_userid,cmnt_userid1);
values.put(cmnt_username,cmnt_username1);
values.put(cmnt_status,cmnt_status1);
values.put(cmnt_imgsigid,cmnt_imgsigid1);
values.put(cmnt_statustype,cmnt_statustype1);
values.put(cmnt_photourl,cmnt_photourl1);
values.put(cmnt_photodim,cmnt_photodim1);
db.insert(table15,null, values);
db.close();
}
public ArrayList<String> getcmntdetails(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table15;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
arraylist.add(c.getString(7));
arraylist.add(c.getString(8));
}
c.close();
return arraylist;
}
public void deletecmntdetails()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table15);
}
public void add_privacynoti(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table13,null, values);
db.close();
}
public String get_privacynoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table13;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void deletelegalnotice()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table13);
}
void add_message(String adminmsg1, String adminmsg_type1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(adminmsg,adminmsg1);
values.put(adminmsg_type,adminmsg_type1);
db.insert(table12,null, values);
db.close();
}
public ArrayList<String> get_message(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table12;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
}
c.close();
return arraylist;
}
void drop_message()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table12);
}
public String get_noticount(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT count(pkey) FROM " + table10 +" where isread=0";
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void add_cmtnnoti(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table9,null, values);
db.close();
}
public String get_cmntnoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table9;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_cmntnoti()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table9);
}
public void add_notilike(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table8,null, values);
db.close();
}
public String get_likenoti(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table8;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_notilike()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table8);
}
public void add_notistatus(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table7,null, values);
db.close();
}
public String get_notistatus(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table7;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void drop_statusnoti()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table7);
}
public void add_cmntvisible(String notification1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notification,notification1);
db.insert(table4,null, values);
db.close();
}
public String get_cmntvisible(){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table4;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
link=c.getString(0);
}
c.close();
return link;
}
public void deletecmntvisible()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table4);
}
void add_notilist(String notiogid1, String noti_type1, String noti_lastname1, String noti_count1, String noti_text1, String noti_userid1, String isread1, String status_userid1, String status_username1, String status_imgsigid1, String cmnt_statustype1, String cmnt_photourl1, String cmnt_photodim1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(notiogid,notiogid1);
values.put(noti_type,noti_type1);
values.put(noti_lastname,noti_lastname1);
values.put(noti_count,noti_count1);
values.put(noti_text,noti_text1);
values.put(date_created,getDateTime());
values.put(noti_userid,noti_userid1);
values.put(isread,isread1);
values.put(status_userid,status_userid1);
values.put(status_username,status_username1);
values.put(status_imgsigid,status_imgsigid1);
values.put(cmnt_statustype,cmnt_statustype1);
values.put(cmnt_photourl,cmnt_photourl1);
values.put(cmnt_photodim,cmnt_photodim1);
db.insert(table10,null, values);
db.close();
}
public ArrayList<String> get_notilist(String limit){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table10 +" ORDER BY date_created desc LIMIT "+limit+",30";
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
arraylist.add(c.getString(7));
arraylist.add(c.getString(8));
arraylist.add(c.getString(0));
arraylist.add(c.getString(9));
arraylist.add(c.getString(10));
arraylist.add(c.getString(11));
arraylist.add(c.getString(12));
arraylist.add(c.getString(13));
arraylist.add(c.getString(14));
}
c.close();
return arraylist;
}
void deletenotilist()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ table10);
}
public String getlikes(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='0' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getcomments(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='1' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getcomments_bld(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='3' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String get_reply(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='2' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String getreplay_bld(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='4' and notiogid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(4);
}
c.close();
return link;
}
public String get_comments1(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='1' and noti_userid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(5);
}
c.close();
return link;
}
public String getreply1(String id){
String link="";
SQLiteDatabase sql=this.getReadableDatabase();
Cursor c=sql.rawQuery("SELECT * FROM " + table10 +" WHERE noti_type='2' and noti_userid=?", new String[]{id});
while(c.moveToNext()) {
link=c.getString(5);
}
c.close();
return link;
}
public void updatereadstatus(String pkey1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(isread,"1");
db.update(table10, newValues, pkey + " = ?",new String[]{pkey1});
}
public void updatereadstatusall()
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(isread,"1");
db.update(table10, newValues, null,null);
}
public void update_likes(String id, String lastname, String userid1, String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(getlikes(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_userid,userid1);
newValues.put(status_imgsigid,status_imgsigid1);
newValues.put(isread,"0");
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "0"});
}
public void update_cmnts(String id, String lastname, String noti_text1, String userid1, String status_userid1, String status_username1, String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(getcomments(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(noti_userid,userid1);
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
newValues.put(isread,"0");
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "1"});
}
public void updatecomments1(String id,String lastname,String noti_text1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(isread,"0");
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "1"});
}
public void updatereplay(String id,String lastname,String noti_text1,String userid1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(noti_count,(Integer.parseInt(get_reply(id))+1)+"");
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(noti_userid,userid1);
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(isread,"0");
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "2"});
}
public void updatereplay1(String id,String lastname,String noti_text1,String status_userid1,String status_username1,String status_imgsigid1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues newValues = new ContentValues();
newValues.put(noti_lastname,lastname);
newValues.put(date_created,getDateTime());
newValues.put(noti_text,noti_text1);
newValues.put(isread,"0");
newValues.put(status_userid,status_userid1);
newValues.put(status_username,status_username1);
newValues.put(status_imgsigid,status_imgsigid1);
db.update(table10, newValues, notiogid + " = ? AND " + noti_type+ " = ?",new String[]{id, "2"});
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
public void add_fvrtstaus(String userid1, String fvrstatusid1, String fvrstatususerid1, String fvrusername1, String fvrstatustext1, String fvrstatusimgsig1)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(dvrt_userid,userid1);
values.put(fvrstatus,fvrstatusid1);
values.put(fvrstatususerid,fvrstatususerid1);
values.put(fvrusername,fvrusername1);
values.put(fvrstatustext,fvrstatustext1);
values.put(fvrstatusimgsig,fvrstatusimgsig1);
db.insert(table18,null, values);
db.close();
}
public ArrayList<String> get_fvrtstaus(){
ArrayList<String> arraylist = new ArrayList<String>();
SQLiteDatabase sql=this.getReadableDatabase();
String query = "SELECT * FROM " + table18;
Cursor c=sql.rawQuery(query,null);
while(c.moveToNext()) {
arraylist.add(c.getString(0));
arraylist.add(c.getString(1));
arraylist.add(c.getString(2));
arraylist.add(c.getString(3));
arraylist.add(c.getString(4));
arraylist.add(c.getString(5));
arraylist.add(c.getString(6));
}
c.close();
return arraylist;
}
public void deletefvrtcoloum(String pkey1)
{
SQLiteDatabase db = this.getWritableDatabase();
db.delete(table18, pkey+"="+pkey1, null);
}
} | 26,315 | 0.686415 | 0.670226 | 712 | 34.962078 | 37.831306 | 436 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.435393 | false | false | 6 |
d8cfda3f2514886daaaeb7f3e6279f97d32d1b10 | 163,208,789,431 | 0460e3823002478cc6299077ea86f3ab076fc158 | /src/day35_ArrayList/ReversedOder.java | 259a4cedb74f1a346196414d11bf44e4b2b20837 | [] | no_license | yonashaile12/Summer2020_B20 | https://github.com/yonashaile12/Summer2020_B20 | b3a966b116a8a59b508e604f31e3f4bfb1674eac | 151b8fc646b67eabd52aeaedf51da92df078cbfa | refs/heads/master | 2023-03-11T15:56:46.143000 | 2021-02-28T03:53:38 | 2021-02-28T03:53:38 | 276,238,236 | 1 | 0 | null | true | 2020-07-01T00:27:23 | 2020-07-01T00:27:23 | 2020-07-01T00:25:28 | 2020-07-01T00:25:26 | 117 | 0 | 0 | 0 | null | false | false | package day35_ArrayList;
import java.util.ArrayList;
/*
1. write a program that can print the list of integers in reversed order
ex:
list=> {1,2,3,4,5}
output: 5 4 3 2 1
*/
public class ReversedOder {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // 0
list.add(20); // 1
// list.add(3, 30); // cannot skip indexes
list.add(2, 30); //2
list.add(40); // 3
list.add(50); // 4
System.out.println(list);
for(int i = list.size()-1; i >= 0; i--){
System.out.print( list.get(i) +" " );
}
}
}
| UTF-8 | Java | 745 | java | ReversedOder.java | Java | [] | null | [] | package day35_ArrayList;
import java.util.ArrayList;
/*
1. write a program that can print the list of integers in reversed order
ex:
list=> {1,2,3,4,5}
output: 5 4 3 2 1
*/
public class ReversedOder {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10); // 0
list.add(20); // 1
// list.add(3, 30); // cannot skip indexes
list.add(2, 30); //2
list.add(40); // 3
list.add(50); // 4
System.out.println(list);
for(int i = list.size()-1; i >= 0; i--){
System.out.print( list.get(i) +" " );
}
}
}
| 745 | 0.467114 | 0.421477 | 31 | 23.032259 | 21.203293 | 73 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.612903 | false | false | 6 |
d53a3c94dfac2157dae8c96dbf74e343346ddf11 | 14,877,766,750,366 | 98cb9afd5ff42bc6d87b63a574a6879806a57a42 | /youlai-admin/src/main/java/com/youlai/admin/controller/UserController.java | 5a6e57db81900072c7d9afe256222aeb4958cd04 | [] | no_license | MavonCmc/youlai | https://github.com/MavonCmc/youlai | 783489dfcbb7fd7201648025150c52c0a5f699cb | d41f9177fdc5b67db337f775aedebdc018dece4e | refs/heads/master | 2023-07-28T10:33:18.934000 | 2021-09-16T10:31:00 | 2021-09-16T10:31:00 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.youlai.admin.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.result.Result;
import com.youlai.admin.api.pojo.entity.SysUser;
import com.youlai.admin.api.pojo.entity.SysUserRole;
import com.youlai.admin.service.ISysUserRoleService;
import com.youlai.admin.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author:GSHG
* @date: 2021-08-19 11:14
* description:
*/
@Api(tags = " 用户接口 ")
@RestController
@RequestMapping("/api/v1/users")
@Slf4j
@AllArgsConstructor
public class UserController {
@Autowired
private ISysUserService iSysUserService;
@Autowired
private ISysUserRoleService iSysUserRoleService;
@ApiOperation(value = "列表分页",httpMethod = "GET")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "nickname", value = "用户昵称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "mobile", value = "手机号码", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "status", value = "状态", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "deptId", value = "部门ID", paramType = "query", dataType = "Long"),
})
@GetMapping
public Result list( Integer page,
Integer limit,
String nickname,
String mobile,
Integer status,
Long deptId){
SysUser user = new SysUser();
user.setNickname(nickname);
user.setMobile(mobile);
user.setStatus(status);
user.setDeptId(deptId);
IPage<SysUser> result = iSysUserService.list(new Page<>(page,limit),user);
return Result.success(result.getRecords(),result.getTotal());
}
@ApiOperation(value = "用户详情")
@ApiImplicitParam(name = "id",value = "用户id",required = true,paramType = "path",dataType = "Long")
@GetMapping("/{id}")
public Result detail(@PathVariable Long id){
SysUser user = iSysUserService.getById(id);
if(user != null){
List<Long> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getRoleId,user.getId())
.select(SysUserRole::getRoleId)
).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
user.setRoleIds(roleIds);
}
return Result.success(user);
}
@ApiOperation(value = "根据用户名获取用户信息")
@ApiImplicitParam(name = "username",value = "用户名",required = true,paramType = "path",dataType = "String")
@GetMapping("username/{username}")
public Result<SysUser> getUserByUsername(@PathVariable String username){
SysUser user = iSysUserService.getByUsername(username);
return Result.success(user);
}
}
| UTF-8 | Java | 3,875 | java | UserController.java | Java | [
{
"context": "ort java.util.stream.Collectors;\n\n\n/**\n * @author:GSHG\n * @date: 2021-08-19 11:14\n * description:\n */\n@A",
"end": 1110,
"score": 0.9996998906135559,
"start": 1106,
"tag": "USERNAME",
"value": "GSHG"
}
] | null | [] | package com.youlai.admin.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.result.Result;
import com.youlai.admin.api.pojo.entity.SysUser;
import com.youlai.admin.api.pojo.entity.SysUserRole;
import com.youlai.admin.service.ISysUserRoleService;
import com.youlai.admin.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author:GSHG
* @date: 2021-08-19 11:14
* description:
*/
@Api(tags = " 用户接口 ")
@RestController
@RequestMapping("/api/v1/users")
@Slf4j
@AllArgsConstructor
public class UserController {
@Autowired
private ISysUserService iSysUserService;
@Autowired
private ISysUserRoleService iSysUserRoleService;
@ApiOperation(value = "列表分页",httpMethod = "GET")
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "页码", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "limit", value = "每页数量", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "nickname", value = "用户昵称", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "mobile", value = "手机号码", paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "status", value = "状态", paramType = "query", dataType = "Long"),
@ApiImplicitParam(name = "deptId", value = "部门ID", paramType = "query", dataType = "Long"),
})
@GetMapping
public Result list( Integer page,
Integer limit,
String nickname,
String mobile,
Integer status,
Long deptId){
SysUser user = new SysUser();
user.setNickname(nickname);
user.setMobile(mobile);
user.setStatus(status);
user.setDeptId(deptId);
IPage<SysUser> result = iSysUserService.list(new Page<>(page,limit),user);
return Result.success(result.getRecords(),result.getTotal());
}
@ApiOperation(value = "用户详情")
@ApiImplicitParam(name = "id",value = "用户id",required = true,paramType = "path",dataType = "Long")
@GetMapping("/{id}")
public Result detail(@PathVariable Long id){
SysUser user = iSysUserService.getById(id);
if(user != null){
List<Long> roleIds = iSysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>()
.eq(SysUserRole::getRoleId,user.getId())
.select(SysUserRole::getRoleId)
).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
user.setRoleIds(roleIds);
}
return Result.success(user);
}
@ApiOperation(value = "根据用户名获取用户信息")
@ApiImplicitParam(name = "username",value = "用户名",required = true,paramType = "path",dataType = "String")
@GetMapping("username/{username}")
public Result<SysUser> getUserByUsername(@PathVariable String username){
SysUser user = iSysUserService.getByUsername(username);
return Result.success(user);
}
}
| 3,875 | 0.674068 | 0.669839 | 98 | 37.602039 | 29.976093 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.806122 | false | false | 6 |
08b03e77d9370a4cf63020d4e42a4dc1c3b25f05 | 14,877,766,746,528 | a3edf5e5c6a171c825a66a32f249f2ff6586fa78 | /Spring循环依赖/src/test/java/cn/mayday/springrecycledp/SpringRecycledpApplicationTests.java | 35f04d4d0ae3c06aa87219c87130d6215e0e4e11 | [] | no_license | mayday05/Spring_Action_mayday | https://github.com/mayday05/Spring_Action_mayday | dace5712c34c49749b33f9b40852cb6830331d46 | 57e4b0737d946fa30d023822d88fa229cd8b4331 | refs/heads/master | 2022-06-28T03:07:53.980000 | 2019-07-02T16:11:03 | 2019-07-02T16:11:03 | 179,304,226 | 1 | 0 | null | false | 2022-06-21T01:23:08 | 2019-04-03T14:11:44 | 2019-07-02T16:11:20 | 2022-06-21T01:23:05 | 358 | 1 | 0 | 1 | Java | false | false | package cn.mayday.springrecycledp;
import cn.mayday.springrecycledp.demo1.StudentA;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRecycledpApplicationTests {
@Test
public void contextLoads() {
}
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext1.xml");
}
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext2.xml");
System.out.println(context.getBean("a", StudentA.class));
}
@Test
public void test3() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext3.xml");
System.out.println(context.getBean("a", StudentA.class));
}
}
| UTF-8 | Java | 1,131 | java | SpringRecycledpApplicationTests.java | Java | [] | null | [] | package cn.mayday.springrecycledp;
import cn.mayday.springrecycledp.demo1.StudentA;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringRecycledpApplicationTests {
@Test
public void contextLoads() {
}
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext1.xml");
}
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext2.xml");
System.out.println(context.getBean("a", StudentA.class));
}
@Test
public void test3() {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext3.xml");
System.out.println(context.getBean("a", StudentA.class));
}
}
| 1,131 | 0.758621 | 0.751547 | 37 | 29.567568 | 32.364094 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.405405 | false | false | 6 |
6b4a83c142a6ed31cdf166902e8bd1d42b668c75 | 7,198,365,218,778 | 6f1342c942910b789e7a4d0ed07b6c56188d4136 | /ASAASys/src/vo/GrailsSearchVO.java | a41fc839460e8f7fc20a46d48f01aac7ede5196a | [] | no_license | syntheticGod/ZJUPR | https://github.com/syntheticGod/ZJUPR | 668b75328d4ec3b14b9e73971c3ee7390b10676e | 7f2584a15b00358a92eeb3520cfa4185683c7be4 | refs/heads/master | 2020-03-29T19:57:59.955000 | 2018-10-26T04:57:13 | 2018-10-26T04:57:13 | 150,289,100 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package vo;
public class GrailsSearchVO {
private String beginDate;
private String endDate;
private double kaipanMin;
private double kaipanMax;
private double shoupanMin;
private double shoupanMax;
private double maxMax;
private double maxMin;
private double minMax;
private double minMin;
public GrailsSearchVO( String beginDate,
String endDate,
double kaipanMin,
double kaipanMax,
double shoupanMin,
double shoupanMax,
double maxMin,
double maxMax,
double minMin,
double minMax ){
this.beginDate=beginDate;
this.endDate=endDate;
this.kaipanMin=kaipanMin;
this.kaipanMax=kaipanMax;
this.shoupanMin=shoupanMin;
this.shoupanMax=shoupanMax;
this.maxMax=maxMax;
this.maxMin=maxMin;
this.minMax=minMax;
this.minMin=minMin;
}
public String getBeginDate(){
return beginDate;
}
public String getEndDate(){
return endDate;
}
public double getKaipanMin(){
return kaipanMin;
}
public double getKaipanMax(){
return kaipanMax;
}
public double getShoupanMin(){
return shoupanMin;
}
public double getShoupanMax(){
return shoupanMax;
}
public double getMaxMax(){
return maxMax;
}
public double getMaxMin(){
return maxMin;
}
public double getMinMax(){
return minMax;
}
public double getMinMin(){
return minMin;
}
}
| UTF-8 | Java | 1,338 | java | GrailsSearchVO.java | Java | [] | null | [] | package vo;
public class GrailsSearchVO {
private String beginDate;
private String endDate;
private double kaipanMin;
private double kaipanMax;
private double shoupanMin;
private double shoupanMax;
private double maxMax;
private double maxMin;
private double minMax;
private double minMin;
public GrailsSearchVO( String beginDate,
String endDate,
double kaipanMin,
double kaipanMax,
double shoupanMin,
double shoupanMax,
double maxMin,
double maxMax,
double minMin,
double minMax ){
this.beginDate=beginDate;
this.endDate=endDate;
this.kaipanMin=kaipanMin;
this.kaipanMax=kaipanMax;
this.shoupanMin=shoupanMin;
this.shoupanMax=shoupanMax;
this.maxMax=maxMax;
this.maxMin=maxMin;
this.minMax=minMax;
this.minMin=minMin;
}
public String getBeginDate(){
return beginDate;
}
public String getEndDate(){
return endDate;
}
public double getKaipanMin(){
return kaipanMin;
}
public double getKaipanMax(){
return kaipanMax;
}
public double getShoupanMin(){
return shoupanMin;
}
public double getShoupanMax(){
return shoupanMax;
}
public double getMaxMax(){
return maxMax;
}
public double getMaxMin(){
return maxMin;
}
public double getMinMax(){
return minMax;
}
public double getMinMin(){
return minMin;
}
}
| 1,338 | 0.718984 | 0.718984 | 73 | 17.328768 | 11.329504 | 46 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.780822 | false | false | 6 |
6577793cdd6a9cd96ce8448d1c0fe59ed0196536 | 4,501,125,783,996 | c000548cb018cb4206d0a4df9ec3fbd098225e5a | /src/main/java/com/ndsc/blog/mapper/TagMapper.java | c8dcdd698a58a4c1cdb78ef393037d45210c5e0c | [] | no_license | fearzero/blog | https://github.com/fearzero/blog | 886248d2b8686c615b3c729b239af8d991d223dc | da8c584b9fd92876829bb67aa7d4c1b708455a03 | refs/heads/master | 2020-07-25T07:16:33.054000 | 2019-09-21T05:34:26 | 2019-09-21T05:34:26 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.ndsc.blog.mapper;
import com.ndsc.blog.entity.Tag;
public interface TagMapper {
int insert(Tag record);
int insertSelective(Tag record);
} | UTF-8 | Java | 161 | java | TagMapper.java | Java | [] | null | [] | package com.ndsc.blog.mapper;
import com.ndsc.blog.entity.Tag;
public interface TagMapper {
int insert(Tag record);
int insertSelective(Tag record);
} | 161 | 0.73913 | 0.73913 | 9 | 17 | 15.180397 | 36 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 6 |
dc88edf1b4d37e91ffbdd85ecb686f85c7f42c5b | 18,769,007,087,368 | d1ee4ec8886774a5460ca5b7314085500502473e | /src/algos/Recursive.java | f103dca43423583fe0fe58f909c4f74aa40bbe6e | [] | no_license | allanx2000/Algorithms | https://github.com/allanx2000/Algorithms | 4e1545f7fb91c1be492368a049022dfb58be361a | 890e2457aa7f16f232ce0985cd037deb09044a61 | refs/heads/master | 2021-01-13T14:28:39.408000 | 2017-01-16T13:49:01 | 2017-01-16T13:49:01 | 79,071,493 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package algos;
/**
* Created by Allan on 1/12/2017.
*/
public interface Recursive {
void printLevel();
}
| UTF-8 | Java | 112 | java | Recursive.java | Java | [
{
"context": "package algos;\n\n/**\n * Created by Allan on 1/12/2017.\n */\npublic interface Recursive {\n ",
"end": 39,
"score": 0.9997929334640503,
"start": 34,
"tag": "NAME",
"value": "Allan"
}
] | null | [] | package algos;
/**
* Created by Allan on 1/12/2017.
*/
public interface Recursive {
void printLevel();
}
| 112 | 0.651786 | 0.589286 | 8 | 13 | 12.349089 | 33 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 6 |
ff710482097e018f74e97e2a5c08b4266d424631 | 18,416,819,771,866 | 352bfdfb8c772e7bf3eb56c37d96dde3c5986ee2 | /src/remeniaka/Lesson4/TaskB1.java | a769ccf6ef80d23f5d7df53b728accc959c275c0 | [] | no_license | Shumski-Sergey/CS2019-15-05 | https://github.com/Shumski-Sergey/CS2019-15-05 | 3ae0adfa52ea5684a17babcae003af78ada2e435 | e23f4146005571cedf91e9d260efe2bc5105ef33 | refs/heads/master | 2020-05-24T11:41:45.414000 | 2019-05-28T21:13:00 | 2019-05-28T21:13:00 | 187,252,197 | 0 | 17 | null | null | null | null | null | null | null | null | null | null | null | null | null | package remeniaka.Lesson4;
import java.util.ArrayList;
public class TaskB1 {
public static void main(String[] args){
ArrayList list=new ArrayList();
list.add("May");
list.add("June");
list.add("July");
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}} } | UTF-8 | Java | 389 | java | TaskB1.java | Java | [
{
"context": "rrayList list=new ArrayList();\n\n list.add(\"May\");\n list.add(\"June\");\n list.add(\"Ju",
"end": 185,
"score": 0.9938341379165649,
"start": 182,
"tag": "NAME",
"value": "May"
},
{
"context": "st();\n\n list.add(\"May\");\n list.add... | null | [] | package remeniaka.Lesson4;
import java.util.ArrayList;
public class TaskB1 {
public static void main(String[] args){
ArrayList list=new ArrayList();
list.add("May");
list.add("June");
list.add("July");
System.out.println(list.size());
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}} } | 389 | 0.55527 | 0.547558 | 17 | 21.941177 | 16.710232 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 6 |
95347ac33d79e003e3f9d7d865c5a2b799932849 | 27,453,430,960,564 | c3623021352d538ac2b21902a694a677b9793725 | /indexer/src/main/java/com/emSoft/miPos/indexer/block/model/DriverBlock.java | fd914d147e1fc659804f9d90af2e931cdac3df20 | [] | no_license | gonzaloGonzalo/miPos | https://github.com/gonzaloGonzalo/miPos | 4e38c53e5bf854f3469b6d52f5317fdc3e90eb8a | 6586690810d333690d130394bf796e5df5544c4c | refs/heads/master | 2020-03-16T13:26:32.660000 | 2018-06-25T03:53:59 | 2018-06-25T03:53:59 | 132,690,476 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.emSoft.miPos.indexer.block.model;
import com.emSoft.miPos.indexer.block.handler.visitor.BlockVisitor;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.time.ZonedDateTime;
import java.util.Map;
/**
* Created by computer on 23/05/18.
*/
@Entity
@Table(name = "driver")
public class DriverBlock extends Block {
private DriverAttributes driverAttributes;
public void accept(final BlockVisitor blockVisitor){
blockVisitor.visit(this);
}
public DriverAttributes getDriverAttributes() {
return driverAttributes;
}
public void setDriverAttributes(DriverAttributes driverAttributes) {
this.driverAttributes = driverAttributes;
}
public void mapValues(Map<String, String> messageMap){
super.mapValues(messageMap);
}
}
| UTF-8 | Java | 826 | java | DriverBlock.java | Java | [
{
"context": "DateTime;\nimport java.util.Map;\n\n/**\n * Created by computer on 23/05/18.\n */\n@Entity\n@Table(name = \"driver\")\n",
"end": 262,
"score": 0.9978756904602051,
"start": 254,
"tag": "USERNAME",
"value": "computer"
}
] | null | [] | package com.emSoft.miPos.indexer.block.model;
import com.emSoft.miPos.indexer.block.handler.visitor.BlockVisitor;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.time.ZonedDateTime;
import java.util.Map;
/**
* Created by computer on 23/05/18.
*/
@Entity
@Table(name = "driver")
public class DriverBlock extends Block {
private DriverAttributes driverAttributes;
public void accept(final BlockVisitor blockVisitor){
blockVisitor.visit(this);
}
public DriverAttributes getDriverAttributes() {
return driverAttributes;
}
public void setDriverAttributes(DriverAttributes driverAttributes) {
this.driverAttributes = driverAttributes;
}
public void mapValues(Map<String, String> messageMap){
super.mapValues(messageMap);
}
}
| 826 | 0.736077 | 0.728814 | 34 | 23.294117 | 22.482058 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.352941 | false | false | 6 |
d8468bb78f4562f9f08c6d5b1fb9e2a6a821d995 | 1,967,095,032,609 | 79814772d82719966c455b823bef43f2635971b6 | /src/test/java/au/org/ala/names/index/provider/KeyAdjusterTest.java | 9759d26e43373bdab9cdd867be6879360f4b7a79 | [] | no_license | rpfigueira/ala-name-matching | https://github.com/rpfigueira/ala-name-matching | 2fe82c6bb40179f38c17bb6fb5744c94b6251a03 | 1a4b021639a68f2369659e1a1ca3ad82c9e83255 | refs/heads/master | 2021-04-09T01:02:31.451000 | 2019-12-02T23:30:36 | 2019-12-02T23:30:36 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package au.org.ala.names.index.provider;
import au.org.ala.names.index.*;
import au.org.ala.names.model.RankType;
import au.org.ala.names.model.TaxonomicType;
import au.org.ala.names.util.TestUtils;
import org.gbif.api.vocabulary.NameType;
import org.gbif.api.vocabulary.NomenclaturalCode;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test cases for {@link KeyAdjuster}
*
* @author Doug Palmer <Doug.Palmer@csiro.au>
* @copyright Copyright © 2017 Atlas of Living Australia
*/
public class KeyAdjusterTest extends TestUtils {
private NameAnalyser analyser;
private KeyAdjuster adjuster;
private NameProvider provider;
@Before
public void setup() {
this.analyser = new ALANameAnalyser();
this.provider = new NameProvider();
this.adjuster = new KeyAdjuster();
MatchTaxonCondition condition1 = new MatchTaxonCondition();
condition1.setScientificName("Viruses");
this.adjuster.addAdjustment(new KeyAdjustment(condition1, null, "VIRUS", null, null, null));
MatchTaxonCondition condition2 = new MatchTaxonCondition();
condition2.setNomenclaturalCode(NomenclaturalCode.PHYLOCODE);
this.adjuster.addAdjustment(new KeyAdjustment(condition2, NomenclaturalCode.BACTERIAL, null, "", null, null));
MatchTaxonCondition condition3 = new MatchTaxonCondition();
condition3.setTaxonRank(RankType.DOMAIN);
this.adjuster.addAdjustment(new KeyAdjustment(condition3, NomenclaturalCode.CULTIVARS, "PLACEHOLDER", "Nurke", NameType.CULTIVAR, RankType.CULTIVAR));
}
@Test
public void testAdjust1() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.ZOOLOGICAL, "Osphranter rufus", this.provider, TaxonomicType.ACCEPTED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertSame(key, key2);
}
@Test
public void testAdjust2() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.BOTANICAL, NomenclaturalCode.BOTANICAL.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.MISAPPLIED, TaxonomicType.MISAPPLIED.getTerm(), RankType.SPECIES, RankType.SPECIES.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertSame(key, key2);
}
@Test
public void testAdjust3() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.VIRUS, "Viruses", this.provider, TaxonomicType.ACCEPTED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(key.getCode(), key2.getCode());
assertEquals("VIRUS", key2.getScientificName());
assertEquals(key.getScientificNameAuthorship(), key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust4() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.PHYLOCODE, "Viruses", this.provider, TaxonomicType.MISAPPLIED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.BACTERIAL, key2.getCode());
assertEquals("VIRUS", key2.getScientificName());
assertEquals(key.getScientificNameAuthorship(), key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust5() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.PHYLOCODE, NomenclaturalCode.PHYLOCODE.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.ACCEPTED, TaxonomicType.ACCEPTED.getTerm(), RankType.SPECIES, RankType.SPECIES.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.BACTERIAL, key2.getCode());
assertEquals(key.getScientificName(), key2.getScientificName());
assertNull(key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust6() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.BOTANICAL, NomenclaturalCode.BOTANICAL.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.MISAPPLIED, TaxonomicType.MISAPPLIED.getTerm(), RankType.DOMAIN, RankType.DOMAIN.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.CULTIVARS, key2.getCode());
assertEquals("PLACEHOLDER", key2.getScientificName());
assertEquals("Nurke", key2.getScientificNameAuthorship());
assertEquals(NameType.CULTIVAR, key2.getType());
assertEquals(RankType.CULTIVAR, key2.getRank());
}
}
| UTF-8 | Java | 6,296 | java | KeyAdjusterTest.java | Java | [
{
"context": "* Test cases for {@link KeyAdjuster}\n *\n * @author Doug Palmer <Doug.Palmer@csiro.au>\n * @copyright Copyri",
"end": 442,
"score": 0.9998840093612671,
"start": 431,
"tag": "NAME",
"value": "Doug Palmer"
},
{
"context": "{@link KeyAdjuster}\n *\n * @author Doug P... | null | [] | package au.org.ala.names.index.provider;
import au.org.ala.names.index.*;
import au.org.ala.names.model.RankType;
import au.org.ala.names.model.TaxonomicType;
import au.org.ala.names.util.TestUtils;
import org.gbif.api.vocabulary.NameType;
import org.gbif.api.vocabulary.NomenclaturalCode;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Test cases for {@link KeyAdjuster}
*
* @author <NAME> <<EMAIL>>
* @copyright Copyright © 2017 Atlas of Living Australia
*/
public class KeyAdjusterTest extends TestUtils {
private NameAnalyser analyser;
private KeyAdjuster adjuster;
private NameProvider provider;
@Before
public void setup() {
this.analyser = new ALANameAnalyser();
this.provider = new NameProvider();
this.adjuster = new KeyAdjuster();
MatchTaxonCondition condition1 = new MatchTaxonCondition();
condition1.setScientificName("Viruses");
this.adjuster.addAdjustment(new KeyAdjustment(condition1, null, "VIRUS", null, null, null));
MatchTaxonCondition condition2 = new MatchTaxonCondition();
condition2.setNomenclaturalCode(NomenclaturalCode.PHYLOCODE);
this.adjuster.addAdjustment(new KeyAdjustment(condition2, NomenclaturalCode.BACTERIAL, null, "", null, null));
MatchTaxonCondition condition3 = new MatchTaxonCondition();
condition3.setTaxonRank(RankType.DOMAIN);
this.adjuster.addAdjustment(new KeyAdjustment(condition3, NomenclaturalCode.CULTIVARS, "PLACEHOLDER", "Nurke", NameType.CULTIVAR, RankType.CULTIVAR));
}
@Test
public void testAdjust1() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.ZOOLOGICAL, "Osphranter rufus", this.provider, TaxonomicType.ACCEPTED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertSame(key, key2);
}
@Test
public void testAdjust2() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.BOTANICAL, NomenclaturalCode.BOTANICAL.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.MISAPPLIED, TaxonomicType.MISAPPLIED.getTerm(), RankType.SPECIES, RankType.SPECIES.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertSame(key, key2);
}
@Test
public void testAdjust3() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.VIRUS, "Viruses", this.provider, TaxonomicType.ACCEPTED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(key.getCode(), key2.getCode());
assertEquals("VIRUS", key2.getScientificName());
assertEquals(key.getScientificNameAuthorship(), key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust4() {
TaxonConceptInstance instance = this.createInstance("ID-1", NomenclaturalCode.PHYLOCODE, "Viruses", this.provider, TaxonomicType.MISAPPLIED );
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.BACTERIAL, key2.getCode());
assertEquals("VIRUS", key2.getScientificName());
assertEquals(key.getScientificNameAuthorship(), key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust5() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.PHYLOCODE, NomenclaturalCode.PHYLOCODE.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.ACCEPTED, TaxonomicType.ACCEPTED.getTerm(), RankType.SPECIES, RankType.SPECIES.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.BACTERIAL, key2.getCode());
assertEquals(key.getScientificName(), key2.getScientificName());
assertNull(key2.getScientificNameAuthorship());
assertEquals(key.getType(), key2.getType());
assertEquals(key.getRank(), key2.getRank());
}
@Test
public void testAdjust6() {
TaxonConceptInstance instance = new TaxonConceptInstance("ID-1", NomenclaturalCode.BOTANICAL, NomenclaturalCode.BOTANICAL.getAcronym(), this.provider,"Acacia dealbata", "Link.", null,null, TaxonomicType.MISAPPLIED, TaxonomicType.MISAPPLIED.getTerm(), RankType.DOMAIN, RankType.DOMAIN.getRank(), null, null,null, null, null, null, null, null, null, null);
NameKey key = this.analyser.analyse(instance.getCode(), instance.getScientificName(), instance.getScientificNameAuthorship(), instance.getRank(), null, false);
NameKey key2 = this.adjuster.adjustKey(key, instance);
assertNotSame(key, key2);
assertEquals(NomenclaturalCode.CULTIVARS, key2.getCode());
assertEquals("PLACEHOLDER", key2.getScientificName());
assertEquals("Nurke", key2.getScientificNameAuthorship());
assertEquals(NameType.CULTIVAR, key2.getType());
assertEquals(RankType.CULTIVAR, key2.getRank());
}
}
| 6,278 | 0.723316 | 0.714263 | 110 | 56.236362 | 67.552124 | 365 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.027273 | false | false | 6 |
eb1c5c83fdb34fa12bafcc547856a8a5b0d343b2 | 10,617,159,198,023 | c0cc7af8bfd85bc58a5518456d8ae63d025d0120 | /src/main/java/com/example/pello/pelloweather/util/Utility.java | ba197340091bc6a5d5a8df5bdfd96a0fc8dafb7c | [
"Apache-2.0"
] | permissive | pellogan/pelloweather | https://github.com/pellogan/pelloweather | 1756863b830dcf6e0b3173ce02a29dcafd2c016c | 0e4a3226807a9a4ae7b59aabcd6e9ebc50fa6a0a | refs/heads/master | 2021-01-10T05:32:51.759000 | 2016-03-22T14:08:38 | 2016-03-22T14:08:38 | 52,268,783 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.pello.pelloweather.util;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.preference.PreferenceManager;
import com.example.pello.pelloweather.activity.MyApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.content.ContextWrapper;
/**
* Created by Pello on 2016/3/1.
*/
public class Utility {
//解析服务器返回的天气json数据,保存到本地数据文件里
public static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject aqiJson = jsonObject.getJSONObject("aqi");
JSONObject realtime = jsonObject.getJSONObject("realtime");
JSONObject todayWeather = jsonObject.getJSONObject("today");
JSONObject yesterdayWeather = jsonObject.getJSONObject("yestoday");
String cityName = aqiJson.getString("city");
String cityCode = aqiJson.getString("city_id");
String pm25 = aqiJson.getString("pm25");
String aqi = aqiJson.getString("aqi");
String temp1 = todayWeather.getString("tempMin");
String temp2 = todayWeather.getString("tempMax");
String realTimeWeather = getRealTimeWeather(realtime);
String weatherToday = getWeatherDescription(todayWeather);
String weatherYesterday = getWeatherDescription(yesterdayWeather);
saveWeahterInfo(context, cityName, cityCode, realTimeWeather, weatherToday, weatherYesterday,
pm25, aqi, temp1, temp2);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void saveWeahterInfo(Context context, String cityName, String cityCode,
String realTimeWeather, String weatherToday, String weatherYesterday,
String pm25, String aqi, String temp1, String temp2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected", true)
.putString("city_name", cityName)
.putString("city_code", cityCode)
.putString("realtime_weather", realTimeWeather)
.putString("weather_today", weatherToday)
.putString("weather_yesterday", weatherYesterday)
.putString("current_date", sdf.format(new Date()))
.putString("pm25", pm25)
.putString("aqi", aqi)
.putString("temp1", temp1)
.putString("temp2", temp2)
.commit();
}
private static String getRealTimeWeather(JSONObject realtime) {
StringBuffer weather = new StringBuffer();
try {
weather.append(realtime.getString("temp") + "℃ ");
weather.append(realtime.getString("weather"));
weather.append(" 湿度:" + realtime.getString("SD") + " ");
weather.append("refreshTime:" + realtime.getString("time"));
} catch (JSONException e) {
e.printStackTrace();
}
return weather.toString();
}
public static String getWeatherDescription(JSONObject jsonWeather) {
StringBuffer weather = new StringBuffer();
try {
String tempMin = jsonWeather.getString("tempMin");
String tempMax = jsonWeather.getString("tempMax");
weather.append(tempMin + "℃");
if (tempMin.equals(tempMax)) {
weather.append(" ");
} else {
weather.append("~" + tempMax + "℃ ");
}
String weatherStart = jsonWeather.getString("weatherStart");
String weatherEnd = jsonWeather.getString("weatherEnd");
weather.append(weatherStart);
if (weatherStart.equals(weatherEnd)) {
weather.append(" , ");
} else {
weather.append("转" + weatherEnd + " , ");
}
String windStart = jsonWeather.getString("windDirectionStart");
String windEnd = jsonWeather.getString("windDirectionEnd");
weather.append(windStart);
if (windStart.equals(windEnd)) {
weather.append(".");
} else {
weather.append("转" + windEnd + ".");
}
} catch (JSONException e) {
e.printStackTrace();
}
return weather.toString();
}
}
| UTF-8 | Java | 4,979 | java | Utility.java | Java | [
{
"context": "ndroid.content.ContextWrapper;\n\n\n/**\n * Created by Pello on 2016/3/1.\n */\npublic class Utility {\n\n\n //解",
"end": 655,
"score": 0.9988313913345337,
"start": 650,
"tag": "USERNAME",
"value": "Pello"
}
] | null | [] | package com.example.pello.pelloweather.util;
import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.preference.PreferenceManager;
import com.example.pello.pelloweather.activity.MyApplication;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.content.ContextWrapper;
/**
* Created by Pello on 2016/3/1.
*/
public class Utility {
//解析服务器返回的天气json数据,保存到本地数据文件里
public static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject aqiJson = jsonObject.getJSONObject("aqi");
JSONObject realtime = jsonObject.getJSONObject("realtime");
JSONObject todayWeather = jsonObject.getJSONObject("today");
JSONObject yesterdayWeather = jsonObject.getJSONObject("yestoday");
String cityName = aqiJson.getString("city");
String cityCode = aqiJson.getString("city_id");
String pm25 = aqiJson.getString("pm25");
String aqi = aqiJson.getString("aqi");
String temp1 = todayWeather.getString("tempMin");
String temp2 = todayWeather.getString("tempMax");
String realTimeWeather = getRealTimeWeather(realtime);
String weatherToday = getWeatherDescription(todayWeather);
String weatherYesterday = getWeatherDescription(yesterdayWeather);
saveWeahterInfo(context, cityName, cityCode, realTimeWeather, weatherToday, weatherYesterday,
pm25, aqi, temp1, temp2);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void saveWeahterInfo(Context context, String cityName, String cityCode,
String realTimeWeather, String weatherToday, String weatherYesterday,
String pm25, String aqi, String temp1, String temp2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putBoolean("city_selected", true)
.putString("city_name", cityName)
.putString("city_code", cityCode)
.putString("realtime_weather", realTimeWeather)
.putString("weather_today", weatherToday)
.putString("weather_yesterday", weatherYesterday)
.putString("current_date", sdf.format(new Date()))
.putString("pm25", pm25)
.putString("aqi", aqi)
.putString("temp1", temp1)
.putString("temp2", temp2)
.commit();
}
private static String getRealTimeWeather(JSONObject realtime) {
StringBuffer weather = new StringBuffer();
try {
weather.append(realtime.getString("temp") + "℃ ");
weather.append(realtime.getString("weather"));
weather.append(" 湿度:" + realtime.getString("SD") + " ");
weather.append("refreshTime:" + realtime.getString("time"));
} catch (JSONException e) {
e.printStackTrace();
}
return weather.toString();
}
public static String getWeatherDescription(JSONObject jsonWeather) {
StringBuffer weather = new StringBuffer();
try {
String tempMin = jsonWeather.getString("tempMin");
String tempMax = jsonWeather.getString("tempMax");
weather.append(tempMin + "℃");
if (tempMin.equals(tempMax)) {
weather.append(" ");
} else {
weather.append("~" + tempMax + "℃ ");
}
String weatherStart = jsonWeather.getString("weatherStart");
String weatherEnd = jsonWeather.getString("weatherEnd");
weather.append(weatherStart);
if (weatherStart.equals(weatherEnd)) {
weather.append(" , ");
} else {
weather.append("转" + weatherEnd + " , ");
}
String windStart = jsonWeather.getString("windDirectionStart");
String windEnd = jsonWeather.getString("windDirectionEnd");
weather.append(windStart);
if (windStart.equals(windEnd)) {
weather.append(".");
} else {
weather.append("转" + windEnd + ".");
}
} catch (JSONException e) {
e.printStackTrace();
}
return weather.toString();
}
}
| 4,979 | 0.611055 | 0.605365 | 137 | 34.919708 | 28.060949 | 109 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.70073 | false | false | 5 |
57484fe192e12c4f6955a5af19f2f25c7d4423e4 | 22,892,175,717,273 | c84c19c6055587461da8b13258609f640e217a1d | /src/main/java/com/diana/service/TimetableServiceImpl.java | e6ead02efa428879a3c77463bd98dd690bdcff5e | [] | no_license | iasai1/TMDF | https://github.com/iasai1/TMDF | b1623a61a2a5aa9d0e61383c9dad5c4c0daa7fce | fc7edb24a4970db9a662fe3cf1a3d1e548d0d5a8 | refs/heads/master | 2020-09-14T01:22:36.610000 | 2019-11-20T15:17:11 | 2019-11-20T15:17:11 | 222,966,108 | 0 | 0 | null | false | 2020-06-18T16:58:18 | 2019-11-20T15:17:02 | 2019-11-20T15:17:18 | 2020-06-18T16:58:15 | 94 | 0 | 0 | 4 | Java | false | false | package com.diana.service;
import com.diana.dao.EventDAO;
import com.diana.dao.TimetableDAO;
import com.diana.model.Event;
import com.diana.model.Timetable;
import com.diana.model.Treatment;
import com.diana.util.error.TimeUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class TimetableServiceImpl implements TimetableService{
@Autowired
private TimetableDAO timetableDAO;
static final Logger LOG = LoggerFactory.getLogger(TimetableServiceImpl.class);
@Override
public String hasAvailableCabinet(LocalDate date, LocalTime time, Treatment treatment) throws TimeUnavailableException {
LOG.info("Checking for cabinet availability on" + date.minusDays(1) + ", at " + time);
Timetable timetable = timetableDAO.getByDateAndTime(date, time);
if (timetable == null){
throw new TimeUnavailableException(date.minusDays(1), time);
}
switch (treatment.getName()){
case "ECG":
if (timetable.getCabinetECG() == null){
return "ECG cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
case "MRI":
if (timetable.getCabinetMRI() == null){
return "MRI cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
case "Physiotherapy":
if (timetable.getCabinetPT() == null){
return "Physiotherapy cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
default:
List<Method> cabinetsGetters = Arrays.stream(timetable.getClass().getDeclaredMethods())
.filter(method -> method.getName().matches("getCabinet\\d.*")).collect(Collectors.toList());
for(Method method: cabinetsGetters){
try {
if(method.invoke(timetable) == null){
return method.getName().substring(3,10) + " " + method.getName().substring(10);
}
} catch (Exception e){
throw new RuntimeException("Unable to call method" + method.getName() + "on " + date + ", " + time);
}
}
throw new TimeUnavailableException(date, time);
}
}
@Override
public String hasAvailableCabinet(Event event, Long appointmentId) throws TimeUnavailableException {
String result = "";
LOG.info("Checking for cabinet availability on" + event.getDate() + ", at " + event.getTime());
Timetable timetable = timetableDAO.getByDateAndTime(event.getDate(), event.getTime());
switch (event.getTreatment().getName()){
case "ECG":
if (timetable.getCabinetECG() == null || timetable.getCabinetECG().getAppointment().getId().equals(appointmentId)){
result = "ECG cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
case "MRI":
if (timetable.getCabinetMRI() == null || timetable.getCabinetMRI().getAppointment().getId().equals(appointmentId)){
result = "MRI cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
case "Physiotherapy":
if (timetable.getCabinetPT() == null || timetable.getCabinetPT().getAppointment().getId().equals(appointmentId)){
result = "Physiotherapy cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
default:
List<Method> cabinetsGetters = Arrays.stream(timetable.getClass().getDeclaredMethods())
.filter(method -> method.getName().matches("getCabinet\\d.*")).collect(Collectors.toList());
for(Method method: cabinetsGetters){
try {
if(method.invoke(timetable) == null || ((Event) method.invoke(timetable)).getAppointment().getId().equals(appointmentId)){
result = method.getName().substring(3,10) + " " + method.getName().substring(10);
}
} catch (Exception e){
throw new RuntimeException("Unable to call method" + method.getName() + "on " + event.getDate() + ", " + event.getTime());
}
}
}
return result;
}
@Override
public void add(Timetable timetable) {
timetableDAO.add(timetable);
}
}
| UTF-8 | Java | 5,293 | java | TimetableServiceImpl.java | Java | [] | null | [] | package com.diana.service;
import com.diana.dao.EventDAO;
import com.diana.dao.TimetableDAO;
import com.diana.model.Event;
import com.diana.model.Timetable;
import com.diana.model.Treatment;
import com.diana.util.error.TimeUnavailableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class TimetableServiceImpl implements TimetableService{
@Autowired
private TimetableDAO timetableDAO;
static final Logger LOG = LoggerFactory.getLogger(TimetableServiceImpl.class);
@Override
public String hasAvailableCabinet(LocalDate date, LocalTime time, Treatment treatment) throws TimeUnavailableException {
LOG.info("Checking for cabinet availability on" + date.minusDays(1) + ", at " + time);
Timetable timetable = timetableDAO.getByDateAndTime(date, time);
if (timetable == null){
throw new TimeUnavailableException(date.minusDays(1), time);
}
switch (treatment.getName()){
case "ECG":
if (timetable.getCabinetECG() == null){
return "ECG cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
case "MRI":
if (timetable.getCabinetMRI() == null){
return "MRI cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
case "Physiotherapy":
if (timetable.getCabinetPT() == null){
return "Physiotherapy cabinet";
} else {
throw new TimeUnavailableException(date, time);
}
default:
List<Method> cabinetsGetters = Arrays.stream(timetable.getClass().getDeclaredMethods())
.filter(method -> method.getName().matches("getCabinet\\d.*")).collect(Collectors.toList());
for(Method method: cabinetsGetters){
try {
if(method.invoke(timetable) == null){
return method.getName().substring(3,10) + " " + method.getName().substring(10);
}
} catch (Exception e){
throw new RuntimeException("Unable to call method" + method.getName() + "on " + date + ", " + time);
}
}
throw new TimeUnavailableException(date, time);
}
}
@Override
public String hasAvailableCabinet(Event event, Long appointmentId) throws TimeUnavailableException {
String result = "";
LOG.info("Checking for cabinet availability on" + event.getDate() + ", at " + event.getTime());
Timetable timetable = timetableDAO.getByDateAndTime(event.getDate(), event.getTime());
switch (event.getTreatment().getName()){
case "ECG":
if (timetable.getCabinetECG() == null || timetable.getCabinetECG().getAppointment().getId().equals(appointmentId)){
result = "ECG cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
case "MRI":
if (timetable.getCabinetMRI() == null || timetable.getCabinetMRI().getAppointment().getId().equals(appointmentId)){
result = "MRI cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
case "Physiotherapy":
if (timetable.getCabinetPT() == null || timetable.getCabinetPT().getAppointment().getId().equals(appointmentId)){
result = "Physiotherapy cabinet";
} else {
throw new TimeUnavailableException(event.getDate(), event.getTime());
}
break;
default:
List<Method> cabinetsGetters = Arrays.stream(timetable.getClass().getDeclaredMethods())
.filter(method -> method.getName().matches("getCabinet\\d.*")).collect(Collectors.toList());
for(Method method: cabinetsGetters){
try {
if(method.invoke(timetable) == null || ((Event) method.invoke(timetable)).getAppointment().getId().equals(appointmentId)){
result = method.getName().substring(3,10) + " " + method.getName().substring(10);
}
} catch (Exception e){
throw new RuntimeException("Unable to call method" + method.getName() + "on " + event.getDate() + ", " + event.getTime());
}
}
}
return result;
}
@Override
public void add(Timetable timetable) {
timetableDAO.add(timetable);
}
}
| 5,293 | 0.56093 | 0.558285 | 122 | 42.385246 | 36.962864 | 150 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.622951 | false | false | 5 |
4bd90e0372b271bd9b8b96b4403ceb2a7da90f49 | 2,010,044,733,560 | 02338a522250fbb2a02c9f19d6a3f9ce36bd3e21 | /dev/advantage/Source/ClientApps/HTMLApps/AltSelfService.app/DocNavPanel.java | 231ab5b44fba91b93a929c0ab1a8c2434778ddfa | [] | no_license | Bharath88/Jenkins-DemoRepo | https://github.com/Bharath88/Jenkins-DemoRepo | 41b0af07c96801d99bb8471726f28c5b437d7e75 | 0c239a90b9fec3f3e0265c57f2844648eeb39a25 | refs/heads/master | 2021-01-19T22:29:02.488000 | 2017-04-20T09:58:35 | 2017-04-20T09:58:35 | 88,821,716 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | //{{IMPORT_STMTS
package advantage.AltSelfService;
import versata.vfc.html.*;
import versata.vfc.*;
import versata.common.*;
import java.io.*;
import javax.swing.text.html.*;
import com.versata.util.logging.*;
//END_IMPORT_STMTS}}
import java.util.*;
import com.amsinc.gems.adv.vfc.html.*;
/*
** DocNavPanel*/
//{{FORM_CLASS_DECL
public class DocNavPanel extends DocNavPanelBase
//END_FORM_CLASS_DECL}}
{
// Declarations for instance variables used in the form
private String msCurrentTabName;
private Hashtable mhTabInfo;
private boolean mboolShowFDT;
private boolean mboolShowDocHist;
private boolean mboolShowDocRef;
/** Whether Doc Comments link is to be displayed or not */
private boolean mboolShowDocComm = true;
/** Whether document has comments */
private boolean mboolShowCommIcon = false;
private static String msDocNavFileLocation = null;
private String msFormName;
// This is the constructor for the generated form. This also constructs
// all the controls on the form. Do not alter this code. To customize paint
// behavior, modify/augment the paint and the handleEvent methods.
//{{FORM_CLASS_CTOR
public DocNavPanel ( PLSApp parentApp ) throws VSException, java.beans.PropertyVetoException {
super(parentApp);
//END_FORM_CLASS_CTOR}}
setDisplayErrors(false);
setDocNavPanelInd(DOC_MULTI_TBL_NAV_PANEL_SHOW);
}
//{{EVENT_CODE
//END_EVENT_CODE}}
public void addListeners() {
//{{EVENT_ADD_LISTENERS
//END_EVENT_ADD_LISTENERS}}
}
//{{EVENT_ADAPTER_CODE
//END_EVENT_ADAPTER_CODE}}
public HTMLDocumentSpec getDocumentSpecification() {
return getDefaultDocumentSpecification();
}
public String getFileName() {
return getDefaultFileName();
}
public String getFileLocation()
{
/* if (msDocNavFileLocation == null)
{
StringBuffer loBuf = new StringBuffer(256);
loBuf.append("..");
loBuf.append(File.separator);
loBuf.append("..");
loBuf.append(File.separator);
loBuf.append("VLSComponents");
loBuf.append(File.separator);
loBuf.append("Classes");
loBuf.append(File.separator);
loBuf.append("advantage");
loBuf.append(File.separator);
loBuf.append("Advantage");
loBuf.append(File.separator);
msDocNavFileLocation = loBuf.toString();
}
return msDocNavFileLocation;
*/
return getPageTemplatePath();
}
public void afterPageInitialize() {
super.afterPageInitialize();
//Write code here for initializing your own control
//or creating new control.
}
public String generate()
{
// Buffer that holds the javascript that has to be wriiten out
StringBuffer loBuf = new StringBuffer(512) ;
StringBuffer loSectionBuf = new StringBuffer(512) ;
String lsTabId ;
String[] lsTabInfo ;
String lsDocTitle = "" ;
VSPage loSrcPage = getSourcePage() ;
TextContentElement loTce ;
if ( loSrcPage != null )
{
lsDocTitle = ((AMSDocTabbedPage)loSrcPage).getDocTitle() ;
mboolShowCommIcon = ((AMSDocTabbedPage)loSrcPage).getDocCommentFlag();
} /* end if ( loSrcPage != null ) */
// Get the element that represents the vstext tag
loTce = (TextContentElement)getElementByName("DOCTREE");
if (loTce == null)
{
System.err.println("Failed to get element DOCTREE");
return super.generate();
}
loBuf.append("<script type=\"text/javascript\" language=\"JavaScript\">");
loBuf.append("\n");
// Set the javascript variable to indicate if the Document Comments link
// to be displayed or not
if (mboolShowDocComm)
{
loBuf.append("mboolDOCTREE_ShowDocComm = true;\n");
if (mboolShowCommIcon) //document comment exists, show icon
{
loBuf.append("mboolDOCTREE_ShowCommIcon = true;\n");
}
else //document does not have associated comments, do not show icon
{
loBuf.append("mboolDOCTREE_ShowCommIcon = false;\n");
}
}
else
{
loBuf.append("mboolDOCTREE_ShowDocComm = false;\n");
}
// Set the javascript variable to indicate if the Future Triggering
// node has to be displayed or not
if (mboolShowFDT)
{
loBuf.append("mboolDOCTREE_ShowFDT = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowFDT = false;\n");
}
// Set the javascript variable to indicate if the Document History
// node has to be displayed or not
if (mboolShowDocHist)
{
loBuf.append("mboolDOCTREE_ShowDocHist = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowDocHist = false;\n");
}
// Set the javascript variable to indicate if the Document Reference
// node has to be displayed or not
if (mboolShowDocRef)
{
loBuf.append("mboolDOCTREE_ShowDocRef = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowDocRef = false;\n");
}
loBuf.append("msDOCTREE_FormName = '");
loBuf.append( msFormName ) ;
loBuf.append("';\n");
// Escape the backslash "\" character
lsDocTitle = AMSPLSDocUtil.replacePattern( lsDocTitle, "\\", "\\\\" );
// Convert the special characters in
// doc title before showing in the page
try
{
lsDocTitle = AMSPLSDocUtil.convertSpecialChars( lsDocTitle );
}
catch( IOException ioExp )
{
raiseException( ioExp.getMessage(), SEVERITY_LEVEL_ERROR );
}
loBuf.append("msDOCTREE_DOC_ID = '");
loBuf.append( handleQuotedString( lsDocTitle ) ) ;
loBuf.append("';\n");
for (Enumeration loKeys = mhTabInfo.keys(); loKeys.hasMoreElements() ;)
{
lsTabId = (String) loKeys.nextElement();
lsTabInfo = (String []) mhTabInfo.get(lsTabId);
// Start adding to the buffer
loBuf.append("msDOCTREE_TABS[");
loBuf.append(lsTabInfo[1]); // Tab Sequence Number
loBuf.append("] = new Array(null,'");
loBuf.append(lsTabInfo[0]); // Tab Name
loBuf.append("','");
loBuf.append(lsTabId); // Tab Id
loBuf.append("',");
// If this is the current tab then set the flag that this tab
// has been visited and put it back into the hash table
if (lsTabId.equals(msCurrentTabName))
{
loBuf.append("true,");
// Update the hash table
lsTabInfo[2] = SESSION_DOC_YES;
mhTabInfo.put(lsTabId, lsTabInfo);
// If there are sections then add javascript arrays
// for them as well
if ((lsTabInfo[3] != null && lsTabInfo[3].length() != 0) &&
(lsTabInfo[4] != null && lsTabInfo[4].length() != 0))
{
int liIndex;
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0] = new Array();\n");
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0][0] = new Array(");
liIndex = lsTabInfo[3].lastIndexOf(",");
loSectionBuf.append(lsTabInfo[3].substring(0,liIndex).trim());
loSectionBuf.append(");\n");
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0][1] = new Array(");
liIndex = lsTabInfo[4].lastIndexOf(",");
loSectionBuf.append(lsTabInfo[4].substring(0,liIndex).trim());
loSectionBuf.append(");\n");
}
}
else
{
loBuf.append("false,");
}
if (lsTabInfo[2] == SESSION_DOC_YES)
{
loBuf.append("true);\n");
}
else
{
loBuf.append("false);\n");
}
}
loSectionBuf.append("\n");
loSectionBuf.append("</script>");
loTce.setValue(loBuf.toString() + loSectionBuf.toString());
return super.generate();
}
/**
* Setter for the Tab Information
*
* Modification Log : Subramanyam Surabhi - 12/23/2000
* - inital version
*
* @param fhTabInfo Hashtable containing the tab information
*/
public void setTabInformation(Hashtable fhTabInfo)
{
mhTabInfo = fhTabInfo;
}
/**
* Setter for the Show FDT flag
*
* Modification Log : Subramanyam Surabhi - 02/12/2001
* - inital version
*
* @param fboolShowFDT Show FDT Flag
*/
public void setShowFDT(boolean fboolShowFDT)
{
mboolShowFDT = fboolShowFDT;
}
/**
* Setter for the Show Document History flag
*
* Modification Log : Subramanyam Surabhi - 07/25/2001
* - inital version
*
* @param fboolShowDocHist Show Document History Flag
*/
public void setShowDocHist(boolean fboolShowDocHist)
{
mboolShowDocHist = fboolShowDocHist;
}
/**
* Setter for the Show Document Reference flag
*
* Modification Log : Subramanyam Surabhi - 07/25/2001
* - inital version
*
* @param fboolShowDocRef Show Document Reference Flag
*/
public void setShowDocRef(boolean fboolShowDocRef)
{
mboolShowDocRef = fboolShowDocRef;
}
/**
* Setter for the Show Document Comments flag
*
* @param boolean Show Document Commetns Flag
*/
public void setShowDocComm(boolean fboolShowDocComm)
{
mboolShowDocComm = fboolShowDocComm;
}
/**
* Setter for the current tab name
*
* Modification Log : Subramanyam Surabhi - 12/23/2000
* - inital version
*
* @param fsTabName Name of the tab
*/
public void setCurrentTabName(String fsTabName)
{
msCurrentTabName = fsTabName;
}
/**
* Setter for the Form Name
*
* Modification Log : Subramanyam Surabhi - 04/16/2001
* - inital version
*
* @param fsFormName Name of the Document Form
*/
public void setFormName(String fsFormName)
{
msFormName = fsFormName;
}
/**
* Method overridden to make all the pages with
* transitions as dependent.
*
* @return true for dependent transitions
*/
public boolean isDependenceOf( VSPage foPage )
{
VSPage loSrcPage = getSourcePage() ;
if ( loSrcPage == null )
{
/*
* This case should never happen because the source
* page should always be the document page.
*/
return false ;
} /* end if ( loSrcPage == null ) */
else
{
if ( foPage == loSrcPage )
{
if ( ((AMSPage)loSrcPage).isClosed() )
{
return false ;
} /* end if ( ((AMSPage)loSrcPage).isClosed() ) */
else
{
return true ;
} /* end else */
} /* end if ( foPage == loSrcPage ) */
else
{
return loSrcPage.isDependenceOf( foPage ) ;
} /* end else */
} /* end else */
} /* end isDependenceOf() */
}
| UTF-8 | Java | 11,756 | java | DocNavPanel.java | Java | [
{
"context": "the Tab Information\n *\n * Modification Log : Subramanyam Surabhi - 12/23/2000\n * ",
"end": 8586,
"score": 0.9998804330825806,
"start": 8567,
"tag": "NAME",
"value": "Subramanyam Surabhi"
},
{
"context": "r the Show FDT flag\n ... | null | [] | //{{IMPORT_STMTS
package advantage.AltSelfService;
import versata.vfc.html.*;
import versata.vfc.*;
import versata.common.*;
import java.io.*;
import javax.swing.text.html.*;
import com.versata.util.logging.*;
//END_IMPORT_STMTS}}
import java.util.*;
import com.amsinc.gems.adv.vfc.html.*;
/*
** DocNavPanel*/
//{{FORM_CLASS_DECL
public class DocNavPanel extends DocNavPanelBase
//END_FORM_CLASS_DECL}}
{
// Declarations for instance variables used in the form
private String msCurrentTabName;
private Hashtable mhTabInfo;
private boolean mboolShowFDT;
private boolean mboolShowDocHist;
private boolean mboolShowDocRef;
/** Whether Doc Comments link is to be displayed or not */
private boolean mboolShowDocComm = true;
/** Whether document has comments */
private boolean mboolShowCommIcon = false;
private static String msDocNavFileLocation = null;
private String msFormName;
// This is the constructor for the generated form. This also constructs
// all the controls on the form. Do not alter this code. To customize paint
// behavior, modify/augment the paint and the handleEvent methods.
//{{FORM_CLASS_CTOR
public DocNavPanel ( PLSApp parentApp ) throws VSException, java.beans.PropertyVetoException {
super(parentApp);
//END_FORM_CLASS_CTOR}}
setDisplayErrors(false);
setDocNavPanelInd(DOC_MULTI_TBL_NAV_PANEL_SHOW);
}
//{{EVENT_CODE
//END_EVENT_CODE}}
public void addListeners() {
//{{EVENT_ADD_LISTENERS
//END_EVENT_ADD_LISTENERS}}
}
//{{EVENT_ADAPTER_CODE
//END_EVENT_ADAPTER_CODE}}
public HTMLDocumentSpec getDocumentSpecification() {
return getDefaultDocumentSpecification();
}
public String getFileName() {
return getDefaultFileName();
}
public String getFileLocation()
{
/* if (msDocNavFileLocation == null)
{
StringBuffer loBuf = new StringBuffer(256);
loBuf.append("..");
loBuf.append(File.separator);
loBuf.append("..");
loBuf.append(File.separator);
loBuf.append("VLSComponents");
loBuf.append(File.separator);
loBuf.append("Classes");
loBuf.append(File.separator);
loBuf.append("advantage");
loBuf.append(File.separator);
loBuf.append("Advantage");
loBuf.append(File.separator);
msDocNavFileLocation = loBuf.toString();
}
return msDocNavFileLocation;
*/
return getPageTemplatePath();
}
public void afterPageInitialize() {
super.afterPageInitialize();
//Write code here for initializing your own control
//or creating new control.
}
public String generate()
{
// Buffer that holds the javascript that has to be wriiten out
StringBuffer loBuf = new StringBuffer(512) ;
StringBuffer loSectionBuf = new StringBuffer(512) ;
String lsTabId ;
String[] lsTabInfo ;
String lsDocTitle = "" ;
VSPage loSrcPage = getSourcePage() ;
TextContentElement loTce ;
if ( loSrcPage != null )
{
lsDocTitle = ((AMSDocTabbedPage)loSrcPage).getDocTitle() ;
mboolShowCommIcon = ((AMSDocTabbedPage)loSrcPage).getDocCommentFlag();
} /* end if ( loSrcPage != null ) */
// Get the element that represents the vstext tag
loTce = (TextContentElement)getElementByName("DOCTREE");
if (loTce == null)
{
System.err.println("Failed to get element DOCTREE");
return super.generate();
}
loBuf.append("<script type=\"text/javascript\" language=\"JavaScript\">");
loBuf.append("\n");
// Set the javascript variable to indicate if the Document Comments link
// to be displayed or not
if (mboolShowDocComm)
{
loBuf.append("mboolDOCTREE_ShowDocComm = true;\n");
if (mboolShowCommIcon) //document comment exists, show icon
{
loBuf.append("mboolDOCTREE_ShowCommIcon = true;\n");
}
else //document does not have associated comments, do not show icon
{
loBuf.append("mboolDOCTREE_ShowCommIcon = false;\n");
}
}
else
{
loBuf.append("mboolDOCTREE_ShowDocComm = false;\n");
}
// Set the javascript variable to indicate if the Future Triggering
// node has to be displayed or not
if (mboolShowFDT)
{
loBuf.append("mboolDOCTREE_ShowFDT = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowFDT = false;\n");
}
// Set the javascript variable to indicate if the Document History
// node has to be displayed or not
if (mboolShowDocHist)
{
loBuf.append("mboolDOCTREE_ShowDocHist = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowDocHist = false;\n");
}
// Set the javascript variable to indicate if the Document Reference
// node has to be displayed or not
if (mboolShowDocRef)
{
loBuf.append("mboolDOCTREE_ShowDocRef = true;\n");
}
else
{
loBuf.append("mboolDOCTREE_ShowDocRef = false;\n");
}
loBuf.append("msDOCTREE_FormName = '");
loBuf.append( msFormName ) ;
loBuf.append("';\n");
// Escape the backslash "\" character
lsDocTitle = AMSPLSDocUtil.replacePattern( lsDocTitle, "\\", "\\\\" );
// Convert the special characters in
// doc title before showing in the page
try
{
lsDocTitle = AMSPLSDocUtil.convertSpecialChars( lsDocTitle );
}
catch( IOException ioExp )
{
raiseException( ioExp.getMessage(), SEVERITY_LEVEL_ERROR );
}
loBuf.append("msDOCTREE_DOC_ID = '");
loBuf.append( handleQuotedString( lsDocTitle ) ) ;
loBuf.append("';\n");
for (Enumeration loKeys = mhTabInfo.keys(); loKeys.hasMoreElements() ;)
{
lsTabId = (String) loKeys.nextElement();
lsTabInfo = (String []) mhTabInfo.get(lsTabId);
// Start adding to the buffer
loBuf.append("msDOCTREE_TABS[");
loBuf.append(lsTabInfo[1]); // Tab Sequence Number
loBuf.append("] = new Array(null,'");
loBuf.append(lsTabInfo[0]); // Tab Name
loBuf.append("','");
loBuf.append(lsTabId); // Tab Id
loBuf.append("',");
// If this is the current tab then set the flag that this tab
// has been visited and put it back into the hash table
if (lsTabId.equals(msCurrentTabName))
{
loBuf.append("true,");
// Update the hash table
lsTabInfo[2] = SESSION_DOC_YES;
mhTabInfo.put(lsTabId, lsTabInfo);
// If there are sections then add javascript arrays
// for them as well
if ((lsTabInfo[3] != null && lsTabInfo[3].length() != 0) &&
(lsTabInfo[4] != null && lsTabInfo[4].length() != 0))
{
int liIndex;
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0] = new Array();\n");
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0][0] = new Array(");
liIndex = lsTabInfo[3].lastIndexOf(",");
loSectionBuf.append(lsTabInfo[3].substring(0,liIndex).trim());
loSectionBuf.append(");\n");
loSectionBuf.append("msDOCTREE_TABS[");
loSectionBuf.append(lsTabInfo[1]);
loSectionBuf.append("][0][1] = new Array(");
liIndex = lsTabInfo[4].lastIndexOf(",");
loSectionBuf.append(lsTabInfo[4].substring(0,liIndex).trim());
loSectionBuf.append(");\n");
}
}
else
{
loBuf.append("false,");
}
if (lsTabInfo[2] == SESSION_DOC_YES)
{
loBuf.append("true);\n");
}
else
{
loBuf.append("false);\n");
}
}
loSectionBuf.append("\n");
loSectionBuf.append("</script>");
loTce.setValue(loBuf.toString() + loSectionBuf.toString());
return super.generate();
}
/**
* Setter for the Tab Information
*
* Modification Log : <NAME> - 12/23/2000
* - inital version
*
* @param fhTabInfo Hashtable containing the tab information
*/
public void setTabInformation(Hashtable fhTabInfo)
{
mhTabInfo = fhTabInfo;
}
/**
* Setter for the Show FDT flag
*
* Modification Log : <NAME> - 02/12/2001
* - inital version
*
* @param fboolShowFDT Show FDT Flag
*/
public void setShowFDT(boolean fboolShowFDT)
{
mboolShowFDT = fboolShowFDT;
}
/**
* Setter for the Show Document History flag
*
* Modification Log : <NAME> - 07/25/2001
* - inital version
*
* @param fboolShowDocHist Show Document History Flag
*/
public void setShowDocHist(boolean fboolShowDocHist)
{
mboolShowDocHist = fboolShowDocHist;
}
/**
* Setter for the Show Document Reference flag
*
* Modification Log : <NAME> - 07/25/2001
* - inital version
*
* @param fboolShowDocRef Show Document Reference Flag
*/
public void setShowDocRef(boolean fboolShowDocRef)
{
mboolShowDocRef = fboolShowDocRef;
}
/**
* Setter for the Show Document Comments flag
*
* @param boolean Show Document Commetns Flag
*/
public void setShowDocComm(boolean fboolShowDocComm)
{
mboolShowDocComm = fboolShowDocComm;
}
/**
* Setter for the current tab name
*
* Modification Log : <NAME> - 12/23/2000
* - inital version
*
* @param fsTabName Name of the tab
*/
public void setCurrentTabName(String fsTabName)
{
msCurrentTabName = fsTabName;
}
/**
* Setter for the Form Name
*
* Modification Log : <NAME> - 04/16/2001
* - inital version
*
* @param fsFormName Name of the Document Form
*/
public void setFormName(String fsFormName)
{
msFormName = fsFormName;
}
/**
* Method overridden to make all the pages with
* transitions as dependent.
*
* @return true for dependent transitions
*/
public boolean isDependenceOf( VSPage foPage )
{
VSPage loSrcPage = getSourcePage() ;
if ( loSrcPage == null )
{
/*
* This case should never happen because the source
* page should always be the document page.
*/
return false ;
} /* end if ( loSrcPage == null ) */
else
{
if ( foPage == loSrcPage )
{
if ( ((AMSPage)loSrcPage).isClosed() )
{
return false ;
} /* end if ( ((AMSPage)loSrcPage).isClosed() ) */
else
{
return true ;
} /* end else */
} /* end if ( foPage == loSrcPage ) */
else
{
return loSrcPage.isDependenceOf( foPage ) ;
} /* end else */
} /* end else */
} /* end isDependenceOf() */
}
| 11,678 | 0.571793 | 0.564903 | 399 | 28.463659 | 23.360701 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.393484 | false | false | 5 |
89e4a3b2aa87823827cce8918da20dbe591de903 | 17,712,445,159,506 | a10d52ce8c6d72bb7e990a6a4021d9931ea9f20d | /ElementRPG/src/com/philon/rpg/ElementRPG.java | aa74c82f0c114fde7b1bfcf312d396606c88a5ba | [] | no_license | philon123/philon | https://github.com/philon123/philon | b3f20401ae02fe635c622b3f37f8fc1bf2e0aa33 | 470ac5956d835e34b4a32ed0c5ce653cf356919a | refs/heads/master | 2015-08-09T04:02:04 | 2013-10-09T22:01:29 | 2013-10-09T22:02:23 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.philon.rpg;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.philon.engine.game.Game;
import com.philon.engine.game.GameMedia;
import com.philon.engine.util.Vector;
public class ElementRPG implements ApplicationListener {
private Game currGame;
public static Vector screenPixSize = new Vector(800, 800);
public static float ratioHW;
@Override
public void create() {
Gdx.graphics.setDisplayMode((int)screenPixSize.x, (int)screenPixSize.y, false);
ratioHW = screenPixSize.y/screenPixSize.x;
Texture.setEnforcePotImages(false);
GameMedia.loadAll();
currGame = new Game();
}
@Override
public void dispose() {
currGame.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
currGame.mainloop();
}
@Override
public void resize(int width, int height) {
screenPixSize = new Vector(width, height);
ratioHW = screenPixSize.y/screenPixSize.x;
currGame.gGraphics.resizedTrigger();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
public static Vector getScreenPixSize() {
return screenPixSize.copy();
}
}
| UTF-8 | Java | 1,360 | java | ElementRPG.java | Java | [] | null | [] | package com.philon.rpg;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Texture;
import com.philon.engine.game.Game;
import com.philon.engine.game.GameMedia;
import com.philon.engine.util.Vector;
public class ElementRPG implements ApplicationListener {
private Game currGame;
public static Vector screenPixSize = new Vector(800, 800);
public static float ratioHW;
@Override
public void create() {
Gdx.graphics.setDisplayMode((int)screenPixSize.x, (int)screenPixSize.y, false);
ratioHW = screenPixSize.y/screenPixSize.x;
Texture.setEnforcePotImages(false);
GameMedia.loadAll();
currGame = new Game();
}
@Override
public void dispose() {
currGame.dispose();
}
@Override
public void render() {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
currGame.mainloop();
}
@Override
public void resize(int width, int height) {
screenPixSize = new Vector(width, height);
ratioHW = screenPixSize.y/screenPixSize.x;
currGame.gGraphics.resizedTrigger();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
public static Vector getScreenPixSize() {
return screenPixSize.copy();
}
}
| 1,360 | 0.693382 | 0.683088 | 59 | 21.050848 | 19.169559 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.355932 | false | false | 5 |
8091895f6fd0ca78f053efb9ce70f525803d6be6 | 13,288,628,848,882 | 397a7713ee52b9d132877eeeae588bf3f0902d53 | /EVE_JPA/src/org/holtz/eve/jpa/dao/impl/TUnuiconfigNodeDAOImpl.java | a959cbc13bed8a9768b8a18fc6be7d9f7874f001 | [] | no_license | rholtzjr/eve_j2ee | https://github.com/rholtzjr/eve_j2ee | ab399b30bba7168be32df24624f15e2b27d684ab | 5e94faa78079092d75444d9adb754832186fbf06 | refs/heads/master | 2022-12-25T16:01:14.946000 | 2020-03-03T22:03:27 | 2020-03-03T22:03:27 | 100,038,635 | 0 | 0 | null | false | 2022-12-16T11:46:34 | 2017-08-11T14:12:49 | 2020-03-03T22:03:44 | 2022-12-16T11:46:30 | 3,925 | 0 | 0 | 26 | Java | false | false | package org.holtz.eve.jpa.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.holtz.eve.jpa.dao.TUnuiconfigNodeDAO;
import org.holtz.eve.jpa.entity.TUnuiconfigNode;
import org.holtz.jpa.util.HibernateUtil;
public class TUnuiconfigNodeDAOImpl implements TUnuiconfigNodeDAO {
private SessionFactory sessionFactory;
private Session session;
private Query query;
public TUnuiconfigNodeDAOImpl() {
getSessionFactory();
setSession(sessionFactory.openSession());
}
@Override
public TUnuiconfigNode getUiconfigNodeById(int id) {
String queryString = "from TUnuiconfigNode uiconfigNode where uiconfigNode.id = :id";
TUnuiconfigNode uiconfigNode = new TUnuiconfigNode();
query = session.createQuery(queryString);
query.setInteger("id", id);
uiconfigNode = (TUnuiconfigNode) query.uniqueResult();
return uiconfigNode;
}
@Override
public TUnuiconfigNode getUiconfigNodeByName(String name) {
//NOOP
return null;
// String queryString = "from TUnuiconfigNode uiconfigNode where uiconfigNode.id like CONCAT('%',:name,'%')";
// TUnuiconfigNode uiconfigNode = new TUnuiconfigNode();
// query = session.createQuery(queryString);
// query.setString("name", name);
// uiconfigNode = (TUnuiconfigNode) query.uniqueResult();
// return uiconfigNode;
}
@Override
public List<TUnuiconfigNode> getUiconfigNodeList() {
String queryString = "from TUnuiconfigNode";
List<TUnuiconfigNode> uiconfigNodeList = new ArrayList<TUnuiconfigNode>();
query = session.createQuery(queryString);
uiconfigNodeList = (List<TUnuiconfigNode>)query.list();
return uiconfigNodeList;
}
@Override
public void save(TUnuiconfigNode uiconfigNode) {
// TODO Auto-generated method stub
}
@Override
public void delete(TUnuiconfigNode uiconfigNode) {
// TODO Auto-generated method stub
}
public SessionFactory getSessionFactory() {
sessionFactory = HibernateUtil.getSessionFactory();
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
| UTF-8 | Java | 2,368 | java | TUnuiconfigNodeDAOImpl.java | Java | [] | null | [] | package org.holtz.eve.jpa.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.holtz.eve.jpa.dao.TUnuiconfigNodeDAO;
import org.holtz.eve.jpa.entity.TUnuiconfigNode;
import org.holtz.jpa.util.HibernateUtil;
public class TUnuiconfigNodeDAOImpl implements TUnuiconfigNodeDAO {
private SessionFactory sessionFactory;
private Session session;
private Query query;
public TUnuiconfigNodeDAOImpl() {
getSessionFactory();
setSession(sessionFactory.openSession());
}
@Override
public TUnuiconfigNode getUiconfigNodeById(int id) {
String queryString = "from TUnuiconfigNode uiconfigNode where uiconfigNode.id = :id";
TUnuiconfigNode uiconfigNode = new TUnuiconfigNode();
query = session.createQuery(queryString);
query.setInteger("id", id);
uiconfigNode = (TUnuiconfigNode) query.uniqueResult();
return uiconfigNode;
}
@Override
public TUnuiconfigNode getUiconfigNodeByName(String name) {
//NOOP
return null;
// String queryString = "from TUnuiconfigNode uiconfigNode where uiconfigNode.id like CONCAT('%',:name,'%')";
// TUnuiconfigNode uiconfigNode = new TUnuiconfigNode();
// query = session.createQuery(queryString);
// query.setString("name", name);
// uiconfigNode = (TUnuiconfigNode) query.uniqueResult();
// return uiconfigNode;
}
@Override
public List<TUnuiconfigNode> getUiconfigNodeList() {
String queryString = "from TUnuiconfigNode";
List<TUnuiconfigNode> uiconfigNodeList = new ArrayList<TUnuiconfigNode>();
query = session.createQuery(queryString);
uiconfigNodeList = (List<TUnuiconfigNode>)query.list();
return uiconfigNodeList;
}
@Override
public void save(TUnuiconfigNode uiconfigNode) {
// TODO Auto-generated method stub
}
@Override
public void delete(TUnuiconfigNode uiconfigNode) {
// TODO Auto-generated method stub
}
public SessionFactory getSessionFactory() {
sessionFactory = HibernateUtil.getSessionFactory();
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
}
| 2,368 | 0.742821 | 0.742821 | 84 | 26.190475 | 24.275442 | 110 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.5 | false | false | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.