blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
f27887e4fa4156af975be81c748a19f8349cc772
872e91e7cf7bb5581a0b5d4702f35a262a6fe4f5
/ElGamal.java
7272c03054632921dbe07a649061ba6f3e52447e
[]
no_license
pieman353/crypto_tools
25629569205155551bb60c554a32eddf46fe54d4
7d445138c26062065d624dbe5b2cb234f2bc6491
refs/heads/master
2020-04-05T05:57:07.581566
2018-11-07T23:41:27
2018-11-07T23:41:27
156,618,823
0
0
null
null
null
null
UTF-8
Java
false
false
688
java
import java.math.*; class ElGamal { /* Input: p = prime number * g = generator * a = private key * b = shared secret * In other words (p,g,a,b) represent ELGamal key * (r,t) = encrypted ElGamal text * Output: plaintext */ public static int decrypt(int p, int g, int a, int b, int r, int t) { BigInteger p_big = BigInteger.valueOf(p); BigInteger r_big = BigInteger.valueOf(r); BigInteger t_big = BigInteger.valueOf(t); BigInteger a_big = BigInteger.valueOf(a); BigInteger ans = (t_big.mod(p_big)).divide(r_big.modPow(a_big, p_big)); return ans.intValue(); } }
9b14fadc1e4ce13596aa0ac72d485090bcc6a2ec
0f909f99aa229aa9d0e49665af7bc51cc2403f65
/src/generated/java/cdm/base/staticdata/party/NaturalPerson.java
78a8ac98e41bd75a502f916c3e2761f36ab65c97
[]
no_license
Xuanling-Chen/cdm-source-ext
8c93bc824e8c01255dfc06456bd6ec1fb3115649
e4cf7d5e549e514760cbd1e2d6789af171e5ea41
refs/heads/master
2023-07-11T20:35:26.485723
2021-08-29T04:12:00
2021-08-29T04:12:00
400,947,430
0
0
null
null
null
null
UTF-8
Java
false
false
17,058
java
package cdm.base.staticdata.party; import cdm.base.staticdata.party.meta.NaturalPersonMeta; import com.google.common.collect.ImmutableList; import com.rosetta.model.lib.GlobalKey; import com.rosetta.model.lib.GlobalKey.GlobalKeyBuilder; import com.rosetta.model.lib.RosettaModelObject; import com.rosetta.model.lib.RosettaModelObjectBuilder; import com.rosetta.model.lib.annotations.RosettaClass; import com.rosetta.model.lib.meta.RosettaMetaData; import com.rosetta.model.lib.path.RosettaPath; import com.rosetta.model.lib.process.BuilderMerger; import com.rosetta.model.lib.process.BuilderProcessor; import com.rosetta.model.lib.process.Processor; import com.rosetta.model.lib.records.Date; import com.rosetta.model.metafields.MetaFields; import com.rosetta.util.ListEquals; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Collectors; import static java.util.Optional.ofNullable; /** * A class to represent the attributes that are specific to a natural person. * @version ${project.version} */ @RosettaClass public interface NaturalPerson extends RosettaModelObject, GlobalKey { NaturalPerson build(); NaturalPerson.NaturalPersonBuilder toBuilder(); /** * The natural person&#39;s date of birth. */ Date getDateOfBirth(); /** * The natural person&#39;s first name. It is optional in FpML. */ String getFirstName(); /** * An honorific title, such as Mr., Ms., Dr. etc. */ String getHonorific(); /** */ List<? extends String> getInitial(); /** */ MetaFields getMeta(); /** */ List<? extends String> getMiddleName(); /** * Name suffix, such as Jr., III, etc. */ String getSuffix(); /** * The natural person&#39;s surname. */ String getSurname(); final static NaturalPersonMeta metaData = new NaturalPersonMeta(); @Override default RosettaMetaData<? extends NaturalPerson> metaData() { return metaData; } static NaturalPerson.NaturalPersonBuilder builder() { return new NaturalPerson.NaturalPersonBuilderImpl(); } default Class<? extends NaturalPerson> getType() { return NaturalPerson.class; } @Override default void process(RosettaPath path, Processor processor) { processor.processBasic(path.newSubPath("dateOfBirth"), Date.class, getDateOfBirth(), this); processor.processBasic(path.newSubPath("firstName"), String.class, getFirstName(), this); processor.processBasic(path.newSubPath("honorific"), String.class, getHonorific(), this); processor.processBasic(path.newSubPath("initial"), String.class, getInitial(), this); processor.processBasic(path.newSubPath("middleName"), String.class, getMiddleName(), this); processor.processBasic(path.newSubPath("suffix"), String.class, getSuffix(), this); processor.processBasic(path.newSubPath("surname"), String.class, getSurname(), this); processRosetta(path.newSubPath("meta"), processor, MetaFields.class, getMeta()); } interface NaturalPersonBuilder extends NaturalPerson, RosettaModelObjectBuilder { MetaFields.MetaFieldsBuilder getOrCreateMeta(); MetaFields.MetaFieldsBuilder getMeta(); NaturalPerson.NaturalPersonBuilder setDateOfBirth(Date dateOfBirth); NaturalPerson.NaturalPersonBuilder setFirstName(String firstName); NaturalPerson.NaturalPersonBuilder setHonorific(String honorific); NaturalPerson.NaturalPersonBuilder addInitial(String initial); NaturalPerson.NaturalPersonBuilder addInitial(String initial, int _idx); NaturalPerson.NaturalPersonBuilder addInitial(List<? extends String> initial); NaturalPerson.NaturalPersonBuilder setInitial(List<? extends String> initial); NaturalPerson.NaturalPersonBuilder setMeta(MetaFields meta); NaturalPerson.NaturalPersonBuilder addMiddleName(String middleName); NaturalPerson.NaturalPersonBuilder addMiddleName(String middleName, int _idx); NaturalPerson.NaturalPersonBuilder addMiddleName(List<? extends String> middleName); NaturalPerson.NaturalPersonBuilder setMiddleName(List<? extends String> middleName); NaturalPerson.NaturalPersonBuilder setSuffix(String suffix); NaturalPerson.NaturalPersonBuilder setSurname(String surname); @Override default void process(RosettaPath path, BuilderProcessor processor) { processor.processBasic(path.newSubPath("dateOfBirth"), Date.class, getDateOfBirth(), this); processor.processBasic(path.newSubPath("firstName"), String.class, getFirstName(), this); processor.processBasic(path.newSubPath("honorific"), String.class, getHonorific(), this); processor.processBasic(path.newSubPath("initial"), String.class, getInitial(), this); processor.processBasic(path.newSubPath("middleName"), String.class, getMiddleName(), this); processor.processBasic(path.newSubPath("suffix"), String.class, getSuffix(), this); processor.processBasic(path.newSubPath("surname"), String.class, getSurname(), this); processRosetta(path.newSubPath("meta"), processor, MetaFields.MetaFieldsBuilder.class, getMeta()); } } //NaturalPerson.NaturalPersonImpl class NaturalPersonImpl implements NaturalPerson { private final Date dateOfBirth; private final String firstName; private final String honorific; private final List<? extends String> initial; private final MetaFields meta; private final List<? extends String> middleName; private final String suffix; private final String surname; protected NaturalPersonImpl(NaturalPerson.NaturalPersonBuilder builder) { this.dateOfBirth = builder.getDateOfBirth(); this.firstName = builder.getFirstName(); this.honorific = builder.getHonorific(); this.initial = ofNullable(builder.getInitial()).filter(_l->!_l.isEmpty()).map(ImmutableList::copyOf).orElse(null); this.meta = ofNullable(builder.getMeta()).map(f->f.build()).orElse(null); this.middleName = ofNullable(builder.getMiddleName()).filter(_l->!_l.isEmpty()).map(ImmutableList::copyOf).orElse(null); this.suffix = builder.getSuffix(); this.surname = builder.getSurname(); } @Override public Date getDateOfBirth() { return dateOfBirth; } @Override public String getFirstName() { return firstName; } @Override public String getHonorific() { return honorific; } @Override public List<? extends String> getInitial() { return initial; } @Override public MetaFields getMeta() { return meta; } @Override public List<? extends String> getMiddleName() { return middleName; } @Override public String getSuffix() { return suffix; } @Override public String getSurname() { return surname; } @Override public NaturalPerson build() { return this; } @Override public NaturalPerson.NaturalPersonBuilder toBuilder() { NaturalPerson.NaturalPersonBuilder builder = builder(); setBuilderFields(builder); return builder; } protected void setBuilderFields(NaturalPerson.NaturalPersonBuilder builder) { ofNullable(getDateOfBirth()).ifPresent(builder::setDateOfBirth); ofNullable(getFirstName()).ifPresent(builder::setFirstName); ofNullable(getHonorific()).ifPresent(builder::setHonorific); ofNullable(getInitial()).ifPresent(builder::setInitial); ofNullable(getMeta()).ifPresent(builder::setMeta); ofNullable(getMiddleName()).ifPresent(builder::setMiddleName); ofNullable(getSuffix()).ifPresent(builder::setSuffix); ofNullable(getSurname()).ifPresent(builder::setSurname); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof RosettaModelObject) || !getType().equals(((RosettaModelObject)o).getType())) return false; NaturalPerson _that = getType().cast(o); if (!Objects.equals(dateOfBirth, _that.getDateOfBirth())) return false; if (!Objects.equals(firstName, _that.getFirstName())) return false; if (!Objects.equals(honorific, _that.getHonorific())) return false; if (!ListEquals.listEquals(initial, _that.getInitial())) return false; if (!Objects.equals(meta, _that.getMeta())) return false; if (!ListEquals.listEquals(middleName, _that.getMiddleName())) return false; if (!Objects.equals(suffix, _that.getSuffix())) return false; if (!Objects.equals(surname, _that.getSurname())) return false; return true; } @Override public int hashCode() { int _result = 0; _result = 31 * _result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0); _result = 31 * _result + (firstName != null ? firstName.hashCode() : 0); _result = 31 * _result + (honorific != null ? honorific.hashCode() : 0); _result = 31 * _result + (initial != null ? initial.hashCode() : 0); _result = 31 * _result + (meta != null ? meta.hashCode() : 0); _result = 31 * _result + (middleName != null ? middleName.hashCode() : 0); _result = 31 * _result + (suffix != null ? suffix.hashCode() : 0); _result = 31 * _result + (surname != null ? surname.hashCode() : 0); return _result; } @Override public String toString() { return "NaturalPerson {" + "dateOfBirth=" + this.dateOfBirth + ", " + "firstName=" + this.firstName + ", " + "honorific=" + this.honorific + ", " + "initial=" + this.initial + ", " + "meta=" + this.meta + ", " + "middleName=" + this.middleName + ", " + "suffix=" + this.suffix + ", " + "surname=" + this.surname + '}'; } } //NaturalPerson.NaturalPersonBuilderImpl class NaturalPersonBuilderImpl implements NaturalPerson.NaturalPersonBuilder, GlobalKeyBuilder { protected Date dateOfBirth; protected String firstName; protected String honorific; protected List<String> initial = new ArrayList<>(); protected MetaFields.MetaFieldsBuilder meta; protected List<String> middleName = new ArrayList<>(); protected String suffix; protected String surname; public NaturalPersonBuilderImpl() { } @Override public Date getDateOfBirth() { return dateOfBirth; } @Override public String getFirstName() { return firstName; } @Override public String getHonorific() { return honorific; } @Override public List<? extends String> getInitial() { return initial; } @Override public MetaFields.MetaFieldsBuilder getMeta() { return meta; } @Override public MetaFields.MetaFieldsBuilder getOrCreateMeta() { MetaFields.MetaFieldsBuilder result; if (meta!=null) { result = meta; } else { result = meta = MetaFields.builder(); } return result; } @Override public List<? extends String> getMiddleName() { return middleName; } @Override public String getSuffix() { return suffix; } @Override public String getSurname() { return surname; } @Override public NaturalPerson.NaturalPersonBuilder setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth==null?null:dateOfBirth; return this; } @Override public NaturalPerson.NaturalPersonBuilder setFirstName(String firstName) { this.firstName = firstName==null?null:firstName; return this; } @Override public NaturalPerson.NaturalPersonBuilder setHonorific(String honorific) { this.honorific = honorific==null?null:honorific; return this; } @Override public NaturalPerson.NaturalPersonBuilder addInitial(String initial) { if (initial!=null) this.initial.add(initial); return this; } @Override public NaturalPerson.NaturalPersonBuilder addInitial(String initial, int _idx) { getIndex(this.initial, _idx, () -> initial); return this; } @Override public NaturalPerson.NaturalPersonBuilder addInitial(List<? extends String> initials) { if (initials != null) { for (String toAdd : initials) { this.initial.add(toAdd); } } return this; } @Override public NaturalPerson.NaturalPersonBuilder setInitial(List<? extends String> initials) { if (initials == null) { this.initial = new ArrayList<>(); } else { this.initial = initials.stream() .collect(Collectors.toCollection(()->new ArrayList<>())); } return this; } @Override public NaturalPerson.NaturalPersonBuilder setMeta(MetaFields meta) { this.meta = meta==null?null:meta.toBuilder(); return this; } @Override public NaturalPerson.NaturalPersonBuilder addMiddleName(String middleName) { if (middleName!=null) this.middleName.add(middleName); return this; } @Override public NaturalPerson.NaturalPersonBuilder addMiddleName(String middleName, int _idx) { getIndex(this.middleName, _idx, () -> middleName); return this; } @Override public NaturalPerson.NaturalPersonBuilder addMiddleName(List<? extends String> middleNames) { if (middleNames != null) { for (String toAdd : middleNames) { this.middleName.add(toAdd); } } return this; } @Override public NaturalPerson.NaturalPersonBuilder setMiddleName(List<? extends String> middleNames) { if (middleNames == null) { this.middleName = new ArrayList<>(); } else { this.middleName = middleNames.stream() .collect(Collectors.toCollection(()->new ArrayList<>())); } return this; } @Override public NaturalPerson.NaturalPersonBuilder setSuffix(String suffix) { this.suffix = suffix==null?null:suffix; return this; } @Override public NaturalPerson.NaturalPersonBuilder setSurname(String surname) { this.surname = surname==null?null:surname; return this; } @Override public NaturalPerson build() { return new NaturalPerson.NaturalPersonImpl(this); } @Override public NaturalPerson.NaturalPersonBuilder toBuilder() { return this; } @SuppressWarnings("unchecked") @Override public NaturalPerson.NaturalPersonBuilder prune() { if (meta!=null && !meta.prune().hasData()) meta = null; return this; } @Override public boolean hasData() { if (getDateOfBirth()!=null) return true; if (getFirstName()!=null) return true; if (getHonorific()!=null) return true; if (getInitial()!=null && !getInitial().isEmpty()) return true; if (getMiddleName()!=null && !getMiddleName().isEmpty()) return true; if (getSuffix()!=null) return true; if (getSurname()!=null) return true; return false; } @SuppressWarnings("unchecked") @Override public NaturalPerson.NaturalPersonBuilder merge(RosettaModelObjectBuilder other, BuilderMerger merger) { NaturalPerson.NaturalPersonBuilder o = (NaturalPerson.NaturalPersonBuilder) other; merger.mergeRosetta(getMeta(), o.getMeta(), this::setMeta); merger.mergeBasic(getDateOfBirth(), o.getDateOfBirth(), this::setDateOfBirth); merger.mergeBasic(getFirstName(), o.getFirstName(), this::setFirstName); merger.mergeBasic(getHonorific(), o.getHonorific(), this::setHonorific); merger.mergeBasic(getInitial(), o.getInitial(), (Consumer<String>) this::addInitial); merger.mergeBasic(getMiddleName(), o.getMiddleName(), (Consumer<String>) this::addMiddleName); merger.mergeBasic(getSuffix(), o.getSuffix(), this::setSuffix); merger.mergeBasic(getSurname(), o.getSurname(), this::setSurname); return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof RosettaModelObject) || !getType().equals(((RosettaModelObject)o).getType())) return false; NaturalPerson _that = getType().cast(o); if (!Objects.equals(dateOfBirth, _that.getDateOfBirth())) return false; if (!Objects.equals(firstName, _that.getFirstName())) return false; if (!Objects.equals(honorific, _that.getHonorific())) return false; if (!ListEquals.listEquals(initial, _that.getInitial())) return false; if (!Objects.equals(meta, _that.getMeta())) return false; if (!ListEquals.listEquals(middleName, _that.getMiddleName())) return false; if (!Objects.equals(suffix, _that.getSuffix())) return false; if (!Objects.equals(surname, _that.getSurname())) return false; return true; } @Override public int hashCode() { int _result = 0; _result = 31 * _result + (dateOfBirth != null ? dateOfBirth.hashCode() : 0); _result = 31 * _result + (firstName != null ? firstName.hashCode() : 0); _result = 31 * _result + (honorific != null ? honorific.hashCode() : 0); _result = 31 * _result + (initial != null ? initial.hashCode() : 0); _result = 31 * _result + (meta != null ? meta.hashCode() : 0); _result = 31 * _result + (middleName != null ? middleName.hashCode() : 0); _result = 31 * _result + (suffix != null ? suffix.hashCode() : 0); _result = 31 * _result + (surname != null ? surname.hashCode() : 0); return _result; } @Override public String toString() { return "NaturalPersonBuilder {" + "dateOfBirth=" + this.dateOfBirth + ", " + "firstName=" + this.firstName + ", " + "honorific=" + this.honorific + ", " + "initial=" + this.initial + ", " + "meta=" + this.meta + ", " + "middleName=" + this.middleName + ", " + "suffix=" + this.suffix + ", " + "surname=" + this.surname + '}'; } } }
71477cc9fe3c37336c17777f7235212da5e79efc
96e2f5416548e2d0d01d09e6de3401c4efed0742
/src/main/java/br/com/zup/mercadolivre/exception/ValidationErrorHandler.java
981659139196db148264d3ad900abed286455de1
[ "Apache-2.0" ]
permissive
fabricio-leitao/orange-talents-02-template-ecommerce
125c0b0a907a5da617b41f577a990c4cf658d54a
fa7152217029af3b7eec8c910544caab67781514
refs/heads/main
2023-03-23T01:53:48.939450
2021-03-01T13:28:23
2021-03-01T13:28:23
343,425,151
0
0
Apache-2.0
2021-03-01T13:25:30
2021-03-01T13:25:30
null
UTF-8
Java
false
false
2,262
java
package br.com.zup.mercadolivre.exception; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class ValidationErrorHandler { @Autowired private MessageSource messageSource; @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException.class) public ValidationErrorsOutoutDto handleValidationError(MethodArgumentNotValidException exception) { List<ObjectError> globalErrors = exception.getBindingResult().getGlobalErrors(); List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors(); return buildValidationErrors(globalErrors, fieldErrors); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(BindException.class) public ValidationErrorsOutoutDto handleValidationError(BindException exception) { List<ObjectError> globalErrors = exception.getBindingResult().getGlobalErrors(); List<FieldError> fieldErrors = exception.getBindingResult().getFieldErrors(); return buildValidationErrors(globalErrors, fieldErrors); } private ValidationErrorsOutoutDto buildValidationErrors(List<ObjectError> globalErrors, List<FieldError> fieldErrors) { ValidationErrorsOutoutDto validationErrors = new ValidationErrorsOutoutDto(); globalErrors.forEach(error -> validationErrors.addError(getErrorMessage(error))); fieldErrors.forEach(error ->{ String errorMessage = getErrorMessage(error); validationErrors.addFieldError(error.getField(), errorMessage); }); return validationErrors; } private String getErrorMessage(ObjectError error) { return messageSource.getMessage(error, LocaleContextHolder.getLocale()); } }
112c4c6c06fc8a5e65d8ab649d2519eeaad32d63
be73270af6be0a811bca4f1710dc6a038e4a8fd2
/crash-reproduction-moho/results/XWIKI-14263-60-24-PESA_II-WeightedSum:TestLen:CallDiversity/com/xpn/xwiki/internal/template/InternalTemplateManager_ESTest_scaffolding.java
285e1b6225debdf7c01f80835bb3da22084138de
[]
no_license
STAMP-project/Botsing-multi-objectivization-using-helper-objectives-application
cf118b23ecb87a8bf59643e42f7556b521d1f754
3bb39683f9c343b8ec94890a00b8f260d158dfe3
refs/heads/master
2022-07-29T14:44:00.774547
2020-08-10T15:14:49
2020-08-10T15:14:49
285,804,495
0
0
null
null
null
null
UTF-8
Java
false
false
459
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Sat Apr 04 05:04:46 UTC 2020 */ package com.xpn.xwiki.internal.template; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; @EvoSuiteClassExclude public class InternalTemplateManager_ESTest_scaffolding { // Empty scaffolding for empty test suite }
bbf0fb9660c4184537b9b68d7f2a775546c0b5db
b40588c5fa5ff9241a7e50ed5f71beea41d4dca6
/src/com/ALEAP/teacherGUI/QuizEditor.java
509d5b2130e5e113c821b600761ae236da43b28f
[]
no_license
grieggs/A-LEAP
97f0e2632aec1645c6ad3a5a837f785682808505
f9a662b419c3e670853668e50ab4d558e878d741
refs/heads/master
2021-01-21T10:37:38.757699
2017-05-11T14:26:40
2017-05-11T14:26:40
83,461,404
0
2
null
null
null
null
UTF-8
Java
false
false
9,477
java
/* * 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.ALEAP.teacherGUI; import com.ALEAP.io.*; import com.ALEAP.objects.*; import java.io.File; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; /** * * @author tjkt */ public class QuizEditor extends javax.swing.JFrame { Quiz active = new Quiz("test"); DefaultListModel topics = null; /** * Creates new form QuizEditor */ public QuizEditor() { initComponents(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void updateList(){ DefaultListModel topics = new DefaultListModel(); for(int x = 0; x < active.getSize(); x++){ topics.addElement(active.getTopic(x).getName()); } topicList.setModel(topics); } public void setQuiz(Quiz newQuiz){ this.active = newQuiz; this.quizNameLabel.setText(active.getName()); updateList(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { quizNameLabel = new javax.swing.JLabel(); editButton = new javax.swing.JButton(); newTopic = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); topicList = new javax.swing.JList<>(); saveButton = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); quizNameLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N quizNameLabel.setText("jLabel1"); editButton.setText("Edit Topic"); editButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editButtonActionPerformed(evt); } }); newTopic.setText("New Topic"); newTopic.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { newTopicActionPerformed(evt); } }); jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jScrollPane1.setViewportView(topicList); saveButton.setText("Save Quiz"); saveButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(quizNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(saveButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(newTopic, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(quizNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(26, 26, 26) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(newTopic) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveButton) .addContainerGap(25, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed // TODO add your handling code here: int index = this.topicList.getSelectedIndex(); if(index != -1){ TopicEditor t = new TopicEditor(); t.setTopic(this.active.getTopic(this.topicList.getSelectedIndex())); t.setVisible(true); } }//GEN-LAST:event_editButtonActionPerformed private void newTopicActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newTopicActionPerformed // TODO add your handling code here: String newName = (String)JOptionPane.showInputDialog( this, "Please enter the name of the new topic", "New Topic", JOptionPane.PLAIN_MESSAGE, null, null, ""); active.addTopic(new Topic(newName)); updateList(); }//GEN-LAST:event_newTopicActionPerformed private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed // TODO add your handling code here: JFileChooser fc = new JFileChooser(); fc.setAcceptAllFileFilterUsed(false); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.addChoosableFileFilter(new FileTypeFilter(".ser", "Quiz File")); if(fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){ String filename = fc.getSelectedFile().toString(); if (!filename .endsWith(".ser")) filename += ".ser"; File file = new File(filename); QuizIO.writeQuiz(file, active); } }//GEN-LAST:event_saveButtonActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(QuizEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(QuizEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(QuizEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(QuizEditor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new QuizEditor().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton editButton; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton newTopic; private javax.swing.JLabel quizNameLabel; private javax.swing.JButton saveButton; private javax.swing.JList<String> topicList; // End of variables declaration//GEN-END:variables }
535dd72361cf2eb116161fff7c7cf6d5a4231cc2
a5c64d8630741086f6e8d71371dc1c53d44f1d99
/src/accountManager/view/StartAgentView.java
c3d393601739f9fc0b60a596fad4c6c3007f3591
[]
no_license
martip23/accountManager
ad1706482fce56e8bec1d31dafe1eb43e79d2a4b
03709fdd6748e87efab8202b1a9e48dc4df53797
refs/heads/master
2021-05-07T08:11:05.840684
2017-12-05T21:08:29
2017-12-05T21:08:29
109,312,346
0
0
null
null
null
null
UTF-8
Java
false
false
915
java
package accountManager.view; import javax.swing.*; import java.awt.*; import java.awt.event.*; import accountManager.controller.*; import accountManager.model.*; /** * Implements the GUI and I/O of GUI. Creates listeners and event * generators to work with Model & Controller. * @author martip23 * */ @SuppressWarnings("serial") public class StartAgentView extends JFrameView { /** * Creates Account Manager view and registers model & controller. * @param model Model to register with view. * @param controller Controller to register with view. */ public StartAgentView(AgentModel model, AgentController controller) { super(model, controller); // TODO Auto-generated constructor stub } @Override public void modelChanged(ModelEvent event) { // TODO Auto-generated method stub } class Handler implements ActionListener { public void actionPerformed(ActionEvent e) { } } }
f679a2c69de48423a5149818a8337698b62085be
159549c971aa5f97dea25c9e78757b38583a5659
/src/main/java/structure/proxy/Test.java
79de90c3e0495307014e9d28d247bd1724789a48
[]
no_license
yangzhenwei-java/designPatterns
0fb855571a6e3cfcff869d464ff5f89214d62f99
726e3fb464e735bf4ac6c6f17a1096af0b1dc61b
refs/heads/master
2021-01-10T01:22:21.423343
2016-04-02T15:30:14
2016-04-02T15:30:14
55,301,755
0
0
null
null
null
null
UTF-8
Java
false
false
178
java
package structure.proxy; public class Test { public static void main(String[] args) { IObject obj = new ProxyObject(); obj.action(); } }
9f714468716790b9d399b109ab370dc2b1725578
2c420abbb3f1de96b63decb1a1ffd597740230fa
/src/main/java/com/aradionov/socketchat/chat/ChatService.java
60d8f8493e68c784cbde5e0fa2503daf529fa6f7
[]
no_license
AndyRadionov/websocketchat
1a3505089af1191fe05961b1443b87f23a21172b
a2cf8a2d0388996c28f7aad0ae476f96ba94f656
refs/heads/master
2021-01-12T00:53:04.024086
2018-07-03T11:55:38
2018-07-03T11:55:38
78,305,801
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package com.aradionov.socketchat.chat; import org.eclipse.jetty.util.ConcurrentHashSet; import java.util.Set; /** * @author Andrey Radionov */ public class ChatService { private Set<ChatWebSocket> webSockets; public ChatService() { this.webSockets = new ConcurrentHashSet<>(); } public void sendMessage(String data) { for (ChatWebSocket socket : webSockets) { try { socket.sendString(data); } catch (Exception e) { System.out.println(e.getMessage()); } } } public void add(ChatWebSocket webSocket) { webSockets.add(webSocket); } public void remove(ChatWebSocket webSocket) { webSockets.remove(webSocket); } }
85ee26411f6c610e30657a5ef39f93ece2b03966
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/3/3_4b8f126e35047a3ca7e364d2d30994974b337bb8/MonitorFrameInfo/3_4b8f126e35047a3ca7e364d2d30994974b337bb8_MonitorFrameInfo_s.java
9e0505e1324b03fb080099cd774c9b83c1d225f0
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
5,731
java
/* * Copyright 2005 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /** * @test * @bug 6230699 * @summary Test ThreadReference.ownedMonitorsAndFrames() * @bug 6701700 * @summary MonitorInfo objects aren't invalidated when the owning thread is resumed * @author Swamy Venkataramanappa * * @run build TestScaffold VMConnection TargetListener TargetAdapter * @run compile -g MonitorFrameInfo.java * @run main MonitorFrameInfo */ import com.sun.jdi.*; import com.sun.jdi.event.*; import com.sun.jdi.request.*; import java.util.*; /********** target program **********/ class MonitorTestTarg { static void foo3() { System.out.println("executing foo3"); } static void foo2() { Object l1 = new Object(); synchronized(l1) { foo3(); } } static void foo1() { foo2(); } public static void main(String[] args){ System.out.println("Howdy!"); Object l1 = new Object(); synchronized(l1) { foo1(); } } } /********** test program **********/ public class MonitorFrameInfo extends TestScaffold { ReferenceType targetClass; ThreadReference mainThread; List monitors; static int expectedCount = 2; static int[] expectedDepth = { 1, 3 }; static String[] expectedNames = {"foo3", "foo2", "foo1", "main"}; MonitorFrameInfo (String args[]) { super(args); } public static void main(String[] args) throws Exception { new MonitorFrameInfo(args).startTests(); } /********** test core **********/ protected void runTests() throws Exception { /* * Get to the top of main() * to determine targetClass and mainThread */ BreakpointEvent bpe = startToMain("MonitorTestTarg"); targetClass = bpe.location().declaringType(); mainThread = bpe.thread(); int initialSize = mainThread.frames().size(); resumeTo("MonitorTestTarg", "foo3", "()V"); if (!mainThread.frame(0).location().method().name() .equals("foo3")) { failure("FAILED: frame failed"); } if (mainThread.frames().size() != (initialSize + 3)) { failure("FAILED: frames size failed"); } if (mainThread.frames().size() != mainThread.frameCount()) { failure("FAILED: frames size not equal to frameCount"); } /* Test monitor frame info. */ if (vm().canGetMonitorFrameInfo()) { System.out.println("Get monitors"); monitors = mainThread.ownedMonitorsAndFrames(); if (monitors.size() != expectedCount) { failure("monitors count is not equal to expected count"); } MonitorInfo mon = null; for (int j=0; j < monitors.size(); j++) { mon = (MonitorInfo)monitors.get(j); System.out.println("Monitor obj " + mon.monitor() + "depth =" +mon.stackDepth()); if (mon.stackDepth() != expectedDepth[j]) { failure("FAILED: monitor stack depth is not equal to expected depth"); } } // The last gotten monInfo is in mon. When we resume the thread, // it should become invalid. We will step out of the top frame // so that the frame depth in this mon object will no longer be correct. // That is why the monInfo's have to become invalid when the thread is // resumed. stepOut(mainThread); boolean ok = false; try { System.out.println("*** Saved Monitor obj " + mon.monitor() + "depth =" +mon.stackDepth()); } catch(InvalidStackFrameException ee) { // ok ok = true; System.out.println("Got expected InvalidStackFrameException after a resume"); } if (!ok) { failure("FAILED: MonitorInfo object was not invalidated by a resume"); } } else { System.out.println("can not get monitors frame info"); } /* * resume until end */ listenUntilVMDisconnect(); /* * deal with results of test * if anything has called failure("foo") testFailed will be true */ if (!testFailed) { println("MonitorFrameInfo: passed"); } else { throw new Exception("MonitorFrameInfo: failed"); } } }
4d2d909d89ea4491f35c2a412d0bdd8aaceebf12
4109433ae26c6a77232df2dd956ac163358f1f54
/src/main/java/ar/com/telefonica/ws/amdocs/engine/RecordWriterGeneric.java
faf3a357a266fb7384d661b8f8bb04da67bc2159
[]
no_license
fanzovino/Commi
22e70cd065bbf26fd1a85501475c275ab9059de9
e86dcd52b1705b59d5e015f97873dc767931053e
refs/heads/master
2021-01-21T09:55:55.097723
2013-09-11T13:49:55
2013-09-11T13:49:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,384
java
/** ****************************************************************************************** * * class RecordWriterGeneric * * Writer implementation for generic output. * * Main responsibilities: * - Process oRec and lookup for specific OutputRecords * - Write to output file * * * @Exceptions: * - write throw Exception * - GenerateFile throw Exception * ********************************************************************************************* * * @package ar.com.telefonica.ws.amdocs.engine * * @author FGA <[email protected]> * @version 1.0 * @created 31-Jul-2013 * *********************************************************************************************/ package ar.com.telefonica.ws.amdocs.engine; import java.util.List; import org.apache.log4j.Logger; public class RecordWriterGeneric implements IRecordWriter,IRecordStream { static Logger logger = Logger.getLogger(RecordWriterGeneric.class); /* * constructors: */ public RecordWriterGeneric() { } public RecordWriterGeneric(ObjectRecord objRecord) { super(); oRec = objRecord; } /* * private variables: */ private String types; private ObjectRecord oRec; //private OutputRecord outputGenerator ; private List<OutputRecord> outPutRecList; /* * setters/getters: */ public List<OutputRecord> getOutPutRecList() { return outPutRecList; } public void setOutPutRecList(List<OutputRecord> outPutRecList) { this.outPutRecList = outPutRecList; } public String getTypes() { return types; } public void setTypes(String types) { this.types = types; } public ObjectRecord getObjRecord() { return oRec; } public void setObjRecord(ObjectRecord objRecord) { this.oRec = objRecord; } /* * Private methods: */ // Generador del archivo final output resuelve el enigma segun la definicion del output Readear private void GenerateFile(ObjectRecord obRec) throws Exception { //6.5. The Delegate Pattern and Registering with the Step //-->>>>>>>>>> try { // TODO: Generador de Archivos } catch (Exception e) { String errMsg = "Problem to generate the file OutPutRecord."; logger.error(errMsg); throw e; } obRec.setProcessingStatus(ObjectRecord.ProcessingStatus.COMPLETE); } /* * Public methods: */ // Genrador del archivo final output resuelve el enigma segun la definicion del output Reader public void write(List<ObjectRecord> obRec) throws Exception { oRec = obRec.get(0); for (OutputRecord output : outPutRecList) { if(this.getTypes().contains(output.getType())){ //funcion de conversion de archivo output! GenerateFile(oRec); }else{ //TODO: Lo pongo en error el ObjectRecord para diferenciar? //oRec.setResultStatus(ObjectRecord.ResultStatus.ERROR); String errMsg = "Undefined OutputRecord generator."; logger.error(errMsg); throw new Exception(errMsg); } } } @Override public void open(Object context) throws Exception { // TODO Auto-generated method stub } @Override public void close() throws Exception { // TODO Auto-generated method stub } @Override public void update(Object context) throws Exception { // TODO Auto-generated method stub } }
fd587998327c94f75c2bfbe25facfe2a8cab0dbe
8fdcd401788243f2d4a8e1307ee0a8444dfe9377
/InterfacesFuncionales/src/clases/EjemploSimpleInterface.java
a5e12e388c25dc2f3ecf25d7f2424999a509fd45
[]
no_license
enrique7mc/Ejemplos-Java-8
296c4df43ee0b2074065641d6c98f5c0aa2b265d
07b9227be9669b7182bb689712722442ef8876e9
refs/heads/master
2021-01-10T12:37:30.339150
2015-06-02T00:01:02
2015-06-02T00:01:02
36,693,138
0
0
null
null
null
null
UTF-8
Java
false
false
266
java
package clases; import interfaces.SimpleInterface; public class EjemploSimpleInterface { public static void main(String[] args) { SimpleInterface obj = () -> System.out.println("Dentro de la interfaz"); obj.procesar(); } }
a25d99f4d5801ed874ec8663f8b50a98205d4588
9543f1302522ab515d29b668adeb8238f325bd06
/Sniffer-Search/src/main/java/com/jpznm/dht/sniffersearch/core/tags/impl/NewTimeTagsImpl.java
a154b77a8e19d0c03b14be61c223c68e0ad7c838
[]
no_license
lianshufeng/dht
9ae537b88868216ce3e3606b22f39bf944f755f7
5b3447cc44e2c904b8f0cc717cd96552d2636959
refs/heads/master
2021-06-13T23:57:43.732952
2021-02-04T06:50:12
2021-02-04T06:50:12
152,176,713
0
0
null
2021-02-04T06:50:55
2018-10-09T02:40:04
Java
UTF-8
Java
false
false
318
java
package com.jpznm.dht.sniffersearch.core.tags.impl; import com.jpznm.dht.sniffersearch.core.tags.TagsTransform; import org.springframework.stereotype.Component; @Component public class NewTimeTagsImpl implements TagsTransform { @Override public boolean execute(String info) { return false; } }
1b5e80c959f6045eb23f4c3e5cf921f2ba79880f
21a44b7fcad424aa9b538edd102ac3b220008897
/L- System/Point.java
3b611f0674e36bc4a61ef2da81259b2a9fe9538a
[]
no_license
AshleshaBhamare/CPSC5002
725eb88f79885e0c7a517831c8c0dbbb8e00a497
45b3c6b891444e1e5c752f05d8449335a0c7eacd
refs/heads/master
2022-12-06T21:47:17.850586
2020-09-03T19:58:16
2020-09-03T19:58:16
292,630,939
0
0
null
null
null
null
UTF-8
Java
false
false
6,956
java
/* * Kevin Lundeen * CPSC 5002, Seattle University * This is free and unencumbered software released into the public domain. */ package abhamare_lab7; /** * Class to hold a 2-d point in space. Both Cartesian and Polar coordinates * are supported. * @author Ashlesha Bhamare */ public class Point { private double x; private double y; /** * Default Point is at (1,1) */ public Point() { this(1.0, 1.0); } /** * Constructor that sets x and y. * @param x initial x coordinate * @param y initial y coordinate */ public Point(double x, double y) { this.x = x; this.y = y; } /** * Get the x coordinate in Cartesian system. * @return x coordinate */ public double getX() { return x; } /** * Get the y coordinate in Cartesian system. * @return y coordinate */ public double getY() { return y; } /** * Set the x coordinate in Cartesian system. * @param x x coordinate */ public void setX(double x) { this.x = x; } /** * Set the y coordinate in Cartesian system. * @param y y coordinate */ public void setY(double y) { this.y = y; } public void setXY(double x, double y) { setX(x); setY(y); } /** * Get the distance coordinate in Polar system. * @return distance from origin */ public double getR() { return Math.sqrt(x * x + y * y); } /** * Get the angle coordinate in Polar system. * @return angle coordinate (counterclockwise from East-pointing axis * in radians) */ public double getTheta() { return Math.atan2(y, x); } /** * Set the distance coordinate in Polar system. * @param r distance from origin */ public void setR(double r) { double theta = getTheta(); x = r * Math.cos(theta); y = r * Math.sin(theta); } /** * Set the angle coordinate in Polar system. * The angle is reduced to the range [0:2pi). * @param thetaCoord angle in radians (counterclockwise from East) */ public void setTheta(double thetaCoord) { double r = getR(); x = r * Math.cos(thetaCoord); y = r * Math.sin(thetaCoord); } /** * Set both the distance and angle coordinates in Polar system. * @param r distance coordinate * @param theta angle coordinate */ public void setRTheta(double r, double theta) { setR(r); setTheta(theta); } /** * Convert to a string * @return string representation of point (using Cartesian) */ @Override public String toString() { return "Point(x=" + x + ",y=" + y + ")"; } /** * Compare this point to another. * @param other point to compare to * @return true if the other point is identical, false otherwise */ public boolean equals(Point other) { return x == other.x && y == other.y; } /** * Copy this point to a new Point object. * @return a new point which is equal to this point */ public Point copy() { Point copyObject = new Point(x, y); return copyObject; } /** * Get the distance between this point and another. * @param other point to get distance to * @return distance to other */ public double distance(Point other) { double dx = other.x - this.x; // use of this is optional double dy = other.y - this.y; return Math.sqrt(dx*dx + dy*dy); } /** * Convenience method will take in other point as (x,y) and * then calculate distance, * @see distance(other) * @param otherx x coord of point to get distance to * @param othery y coord of point to get distance to * @return distance to other */ public double distance(double otherx, double othery) { return this.distance(new Point(otherx, othery)); } /** * Static method to get distance between two points. * @param a first point * @param b second point * @return distance from a to b */ public static double distance(Point a, Point b) { return a.distance(b); } /** * Static method to get distance between two points specified * by their (x,y) coordinates. * @param ax x coord of first point * @param ay y coord of first point * @param bx x coord of second point * @param by y coord of second point * @return distance from a to b */ public static double distance(double ax, double ay, double bx, double by) { return Point.distance(new Point(ax, ay), new Point(bx, by)); } /** * Move this point the given distance in the given direction. * @param distance units to move * @param angle direction to move (radians counterclockwise from East) */ public void move(double distance, double angle) { Point temp = Point.pointFromPolar(distance, angle); this.x += temp.getX(); this.y += temp.getY(); } /** * Construct a Point from Polar coordinates. * @param rCoord distance from origin * @param thetaCoord angle in radians from East * @return a Point with those Polar coordinates */ public static Point pointFromPolar(double rCoord, double thetaCoord) { Point rThetaPoint = new Point(); rThetaPoint.setR(rCoord); rThetaPoint.setTheta(thetaCoord); return rThetaPoint; } /** * Tests. * @param args not used */ public static void main(String[] args) { System.out.println("some Point tests"); Point point = new Point(); System.out.println("default: " + point); point = new Point(1,-3.5); System.out.println("(1,-3.5): " + point); System.out.println("which is r:" + point.getR() + " theta:" + point.getTheta()); point.setX(0.0); point.setY(0.0); System.out.println("reset to zeros: " + point); point.setR(Math.sqrt(2)); point.setTheta(Math.PI / 4); System.out.println("set to r=1, theta=pi/4: " + point); Point p3 = pointFromPolar(Math.sqrt(2), Math.PI/4); System.out.println("p3: " + p3); System.out.println("point.equals(p3): " + point.equals(p3)); Point p4 = point.copy(); System.out.println("p3: " + p3); System.out.println("p4.equals(p3): " + p4.equals(p3)); double distance = Point.distance(new Point(1,-1), new Point(-1,1)); System.out.println("distance from (1,-1) to (-1,1), expect 2sqrt(2): " + distance); } }
ee81d6335159f96d91e4a2b19d29a74b1f882b6e
45f572eb782ac87d9897b4b0f7406b770b6041f2
/src/main/java/com/hvisions/mes/domain/MaterialPack.java
d1876a954ef482fb5374a673ceba6a08d52102c8
[]
no_license
pendd/traceability
c41cb96b17949a366d8acc233e5a38c95e92d2ea
7ca3b681179f295b8551d49c1036a7aea6d3f09b
refs/heads/master
2021-03-10T14:26:09.412910
2020-03-24T06:06:07
2020-03-24T06:06:07
246,461,094
0
0
null
null
null
null
UTF-8
Java
false
false
1,546
java
package com.hvisions.mes.domain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; /** * 原料包装 * * @author dpeng * @create 2019-06-05 10:27 */ @Data @ApiModel public class MaterialPack { @ApiModelProperty(hidden = true) private Integer packId; @ApiModelProperty(hidden = true) private Date createTime; @ApiModelProperty(value = "用户ID",name = "userId",required = true,example = "1") private Integer userId; @ApiModelProperty(value = "第一层码",name = "firstCode",required = true,example = "1%1001") private String firstCode; @ApiModelProperty(value = "上级码",name = "secondCode",required = true,example = "1%100000001") private String secondCode; @ApiModelProperty(hidden = true) private Integer packTypeId; ////////////////// 冗余字段 /////////////// @ApiModelProperty(hidden = true) private Integer supplierId; @ApiModelProperty(hidden = true) private Integer materialId; @ApiModelProperty(hidden = true) private String supplierNumber; @ApiModelProperty(hidden = true) private Integer batchId; @ApiModelProperty(hidden = true) private Integer storeroomId; @ApiModelProperty(hidden = true) private String unit; @ApiModelProperty(hidden = true) private Integer teamId; @ApiModelProperty(hidden = true) private String materialSignCode; @ApiModelProperty(hidden = true) private String specs; }
8a1d86264d8dbe0947c6ec722b0bd853a60b94b2
0ecf0e8409273710f27d3ff8f98a1a2af5714734
/hello.java
af5f1de846df49fb579b526e9821e1e92d6b03a9
[]
no_license
hesaidyou/gitfiles
83ae3735245d4a949e68e2c616a85c32f4ad7201
0f95330c17f893683bbe906dc6eb19acb4e6581b
refs/heads/master
2020-03-11T04:14:04.700524
2017-06-07T03:22:27
2017-06-07T03:22:27
null
0
0
null
null
null
null
GB18030
Java
false
false
237
java
public class hello { public static void main(String[] args) { String s("我很高兴学习java"); System.out.println("Hello git~~~~~"); System.out.println(s); System.out.println("we are student"); } }
[ "刘清" ]
刘清
c768784b9b54499cb14b8acf20883d9b0fbb34c2
8baf2fb3c14a3824cf8f7a644cad61f961beae25
/src/main/java/Controllers/astar/MovePair.java
63979ac17fd4d59ade53e01fbe681fee2a7e17ad
[]
no_license
webpigeon/TinyCoop
2c8134935f6b43acfa67bfdcd51b83c14c07c587
16ac22c83d7005ed5f411808e42dbe4eb0b4cf24
refs/heads/master
2020-12-29T01:53:55.384261
2015-10-27T12:55:53
2015-10-27T12:55:53
38,317,836
0
0
null
null
null
null
UTF-8
Java
false
false
913
java
package Controllers.astar; import FastGame.Action; import FastGame.CoopGame; /** * Created by jwalto on 02/07/2015. */ public class MovePair { protected Action p1Move; protected Action p2Move; public MovePair(Action p1, Action p2) { this.p1Move = p1; this.p2Move = p2; } public String toString() { return String.format("(%s,%s)", p1Move, p2Move); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MovePair movePair = (MovePair) o; if (!p1Move.equals(movePair.p1Move)) return false; if (!p2Move.equals(movePair.p2Move)) return false; return true; } @Override public int hashCode() { int result = p1Move.hashCode(); result = 31 * result + p2Move.hashCode(); return result; } }
0780c9ccc6b656923b5f9044d0724dc3b81525a7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/20/20_8dc860b920dd9f98fee5901adb878be298e121dd/ChangeVmConfiguration/20_8dc860b920dd9f98fee5901adb878be298e121dd_ChangeVmConfiguration_s.java
e313876ddcc7a1729c3d0211f7dc33a43c8a80f0
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
6,903
java
package at.ac.tuwien.lsdc.actions; import java.util.List; import at.ac.tuwien.lsdc.Configuration; import at.ac.tuwien.lsdc.resources.Resource; import at.ac.tuwien.lsdc.resources.VirtualMachine; public class ChangeVmConfiguration extends Action { private VirtualMachine vm; private int optimizedCpuAllocation; private int optimizedMemoryAllocation; private int optimizedStorageAllocation; private static int configurationChangeCosts; private static int topRegion; private static int bottomRegion; // tick count to look in the past private final int tickCount = 10; @Override public void init(Resource problem) { if (problem instanceof VirtualMachine) { this.vm = (VirtualMachine) problem; } // set init values ChangeVmConfiguration.setConfigurationChangeCosts(Configuration.getInstance().getVmConfigurationChangeCosts()); ChangeVmConfiguration.setTopRegion(Configuration.getInstance().getTopRegion()); ChangeVmConfiguration.setBottomRegion(Configuration.getInstance().getBottomRegion()); } public static int getBottomRegion() { return bottomRegion; } public static void setBottomRegion(int bottomRegion) { ChangeVmConfiguration.bottomRegion = bottomRegion; } @Override public int predict() { this.calculateBetterAllocationValues(); // decide how urgent a configurationchange is 0-100, 100 = urgent int prediction = 0; prediction = (Math.abs(this.vm.getCurrentCpuAllocation() - this.optimizedCpuAllocation) + Math.abs(this.vm.getCurrentMemoryAllocation() - this.optimizedMemoryAllocation) + Math.abs(this.vm.getCurrentStorageAllocation() - this.optimizedStorageAllocation)) / 3; int slaViolationUrgency = 10; int slaViolationCount = this.vm.getNumberOfSlaViolations(this.tickCount); if (prediction < slaViolationUrgency && slaViolationCount > 0) { // reallocation should be neccessary, chose 10% importance prediction = slaViolationUrgency + slaViolationCount; if (prediction > 100) { prediction = 100; } } return 0; } /** * Calculates better VM allocation values for the given VM, depending in which zone it's currently in. */ private void calculateBetterAllocationValues() { this.optimizedCpuAllocation = this.calculateOptimizedCpuAllocation(this.tickCount); this.optimizedMemoryAllocation = this.calculateOptimizedMemoryAllocation(this.tickCount); this.optimizedStorageAllocation = this.calculateOptimizedStorageAllocation(this.tickCount); } /** * Calculates an optimized CPU allocation value for the VM * * @param ticks Based on the last n ticks * @return The optimized CPU allocation value */ private int calculateOptimizedCpuAllocation(int ticks) { return this.calculateOptimizedAllocation(this.vm.getCurrentCpuAllocation(), this.vm.getCpuAllocationHistory(this.tickCount), this.vm.getCpuUsageHistory(this.tickCount)); } /** * Calculates an optimized memory allocation value for the VM * * @param ticks Based on the last n ticks * @return The optimized memory allocation value */ private int calculateOptimizedMemoryAllocation(int ticks) { return this.calculateOptimizedAllocation(this.vm.getCurrentMemoryAllocation(), this.vm.getMemoryAllocationHistory(this.tickCount), this.vm.getMemoryUsageHistory(this.tickCount)); } /** * Calculates an optimized storage allocation value for the VM * * @param ticks Based on the last n ticks * @return The optimized storage allocation value */ private int calculateOptimizedStorageAllocation(int ticks) { return this.calculateOptimizedAllocation(this.vm.getCurrentStorageAllocation(), this.vm.getStorageAllocationHistory(this.tickCount), this.vm.getStorageUsageHistory(this.tickCount)); } /** * Calculates an optimized allocation value for a given history of values * * @param currentAllocation * @param allocationHistory * @param usageHistory * @return Optimized allocation value */ private int calculateOptimizedAllocation(int currentAllocation, List<Integer> allocationHistory, List<Integer> usageHistory) { int allocation = currentAllocation; int optimizedAllocation = 0; int topRegionReached = 0; int bottomRegionReached = 0; // calculate how often the VM went into a dangerous zone in the last n ticks (compare allocated to used resources) for (int i = 0; i < allocationHistory.size(); i++) { Integer allocated = allocationHistory.get(i); Integer used = usageHistory.get(i); // calculate percentage of the used resources vs. the allocated resources int ratio = (int) ((used / (float) allocated) * 100); if (ratio > ChangeVmConfiguration.topRegion) { // need more resources topRegionReached++; } else if (ratio < ChangeVmConfiguration.bottomRegion) { // need less resources bottomRegionReached++; } else { // resource allocation is perfect // do nothing } // calculate allocation so that "used" is 95% of the allocation optimizedAllocation = (int) ((float) used / ChangeVmConfiguration.topRegion * 100); if (topRegionReached > 1 || bottomRegionReached > 1) { // need to change the allocation if (allocation < optimizedAllocation) { allocation = optimizedAllocation; } } } if (allocation > 100) { allocation = 100; } else if (allocation < 0) { allocation = 0; } return allocation; } @Override public int estimate() { return ChangeVmConfiguration.configurationChangeCosts; } @Override public boolean preconditions() { // VMs can always be changed return true; } @Override public void execute() { // change CPU allocation if (this.vm.getCurrentCpuAllocation() != this.optimizedCpuAllocation) { this.vm.setCurrentCpuAlloction(this.optimizedCpuAllocation); } // change memory allocation if (this.vm.getCurrentMemoryAllocation() != this.optimizedMemoryAllocation) { this.vm.setCurrentMemoryAlloction(this.optimizedMemoryAllocation); } // change storage allocation if (this.vm.getCurrentStorageAllocation() != this.optimizedStorageAllocation) { this.vm.setCurrentStorageAlloction(this.optimizedStorageAllocation); } } @Override public boolean evaluate() { // nothing to do here return true; } @Override public void terminate() { // unused } public static int getConfigurationChangeCosts() { return configurationChangeCosts; } public static void setConfigurationChangeCosts(int configurationChangeCosts) { ChangeVmConfiguration.configurationChangeCosts = configurationChangeCosts; } public static int getTopRegion() { return topRegion; } public static void setTopRegion(int topRegion) { ChangeVmConfiguration.topRegion = topRegion; } }
682446ba530ed7fba6fb9faf446ef5e260d2ac71
48541b2e7137ad1b8fc5639c954a2c55ee208e78
/jodconverter-core/src/main/java/org/jodconverter/job/DocumentSpecs.java
5ac7eb54091f0f9a3eee05408c497fc1990dfc36
[ "Apache-2.0" ]
permissive
gary-dgc/jodconverter
cf099a33f62de2ab52db0baa104eb9cdfc2b5c66
eafd1b73a0ffb9953649eb2997ec5a5e7f8f0cbc
refs/heads/master
2020-12-07T14:04:16.614523
2020-01-08T19:39:15
2020-01-08T19:39:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,271
java
/* * Copyright 2004 - 2012 Mirko Nasato and contributors * 2016 - 2020 Simon Braconnier and contributors * * This file is part of JODConverter - Java OpenDocument Converter. * * 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.jodconverter.job; import java.io.File; import org.jodconverter.document.DocumentFormat; /** * An interface that provides, for a document, the physical file and format required by a conversion * process. */ interface DocumentSpecs { /** * Gets the file where is located the document. * * @return A file instance. */ File getFile(); /** * Gets the {@link DocumentFormat} specification for the document. * * @return The document format. */ DocumentFormat getFormat(); }
6d4abe074d6d3122a1c91bb85021ead2d320b2a6
94c6db89c1cf9cba8205830e0c8aaa7209ad9a49
/mortgage/src/main/java/com/ing/mortgage/exception/InvalidMobileNumberException.java
7da785822489c933ce0b4600b9ce5badc09169b3
[]
no_license
SubhaMaheswaran27/Squad1works
edfe5d1e362c63f3d48feefe7f002f2862388b45
616c53d4aa8c1f330d427b31ff78adedea47f39a
refs/heads/master
2020-08-27T07:45:11.308797
2019-10-24T12:09:05
2019-10-24T12:09:05
217,288,638
0
0
null
null
null
null
UTF-8
Java
false
false
356
java
package com.ing.mortgage.exception; import java.io.Serializable; public class InvalidMobileNumberException extends RuntimeException implements Serializable { private static final long serialVersionUID = 1L; private static final String MESSAGE = "Please enter a valid mobile Number"; public InvalidMobileNumberException() { super(MESSAGE); } }
fe3a0215d1a3f13afd97614cfcb82e91d1b5637f
7fece18c2545f49374914079bbd0ce4d9d312303
/src/chapter10questions/Q1114CombineTwoLists.java
dfaf73519db5a371aa7305432f7b71a70b3b027a
[]
no_license
ryesil/java_book_questions
911b2b97330cafe2f696bd5f2324e753e0e0d548
05d8d4e14f0d58cae99743f41bf0e6a2e84fc783
refs/heads/master
2023-07-09T03:25:38.798645
2021-08-08T13:52:57
2021-08-08T13:52:57
393,973,964
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package chapter10questions; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Q1114CombineTwoLists { public static void main(String[] args) { ArrayList<Integer> list1=new ArrayList<>(); ArrayList<Integer> list2=new ArrayList<>(); list1.add(1); list1.add(2); list2.add(3); list2.add(4); union(list1,list2); } public static List<Integer> union(ArrayList<Integer> list1,ArrayList<Integer> list2){ List<Integer> store=new ArrayList<>(list1); for(int i=0;i<list2.size();i++) { store.add(list2.get(i)); } System.out.println(store); return store; } }
6642c5596b8a199ff4509fe069fb77433d49832f
6925f8f5e195b6cc606f3e91f2c735d6a99a5a7a
/Save/app/src/main/java/com/github/albalitz/save/activities/RegisterActivity.java
6d1a0c5c5cf311194804cd25b0e176ba3198e9ca
[ "MIT" ]
permissive
vaginessa/save-android
8b0806a8094942f1f26090f62f9449e0ba5c36d9
a49fdde2a116e088a6cd0c6bf33f815a5e908380
refs/heads/master
2021-01-21T08:20:23.079507
2017-05-14T18:06:27
2017-05-14T18:06:27
91,623,419
0
0
MIT
2019-01-18T12:33:55
2017-05-17T21:55:05
Java
UTF-8
Java
false
false
3,983
java
package com.github.albalitz.save.activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.github.albalitz.save.R; import com.github.albalitz.save.persistence.api.Api; import com.github.albalitz.save.persistence.Link; import com.github.albalitz.save.utils.Utils; import org.json.JSONException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; public class RegisterActivity extends AppCompatActivity implements ApiActivity, SnackbarActivity { private EditText editTextUsername; private EditText editTextPassword; private Button buttonRegister; private Button buttonCancel; private Api api; private TextWatcher watcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d(this.toString(), "onTextChanged triggered."); setRegisterButtonState(filledBothInputs()); } @Override public void afterTextChanged(Editable s) {} }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(this.toString(), "Creating RegisterActivity."); super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); api = new Api(this); // assign content editTextUsername = (EditText) findViewById(R.id.editTextUsername); editTextPassword = (EditText) findViewById(R.id.editTextPassword); buttonCancel = (Button) findViewById(R.id.buttonCancel); buttonRegister = (Button) findViewById(R.id.buttonRegister); // prepare stuff Log.v(this.toString(), "Adding button click listener ..."); setRegisterButtonState(filledBothInputs()); buttonCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); buttonRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { registerUser(); } }); Log.v(this.toString(), "Adding TextWatcher ..."); editTextUsername.addTextChangedListener(watcher); editTextPassword.addTextChangedListener(watcher); } protected boolean filledBothInputs() { for (String input : Arrays.asList( editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim() )) { if (input.isEmpty()) { return false; } } return true; } protected void setRegisterButtonState(boolean state) { Log.v(this.toString(), "Register button state is now " + state + "."); buttonRegister.setEnabled(state); } private void registerUser() { Utils.showSnackbar(this, "Registering..."); String username = editTextUsername.getText().toString(); String password = editTextPassword.getText().toString(); try { api.registerUser(username, password); } catch (JSONException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void onRegistrationError(String message) { // todo } @Override public void onRegistrationSuccess() { finish(); } @Override public void onSavedLinksUpdate(ArrayList<Link> savedLinks) {} @Override public View viewFromActivity() { return findViewById(R.id.buttonRegister); } }
ffefa23e89c142f235cf449896c096df2596db24
0922eb3654c26db65a33c44c0af760ff751c556e
/src/cvg/sfmPipeline/main/MatchesOutMessage.java
3197dbd66bdf5e07aa34349bd8b26cf6279d3e0c
[]
no_license
ZhangPeike/Android-SfM-client
c75f9b917ef850bd6b9f134ba3994147d099a4fb
a53e818f2d70215f66b39c2f78b53d27b377546b
refs/heads/master
2021-01-21T07:14:48.314813
2012-08-27T13:12:10
2012-08-27T13:12:10
45,677,637
1
0
null
2015-11-06T11:14:14
2015-11-06T11:14:14
null
UTF-8
Java
false
true
44,814
java
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: matches.proto package cvg.sfmPipeline.main; public final class MatchesOutMessage { private MatchesOutMessage() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface DMatchesOrBuilder extends com.google.protobuf.MessageOrBuilder { // optional uint32 queryIdx = 1; boolean hasQueryIdx(); int getQueryIdx(); // optional uint32 trainIdx = 2; boolean hasTrainIdx(); int getTrainIdx(); // optional uint32 imgIdx = 3; boolean hasImgIdx(); int getImgIdx(); // optional float distance = 4; boolean hasDistance(); float getDistance(); } public static final class DMatches extends com.google.protobuf.GeneratedMessage implements DMatchesOrBuilder { // Use DMatches.newBuilder() to construct. private DMatches(Builder builder) { super(builder); } private DMatches(boolean noInit) {} private static final DMatches defaultInstance; public static DMatches getDefaultInstance() { return defaultInstance; } public DMatches getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_DMatches_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_DMatches_fieldAccessorTable; } private int bitField0_; // optional uint32 queryIdx = 1; public static final int QUERYIDX_FIELD_NUMBER = 1; private int queryIdx_; public boolean hasQueryIdx() { return ((bitField0_ & 0x00000001) == 0x00000001); } public int getQueryIdx() { return queryIdx_; } // optional uint32 trainIdx = 2; public static final int TRAINIDX_FIELD_NUMBER = 2; private int trainIdx_; public boolean hasTrainIdx() { return ((bitField0_ & 0x00000002) == 0x00000002); } public int getTrainIdx() { return trainIdx_; } // optional uint32 imgIdx = 3; public static final int IMGIDX_FIELD_NUMBER = 3; private int imgIdx_; public boolean hasImgIdx() { return ((bitField0_ & 0x00000004) == 0x00000004); } public int getImgIdx() { return imgIdx_; } // optional float distance = 4; public static final int DISTANCE_FIELD_NUMBER = 4; private float distance_; public boolean hasDistance() { return ((bitField0_ & 0x00000008) == 0x00000008); } public float getDistance() { return distance_; } private void initFields() { queryIdx_ = 0; trainIdx_ = 0; imgIdx_ = 0; distance_ = 0F; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt32(1, queryIdx_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeUInt32(2, trainIdx_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeUInt32(3, imgIdx_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeFloat(4, distance_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, queryIdx_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, trainIdx_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(3, imgIdx_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeFloatSize(4, distance_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.DMatches parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(cvg.sfmPipeline.main.MatchesOutMessage.DMatches prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_DMatches_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_DMatches_fieldAccessorTable; } // Construct using cvg.sfmPipeline.main.MatchesOutMessage.DMatches.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); queryIdx_ = 0; bitField0_ = (bitField0_ & ~0x00000001); trainIdx_ = 0; bitField0_ = (bitField0_ & ~0x00000002); imgIdx_ = 0; bitField0_ = (bitField0_ & ~0x00000004); distance_ = 0F; bitField0_ = (bitField0_ & ~0x00000008); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return cvg.sfmPipeline.main.MatchesOutMessage.DMatches.getDescriptor(); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches getDefaultInstanceForType() { return cvg.sfmPipeline.main.MatchesOutMessage.DMatches.getDefaultInstance(); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches build() { cvg.sfmPipeline.main.MatchesOutMessage.DMatches result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private cvg.sfmPipeline.main.MatchesOutMessage.DMatches buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { cvg.sfmPipeline.main.MatchesOutMessage.DMatches result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches buildPartial() { cvg.sfmPipeline.main.MatchesOutMessage.DMatches result = new cvg.sfmPipeline.main.MatchesOutMessage.DMatches(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.queryIdx_ = queryIdx_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.trainIdx_ = trainIdx_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.imgIdx_ = imgIdx_; if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000008; } result.distance_ = distance_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof cvg.sfmPipeline.main.MatchesOutMessage.DMatches) { return mergeFrom((cvg.sfmPipeline.main.MatchesOutMessage.DMatches)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(cvg.sfmPipeline.main.MatchesOutMessage.DMatches other) { if (other == cvg.sfmPipeline.main.MatchesOutMessage.DMatches.getDefaultInstance()) return this; if (other.hasQueryIdx()) { setQueryIdx(other.getQueryIdx()); } if (other.hasTrainIdx()) { setTrainIdx(other.getTrainIdx()); } if (other.hasImgIdx()) { setImgIdx(other.getImgIdx()); } if (other.hasDistance()) { setDistance(other.getDistance()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 8: { bitField0_ |= 0x00000001; queryIdx_ = input.readUInt32(); break; } case 16: { bitField0_ |= 0x00000002; trainIdx_ = input.readUInt32(); break; } case 24: { bitField0_ |= 0x00000004; imgIdx_ = input.readUInt32(); break; } case 37: { bitField0_ |= 0x00000008; distance_ = input.readFloat(); break; } } } } private int bitField0_; // optional uint32 queryIdx = 1; private int queryIdx_ ; public boolean hasQueryIdx() { return ((bitField0_ & 0x00000001) == 0x00000001); } public int getQueryIdx() { return queryIdx_; } public Builder setQueryIdx(int value) { bitField0_ |= 0x00000001; queryIdx_ = value; onChanged(); return this; } public Builder clearQueryIdx() { bitField0_ = (bitField0_ & ~0x00000001); queryIdx_ = 0; onChanged(); return this; } // optional uint32 trainIdx = 2; private int trainIdx_ ; public boolean hasTrainIdx() { return ((bitField0_ & 0x00000002) == 0x00000002); } public int getTrainIdx() { return trainIdx_; } public Builder setTrainIdx(int value) { bitField0_ |= 0x00000002; trainIdx_ = value; onChanged(); return this; } public Builder clearTrainIdx() { bitField0_ = (bitField0_ & ~0x00000002); trainIdx_ = 0; onChanged(); return this; } // optional uint32 imgIdx = 3; private int imgIdx_ ; public boolean hasImgIdx() { return ((bitField0_ & 0x00000004) == 0x00000004); } public int getImgIdx() { return imgIdx_; } public Builder setImgIdx(int value) { bitField0_ |= 0x00000004; imgIdx_ = value; onChanged(); return this; } public Builder clearImgIdx() { bitField0_ = (bitField0_ & ~0x00000004); imgIdx_ = 0; onChanged(); return this; } // optional float distance = 4; private float distance_ ; public boolean hasDistance() { return ((bitField0_ & 0x00000008) == 0x00000008); } public float getDistance() { return distance_; } public Builder setDistance(float value) { bitField0_ |= 0x00000008; distance_ = value; onChanged(); return this; } public Builder clearDistance() { bitField0_ = (bitField0_ & ~0x00000008); distance_ = 0F; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:sfm.DMatches) } static { defaultInstance = new DMatches(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:sfm.DMatches) } public interface MatchesProtoOrBuilder extends com.google.protobuf.MessageOrBuilder { // optional fixed64 imageLseq = 1; boolean hasImageLseq(); long getImageLseq(); // optional fixed64 imageRseq = 2; boolean hasImageRseq(); long getImageRseq(); // repeated .sfm.DMatches matches = 3; java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches> getMatchesList(); cvg.sfmPipeline.main.MatchesOutMessage.DMatches getMatches(int index); int getMatchesCount(); java.util.List<? extends cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder> getMatchesOrBuilderList(); cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder getMatchesOrBuilder( int index); } public static final class MatchesProto extends com.google.protobuf.GeneratedMessage implements MatchesProtoOrBuilder { // Use MatchesProto.newBuilder() to construct. private MatchesProto(Builder builder) { super(builder); } private MatchesProto(boolean noInit) {} private static final MatchesProto defaultInstance; public static MatchesProto getDefaultInstance() { return defaultInstance; } public MatchesProto getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_MatchesProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_MatchesProto_fieldAccessorTable; } private int bitField0_; // optional fixed64 imageLseq = 1; public static final int IMAGELSEQ_FIELD_NUMBER = 1; private long imageLseq_; public boolean hasImageLseq() { return ((bitField0_ & 0x00000001) == 0x00000001); } public long getImageLseq() { return imageLseq_; } // optional fixed64 imageRseq = 2; public static final int IMAGERSEQ_FIELD_NUMBER = 2; private long imageRseq_; public boolean hasImageRseq() { return ((bitField0_ & 0x00000002) == 0x00000002); } public long getImageRseq() { return imageRseq_; } // repeated .sfm.DMatches matches = 3; public static final int MATCHES_FIELD_NUMBER = 3; private java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches> matches_; public java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches> getMatchesList() { return matches_; } public java.util.List<? extends cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder> getMatchesOrBuilderList() { return matches_; } public int getMatchesCount() { return matches_.size(); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches getMatches(int index) { return matches_.get(index); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder getMatchesOrBuilder( int index) { return matches_.get(index); } private void initFields() { imageLseq_ = 0L; imageRseq_ = 0L; matches_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized != -1) return isInitialized == 1; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeFixed64(1, imageLseq_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeFixed64(2, imageRseq_); } for (int i = 0; i < matches_.size(); i++) { output.writeMessage(3, matches_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeFixed64Size(1, imageLseq_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeFixed64Size(2, imageRseq_); } for (int i = 0; i < matches_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, matches_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input)) { return builder.buildParsed(); } else { return null; } } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { Builder builder = newBuilder(); if (builder.mergeDelimitedFrom(input, extensionRegistry)) { return builder.buildParsed(); } else { return null; } } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements cvg.sfmPipeline.main.MatchesOutMessage.MatchesProtoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_MatchesProto_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return cvg.sfmPipeline.main.MatchesOutMessage.internal_static_sfm_MatchesProto_fieldAccessorTable; } // Construct using cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getMatchesFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); imageLseq_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); imageRseq_ = 0L; bitField0_ = (bitField0_ & ~0x00000002); if (matchesBuilder_ == null) { matches_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { matchesBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.getDescriptor(); } public cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto getDefaultInstanceForType() { return cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.getDefaultInstance(); } public cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto build() { cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } private cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException( result).asInvalidProtocolBufferException(); } return result; } public cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto buildPartial() { cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto result = new cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.imageLseq_ = imageLseq_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.imageRseq_ = imageRseq_; if (matchesBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { matches_ = java.util.Collections.unmodifiableList(matches_); bitField0_ = (bitField0_ & ~0x00000004); } result.matches_ = matches_; } else { result.matches_ = matchesBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto) { return mergeFrom((cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto other) { if (other == cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.getDefaultInstance()) return this; if (other.hasImageLseq()) { setImageLseq(other.getImageLseq()); } if (other.hasImageRseq()) { setImageRseq(other.getImageRseq()); } if (matchesBuilder_ == null) { if (!other.matches_.isEmpty()) { if (matches_.isEmpty()) { matches_ = other.matches_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureMatchesIsMutable(); matches_.addAll(other.matches_); } onChanged(); } } else { if (!other.matches_.isEmpty()) { if (matchesBuilder_.isEmpty()) { matchesBuilder_.dispose(); matchesBuilder_ = null; matches_ = other.matches_; bitField0_ = (bitField0_ & ~0x00000004); matchesBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getMatchesFieldBuilder() : null; } else { matchesBuilder_.addAllMessages(other.matches_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( this.getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: this.setUnknownFields(unknownFields.build()); onChanged(); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { this.setUnknownFields(unknownFields.build()); onChanged(); return this; } break; } case 9: { bitField0_ |= 0x00000001; imageLseq_ = input.readFixed64(); break; } case 17: { bitField0_ |= 0x00000002; imageRseq_ = input.readFixed64(); break; } case 26: { cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder subBuilder = cvg.sfmPipeline.main.MatchesOutMessage.DMatches.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addMatches(subBuilder.buildPartial()); break; } } } } private int bitField0_; // optional fixed64 imageLseq = 1; private long imageLseq_ ; public boolean hasImageLseq() { return ((bitField0_ & 0x00000001) == 0x00000001); } public long getImageLseq() { return imageLseq_; } public Builder setImageLseq(long value) { bitField0_ |= 0x00000001; imageLseq_ = value; onChanged(); return this; } public Builder clearImageLseq() { bitField0_ = (bitField0_ & ~0x00000001); imageLseq_ = 0L; onChanged(); return this; } // optional fixed64 imageRseq = 2; private long imageRseq_ ; public boolean hasImageRseq() { return ((bitField0_ & 0x00000002) == 0x00000002); } public long getImageRseq() { return imageRseq_; } public Builder setImageRseq(long value) { bitField0_ |= 0x00000002; imageRseq_ = value; onChanged(); return this; } public Builder clearImageRseq() { bitField0_ = (bitField0_ & ~0x00000002); imageRseq_ = 0L; onChanged(); return this; } // repeated .sfm.DMatches matches = 3; private java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches> matches_ = java.util.Collections.emptyList(); private void ensureMatchesIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { matches_ = new java.util.ArrayList<cvg.sfmPipeline.main.MatchesOutMessage.DMatches>(matches_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilder< cvg.sfmPipeline.main.MatchesOutMessage.DMatches, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder, cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder> matchesBuilder_; public java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches> getMatchesList() { if (matchesBuilder_ == null) { return java.util.Collections.unmodifiableList(matches_); } else { return matchesBuilder_.getMessageList(); } } public int getMatchesCount() { if (matchesBuilder_ == null) { return matches_.size(); } else { return matchesBuilder_.getCount(); } } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches getMatches(int index) { if (matchesBuilder_ == null) { return matches_.get(index); } else { return matchesBuilder_.getMessage(index); } } public Builder setMatches( int index, cvg.sfmPipeline.main.MatchesOutMessage.DMatches value) { if (matchesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMatchesIsMutable(); matches_.set(index, value); onChanged(); } else { matchesBuilder_.setMessage(index, value); } return this; } public Builder setMatches( int index, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder builderForValue) { if (matchesBuilder_ == null) { ensureMatchesIsMutable(); matches_.set(index, builderForValue.build()); onChanged(); } else { matchesBuilder_.setMessage(index, builderForValue.build()); } return this; } public Builder addMatches(cvg.sfmPipeline.main.MatchesOutMessage.DMatches value) { if (matchesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMatchesIsMutable(); matches_.add(value); onChanged(); } else { matchesBuilder_.addMessage(value); } return this; } public Builder addMatches( int index, cvg.sfmPipeline.main.MatchesOutMessage.DMatches value) { if (matchesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMatchesIsMutable(); matches_.add(index, value); onChanged(); } else { matchesBuilder_.addMessage(index, value); } return this; } public Builder addMatches( cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder builderForValue) { if (matchesBuilder_ == null) { ensureMatchesIsMutable(); matches_.add(builderForValue.build()); onChanged(); } else { matchesBuilder_.addMessage(builderForValue.build()); } return this; } public Builder addMatches( int index, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder builderForValue) { if (matchesBuilder_ == null) { ensureMatchesIsMutable(); matches_.add(index, builderForValue.build()); onChanged(); } else { matchesBuilder_.addMessage(index, builderForValue.build()); } return this; } public Builder addAllMatches( java.lang.Iterable<? extends cvg.sfmPipeline.main.MatchesOutMessage.DMatches> values) { if (matchesBuilder_ == null) { ensureMatchesIsMutable(); super.addAll(values, matches_); onChanged(); } else { matchesBuilder_.addAllMessages(values); } return this; } public Builder clearMatches() { if (matchesBuilder_ == null) { matches_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { matchesBuilder_.clear(); } return this; } public Builder removeMatches(int index) { if (matchesBuilder_ == null) { ensureMatchesIsMutable(); matches_.remove(index); onChanged(); } else { matchesBuilder_.remove(index); } return this; } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder getMatchesBuilder( int index) { return getMatchesFieldBuilder().getBuilder(index); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder getMatchesOrBuilder( int index) { if (matchesBuilder_ == null) { return matches_.get(index); } else { return matchesBuilder_.getMessageOrBuilder(index); } } public java.util.List<? extends cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder> getMatchesOrBuilderList() { if (matchesBuilder_ != null) { return matchesBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(matches_); } } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder addMatchesBuilder() { return getMatchesFieldBuilder().addBuilder( cvg.sfmPipeline.main.MatchesOutMessage.DMatches.getDefaultInstance()); } public cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder addMatchesBuilder( int index) { return getMatchesFieldBuilder().addBuilder( index, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.getDefaultInstance()); } public java.util.List<cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder> getMatchesBuilderList() { return getMatchesFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< cvg.sfmPipeline.main.MatchesOutMessage.DMatches, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder, cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder> getMatchesFieldBuilder() { if (matchesBuilder_ == null) { matchesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< cvg.sfmPipeline.main.MatchesOutMessage.DMatches, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder, cvg.sfmPipeline.main.MatchesOutMessage.DMatchesOrBuilder>( matches_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); matches_ = null; } return matchesBuilder_; } // @@protoc_insertion_point(builder_scope:sfm.MatchesProto) } static { defaultInstance = new MatchesProto(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:sfm.MatchesProto) } private static com.google.protobuf.Descriptors.Descriptor internal_static_sfm_DMatches_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_sfm_DMatches_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_sfm_MatchesProto_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_sfm_MatchesProto_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\rmatches.proto\022\003sfm\"P\n\010DMatches\022\020\n\010quer" + "yIdx\030\001 \001(\r\022\020\n\010trainIdx\030\002 \001(\r\022\016\n\006imgIdx\030\003" + " \001(\r\022\020\n\010distance\030\004 \001(\002\"T\n\014MatchesProto\022\021" + "\n\timageLseq\030\001 \001(\006\022\021\n\timageRseq\030\002 \001(\006\022\036\n\007" + "matches\030\003 \003(\0132\r.sfm.DMatchesB)\n\024cvg.sfmP" + "ipeline.mainB\021MatchesOutMessage" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_sfm_DMatches_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_sfm_DMatches_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_sfm_DMatches_descriptor, new java.lang.String[] { "QueryIdx", "TrainIdx", "ImgIdx", "Distance", }, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.class, cvg.sfmPipeline.main.MatchesOutMessage.DMatches.Builder.class); internal_static_sfm_MatchesProto_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_sfm_MatchesProto_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_sfm_MatchesProto_descriptor, new java.lang.String[] { "ImageLseq", "ImageRseq", "Matches", }, cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.class, cvg.sfmPipeline.main.MatchesOutMessage.MatchesProto.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } // @@protoc_insertion_point(outer_class_scope) }
693f67095634c09a06b61d5355a44e4a3817c607
66094a0afebe61ae4e8e95b626ded308e84bf0ea
/app/src/main/java/com/example/poblenou/eltemps/WeatherFragment.java
edc6c1c9f409f160b5f902bdba32ca9514390223
[]
no_license
24547744m/ElTemps
06e51621bd288a3de6c217089eeb8279ab7f2817
042fe1d115d9e8d07f7a437d6f4d55d2f8ad3ad9
refs/heads/master
2021-01-24T20:01:21.913702
2015-10-28T20:39:57
2015-10-28T20:39:57
44,618,123
0
0
null
2015-10-28T19:14:40
2015-10-20T16:04:37
Java
UTF-8
Java
false
false
2,711
java
package com.example.poblenou.eltemps; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; /** * A placeholder fragment containing a simple view. */ public class WeatherFragment extends Fragment { private ArrayList<String> items; private ArrayAdapter<String> adapter; public WeatherFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); String[] data = { "Lun 23/6 - Soleado - 31/17", "Mar 24/6 - Niebla - 21/8", "Mier 25/6 - Nublado - 22/17", "Jue 26/6 - Lluvioso - 18/11", "Vie 27/6 - Niebla - 21/10", "Sab 28/6 - Soleado - 23/18", "Dom 29/6 - Soleado - 20/7" }; items = new ArrayList<>(Arrays.asList(data)); adapter = new ArrayAdapter<>( getContext(), R.layout.listview_forecasts_row, R.id.tvForecast, items ); ListView lvForecast = (ListView) rootView.findViewById(R.id.lvForecasts); lvForecast.setAdapter(adapter); return rootView; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_weather_fragment, menu); } @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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } if (id == R.id.action_refresh) { refresh(); return true; } return super.onOptionsItemSelected(item); } private void refresh() { OwmApiClient apiClient = new OwmApiClient(); apiClient.updateForecasts(adapter); } }
dfefbe81e065f7bcc155ef1b01888aa5501059c0
b92333aa8e1d3ead598c3e6e35da6ef31399d5d9
/app/src/main/java/com/example/pc/attendance/helpers/data/MultipartUtility.java
3fba17c2f7eecef973532e02d561cb7656925815
[]
no_license
lucquyenw/DiemDanh
c26ba3ff686bbe523fd46def0cdbc867105264b0
633c2d4bce61088763e76508695d46fd36791c49
refs/heads/master
2020-03-26T03:43:23.249489
2018-08-12T13:15:47
2018-08-12T13:15:47
144,468,145
0
0
null
null
null
null
UTF-8
Java
false
false
4,364
java
package com.example.pc.attendance.helpers.data; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; /** * Created by azaudio on 7/11/2018. */ public class MultipartUtility { private HttpURLConnection httpConn; private DataOutputStream request; private final String boundary = "*****"; private final String crlf = "\r\n"; private final String twoHyphens = "--"; /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @throws IOException */ public MultipartUtility(String requestURL) throws IOException { // creates a unique boundary based on time stamp URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty( "Content-Type", "multipart/form-data;boundary=" + this.boundary); request = new DataOutputStream(httpConn.getOutputStream()); } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value)throws IOException { request.writeBytes(this.twoHyphens + this.boundary + this.crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf); request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf); request.writeBytes(this.crlf); request.writeBytes(value+ this.crlf); request.flush(); } /** * Adds a upload file section to the request * * @param fieldName name attribute in <input type="file" name="..." /> * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); request.writeBytes(this.twoHyphens + this.boundary + this.crlf); request.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + fileName + "\"" + this.crlf); request.writeBytes(this.crlf); byte[] bytes = Files.readAllBytes(uploadFile.toPath()); request.write(bytes); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public String finish() throws IOException { String response =""; request.writeBytes(this.crlf); request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf); request.flush(); request.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_CREATED) { InputStream responseStream = new BufferedInputStream(httpConn.getInputStream()); BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); String line = ""; StringBuilder stringBuilder = new StringBuilder(); while ((line = responseStreamReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } responseStreamReader.close(); response = stringBuilder.toString(); Log.d("Mujltipart",response); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response; } }
069f3030157632652c6e89da51330a029cc569b0
b2bd1d6ac6c18e3bd92331b8072e25b33599c638
/src/Display.java
d481abd578a2cf087c26d37eb578d1e470e4141b
[]
no_license
sacooper/Lab5-Orienteering
13fb22b7c0e209fe0110f6776cf856e6b0353258
da8f03c93966b1f6c3c9a5358a82ed73fe2b0ecb
refs/heads/master
2016-09-06T16:31:31.258681
2014-10-15T15:28:49
2014-10-15T15:28:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,163
java
/* * OdometryDisplay.java * * Controls what is displayed on the NXT screen */ import lejos.nxt.LCD; public class Display { /**** * Print the current values of x, y, and theta to the screen. * * Modified to be called from the Odometry class, to allow for more control * @param <Position> * * @param x The current x value of the odometer in cm * @param y The current y value of the domoeter in cm * @param theta The current value of theta (amount the robot has rotated) in radians */ public static void printDemoInfo(final double x, final double y, final double theta, final int observations, final Position start){ new Thread(new Runnable(){ public void run(){ String sx = formattedDoubleToString((((double)start.getX()) - 0.5)*Odometer.TILE_SIZE, 2); String sy = formattedDoubleToString((((double)start.getY()) - 0.5)*Odometer.TILE_SIZE, 2); LCD.clear(); // clear the lines for displaying odometry information LCD.drawString("X: ", 0, 0); LCD.drawString("Y: ", 0, 1); LCD.drawString("T: ", 0, 2); LCD.drawString("Observations: " + observations, 0, 3); LCD.drawString("Start: ", 0, 4); LCD.drawString("(" + sx + ", " + sy + ")", 0, 5); LCD.drawString(start.getDir().asCardinal(), 0, 6); LCD.drawString(formattedDoubleToString(x, 2), 3, 0); LCD.drawString(formattedDoubleToString(y, 2), 3, 1); LCD.drawString(formattedDoubleToString(theta, 2), 3, 2);}}).start();} public static void printLocalizationInfo(int x, int y, Direction current, boolean blocked, int size){ new Thread(new Runnable(){ public void run(){ LCD.clear(); LCD.drawString(blocked + "" , 0, 0); LCD.drawString("# possible: " + size, 0, 1); LCD.drawString("Relative Location:", 0, 2); LCD.drawString(x + ", " + y + ", " + current.toString(), 0, 3); }}).start();} private static String formattedDoubleToString(double x, int places) { String result = ""; String stack = ""; long t; // put in a minus sign as needed if (x < 0.0) result += "-"; // put in a leading 0 if (-1.0 < x && x < 1.0) result += "0"; else { t = (long)x; if (t < 0) t = -t; while (t > 0) { stack = Long.toString(t % 10) + stack; t /= 10; } result += stack; } // put the decimal, if needed if (places > 0) { result += "."; // put the appropriate number of decimals for (int i = 0; i < places; i++) { x = Math.abs(x); x = x - Math.floor(x); x *= 10.0; result += Long.toString((long)x); } } return result; } /****** * Print the main menu */ public static void printMainMenu() { // clear the display LCD.clear(); // ask the user whether the motors should Avoid Block or Go to locations LCD.drawString("< Left | Right >", 0, 0); LCD.drawString(" | ", 0, 1); LCD.drawString(" STOCH | DET. ", 0, 2); LCD.drawString("----------------", 0, 3); LCD.drawString(" DEMO=ENTER ", 0, 4); LCD.drawString(" vvvvvv ", 0, 5); } }
b7ae83664e6c22c6c5ff389ad60843e9d8feb076
42fcf1d879cb75f08225137de5095adfdd63fa21
/src/main/java/org/jooq/routines/GetEqualSetSkuidNrforFsc.java
59dcc89f441b19b1b9879b017d73428e47dc21f8
[]
no_license
mpsgit/JOOQTest
e10e9c8716f2688c8bf0160407b1244f9e70e8eb
6af2922bddc55f591e94a5a9a6efd1627747d6ad
refs/heads/master
2021-01-10T06:11:40.862153
2016-02-28T09:09:34
2016-02-28T09:09:34
52,711,455
0
0
null
null
null
null
UTF-8
Java
false
false
2,259
java
/** * This class is generated by jOOQ */ package org.jooq.routines; import java.math.BigDecimal; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Parameter; import org.jooq.Wetrn; import org.jooq.impl.AbstractRoutine; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class GetEqualSetSkuidNrforFsc extends AbstractRoutine<BigDecimal> { private static final long serialVersionUID = -816648109; /** * The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.RETURN_VALUE</code>. */ public static final Parameter<BigDecimal> RETURN_VALUE = createParameter("RETURN_VALUE", org.jooq.impl.SQLDataType.NUMERIC, false); /** * The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.T_SET_ID</code>. */ public static final Parameter<BigDecimal> T_SET_ID = createParameter("T_SET_ID", org.jooq.impl.SQLDataType.NUMERIC, false); /** * The parameter <code>WETRN.GET_EQUAL_SET_SKUID_NRFOR_FSC.S_SET_ID</code>. */ public static final Parameter<BigDecimal> S_SET_ID = createParameter("S_SET_ID", org.jooq.impl.SQLDataType.NUMERIC, false); /** * Create a new routine call instance */ public GetEqualSetSkuidNrforFsc() { super("GET_EQUAL_SET_SKUID_NRFOR_FSC", Wetrn.WETRN, org.jooq.impl.SQLDataType.NUMERIC); setReturnParameter(RETURN_VALUE); addInParameter(T_SET_ID); addInParameter(S_SET_ID); } /** * Set the <code>T_SET_ID</code> parameter IN value to the routine */ public void setTSetId(Number value) { setNumber(T_SET_ID, value); } /** * Set the <code>T_SET_ID</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setTSetId(Field<? extends Number> field) { setNumber(T_SET_ID, field); } /** * Set the <code>S_SET_ID</code> parameter IN value to the routine */ public void setSSetId(Number value) { setNumber(S_SET_ID, value); } /** * Set the <code>S_SET_ID</code> parameter to the function to be used with a {@link org.jooq.Select} statement */ public void setSSetId(Field<? extends Number> field) { setNumber(S_SET_ID, field); } }
1418c045d8f264ff68a33d2be74d903527d0e75e
2a517d24718f83e6a38c0665d833f25bcc6915f7
/src/com/fa2id/app/user/UserInteractionFactory.java
aad5b854d48bce594b68d0e26395dd4ef1adfc07
[]
no_license
fa2id/currency-converter
32e48782f9375b0c7cda1e6155fc61df385e758c
58ec102f7e42f88069a8caa7d8eaf322bf9cf516
refs/heads/master
2020-04-21T00:33:06.578708
2019-02-05T14:10:40
2019-02-05T14:10:40
169,199,936
0
0
null
null
null
null
UTF-8
Java
false
false
391
java
package com.fa2id.app.user; /** * This is the factory class for UserInteraction. * * @author Farid Ariafard * www.fa2id.com */ public class UserInteractionFactory { /** * This method creates UserInteraction object. * * @return UserInteraction object. */ public static UserInteraction create() { return new UserInteractionImplementation(); } }
af6b407aa8a01dfdf96d625f9b4ec4e6abf326e2
9969d049569acd730274361dda41311cbf41e614
/Facebook.java
bd66a1b9314d65d53d3f9e08a284a8b461c5330a
[]
no_license
Akaenki/LeetCode
e66c480d5887c28ec430c02dc9875835e2b6d0ea
ade02cfad43b15ea18e89dc2fe6299260e47ec74
refs/heads/master
2021-04-15T03:44:55.643109
2018-10-24T19:09:03
2018-10-24T19:09:03
126,733,626
0
0
null
null
null
null
UTF-8
Java
false
false
9,018
java
import javafx.util.Pair; import java.util.*; public class Facebook { /* 1 2 3 4 5 6 7 8 k = 7 i j 2^(j-i-1) */ public int numSubset(int[] arr, int k){ int end = arr.length-1, sum = 0; for(int i = 0; i<arr.length; ++i){ while(end >= 0 && arr[end] > k-arr[i]) end--; if(end < i) break; if(arr[i] + arr[end] != k){ k++; continue; } if(end == i) sum += 1; else sum += Math.pow(2, end-i-1); //sum += 1 << end-i-1; } return sum; } /** max + min <= k **/ public int numSubset2(int[] arr, int k){ int end = arr.length-1, sum = 0; for(int i = 0; i<arr.length; ++i){ while(end >= 0 && arr[end] > k-arr[i]) end--; if(end < i) break; else sum += Math.pow(2, end-i); } return sum; } /* Special Case: Merge 3 Lists/Arrays */ public List<Integer> mergeLists(List<Integer> a, List<Integer> b, List<Integer> c){ int pa = 0, pb = 0, pc = 0; List<Integer> res = new ArrayList<>(); while(pa<a.size()||pb<b.size()||pc<c.size()){ int aa = pa < a.size() ? a.get(pa) : Integer.MAX_VALUE, bb = pb < b.size() ? b.get(pb) : Integer.MAX_VALUE, cc = pc < c.size() ? c.get(pc) : Integer.MAX_VALUE; if(aa <= bb && aa <= cc){ res.add(aa); pa++; } else if(bb <= aa && bb <= cc){ res.add(bb); pb++; } else{ res.add(cc); pc++; } } return res; } private int parseTime(String str) { int start = 0; for (int i = str.length() - 1; i >= 0; --i) { if (str.charAt(i) == 'p') { start = 12 * 100; break; } } String[] time = str.split(":"); int hr = 0; for (char c : time[0].toCharArray()) { if (!Character.isDigit(c)) break; hr = hr * 10 + Character.getNumericValue(c); } hr = hr % 12; int min = 0; if(time.length > 1) { for (char c : time[1].toCharArray()) { if (!Character.isDigit(c)) break; min = min * 10 + Character.getNumericValue(c); } } return hr*100 + min + start; } public int[] longestSub(int[] arr){ int max = 0, end = 1, cur = 1; for(int i = 1; i<arr.length; ++i){ if(arr[i] > arr[i-1]) cur++; else cur = 1; if(cur > max){ max = cur; end = i; } } int[] res = new int[max]; for(int i = 0; i< max; ++i) res[i] = arr[end-max+1+i]; return res; } public String validPar(String s){ int open = 0, close = 0; HashSet<Integer> delete = new HashSet<>(); for(int i = 0; i<s.length(); ++i) { if (s.charAt(i) == '(') open++; else if (s.charAt(i) == ')') { if (open > 0) open--; else delete.add(i); } } for(int i = s.length()-1; i>=0; --i){ if(s.charAt(i) == ')') close++; else if(s.charAt(i) == '('){ if(close > 0) close--; else delete.add(i); } } StringBuilder sb = new StringBuilder(); for(int i = 0; i<s.length(); ++i){ if(delete.contains(i)) continue; sb.append(s.charAt(i)); } return sb.toString(); } public boolean compareStr(String a, String b){ int pa = a.length()-1, pb = b.length()-1, count = 1; while(pa >= 0 && pb >=0){ if(Character.isDigit(b.charAt(pb))){ count = Character.getNumericValue(b.charAt(pb)); pb--; continue; } else if(count ==0) { count = 1; pb--; continue; } else if(a.charAt(pa) != b.charAt(pb)) return false; else{ pa--; count--; } } return pa <=0 && pb<=0 && count==0; } public static void main(String[] args) { Facebook o = new Facebook(); //List<Integer> a = Arrays.asList(1,4,7,10,13), b = Arrays.asList(1,4,7,10,13), c = Arrays.asList(3,6,9,12,100); //List<Integer> res = o.mergeLists(a,b,c); System.out.println(o.validPar("(a)((b)c)))")); } public static List<String> sort(List<String> input){ HashMap<String, Integer> months = new HashMap<>(); months.put("Jan", 1); months.put("Feb", 2); months.put("Mar", 3); months.put("Apr", 4); months.put("May", 5); months.put("Jun", 6); months.put("Jul", 7); months.put("Aug", 8); months.put("Sep", 9); months.put("Oct", 10); months.put("Nov", 11); months.put("Dec", 12); Collections.sort(input, new Comparator<String>() { @Override public int compare(String o1, String o2) { return 0; } }); } public boolean isNumber(String s){ boolean isDot = false; for(int i = 0; i<s.length(); ++i){ char c = s.charAt(i); if(i == 0 ){ if(c == '0' && s.charAt(i+1) != '.') return false; if(c != '-' && !Character.isDigit(c)) return false; } else if(i == s.length()-1){ if(c == '0' || c == '.' || !Character.isDigit(c)) return false; }else{ if(c == '0' && !Character.isDigit(s.charAt(i-1)) && s.charAt(i+1) != '.') return false; if(Character.isDigit(c)) continue; if(c == '.'){ if(isDot) return false; else isDot = true; }else return false; } } return true; } public List<List<int[]>> allPaths(int[][] grid, int[] start, int[] end){ List<List<int[]>> paths = new ArrayList<>(); List<int[]> path = new ArrayList<>(); path.add(start); backtrack(grid, start, end, paths, path, new boolean[grid.length][grid[0].length]); return paths; } private void backtrack(int[][] grid, int[] loc, int[] end, List<List<int[]>> all, List<int[]> cur, boolean[][] isVisited){ if(loc[0] == end[0] && loc[1] == end[1]){ all.add(new ArrayList<>(cur)); return; } int x = loc[0], y = loc[1]; List<int[]> nbs = nbs(grid, loc); for(int[] nb : nbs) { int i = nb[0], j = nb[1]; if (!isVisited[i][j]) { cur.add(nb); isVisited[i][j] = true; backtrack(grid, nb, end, all, cur, isVisited); cur.remove(cur.size() - 1); isVisited[i][j] = false; } } } int[][] dirs = {{0,1}, {0,-1},{1,0},{-1,0}}; private List<int[]> nbs(int[][] grid, int[] loc){ int x = loc[0], y = loc[1]; List<int[]> nbs = new ArrayList<>(); for(int[] dir : dirs){ int i = x + dir[0], j = y + dir[1]; if(i < 0 || i>=grid.length|| j<0 || j>=grid[0].length || grid[i][j] != 0) continue; nbs.add(new int[]{i, j}); } return nbs; } public List<String> shortest(int[][] grid, int[] start, int[] end){ int m = grid.length, n = grid[0].length; int[][] steps = new int[m][n]; for(int i = 0; i<m; ++i) for(int j = 0; j<n; ++j) steps[i][j] = Integer.MAX_VALUE; HashMap<String, String> map = new HashMap<>(); steps[start[0]][start[1]] = 0; Queue<int[]> q = new LinkedList<>(); q.offer(start); while(!q.isEmpty()){ int[] cur = q.poll(); int step = steps[cur[0]][cur[1]] + 1; List<int[]> nbs = nbs(grid, cur); for(int[] nb : nbs){ if(steps[nb[0]][nb[1]] > step){ map.put(nb[0]+","+nb[1], cur[0]+","+cur[1]); q.offer(nb); steps[nb[0]][nb[1]] = step; } } } LinkedList<String> res = new LinkedList<>(); String e = end[0]+","+end[1]; while(map.containsKey(e)){ res.addFirst(e); e = map.get(e); } return res; } /*public static void main(String[] args) { Facebook o = new Facebook(); int[][] vector = {{0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 1}, {1, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 1, 0, 0, 0, 0} }; //List<List<int[]>> res = o.allPaths(vector, new int[]{0, 0}, new int[]{1, 5}); List<String> res = o.shortest(vector, new int[]{0, 0}, new int[]{4, 5}); for(String r : res){ System.out.println(r); } }*/ }
39a9189afde3e3d9f23dc6ae90994144d8758acb
c42531b0f0e976dd2b11528504e349d5501249ae
/Hartsbourne/MHSystems/app/src/main/java/com/mh/systems/hartsbourne/web/models/clubnews/ClubNewsItems.java
c18361b960687d8b567974bee056df55446353a4
[ "MIT" ]
permissive
Karan-nassa/MHSystems
4267cc6939de7a0ff5577c22b88081595446e09e
a0e20f40864137fff91784687eaf68e5ec3f842c
refs/heads/master
2021-08-20T05:59:06.864788
2017-11-28T08:02:39
2017-11-28T08:02:39
112,189,266
0
0
null
null
null
null
UTF-8
Java
false
false
1,315
java
package com.mh.systems.hartsbourne.web.models.clubnews; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class ClubNewsItems { @SerializedName("Message") @Expose private String Message; @SerializedName("Result") @Expose private Integer Result; @SerializedName("Data") @Expose private List<ClubNewsData> Data = new ArrayList<ClubNewsData>(); /** * * @return * The Message */ public String getMessage() { return Message; } /** * * @param Message * The Message */ public void setMessage(String Message) { this.Message = Message; } /** * * @return * The Result */ public Integer getResult() { return Result; } /** * * @param Result * The Result */ public void setResult(Integer Result) { this.Result = Result; } /** * * @return * The Data */ public List<ClubNewsData> getData() { return Data; } /** * * @param Data * The Data */ public void setData(List<ClubNewsData> Data) { this.Data = Data; } }
1fd2788e8d6752c21d9218d41812b2c2b81f580b
5f4ace6d5994a707549f422d4665b5f364d2abc1
/hunter-portals/src/main/java/com/gt/hunter/portals/domain/Job.java
cd34aa8626fab223e5087dc0516cac7bab4355f2
[]
no_license
tangguoqiang/hunter
e9b85f9dfffab4ba5da58be1f648f1c347bd0dd9
6a2eba8cfe0cd0b478a748faddaece7c695fd189
refs/heads/master
2021-01-20T21:06:21.474239
2016-06-03T15:33:01
2016-06-03T15:33:01
60,358,391
0
0
null
null
null
null
UTF-8
Java
false
false
2,105
java
package com.gt.hunter.portals.domain; import java.io.Serializable; import com.gt.hunter.portals.common.annotation.Column; public class Job implements Serializable{ /** * */ private static final long serialVersionUID = -8070311796680471665L; @Column private String id; @Column private String companyId; @Column private String department; @Column private String post; @Column private String salary; @Column private String degree; @Column private String nature; @Column private String place; @Column private String experience; @Column private String publishTime; @Column private String status; private String company; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCompanyId() { return companyId; } public void setCompanyId(String companyId) { this.companyId = companyId; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getDegree() { return degree; } public void setDegree(String degree) { this.degree = degree; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getNature() { return nature; } public void setNature(String nature) { this.nature = nature; } public String getPlace() { return place; } public void setPlace(String place) { this.place = place; } public String getExperience() { return experience; } public void setExperience(String experience) { this.experience = experience; } public String getPublishTime() { return publishTime; } public void setPublishTime(String publishTime) { this.publishTime = publishTime; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } }
cf9f8aa8bbe0594d3b20d909e3481ec45c3426ec
f3ace548bf9fd40e8e69f55e084c8d13ad467c1c
/excuterWrong/SimpleTree/AORB_12/SimpleTree.java
23bce5db66139d32d7dbcf31478ef178b5cde50d
[]
no_license
phantomDai/concurrentProgramTesting
307d008f3bba8cdcaf8289bdc10ddf5cabdb8a04
8ac37f73c0413adfb1ea72cb6a8f7201c55c88ac
refs/heads/master
2021-05-06T21:18:13.238925
2017-12-06T11:10:01
2017-12-06T11:10:02
111,872,421
0
0
null
null
null
null
UTF-8
Java
false
false
2,051
java
// This is a mutant program. // Author : ysma package mutants.SimpleTree.AORB_12; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class SimpleTree<T> implements PQueue<T> { int range; java.util.List<TreeNode> leaves; SimpleTree.TreeNode root; public SimpleTree( int logRange ) { range = 1 << logRange; leaves = new java.util.ArrayList<TreeNode>( range ); root = buildTree( logRange, 0 ); } SimpleTree.TreeNode buildTree( int height, int slot ) { SimpleTree.TreeNode root = new SimpleTree.TreeNode(); root.counter = new java.util.concurrent.atomic.AtomicInteger( 0 ); if (height == 0) { root.bin = new Bin<T>(); leaves.add( slot, root ); } else { root.left = buildTree( height - 1, 2 * slot ); root.right = buildTree( height + 1, 2 * slot + 1 ); root.left.parent = root.right.parent = root; } return root; } public void add( T item, int priority ) { SimpleTree.TreeNode node = leaves.get( priority ); node.bin.put( item ); while (node != root) { SimpleTree.TreeNode parent = node.parent; if (node == parent.left) { parent.counter.getAndIncrement(); } node = parent; } } public T removeMin() { SimpleTree.TreeNode node = root; while (!node.isLeaf()) { if (node.counter.getAndDecrement() > 0) { node = node.left; } else { node = node.right; } } return (T) node.bin.get(); } public class TreeNode { java.util.concurrent.atomic.AtomicInteger counter; SimpleTree.TreeNode parent; SimpleTree.TreeNode right; SimpleTree.TreeNode left; Bin<T> bin; public boolean isLeaf() { return right == null; } } }
b4d533d21e9b3c96d7dd3a4841eaf5b55992dc78
713a06e5213457211875a91f6b488d8d2e49b923
/src/main/java/com/authservice/config/AuthorizationServerConfiguration.java
66735f63ff210b1dae2e538d9df3eca2eb4702cd
[]
no_license
Lindsay-Austin/is-server-auth
a7e27124ae7212cffd9e371fd1d7466070e14cb1
303515c1cb48d1518cfd5b4536b441f0e9da25eb
refs/heads/master
2022-12-11T00:02:58.861459
2020-09-06T09:07:13
2020-09-06T09:07:13
287,937,950
0
0
null
null
null
null
UTF-8
Java
false
false
5,335
java
package com.authservice.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import javax.sql.DataSource; /** * 认证授权服务端 * * @author leftso * */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Value("${resource.id:spring-boot-application}") // 默认值spring-boot-application private String resourceId; @Value("${access_token.validity_period:3600}") // 默认值3600 int accessTokenValiditySeconds = 3600; @Autowired private AuthenticationManager authenticationManager; @Autowired private PasswordEncoder passwordEncoder; @Autowired private DataSource datasource; @Bean public TokenStore tokenStore(){ return new JdbcTokenStore(datasource); }; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints .tokenStore(tokenStore()) .authenticationManager(this.authenticationManager); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { /*oauthServer.tokenKeyAccess("isAnonymous() || hasAuthority('ROLE_TRUSTED_CLIENT')"); oauthServer.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");*/ oauthServer.checkTokenAccess("isAuthenticated()"); } public static void main(String[] args){ System.out.println(new BCryptPasswordEncoder().encode("123456")); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { /*clients.inMemory().withClient("normal-app") .authorizedGrantTypes("authorization_code", "implicit") .authorities("ROLE_CLIENT") .scopes("read", "write") .resourceIds("order-server") .accessTokenValiditySeconds(accessTokenValiditySeconds) .and() .withClient("trusted-app") .authorizedGrantTypes("client_credentials", "password") .authorities("ROLE_TRUSTED_CLIENT") .scopes("read", "write") .resourceIds("order-server") .accessTokenValiditySeconds(accessTokenValiditySeconds) .secret(passwordEncoder.encode("123456"));*/ clients.jdbc(datasource); } /** * token converter * * @return */ // @Bean // public JwtAccessTokenConverter accessTokenConverter() { // JwtAccessTokenConverter accessTokenConverter = new JwtAccessTokenConverter() { // /*** // * 重写增强token方法,用于自定义一些token返回的信息 // */ // @Override // public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { // String userName = authentication.getUserAuthentication().getName(); // User user = (User) authentication.getUserAuthentication().getPrincipal();// 与登录时候放进去的UserDetail实现类一直查看link{SecurityConfiguration} // /** 自定义一些token属性 ***/ // final Map<String, Object> additionalInformation = new HashMap<>(); // additionalInformation.put("userName", userName); // additionalInformation.put("roles", user.getAuthorities()); // ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation); // OAuth2AccessToken enhancedToken = super.enhance(accessToken, authentication); // return enhancedToken; // } // // }; // accessTokenConverter.setSigningKey("123");// 测试用,资源服务使用相同的字符达到一个对称加密的效果,生产时候使用RSA非对称加密方式 // return accessTokenConverter; // } /** * token store * * @param accessTokenConverter * @return */ // @Bean // public TokenStore tokenStore() { // TokenStore tokenStore = new JwtTokenStore(accessTokenConverter()); // return tokenStore; // } }
b1f8a3672647c04228e20b93f4c7bab4c2819ce6
71db976ba832ca057166eb1738e467a1bc3df3e6
/conicplot/src/main/java/org/newtonmaps/conicplot/ConicMatrix.java
f1858609f70d48d98a2db1f7863139abacf561c5
[]
no_license
hronir/newtonmaps
dcde437e22aa21f603d5f57ae1e4616e1097dadb
b8e5f5ed3d51fed6bb16a74a15637480b6f49494
refs/heads/master
2016-09-10T18:04:21.813874
2014-05-09T16:41:38
2014-05-09T16:41:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,842
java
package org.newtonmaps.conicplot; public class ConicMatrix { public static final int DIMENSION = 3; private double[][] coefficients; public ConicMatrix() { this.coefficients = new double[DIMENSION][]; for (int i = 0; i < DIMENSION; i++) { this.coefficients[i] = new double[i + 1]; } } public ConicMatrix setValues(double... values) { int k = 0; for (int i = 0; i < DIMENSION; i++) { for (int j = 0; j <= i; j++) { this.coefficients[i][j] = values[k]; k++; } } return this; } public ConicMatrix copyTo(ConicMatrix result) { for (int i = 0; i < DIMENSION; i++) { for (int j = 0; j <= i; j++) { result.coefficients[i][j] = this.coefficients[i][j]; } } return result; } public double evaluate(double... p) { double v = 0; for (int i = 0; i < DIMENSION; i++) { v += this.coefficients[i][i] * p[i] * p[i]; for (int j = 0; j < i; j++) { v += 2D * this.coefficients[i][j] * p[i] * p[j]; } } return v; } public double evaluateGradient(int i, double... p) { double v = 0; for (int j = 0; j < DIMENSION; j++) { v += 2D * getCoefficient(i, j) * p[j]; } return v; } public double getCoefficient(int i, int j) { return i < j ? this.coefficients[j][i] : this.coefficients[i][j]; } public ConicMatrix slopeConic(int a, int b, ConicMatrix result) { for (int i = 0; i < DIMENSION; i++) { for (int j = 0; j <= i; j++) { result.coefficients[i][j] = -getCoefficient(i, a) * getCoefficient(j, a) + getCoefficient(i, b) * getCoefficient(j, b); } } return result; } // public int evaluateSlopeSign(int a, double... p) { // double d = 0; // for (int k = 0; k < DIMENSION; k++) { // d += getCoefficient(a, k) * p[k]; // } // return d < 0D ? -1 : d > 0D ? 1 : 0; // } public ConicMatrix swapVariable(int a, int b, ConicMatrix result) { for (int i = 0; i < DIMENSION; i++) { int i1 = swap(a, b, i); for (int j = 0; j <= i; j++) { int j1 = swap(a, b, j); result.coefficients[i][j] = getCoefficient(i1, j1); } } return result; } public ConicMatrix variableSymetry(int a, ConicMatrix result) { for (int i = 0; i < DIMENSION; i++) { for (int j = 0; j <= i; j++) { result.coefficients[i][j] = this.coefficients[i][j]; } } for (int i = 0; i < a; i++) { result.coefficients[a][i] = -result.coefficients[a][i]; } for (int i = a + 1; i < DIMENSION; i++) { result.coefficients[i][a] = -result.coefficients[i][a]; } return result; } private static int swap(int a, int b, int i) { return i == a ? b : i == b ? a : i; } public int evaluateSlopeSign(double... p) { double x = 0; double y = 0; for (int i = 0; i < DIMENSION; i++) { x += getCoefficient(0, i) * p[i]; y += getCoefficient(1, i) * p[i]; } double k = x * y; return k > 0 ? 1 : k < 0 ? -1 : 0; } }
b9842984d49ac823ce8243f4fb4c35cfc78645df
73416f4cbacafa2f987ceef077752a669b75fa0a
/src/test/java/cn/leancloud/kafka/consumer/integration/RevokePausedPartitionTest.java
bc0f9ec2619a16ad5caffc9ae0661e777a192209
[ "MIT" ]
permissive
leancloud/kafka-java-consumer
12c07f9070bcef30a5f4678a9410122ad92f9c50
f22719995c57eb66a411b98b1ed71e2dbad940f9
refs/heads/master
2022-02-07T07:22:08.322156
2022-01-05T01:09:41
2022-01-05T01:09:41
230,073,616
4
0
MIT
2022-01-05T01:10:22
2019-12-25T08:55:11
Java
UTF-8
Java
false
false
7,471
java
package cn.leancloud.kafka.consumer.integration; import org.apache.kafka.clients.consumer.*; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.errors.WakeupException; import org.apache.kafka.common.serialization.IntegerDeserializer; import org.apache.kafka.common.serialization.IntegerSerializer; import org.apache.kafka.common.serialization.StringDeserializer; import org.apache.kafka.common.serialization.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Closeable; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; public class RevokePausedPartitionTest { private static final Logger logger = LoggerFactory.getLogger(RevokePausedPartitionTest.class); private static final String topic = "Testing"; private Map<String, Object> configs; private Consumer<Integer, String> pausePartitionConsumer; private Consumer<Integer, String> normalConsumer; public RevokePausedPartitionTest() { configs = new HashMap<>(); configs.put("bootstrap.servers", "localhost:9092"); configs.put("auto.offset.reset", "earliest"); configs.put("group.id", "2614911922612339122"); configs.put("max.poll.records", 100); configs.put("max.poll.interval.ms", "5000"); configs.put("key.deserializer", IntegerDeserializer.class.getName()); configs.put("value.deserializer", StringDeserializer.class.getName()); } void run() throws Exception { final Map<String, Object> producerConfigs = new HashMap<>(); producerConfigs.put("bootstrap.servers", "localhost:9092"); KafkaProducer<Integer, String> producer = new KafkaProducer<>(configs, new IntegerSerializer(), new StringSerializer()); for (int i = 0; i < 100; i++) { final ProducerRecord<Integer, String> record = new ProducerRecord<>(topic, null, "" + i); producer.send(record, (metadata, exception) -> { if (exception != null) { logger.error("Produce record failed", exception); } }); } CompletableFuture<Void> rebalanceTrigger = new CompletableFuture<>(); pausePartitionConsumer = new KafkaConsumer<>(configs); pausePartitionConsumer.subscribe(Collections.singletonList(topic), new RebalanceListener("paused consumer")); new Thread(new PausePartitionConsumerJob( pausePartitionConsumer, rebalanceTrigger)) .start(); rebalanceTrigger.whenComplete((r, t) -> { normalConsumer = new KafkaConsumer<>(configs); normalConsumer.subscribe(Collections.singletonList(topic), new RebalanceListener("normal consumer")); new Thread(new NormalConsumerJob( normalConsumer)) .start(); for (int i = 100; i < 200; i++) { final ProducerRecord<Integer, String> record = new ProducerRecord<>(topic, null, "" + i); producer.send(record, (metadata, exception) -> { if (exception != null) { logger.error("Produce record failed", exception); } }); } }); } private static class PausePartitionConsumerJob implements Runnable, Closeable { private Consumer<Integer, String> pausePartitionConsumer; private CompletableFuture<Void> rebalanceTrigger; private volatile boolean closed; public PausePartitionConsumerJob(Consumer<Integer, String> consumer, CompletableFuture<Void> rebalanceTrigger) { this.pausePartitionConsumer = consumer; this.rebalanceTrigger = rebalanceTrigger; } @Override public void run() { while (true) { try { ConsumerRecords<Integer, String> records = pausePartitionConsumer.poll(100); if (!records.isEmpty()) { if (!rebalanceTrigger.isDone()) { pausePartitionConsumer.pause(records.partitions()); handleRecords(records); rebalanceTrigger.complete(null); } else { handleRecords(records); } } } catch (WakeupException ex) { if (closed) { break; } } catch (Exception ex) { logger.error("Paused consumer got unexpected exception", ex); } } } @Override public void close() throws IOException { closed = true; pausePartitionConsumer.wakeup(); } private void handleRecords(ConsumerRecords<Integer, String> records) { for (ConsumerRecord<Integer, String> record : records) { logger.info("receive msgs on pause partition consumer " + record); } } } private static class NormalConsumerJob implements Runnable, Closeable { private Consumer<Integer, String> consumer; private volatile boolean closed; public NormalConsumerJob(Consumer<Integer, String> consumer) { this.consumer = consumer; } @Override public void run() { while (true) { try { ConsumerRecords<Integer, String> records = consumer.poll(100); if (!records.isEmpty()) { handleRecords(records); } } catch (WakeupException ex) { if (closed) { break; } } catch (Exception ex) { logger.error("Normal consumer got unexpected exception", ex); } } } @Override public void close() throws IOException { closed = true; consumer.wakeup(); } private void handleRecords(ConsumerRecords<Integer, String> records) { for (ConsumerRecord<Integer, String> record : records) { logger.info("receive msgs on normal consumer " + record); } } } private static class RebalanceListener implements ConsumerRebalanceListener { private String consumerName; public RebalanceListener(String consumerName) { this.consumerName = consumerName; } @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { logger.info("Partitions " + partitions + " revoked from consumer: " + consumerName); } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { logger.info("Partitions " + partitions + " assigned to consumer: " + consumerName); } } public static void main(String[] args) throws Exception { RevokePausedPartitionTest test = new RevokePausedPartitionTest(); test.run(); } }
dbbec3ebf0d5d6558ab12a6586bad0a7a303583f
7812038b49406b700f2a14b04b6a71b2224540a3
/app/src/main/java/com/ltbrew/brewbeer/service/PldForBrewSession.java
ff8af2330095289f03483d6e09f3fd0c7e29b2ba
[]
no_license
JasonQiusip/brewbeer
63671b33cdab494cff96dbba36e136923f17c394
246dff2d01df1b1437466f99e27f607466bddcf3
refs/heads/master
2021-01-21T14:25:23.496027
2016-07-08T08:53:43
2016-07-08T08:53:43
57,968,702
2
1
null
null
null
null
UTF-8
Java
false
false
1,092
java
package com.ltbrew.brewbeer.service; import android.os.Parcel; import android.os.Parcelable; /** * Created by 151117a on 2016/5/25. */ public class PldForBrewSession implements Parcelable { public String packId; public String formulaId; public int state; public PldForBrewSession(){} protected PldForBrewSession(Parcel in) { packId = in.readString(); formulaId = in.readString(); state = in.readInt(); } public static final Creator<PldForBrewSession> CREATOR = new Creator<PldForBrewSession>() { @Override public PldForBrewSession createFromParcel(Parcel in) { return new PldForBrewSession(in); } @Override public PldForBrewSession[] newArray(int size) { return new PldForBrewSession[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(packId); parcel.writeString(formulaId); parcel.writeInt(state); } }
df1293e7f64be2c2ad57f65a0b177a07aa2bc9fb
7274583b08e6a3d858134cad42f330c1544584ff
/src/main/java/blue/thejester/badderbaddies/entity/blaze/ThunderBlaze.java
9141489cc8b0e8d16b248f9b4390b16b9e528da4
[]
no_license
AnnaErisian/Badder-Baddies
ff2a7e48c6a040f92e65f6af6b778d88f108394d
ee7eb4809702ef95d8bff62d21da793821c438c1
refs/heads/master
2022-11-16T21:32:36.970666
2020-07-13T13:37:15
2020-07-13T13:37:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,118
java
package blue.thejester.badderbaddies.entity.blaze; import blue.thejester.badderbaddies.BadderBaddies; import blue.thejester.badderbaddies.client.render.blaze.RenderThunderBlaze; import blue.thejester.badderbaddies.entity.LootTables; import net.minecraft.entity.projectile.EntitySmallFireball; import net.minecraft.util.ResourceLocation; import net.minecraft.world.World; import net.minecraftforge.fml.client.registry.RenderingRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class ThunderBlaze extends EntityMyBlaze { public static final String NAME = "blaze_thunder"; public ThunderBlaze(World worldIn) { super(worldIn); this.experienceValue += 20; } @Override protected double healthBoost() { return 10; } @Override protected double numFireballs() { return 1; } @Override protected float magicContactDamage() { return 3; } protected void initEntityAI() { super.initEntityAI(); this.tasks.addTask(4, new EntityMyBlaze.AIFireballAttack(this, false)); } @Override protected EntitySmallFireball createFireball(World world, EntityMyBlaze blaze, double v, double d2, double v1) { return new LightningFireball(world, blaze, v, d2, v1); } protected ThunderBlaze createInstance() { return new ThunderBlaze(this.world); } @Override protected ResourceLocation getLootTable() { return LootTables.BLAZE_THUNDER; } public static void registerSelf(int id) { ResourceLocation entity_name = new ResourceLocation(BadderBaddies.MODID, NAME); EntityRegistry.registerModEntity(entity_name, ThunderBlaze.class, NAME, id, BadderBaddies.instance, 64, 3, true, 0xe6a601, 0xffff00); } @SideOnly(Side.CLIENT) public static void registerOwnRenderer() { RenderingRegistry.registerEntityRenderingHandler(ThunderBlaze.class, RenderThunderBlaze.FACTORY); } }
23fba1e9231bd341dfdadfa33c5a91e3b3dfa631
4cefbeb2d37b70b0d4f648132635e3ac6ce17df1
/app/src/main/java/com/skpissay/util/RxBus.java
80d047e4cc5f1f5c672ccfd587777f88701b3be3
[]
no_license
Sach16/Checkgaadi-Mvvm
1c92f313e8e91cc135449cec1f71f315a1f0476a
356b115f758d710db33f2552dec0b2c5581efc2b
refs/heads/master
2020-03-28T21:01:32.121330
2018-09-17T12:51:29
2018-09-17T12:51:29
149,123,423
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package com.skpissay.util; import rx.Observable; import rx.subjects.PublishSubject; import rx.subjects.SerializedSubject; import rx.subjects.Subject; /** * Created by mertsimsek on 13/01/17. */ public class RxBus { private static RxBus instance = null; private final Subject<Object, Object> _bus = new SerializedSubject<>(PublishSubject.create()); private RxBus() { } public static RxBus getInstance() { if (instance == null) instance = new RxBus(); return instance; } public void send(Object o) { _bus.onNext(o); } public Observable<Object> toObserverable() { return _bus; } public boolean hasObservers() { return _bus.hasObservers(); } }
9e6dae456bf7262407c0d91ff6a535eb1aeda9bb
883b999347c620fc4bb960cf5abb71ebe00c2867
/pinyougou-parent/pinyougou-manager-web/src/main/java/com/pinyougou/manager/controller/GoodsController.java
614f234beeec79e0db017cbcf7b5d9d78b93e817
[]
no_license
longgang/pinyougou
d58a91dd6b7520451724e7df125a192f5c843461
a316ca32b8b8d7933ab834576ae3c8977c9d793b
refs/heads/master
2020-03-23T07:19:27.019132
2018-06-25T08:22:29
2018-06-25T08:22:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,979
java
package com.pinyougou.manager.controller; import java.util.List; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.dubbo.config.annotation.Reference; import com.pinyougou.pojo.TbGoods; import com.pinyougou.sellergoods.service.GoodsService; import entity.PageResult; import entity.Result; /** * controller * @author Administrator * */ @RestController @RequestMapping("/goods") public class GoodsController { @Reference private GoodsService goodsService; /** * 返回全部列表 * @return */ @RequestMapping("/findAll") public List<TbGoods> findAll(){ return goodsService.findAll(); } /** * 返回全部列表 * @return */ @RequestMapping("/findPage") public PageResult findPage(int page,int rows){ return goodsService.findPage(page, rows); } /** * 修改 * @param goods * @return */ @RequestMapping("/update") public Result update(@RequestBody TbGoods goods){ try { goodsService.update(goods); return new Result(true, "修改成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "修改失败"); } } /** * 获取实体 * @param id * @return */ @RequestMapping("/findOne") public TbGoods findOne(Long id){ return goodsService.findOne(id); } /** * 批量删除 * @param ids * @return */ @RequestMapping("/delete") public Result delete(Long [] ids){ try { goodsService.delete(ids); return new Result(true, "删除成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "删除失败"); } } /** * 查询+分页 * @param brand * @param page * @param rows * @return */ @RequestMapping("/search") public PageResult search(@RequestBody TbGoods goods, int page, int rows ){ return goodsService.findPage(goods, page, rows); } }
a1aa0c911d4d95959b1771d70949a8a96297d611
1e906b18093f1d62a2d8388e77030c50fcae032f
/android/app/src/main/java/com/awesomeprojectn/MainActivity.java
a07d3ead7e555e3420ce488e2fec1c6e7ff7c3d6
[]
no_license
sjsj2/awesome-react-project
a8fc59186565ff692fff3b3c968719105c855a48
921e539aa4bf335611b089f943d7502e781f21d5
refs/heads/master
2021-09-11T18:57:42.575257
2018-04-11T02:51:02
2018-04-11T02:51:02
107,648,836
0
0
null
null
null
null
UTF-8
Java
false
false
375
java
package com.awesomeprojectn; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "AwesomeProjectN"; } }
90ee1f5a24f3a1dbb2feb23c2b4faa1464390f23
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/3/3_eb14df3d6c01dcbb873e0428b89e358889a39165/TabRenderer/3_eb14df3d6c01dcbb873e0428b89e358889a39165_TabRenderer_t.java
7c4ef9238bab910be4ce74ced9b740b10eef1648
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
1,862
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.helix.mobile.component.tab; import java.io.IOException; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.primefaces.renderkit.CoreRenderer; /** * This rendering is invoked by each page, which checks to see if it in a tab bar and, * if so, renders the tab bar. * * @author shallem */ public class TabRenderer extends CoreRenderer { @Override public void encodeBegin(FacesContext context, UIComponent component) throws IOException { Tab tab = (Tab)component; Boolean isActive = (Boolean)tab.getAttributes().get("active"); ResponseWriter writer = context.getResponseWriter(); writer.startElement("li", component); writer.startElement("a", component); writer.writeAttribute("href", "#" + tab.getPage(), null); writer.writeAttribute("style", "height: 48px", null); //writer.writeAttribute("data-icon", "custom", null); if (!tab.isCustomIcon()) { writer.writeAttribute("data-icon", tab.getIcon(), null); } String styleClass = "ui-icon-" + tab.getIcon(); if (isActive) { writer.writeAttribute("class", styleClass + " ui-btn-active", null); } else { writer.writeAttribute("class", styleClass, null); } if (tab.getName() != null) { //writer.write(tab.getName()); } } @Override public void encodeEnd(FacesContext context, UIComponent component) throws IOException { ResponseWriter writer = context.getResponseWriter(); writer.endElement("a"); writer.endElement("li"); } }
6a79522f456b7b6f3969e1d5ad62b31d6a32cf9f
d78f20b6412c0deae07028acd067aff4f23db1f3
/GQ_Android/test/com/qeevee/gq/tests/TestNPCTalkUtils.java
3e770beae64a58a1e88fa080d37511411837628d
[]
no_license
f-l-o/android
617fd5d81d0463993faada124519e201367f4112
57df1a41c3a4a29e7b152b69f566342494ba92ae
refs/heads/master
2020-12-24T10:14:39.782547
2013-03-05T15:13:31
2013-03-05T15:13:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,566
java
package com.qeevee.gq.tests; import static com.qeevee.gq.tests.TestUtils.getFieldValue; import java.util.Iterator; import android.os.CountDownTimer; import android.widget.Button; import edu.bonn.mobilegaming.geoquest.mission.DialogItem; import edu.bonn.mobilegaming.geoquest.mission.NPCTalk; public class TestNPCTalkUtils { /** * This helper method emulates the Timer used in the real application. It * very specialized according to the implementation, e.g. the delta between * word appearance is set to 100ms as in the code. */ public static void letCurrentDialogItemAppearCompletely(NPCTalk npcTalk) { CountDownTimer timer = (CountDownTimer) getFieldValue(npcTalk, "myCountDownTimer"); timer.onFinish(); DialogItem dialogItem = (DialogItem) getFieldValue(npcTalk, "currItem"); timer = (CountDownTimer) getFieldValue(npcTalk, "myCountDownTimer"); for (int i = 0; i < dialogItem.getNumParts(); i++) { timer.onTick(100l * (dialogItem.getNumParts() - (i + 1))); } timer.onFinish(); } @SuppressWarnings("unchecked") public static void forwardUntilLastDialogItemIsShown(NPCTalk npcTalk) { Iterator<DialogItem> dialogItemIterator = (Iterator<DialogItem>) getFieldValue(npcTalk, "dialogItemIterator"); Button button = (Button) getFieldValue(npcTalk, "proceedButton"); while (dialogItemIterator.hasNext()) { letCurrentDialogItemAppearCompletely(npcTalk); button.performClick(); } letCurrentDialogItemAppearCompletely(npcTalk); } }
2355a527bace475b9e2c0e3fa5ff8ce0ed3d2ebb
925af24267bbdb4f6ab3bca62e61e9bbaf9d4ceb
/ASD1/src/gameobject/data/behaviour/ai/idle/IdleAIRoutines.java
97bcc6e68d952bb0a67d8cce59d732d31c8d5086
[]
no_license
Hobajt/pj1_projekt
642ddec0c8fe4f32a2fb7ec0b2ce343ac288e366
0359d4f317162ed099f4e40bfdda4cecef04a69d
refs/heads/master
2021-09-23T17:49:08.068741
2017-12-19T23:32:18
2017-12-19T23:32:18
114,043,715
0
0
null
null
null
null
UTF-8
Java
false
false
745
java
/* * 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 gameobject.data.behaviour.ai.idle; import gameobject.GameObject; import gameobject.data.behaviour.ai.AIState; import java.util.List; import util.Point; /** * Idle behaviour for movement around predefined path * @author Radek */ public class IdleAIRoutines extends IdleAI { private List<Point> route; private transient int nextStop; @Override public AIState update(AIState state) { return AIState.IDLE; } public IdleAIRoutines(IdleAIData data, GameObject owner) { super(data, owner); } }
fa790016c6206e8e1c2592843ea54100a533cdab
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/11/11_71a931e4cf57dfb24cb50d836e30b708ced7f9fe/NewWinner/11_71a931e4cf57dfb24cb50d836e30b708ced7f9fe_NewWinner_t.java
87c3e28fa2d325865bc796e58923e3923b6c1515
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
5,703
java
package com.Grateds.Reversi.GUI; import com.Grateds.Reversi.User; import com.Grateds.Reversi.CONTROLLER.Controller; /** * * @author Abuzaid */ public class NewWinner extends javax.swing.JFrame { /** * */ private static final long serialVersionUID = 1L; /** * Creates new form UserInterface */ private Controller controller; public NewWinner(Controller c) { controller = c; initComponents(); this.setLocationRelativeTo(getOwner()); this.setResizable(false); this.setVisible(true); this.setDefaultCloseOperation(HIDE_ON_CLOSE); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jTextField2 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("NEW WINNER"); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setText("Name"); jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel3.setText("Score"); jTextField2.setEditable(false); jTextField2.setText(controller.get_totalScore()+""); jButton1.setText("Submit"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(17, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(47, 47, 47) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(34, 34, 34)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jButton1) .addGap(130, 130, 130)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButton1) .addGap(0, 18, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed controller.stop(); boolean terminate = false; while(!jTextField1.getText().equals("") && !terminate){ User u = new User(); String score = jTextField2.getText(); u.create(jTextField1.getText(), Integer.parseInt(score)); terminate = true; this.setVisible(false); } controller.resume(); }//GEN-LAST:event_jComboBox1ActionPerformed /** * @param args the command line arguments */ // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; // End of variables declaration//GEN-END:variables }
db0fa9972758b406a583b13f8cf0e85558f7cdcb
d921635ac17be024d10464e757f58d8769412bb1
/src/main/java/guru/springframework/Franc.java
75c821989b7a082fa0a784274e84b158076ad612
[ "Apache-2.0" ]
permissive
ahmeed83/tdd-by-example
e6031f0e7828a585dfa8eda8e3353c7015f175cb
0ca9e48983536392ba84e219b550b2b37285f373
refs/heads/master
2020-04-06T08:54:57.583832
2018-11-14T06:00:51
2018-11-14T06:00:51
157,321,531
0
0
null
2018-11-13T04:44:39
2018-11-13T04:44:39
null
UTF-8
Java
false
false
243
java
package guru.springframework; public class Franc extends Money { public Franc(final int amount) { this.amount = amount; } public Money times(final int multiplier) { return new Franc(amount * multiplier); } }
7629c0f2976a64367115b054179570383e7d33ec
8a27c18ec9774c6dcbfdfce4e0bd5461b0594b08
/src/org/opensha/refFaultParamDb/gui/addEdit/deformationModel/DeformationModelTableModel.java
0774e2552d8f5f83334fa54a716ac863a134597d
[ "Apache-2.0" ]
permissive
GNS-Science/opensha-core
81b96bca74254082fc83e8f7cebf67c24312d722
75143f6dd0b1d268471bfa55be8c7bd6ef559d73
refs/heads/master
2023-05-03T16:56:52.342902
2021-05-12T01:48:08
2021-05-12T01:48:08
364,415,943
0
0
Apache-2.0
2021-05-10T03:07:31
2021-05-04T23:51:04
Java
UTF-8
Java
false
false
3,606
java
/** * */ package org.opensha.refFaultParamDb.gui.addEdit.deformationModel; import java.util.ArrayList; import java.util.HashMap; import javax.swing.table.DefaultTableModel; import org.opensha.refFaultParamDb.dao.db.DB_AccessAPI; import org.opensha.refFaultParamDb.dao.db.DB_ConnectionPool; import org.opensha.refFaultParamDb.dao.db.DeformationModelDB_DAO; import org.opensha.refFaultParamDb.dao.db.FaultSectionVer2_DB_DAO; import org.opensha.refFaultParamDb.vo.EstimateInstances; import org.opensha.refFaultParamDb.vo.FaultSectionSummary; /** * * Deformation model table model * @author vipingupta * */ public class DeformationModelTableModel extends DefaultTableModel { /** * */ private static final long serialVersionUID = 1L; private final static String []columnNames = { "Section Name", "Slip Rate", "Aseismic Slip Factor"}; private int deformationModelId; private ArrayList<Integer> faultSectionsInModel; private HashMap<Integer, String> faultSectionsSummaryMap = new HashMap<Integer, String>(); private FaultSectionVer2_DB_DAO faultSectionDB_DAO; private DeformationModelDB_DAO deformationModelDAO; private ArrayList<FaultSectionSummary> faultSectionSummries; public DeformationModelTableModel(DB_AccessAPI dbConnection) { faultSectionDB_DAO = new FaultSectionVer2_DB_DAO(dbConnection); deformationModelDAO = new DeformationModelDB_DAO(dbConnection); faultSectionSummries = faultSectionDB_DAO.getAllFaultSectionsSummary(); for(int i=0; i<faultSectionSummries.size(); ++i) { FaultSectionSummary faultSectionSummary = (FaultSectionSummary)faultSectionSummries.get(i); faultSectionsSummaryMap.put(new Integer(faultSectionSummary.getSectionId()), faultSectionSummary.getSectionName()); } } public void setDeformationModel(int deformationModelId, ArrayList faultSectionIdList) { this.deformationModelId = deformationModelId; faultSectionsInModel = new ArrayList(); for(int i=0; i<faultSectionSummries.size(); ++i) { FaultSectionSummary faultSectionSummary = (FaultSectionSummary)faultSectionSummries.get(i); if(faultSectionIdList.contains(new Integer(faultSectionSummary.getSectionId()))) faultSectionsInModel.add(new Integer(faultSectionSummary.getSectionId())); } } public int getdeformationModelId() { return deformationModelId; } public int getColumnCount() { return columnNames.length; } public Class getColumnClass(int col) { if(col==0) return String.class; else return EstimateInstances.class; } public int getRowCount() { int numRows = 0; if(faultSectionsInModel!=null) numRows = faultSectionsInModel.size(); return numRows; } public String getColumnName(int col) { return columnNames[col]; } public int getFaultSectionId(int row) { return ((Integer)faultSectionsInModel.get(row)).intValue(); } public Object getValueAt(int row, int col) { int faultSectionId= ((Integer)faultSectionsInModel.get(row)).intValue(); return faultSectionsSummaryMap.get(new Integer(faultSectionId)); } public Object getValueForSlipAndAseismicFactor(int row, int col) { int faultSectionId= ((Integer)faultSectionsInModel.get(row)).intValue(); if(col==2) { //aseismic slip factor return deformationModelDAO.getAseismicSlipEstimate(deformationModelId, faultSectionId); } else if(col==1) { // slip rate return deformationModelDAO.getSlipRateEstimate(deformationModelId, faultSectionId); } return faultSectionsInModel.get(row); } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { return false; } }
bf6792662672fad410c43313a964bcb66f19ea38
e1450a329c75a55cf6ccd0ce2d2f3517b3ee51c5
/src/main/java/home/javarush/javaCore/task13/task1308/Solution.java
9682cd08b0a5e5829b939faa064df08d227fc398
[]
no_license
nikolaydmukha/netology-java-base-java-core
afcf0dd190f4c912c5feb2ca8897bc17c09a9ec1
eea55c27bbbab3b317c3ca5b0719b78db7d27375
refs/heads/master
2023-03-18T13:33:24.659489
2021-03-25T17:31:52
2021-03-25T17:31:52
326,259,412
0
0
null
null
null
null
UTF-8
Java
false
false
300
java
package home.javarush.javaCore.task13.task1308; /* Эй, ты там живой? */ public class Solution { public static void main(String[] args) throws Exception { } public interface Person { boolean isAlive(); } public interface Presentable extends Person{ } }
82ac1d7ea2df619474ed2bf941090e12a3416764
46f443ec46857a3c2715a832f67681e98d23a0fa
/ConfigurationWithJavaCode/src/main/java/ru/rickSanchez/withoutAnnotation/RapMusic.java
ae77e39ede55cd4f2e15605ff0f67b6cf0acdaa7
[]
no_license
MRCoolZero/Spring
4c4bef97cd20b9a5d1fe54850ff936d8b531f211
609524e2b8e8fd9c89763e9222fe31acd75a4aa6
refs/heads/master
2023-01-14T12:18:09.972834
2020-11-22T16:49:42
2020-11-22T16:49:42
315,085,831
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package ru.rickSanchez.withoutAnnotation; public class RapMusic implements Music{ @Override public String getSong() { return "RapMusic"; } }
7f351759721dbc4ba9a26cc9d6a9e49a1cc3890f
cdeee1295065d0ba965dd0c502973e9c3aa60618
/gameserver/data/scripts/ai/ZakenDaytime83.java
1e1be341ec3139974e9d7c6bffea344227b8cec3
[]
no_license
forzec/l-server
526b1957f289a4223942d3746143769c981a5508
0f39edf60a14095b269b4a87c1b1ac01c2eb45d8
refs/heads/master
2021-01-10T11:39:14.088518
2016-03-19T18:28:04
2016-03-19T18:28:04
54,065,298
5
0
null
null
null
null
UTF-8
Java
false
false
1,319
java
package ai; import org.mmocore.gameserver.ai.CtrlEvent; import org.mmocore.gameserver.ai.Fighter; import org.mmocore.gameserver.model.Creature; import org.mmocore.gameserver.model.entity.Reflection; import org.mmocore.gameserver.model.instances.NpcInstance; import instances.ZakenDay83; /** * Daytime Zaken. * - иногда призывает 4х мобов id: 29184 * * @author pchayka */ public class ZakenDaytime83 extends Fighter { private long _spawnTimer = 0L; private static final long _spawnReuse = 60000L; private static final int _summonId = 29184; private NpcInstance actor = getActor(); Reflection r = actor.getReflection(); public ZakenDaytime83(NpcInstance actor) { super(actor); } @Override protected void thinkAttack() { if(actor.getCurrentHpPercents() < 70 && _spawnTimer + _spawnReuse < System.currentTimeMillis()) { for(int i = 0; i < 4; i++) { NpcInstance add = r.addSpawnWithoutRespawn(_summonId, actor.getLoc(), 250); add.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, getAttackTarget(), 2000); } _spawnTimer = System.currentTimeMillis(); } super.thinkAttack(); } @Override protected void onEvtDead(Creature killer) { ((ZakenDay83) r).notifyZakenDeath(actor); r.setReenterTime(System.currentTimeMillis()); super.onEvtDead(killer); } }
[ "dmitry@0xffff" ]
dmitry@0xffff
c03cc6684b7c5dd7d224f9a70c504574f9d6f9b2
9f204342f63c82b26908792c84144d80c67911cc
/src/org/enhydra/shark/partmappersistence/data/XPDLParticipantProcessQuery.java
608c3da77a110f447c3600ec9c2e276286954e93
[]
no_license
kinnara-digital-studio/shark
eaada7bbb4ba976e1c876defdcab9d5ee15b81eb
7abf690837152da11ddda360ad2436ec68c7bdb4
refs/heads/master
2023-03-16T07:27:02.867938
2013-05-05T13:12:25
2013-05-05T13:12:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
78,547
java
/*----------------------------------------------------------------------------- * Enhydra Java Application Server * Copyright 1997-2000 Lutris Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes Enhydra software developed by Lutris * Technologies, Inc. and its contributors. * 4. Neither the name of Lutris Technologies nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LUTRIS TECHNOLOGIES AND CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL LUTRIS TECHNOLOGIES OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *----------------------------------------------------------------------------- * org.enhydra.shark.partmappersistence.data/XPDLParticipantProcessQuery.java *----------------------------------------------------------------------------- */ package org.enhydra.shark.partmappersistence.data; import org.enhydra.dods.DODS; import com.lutris.dods.builder.generator.query.*; import com.lutris.appserver.server.sql.*; //import org.enhydra.dods.cache.LRUCache; import org.enhydra.dods.cache.DataStructCache; import org.enhydra.dods.cache.QueryCache; import org.enhydra.dods.cache.QueryCacheItem; import org.enhydra.dods.cache.QueryResult; import org.enhydra.dods.cache.DataStructShell; import org.enhydra.dods.cache.DOShell; import org.enhydra.dods.cache.Condition; import org.enhydra.dods.statistics.Statistics; import org.enhydra.dods.cache.CacheConstants; import org.enhydra.dods.statistics.*; import com.lutris.logging.LogChannel; import com.lutris.logging.Logger; import com.lutris.appserver.server.sql.CachedDBTransaction; //import org.enhydra.dods.util.LRUMap; import java.sql.*; import java.util.*; import java.math.*; import java.util.Date; // when I say Date, I don't mean java.sql.Date // WebDocWf extension for DODS row instance based security // The following line has been added import org.webdocwf.dods.access.*; // end of WebDocWf extension for DODS row instance based security /** * XPDLParticipantProcessQuery is used to query the XPDLParticipantProcess table in the database.<BR> * It returns objects of type XPDLParticipantProcessDO. * <P> * General usage: * <P> * In DODS: * Create a Data Object named "Dog", * and create an Attribute named "Name", * and set that Attribute to "Can be queried." * DODS will then generate the method DogQuery.setQueryName(). * <P> * In your Business Layer, prepare the query:<BR> * <P><PRE> * DogQuery dq = new DogQuery(); * dq.setQueryName("Rex") * if ( Rex is a reserved name ) * dq.requireUniqueInstance(); * </PRE> * Then, get the query results one of two ways: * <P> * #1:<PRE> * String names = ""; * DogDO[] dogs = dq.getDOArray(); * for ( int i = 0; i < dogs.length; i++ ) { * names += dogs[i].getName() + " "; * } * </PRE> * or #2:<PRE> * String names = ""; * DogDO dog; * while ( null != ( dog = dq.getNextDO() ) ) { * names += dog.getName() + " "; * } * </PRE> * <P> * Note: If <CODE>requireUniqueInstance()</CODE> was called, * then <CODE>getDOArray()</CODE> or <CODE>getNextDO()</CODE> * will throw an exception if more than one "Rex" was found. * <P> * Note: Results of the query will come from the Data Object cache if: * - The cache is available. * - Matches were found in the cache. * - No other tables (Data Objects of other types) were involved * in the query. * This can happen if you extend the <CODE>DogQuery</CODE> class * and you make calls to the <CODE>QueryBuilder</CODE> object * to add SQL involving other tables. * If any of these conditions is not true, * then any results from the query will come from the database. * <P> * To reuse the query object, call: * <P><PRE> * dq.reset(); * </PRE> * @author NN * @version $Revision: 1.13 $ */ public class XPDLParticipantProcessQuery implements ExtendedQuery { private QueryBuilder builder; /** * logical name of the database for which XPDLParticipantProcessQuery object has been created */ private String logicalDatabase; private ResultSet resultSet = null; private boolean uniqueInstance = false; private boolean loadData = false; private XPDLParticipantProcessDO[] DOs = null; private int arrayIndex = -1; private boolean needToRun = true; // 12.04.2004 tj // private LRUMap cacheHits = null; private Vector cacheHits = null; private boolean isQueryByOId = false; private boolean hasNonOidCond = false; private boolean hitDb = false; private boolean userHitDb = false; private int maxDBrows = 0; private boolean orderRelevant = true; // true if order of query results is relavant, otherwise false private QueryCacheItem queryItem = null; private String currentHandle = null; private HashMap refs = new HashMap(); private int iCurrentFetchSize = -1; private int iCurrentQueryTimeout = 0; DBTransaction transaction = null; private int queryTimeLimit = 0; /** * Public constructor. * * @param dbTrans current database transaction */ public XPDLParticipantProcessQuery(DBTransaction dbTrans) { builder = new QueryBuilder( "XPDLParticipantProcess", XPDLParticipantProcessDO.columnsNameString ); Integer tmpInt = XPDLParticipantProcessDO.getConfigurationAdministration(). getTableConfiguration().getQueryTimeLimit(); if(tmpInt!=null) { queryTimeLimit = tmpInt.intValue(); }else { queryTimeLimit = 0; } String dbName = null; if(dbTrans!=null) dbName = dbTrans.getDatabaseName(); else dbName = XPDLParticipantProcessDO.get_logicalDBName(); try { transaction = dbTrans; String vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName); if (vendor != null) { builder.setDatabaseVendor(vendor); logicalDatabase = dbName; } else { builder.setDatabaseVendor(); logicalDatabase = DODS.getDatabaseManager().getDefaultDB(); } } catch (Exception e) { builder.setDatabaseVendor(); logicalDatabase = DODS.getDatabaseManager().getDefaultDB(); } builder.setUserStringAppendWildcard( false ); builder.setUserStringTrim( false ); reset(); } /** * Return logical name of the database that XPDLParticipantProcessQuery object uses * * @return param logical database name * */ public String getLogicalDatabase() { return logicalDatabase; } /** * Return java.sql.PreparedStatement from QueryBuilder class * * @return PreparedStatement from this query object. * */ public PreparedStatement getStatement(){ return builder.getStatement(); } /** * Change logical database to another logical database (which name is dbName) * * @param dbName the logical name of the database * @exception SQLException * @exception DatabaseManagerException */ public void setLogicalDatabase(String dbName) throws SQLException, DatabaseManagerException { String vendor = DODS.getDatabaseManager().logicalDatabaseType(dbName); if (vendor != null) { builder.setDatabaseVendor(vendor); logicalDatabase = dbName; } else { builder.setDatabaseVendor(); logicalDatabase = DODS.getDatabaseManager().getDefaultDB(); } reset(); } // WebDocWf extension for unique query results without SQL DISTINCT // The following lines has been added: private boolean unique = false; /** * Set the unique flag of the query * * @param newUnique The unique flag for the query * * WebDocWf extension * */ public void setUnique(boolean newUnique) { unique = newUnique; } /** * Get the unique flag of the query * * @return The unique flag of the query * * WebDocWf extension * */ public boolean getUnique() { return unique; } // WebDocWf extension for skipping the n first rows of the result // The following lines has been added: private int readSkip = 0; /** * Set the readSkip number of the query * * @param newReadSkip The number of results to skip. * * WebDocWf extension * */ public void setReadSkip(int newReadSkip) { readSkip = newReadSkip; } /** * Get the readSkip number of the query * * @return The number of rows which are skipped * * WebDocWf extension * */ public int getReadSkip() { return readSkip; } // WebDocWf extension for select rowcount limit // The following lines has been added: private int databaseLimit = 0; /** * Set the database limit of the query * * @param newLimit The limit for the query * * WebDocWf extension * */ public void setDatabaseLimit(int newLimit) { databaseLimit = newLimit; } /** * Get the database limit of the query * * @return The database limit of the query * * WebDocWf extension * */ public int getDatabaseLimit() { return databaseLimit; } private boolean databaseLimitExceeded = false; /** * Get the database limit exceeded flag of the query. * * @return The database limit exceeded flag of the query * True if there would have been more rows than the limit, otherwise false. * * WebDocWf extension */ public boolean getDatabaseLimitExceeded() { return databaseLimitExceeded; } // end of WebDocWf extension for select rowcount limit /** * Set that all queries go to database, not to cache. */ public void hitDatabase() { userHitDb = true; } // WebDocWf extension for extended wildcard support // The following rows have been added: /** * Set user string wildcard. * * @param newUserStringWildcard New user string wildcard. * * WebDocWf extension */ public void setUserStringWildcard(String newUserStringWildcard) { builder.setUserStringWildcard( newUserStringWildcard ); } /** * Set user string single wildcard. * * @param newUserStringSingleWildcard New user string single wildcard. * * WebDocWf extension */ public void setUserStringSingleWildcard(String newUserStringSingleWildcard) { builder.setUserStringSingleWildcard( newUserStringSingleWildcard ); } /** * Set user string single wildcard escape. * * @param newUserStringSingleWildcardEscape New user string single wildcard escape. * * WebDocWf extension */ public void setUserStringSingleWildcardEscape(String newUserStringSingleWildcardEscape) { builder.setUserStringSingleWildcardEscape( newUserStringSingleWildcardEscape ); } /** * Set user string wildcard escape. * * @param newUserStringWildcardEscape New user string wildcard escape. * * WebDocWf extension */ public void setUserStringWildcardEscape(String newUserStringWildcardEscape) { builder.setUserStringWildcardEscape( newUserStringWildcardEscape ); } /** * Set user string append wildcard. * * @param userStringAppendWildcard New user string append wildcard. * * WebDocWf extension */ public void setUserStringAppendWildcard(boolean userStringAppendWildcard ) { builder.setUserStringAppendWildcard( userStringAppendWildcard ); } /** * Set user string trim. * * @param userStringTrim New user string trim. * * WebDocWf extension */ public void setUserStringTrim(boolean userStringTrim ) { builder.setUserStringTrim( userStringTrim ); } /** * Get user string wildcard. * * @return User string wildcard. * * WebDocWf extension */ public String getUserStringWildcard() { return builder.getUserStringWildcard(); } /** * Get user string single wildcard. * * @return User string single wildcard. * * WebDocWf extension */ public String getUserStringSingleWildcard() { return builder.getUserStringSingleWildcard(); } /** * Get user string single wildcard escape. * * @return User string single wildcard escape. * * WebDocWf extension */ public String getUserStringSingleWildcardEscape() { return builder.getUserStringSingleWildcardEscape(); } /** * Get user string wildcard escape. * * @return User string wildcard escape. * * WebDocWf extension */ public String getUserStringWildcardEscape() { return builder.getUserStringWildcardEscape(); } /** * Get user string append wildcard. * * @return User string append wildcard. * * WebDocWf extension */ public boolean getUserStringAppendWildcard() { return builder.getUserStringAppendWildcard(); } /** * Get user string trim. * * @return User string trim. * * WebDocWf extension */ public boolean getUserStringTrim() { return builder.getUserStringTrim(); } // end of WebDocWf extension for extended wildcard support /** * Perform the query on the database, and prepare the array of returned * DO objects. * * @param DOs Vector of result oids which will be switched with the whole DOs * (from the database). * @exception DataObjectException If a database access error occurs. * @exception NonUniqueQueryException If too many rows were found. */ private void getQueryByOIds(Vector DOs, Date mainQueryStartTime) throws DataObjectException { if (DOs.size() == 0) return; XPDLParticipantProcessDO DO = null; DOShell shell = null; XPDLParticipantProcessQuery tmpQuery = null; Date startQueryTime = new Date(); long queryTime = 0; boolean queryTimeLimitError = false; for (int i=0; i<DOs.size(); i++) { shell = (DOShell)DOs.elementAt(i); tmpQuery = new XPDLParticipantProcessQuery(transaction); try { tmpQuery.setQueryHandle( shell.handle ); tmpQuery.requireUniqueInstance(); DO = tmpQuery.getNextDO(); Date currentQueryTime = new Date(); long passedQueryTime = currentQueryTime.getTime()- mainQueryStartTime.getTime(); if ((queryTimeLimit > 0) && (passedQueryTime > queryTimeLimit)) { DODS.getLogChannel().write(Logger.WARNING,"Froced QueryByOIds Query interrupt," +" query time limit exceeded (errID=30)."); DODS.getLogChannel().write(Logger.DEBUG,"Froced QueryByOIds Query interrupt," +" query time limit exceeded (errID=30)(" +" QueryTimeLimit = "+queryTimeLimit +" : PassedQueryTime = "+passedQueryTime +" ) SQL = " + tmpQuery.getQueryBuilder().getSQLwithParms()); queryTimeLimitError = true; throw new SQLException("Froced query interrupt in QueryByOIds (errID=30)."); } if ( null == DO ){ throw new DataObjectException("XPDLParticipantProcessDO DO not found for id=" + shell.handle ); } } catch ( Exception e ) { if(queryTimeLimitError) { throw new DataObjectException(e.getMessage()); } else { throw new DataObjectException("Duplicate ObjectId"); } } shell.dataObject = DO; } Date stopQueryTime = new Date(); queryTime = stopQueryTime.getTime() - startQueryTime.getTime(); XPDLParticipantProcessDO.statistics.updateQueryByOIdAverageTime((new Long(queryTime)).intValue(),DOs.size()); } /** * Perform the query on the database, and prepare the * array of returned DO objects. * * @exception DataObjectException If a database access error occurs. * @exception NonUniqueQueryException If too many rows were found. */ private void runQuery() throws DataObjectException, NonUniqueQueryException { needToRun = false; arrayIndex = -1; DBQuery dbQuery = null; Date startQueryTime = new Date(); long queryTime = 0; boolean readDOs = false; boolean canUseQueryCache = true; CacheStatistics stat = null; boolean resultsFromQCache = false; QueryCacheItem queryCachedItem = null; if(builder.isUnionTableJoin())throw new DataObjectException( "Could not use 'UNION [ALL]' statement in query witch retrieve data object." ); if ((transaction!=null) && (transaction instanceof com.lutris.appserver.server.sql.CachedDBTransaction)) { if(((com.lutris.appserver.server.sql.CachedDBTransaction)transaction).getAutoWrite()) try { transaction.write(); } catch (SQLException sqle) { sqle.printStackTrace(); throw new DataObjectException("Couldn't write transaction: "+sqle); } ((com.lutris.appserver.server.sql.CachedDBTransaction)transaction).dontAggregateDOModifications(); } try { QueryResult results = null; DOShell shell = null; if (isQueryByOId && !hasNonOidCond) { // query by OId builder.setCurrentFetchSize(1); results = new QueryResult(); if (currentHandle != null) { if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) { XPDLParticipantProcessDO DO= (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(currentHandle); if(DO!=null){ shell = new DOShell(DO); results.DOs.add(shell); resultsFromQCache = true; } // tj 12.04.2004 put under comment next 2 lines // else // resultsFromQCache = false; } if(!resultsFromQCache) { // DO isn't found in the transaction cache XPDLParticipantProcessDataStruct DS = (XPDLParticipantProcessDataStruct)XPDLParticipantProcessDO.cache.getDataStructByHandle(currentHandle); if (DS != null && !(DS.isEmpty && loadData)) { // DO is found in the cache XPDLParticipantProcessDO DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction); shell = new DOShell(DO); results.DOs.add(shell); resultsFromQCache = true; } // tj 12.04.2004 put under comment next 4 lines // else{ // DO isn't found in the cache // if (XPDLParticipantProcessDO.cache.isFull()) // resultsFromQCache = false; // } } }//currentHandle != null } else { // other queries if ( XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded) &&(!hitDb) && (maxDBrows == 0) && (databaseLimit == 0) && (readSkip == 0) && !builder.isMultiTableJoin() ) { resultsFromQCache = true; } else { if (XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) { if (builder.isMultiTableJoin()) { // statistics about multi join query stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.MULTI_JOIN_QUERY_CACHE); if (stat!= null){ stat.incrementCacheAccessNum(1); } } else { if (hitDb) { // statistics about complex query stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE); if (stat!= null){ stat.incrementCacheAccessNum(1); } }else{ // statistics about simple query stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE); if (stat!= null){ stat.incrementCacheAccessNum(1); } } } } if(transaction != null) canUseQueryCache = !transaction.preventCacheQueries(); if ((XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) && canUseQueryCache) { String queryID = builder.getSQLwithParms(); //unique representation of query int resNum = 0; int evaluateNo = 0; if (builder.isMultiTableJoin()) { queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryCacheItem(logicalDatabase, queryID); } else{ if (hitDb) queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryCacheItem(logicalDatabase, queryID); else queryCachedItem = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryCacheItem(logicalDatabase, queryID); } queryItem.setQueryId(queryID); // queryItem defined as private template attribute if (queryCachedItem == null) { // query doesn't exist // tj 03.09.2004 if ((!builder.isMultiTableJoin()) || XPDLParticipantProcessDO.isAllReadOnly()) if (builder.isMultiTableJoin()){ ((QueryCache)XPDLParticipantProcessDO.cache).addMultiJoinQuery(queryItem); // register multi join query } else { if (hitDb) ((QueryCache)XPDLParticipantProcessDO.cache).addComplexQuery(queryItem); // register complex query else ((QueryCache)XPDLParticipantProcessDO.cache).addSimpleQuery(queryItem); // register simple query } } else{ // query found if ( !(isOrderRelevant() && queryCachedItem.isModifiedQuery()) ) { if (builder.isMultiTableJoin()){ // statistics about multi join cache stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.MULTI_JOIN_QUERY_CACHE); if (stat!= null){ stat.incrementCacheHitsNum(1); } } else { if (hitDb) { // statistics about complex cache stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.COMPLEX_QUERY_CACHE); if (stat!= null){ stat.incrementCacheHitsNum(1); } }else{ // statistics about simple cache stat = null; stat = XPDLParticipantProcessDO.statistics.getCacheStatistics(CacheConstants.SIMPLE_QUERY_CACHE); if (stat!= null){ stat.incrementCacheHitsNum(1); } } } int limitOfRes; if (databaseLimit == 0) limitOfRes = 0; else limitOfRes = readSkip+databaseLimit+1; if (! unique) { if (builder.isMultiTableJoin()) { results = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows); } else { if (hitDb) results = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows); else results = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows); } }else{ // (! unique) if (builder.isMultiTableJoin()) { results = ((QueryCache)XPDLParticipantProcessDO.cache).getMultiJoinQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true); } else { if (hitDb) results = ((QueryCache)XPDLParticipantProcessDO.cache).getComplexQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true); else results = ((QueryCache)XPDLParticipantProcessDO.cache).getSimpleQueryResults(logicalDatabase, queryID, limitOfRes, maxDBrows, true); } } // (! unique) if (results != null) { resNum = results.DOs.size(); // tj 01.02.2004 remove skipped if (readSkip > 0) { if (results.DOs.size() > readSkip) { for (int i = 0; i < readSkip; i++) { results.DOs.remove(0); } } else { results.DOs.clear(); } } //sinisa 06.08.2003. results = getCachedResults(results); if (databaseLimit != 0) { // databaseLimitExceeded begin if (resNum == readSkip+databaseLimit+1) { resNum--; databaseLimitExceeded = true; results.DOs.remove(databaseLimit); }else{ if ( (resNum == readSkip+databaseLimit) && (!queryCachedItem.isCompleteResult()) ) databaseLimitExceeded = true; } } // databaseLimitExceeded end if ( (databaseLimit!=0 &&(resNum == (readSkip+databaseLimit))) || (maxDBrows!=0 && (resNum + results.skippedUnique) == maxDBrows) || (queryCachedItem.isCompleteResult()) ) { int lazyTime = XPDLParticipantProcessDO.statistics.getQueryByOIdAverageTime()*results.lazy.size(); if (lazyTime <= queryCachedItem.getTime()) { resultsFromQCache = true; getQueryByOIds(results.lazy,startQueryTime); // gets cached query results from database }else databaseLimitExceeded = false; }else databaseLimitExceeded = false; //remove skiped } // (results != null) } // !(isOrderRelevant() && queryCachedItem.isModifiedQuery()) } // query found } // if QUERY_CACHING } // full caching } // other queries if (( userHitDb) || (!resultsFromQCache)) { // go to database dbQuery = XPDLParticipantProcessDO.createQuery(transaction); if(uniqueInstance) builder.setCurrentFetchSize(1); results = new QueryResult(); int resultCount=0; boolean bHasMoreResults = false; if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) { builder.resetSelectedFields(); builder.setSelectClause("XPDLParticipantProcess."+XPDLParticipantProcessDO.get_OIdColumnName()+", XPDLParticipantProcess."+XPDLParticipantProcessDO.get_versionColumnName()); } else builder.setSelectClause(XPDLParticipantProcessDO.columnsNameString); dbQuery.query( this ); // invokes executeQuery if (! unique) { int iteration = 0; try { while ( (bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) { XPDLParticipantProcessDO newDO; XPDLParticipantProcessDataStruct newDS; Date currentQueryTime = new Date(); long passedQueryTime = currentQueryTime.getTime()-startQueryTime.getTime(); if ( (queryTimeLimit > 0)&& (passedQueryTime > queryTimeLimit)){ DODS.getLogChannel().write(Logger.WARNING,"Froced query interrupt,"+ " query time limit exceeded (errID=10)."); DODS.getLogChannel().write(Logger.DEBUG,"Froced query interrupt,"+ " query time limit exceeded (errID=10)(" + " QueryTimeLimit = "+queryTimeLimit+ " : PassedQueryTime = "+passedQueryTime+ " ) SQL = " + builder.getSQLwithParms()); throw new SQLException("Froced query interrupt (errID=10)."); } if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) { newDO = XPDLParticipantProcessDO.ceInternal ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction); newDO.set_Version(resultSet.getInt(XPDLParticipantProcessDO.get_versionColumnName())); } else newDO = XPDLParticipantProcessDO.ceInternal ( resultSet , refs, transaction); if(transaction==null) { if(newDO!=null && newDO.isTransactionCheck()) { DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" XPDLParticipantProcessDO class, oid: "+newDO.get_Handle()+", version: "+newDO.get_Version()+" \n"); (new Throwable()).printStackTrace(DODS.getLogChannel().getLogWriter(Logger.WARNING)); } } if (queryItem != null) { queryItem.add((XPDLParticipantProcessDataStruct)newDO.originalData_get()); } if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) {} else newDS =XPDLParticipantProcessDO.addToCache((XPDLParticipantProcessDataStruct)newDO.originalData_get()); if (resultCount >= readSkip) { shell = new DOShell(newDO); results.DOs.add(shell); } resultCount++; iteration++; } // while }catch (SQLException e) { DODS.getLogChannel().write( Logger.ERROR, "(SQLError):(ReadingResultSet):(errID=50):("+e.getMessage()+")"); DODS.getLogChannel().write( Logger.DEBUG, "(SQLError):(ReadingResultSet):(errID=50):(element-at:"+iteration+") sql = "+ builder.getSQLwithParms()); throw e; } } // (!unique) else { // (! unique) int iteration = 0; HashSet hsResult = new HashSet(readSkip+databaseLimit); try { while((bHasMoreResults = resultSet.next()) && (databaseLimit==0 || (results.DOs.size()<databaseLimit)) ) { XPDLParticipantProcessDO newDO; XPDLParticipantProcessDataStruct newDS; Date currentQueryTime = new Date(); long passedQueryTime = currentQueryTime.getTime()-startQueryTime.getTime(); if ( (queryTimeLimit > 0)&& (passedQueryTime > queryTimeLimit)){ DODS.getLogChannel().write(Logger.WARNING,"Froced query interrupt,"+ " query time limit exceeded (errID=20)."); DODS.getLogChannel().write(Logger.DEBUG,"Froced query interrupt,"+ " query time limit exceeded (errID=20)(" + " QueryTimeLimit = "+queryTimeLimit+ " : PassedQueryTime = "+passedQueryTime+ " ) SQL = " + builder.getSQLwithParms()); throw new SQLException("Froced query interrupt (errID=20)."); } if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) { newDO = XPDLParticipantProcessDO.ceInternal ( new ObjectId(resultSet.getBigDecimal(CoreDO.get_OIdColumnName())) , refs, transaction); newDO.set_Version(resultSet.getInt(XPDLParticipantProcessDO.get_versionColumnName())); } else newDO = XPDLParticipantProcessDO.ceInternal ( resultSet , refs , transaction); if(transaction==null) { if(newDO!=null && newDO.isTransactionCheck()) { DODS.getLogChannel().write(Logger.WARNING, "DO without transaction context is created : Database: "+newDO.get_OriginDatabase()+" XPDLParticipantProcessDO class, oid: "+newDO.get_Handle()+", version: "+newDO.get_Version()+" \n"); (new Throwable()).printStackTrace(DODS.getLogChannel().getLogWriter(Logger.WARNING)); } } if (queryItem != null) { queryItem.add((XPDLParticipantProcessDataStruct)newDO.originalData_get()); } if (( (XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()) && (!builder.getPreventPrimaryKeySelect()) && !loadData) { } else newDS = XPDLParticipantProcessDO.addToCache((XPDLParticipantProcessDataStruct)newDO.originalData_get()); if (!hsResult.contains(newDO.get_Handle())) { hsResult.add(newDO.get_Handle()); if (resultCount >= readSkip) { shell = new DOShell(newDO); results.DOs.add(shell); } resultCount++; } iteration++; } // while }catch (SQLException e) { DODS.getLogChannel().write( Logger.ERROR, "(SQLError):(ReadingResultSet):(errID=40)("+e.getMessage()+")"); DODS.getLogChannel().write( Logger.DEBUG, "(SQLError):(ReadingResultSet):(errID=40):(element-at:"+iteration+") sql = "+ builder.getSQLwithParms()); throw e; } } // else (! unique) if ((results.DOs.size()==databaseLimit)&& bHasMoreResults) { resultSet.close(); databaseLimitExceeded = true; } if (maxDBrows > 0) { if (!bHasMoreResults) { if ((databaseLimit > 0) && databaseLimit < maxDBrows ) queryItem.setCompleteResult(true); } } else { if (!bHasMoreResults) queryItem.setCompleteResult(true); } Date stopQueryTime = new Date(); queryTime = stopQueryTime.getTime() - startQueryTime.getTime(); if (queryItem != null) { queryItem.setTime((new Long(queryTime)).intValue()); if (queryCachedItem != null) { if ( queryItem.isCompleteResult() || (queryCachedItem.isModifiedQuery() && isOrderRelevant()) || (queryCachedItem.getResultNum() < queryItem.getResultNum()) ) { // tj 03.09.2004 if ((!builder.isMultiTableJoin()) || XPDLParticipantProcessDO.isAllReadOnly() ) if (builder.isMultiTableJoin()){ ((QueryCache)XPDLParticipantProcessDO.cache).addMultiJoinQuery(queryItem); } else { if (hitDb) { ((QueryCache)XPDLParticipantProcessDO.cache).addComplexQuery(queryItem); } else { ((QueryCache)XPDLParticipantProcessDO.cache).addSimpleQuery(queryItem); } } // else from if (builder.isMultiTableJoin()) } else { if ( (queryCachedItem.getResultNum() < (readSkip + databaseLimit) ) && (queryCachedItem.getResultNum() < maxDBrows) ) { queryCachedItem.setCompleteResult(true); } } if ( (queryItem.getResultNum() < (readSkip + databaseLimit) ) && (queryItem.getResultNum() < maxDBrows) ) queryItem.setCompleteResult(true); } // (queryCachedItem != null) } // (queryItem != null) int maxExecuteTime = XPDLParticipantProcessDO.cache.getTableConfiguration().getMaxExecuteTime(); if (maxExecuteTime > 0 && queryTime > maxExecuteTime) DODS.getLogChannel().write(Logger.WARNING, "sql = " + builder.getSQLwithParms()+" execute time = "+queryTime + "max table execute time = "+maxExecuteTime); } else { // ( userHitDb) || (!resultsFromQCache) if ( XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded) && (!hitDb) && (maxDBrows == 0) && (databaseLimit == 0) && (readSkip == 0) && !builder.isMultiTableJoin()) { results = new QueryResult(); if (readSkip<cacheHits.size()) { // 12.04.2004 tj Vector vect = new Vector(cacheHits.values()); results.DOs = new Vector(); XPDLParticipantProcessDO DO = null; XPDLParticipantProcessDataStruct DS = null; String cachePrefix = getLogicalDatabase()+"."; int i = 0; int resNumber = 0; Vector uniqueResults = new Vector(); while (i < cacheHits.size() ) { // && ((databaseLimit==0) || (results.DOs.size()<=databaseLimit)) // && ((maxDBrows==0) || (i < maxDBrows)) boolean findInTransactionCache = false; DS = (XPDLParticipantProcessDataStruct)cacheHits.get(i); if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) { DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle()); if(DO != null) findInTransactionCache = true; } if(!findInTransactionCache){ DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction); } if (unique) { if (!uniqueResults.contains(cachePrefix+DS.get_Handle())) { uniqueResults.add(cachePrefix+DS.get_Handle()); //if (resNumber >= readSkip ){ results.DOs.add(DO); //} resNumber++; } } else { //if (resNumber >= readSkip ){ results.DOs.add(DO); //} resNumber++; } i++; } readDOs = true; } /* if ((databaseLimit != 0) && (results.DOs.size() == databaseLimit+1)) { databaseLimitExceeded = true; results.DOs.remove(databaseLimit); } */ } //if full } // ( userHitDb) || (!resultsFromQCache) // end of WebDocWf extension if (results != null) { // tj 01.02.2004 if ( results.DOs.size() > 1 && uniqueInstance ) throw new NonUniqueQueryException("Too many rows returned from database" ); DOs = new XPDLParticipantProcessDO [ results.DOs.size() ]; XPDLParticipantProcessDataStruct orig; if (readDOs) { for ( int i = 0; i < results.DOs.size(); i++ ) { DOs[i] = (XPDLParticipantProcessDO)results.DOs.elementAt(i); } } else { for ( int i = 0; i < results.DOs.size(); i++ ) { DOs[i] = (XPDLParticipantProcessDO)((DOShell)results.DOs.elementAt(i)).dataObject; } } arrayIndex = 0; } else { DOs = new XPDLParticipantProcessDO [0]; } if (isQueryByOId && !hasNonOidCond) { XPDLParticipantProcessDO.statistics.incrementQueryByOIdNum(); XPDLParticipantProcessDO.statistics.updateQueryByOIdAverageTime((new Long(queryTime)).intValue(),1); } else { XPDLParticipantProcessDO.statistics.incrementQueryNum(); XPDLParticipantProcessDO.statistics.updateQueryAverageTime((new Long(queryTime)).intValue()); } } catch ( SQLException se ) { if (null == se.getSQLState() ) { throw new DataObjectException("Unknown SQLException", se ); } if ( se.getSQLState().startsWith("02") && se.getErrorCode() == 100 ) { throw new DataObjectException("Update or delete DO is out of synch", se ); } else if ( se.getSQLState().equals("S1000") && se.getErrorCode() == -268) { throw new DataObjectException("Integrity constraint violation", se ); } else { throw new DataObjectException( "Data Object Error", se ); } } catch ( ObjectIdException oe ) { throw new DataObjectException( "Object ID Error", oe ); } catch ( DatabaseManagerException de ) { throw new DataObjectException( "Database connection Error", de ); } finally { if ( null != dbQuery )dbQuery.release(); } } /** * Limit the number of rows (DOs) returned. * NOTE: When setting a limit on rows returned by a query, * you usually want to use a call to an addOrderBy method * to cause the most interesting rows to be returned first. * However, the DO cache does not yet support the Order By operation. * Using the addOrderBy method forces the query to hit the database. * So, setMaxRows also forces the query to hit the database. * * @param maxRows Max number of rows (DOs) returned. * * @exception DataObjectException If a database access error occurs. * @exception NonUniqueQueryException If too many rows were found. */ public void setMaxRows( int maxRows ) throws DataObjectException, NonUniqueQueryException { maxDBrows = maxRows; builder.setMaxRows( maxRows ); } /** * Return limit of rows (DOs) returned. * @return Max number of rows (DOs) returned. * */ public int getMaxRows() { return maxDBrows; } /** * Returns attribute orderRelevant. * * @return true if order of query results is relavant, otherwise false. */ public boolean isOrderRelevant() { return orderRelevant; } /** * Sets attribute orderRelevant. * * @param newOrderRelevant new value of attribute orderRelavant. */ public void setOrderRelevant(boolean newOrderRelevant) { orderRelevant = newOrderRelevant; } /** * Return QueryResult with read DOs or DataStructs from caches. * * @param result QueryResult object with result oids. * @return QueryResult object with filled DOs or DataStructs that are found * in the cache. * * @exception DataObjectException If a database access error occurs. */ public QueryResult getCachedResults(QueryResult result) throws DataObjectException { Vector tempVec = result.DOs; if (tempVec == null) return null; result.DOs = new Vector(); result.lazy = new Vector(); DOShell shell = null; XPDLParticipantProcessDO cacheDO = null; XPDLParticipantProcessDataStruct cacheDS = null; String handle = ""; String cachePrefix=getLogicalDatabase()+"."; for(int i=0; i < tempVec.size(); i++) { if(tempVec.get(i)!=null) { cacheDO = null; cacheDS = null; handle=(String)tempVec.get(i); shell = new DOShell(handle); if(transaction!=null && _tr_(transaction).getTransactionCache()!=null && !loadData) { try { cacheDO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+handle); } catch (Exception e) { } } if (cacheDO == null){ cacheDS = (XPDLParticipantProcessDataStruct)XPDLParticipantProcessDO.cache.getDataStructByHandle(cachePrefix+handle); if(cacheDS!=null) { try { cacheDO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(cacheDS.get_OId(), transaction); } catch (Exception e) { } } } if (cacheDO == null){ result.lazy.add(shell); } else { shell.dataObject = cacheDO; } result.DOs.add(shell); } } //for return result; } /** * Return array of DOs constructed from ResultSet returned by query. * * @return Array of DOs constructed from ResultSet returned by query. * * @exception DataObjectException If a database access error occurs. * @exception NonUniqueQueryException If too many rows were found. */ public XPDLParticipantProcessDO[] getDOArray() throws DataObjectException, NonUniqueQueryException { if ( needToRun ) runQuery(); return DOs; } /** * Return successive DOs from array built from ResultSet returned by query. * * @return DOs from array built from ResultSet returned by query. * * @exception DataObjectException If a database access error occurs. * @exception NonUniqueQueryException If too many rows were found. */ public XPDLParticipantProcessDO getNextDO() throws DataObjectException, NonUniqueQueryException { if ( needToRun ) runQuery(); if ( null == DOs ) { /* This should never happen. * runQuery() should either throw an exception * or create an array of DOs, possibly of zero length. */ return null; } if ( arrayIndex < DOs.length ) return DOs[ arrayIndex++ ]; return null; } /** * Set the OID to query. * WARNING! This method assumes that table <CODE>XPDLParticipantProcess</CODE> * has a column named <CODE>"oid"</CODE>. * This method is called from the DO classes to retrieve an object by id. * * @param oid The object id to query. */ public void setQueryOId(ObjectId oid) { // Remove from cacheHits any DO that does not meet this // setQuery requirement. String handle = getLogicalDatabase()+ "." +oid.toString(); if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) { // 12.04.2004 tj new XPDLParticipantProcessDataStruct DS = null; for ( int i = 0; i < cacheHits.size(); i++ ) { DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i ); String cacheHandle = null; try{ cacheHandle = DS.get_CacheHandle(); } catch (Exception e){} if (cacheHandle != null) { if ( ! cacheHandle.equals( handle ) ) cacheHits.removeElementAt( i-- ); } } // for } // full if (isQueryByOId) { // query by OId already has been invoked hasNonOidCond = true; // this is not simple query by oid: has at least two conditions for oids } else { // (isQueryByOid) currentHandle = handle; } isQueryByOId = true; try { Condition cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_OID,handle,"="); queryItem.addCond(cond); } catch (Exception e){ DODS.getLogChannel().write(Logger.DEBUG," XPDLParticipantProcessQuery class\n :"+" condition are not added"); } // Also prepare the SQL needed to query the database // in case there is no cache, or the query involves other tables. builder.addWhere( XPDLParticipantProcessDO.PrimaryKey, oid.toBigDecimal(), QueryBuilder.EQUAL ); } /** * Set the object handle to query. * This is a variant of setQueryOId(). * * @param handle The string version of the id to query. * @exception ObjectIdException */ public void setQueryHandle(String handle) throws ObjectIdException { ObjectId oid = new ObjectId( handle ); setQueryOId( oid ); } /** * Set "unique instance" assertion bit. * The first call to the next() method will throw an exception * if more than one object was found. */ public void requireUniqueInstance() { uniqueInstance = true; } /** * Set loadData parameter. if parameter is set to true, Query select t.* is performed. * @param newValue boolean (true/false) */ public void setLoadData(boolean newValue) { loadData = newValue; } /** * Return true if Query is prepared for select t1.* statement. Otherwise return false. * @return boolean (true/false) */ public boolean getLoadData() { if(loadData) return true; else return ((XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isLazyLoading()) || isCaching()); } /** * Reset the query parameters. */ public void reset() { if(XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) { if(XPDLParticipantProcessDO.cache.getTableConfiguration().getFullCacheCountLimit() > 0){ if(XPDLParticipantProcessDO.cache.getCacheAdministration(CacheConstants.DATA_CACHE).getCacheSize() > XPDLParticipantProcessDO.cache.getTableConfiguration().getFullCacheCountLimit()) XPDLParticipantProcessDO.isFullCacheNeeded = false; } } if(XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) { Map m = null; synchronized (XPDLParticipantProcessDO.cache) { m = XPDLParticipantProcessDO.cache.getCacheContent(); if(m!=null) cacheHits = new Vector(m.values()); else cacheHits = new Vector(); } } DOs = null; uniqueInstance = false; needToRun = true; isQueryByOId = false; hasNonOidCond = false; loadData=false; builder.reset(); if (XPDLParticipantProcessDO.cache.getLevelOfCaching() == CacheConstants.QUERY_CACHING) { queryItem = ((QueryCache)XPDLParticipantProcessDO.cache).newQueryCacheItemInstance(logicalDatabase); } } /** * Return the appropriate QueryBuilder flag for selecting * exact matches (SQL '=') or inexact matches (SQL 'matches'). * * @param exact Flag that indicates whether it is exact match (SQL '=') or * inexact matches (SQL 'matches'). * @return boolean True if it is exact match, otherwise false. * */ private boolean exactFlag( boolean exact ) { return exact ? QueryBuilder.EXACT_MATCH : QueryBuilder.NOT_EXACT; } // // Implementation of Query interface // /** * Method to query objects from the database. * The following call in runQuery() * dbQuery.query( this ); * causes the dbQuery object to invoke * executeQuery() * * @param conn Handle to database connection. * * @return ResultSet with the results of the query. * * @exception java.sql.SQLException If a database access error occurs. */ public ResultSet executeQuery(DBConnection conn) throws SQLException { builder.setCurrentFetchSize(iCurrentFetchSize); builder.setCurrentQueryTimeout(iCurrentQueryTimeout); resultSet = builder.executeQuery( conn ); return resultSet; } /** * WARNING! This method is disabled. * It's implementation is forced by the Query interface. * This method is disabled for 2 reasons: * 1) the getDOArray() and getNextDO() methods are better * because they return DOs instead of JDBC objects. * 2) the ceInternal() method throws an exception * that we cannot reasonably handle here, * and that we cannot throw from here. * * @param rs JDBC result set from which the next object * will be instantiated. * @return Next result. * * @exception java.sql.SQLException * If a database access error occurs. * @exception com.lutris.appserver.server.sql.ObjectIdException * If an invalid object id was queried from the database. */ public Object next(ResultSet rs) throws SQLException, ObjectIdException { // TODO: It would be nice to throw an unchecked exception here // (an exception that extends RuntimeException) // that would be guaranteed to appear during application testing. throw new ObjectIdException("next() should not be used. Use getNextDO() instead." ); //return null; } // WebDocWf extension for extended wildcard support // The following lines have been added: /** * Convert a String with user wildcards into a string with DB wildcards * * @param userSearchValue The string with user wildcards * * @return The string with DB wildcards * * WebDocWf extension * */ public String convertUserSearchValue( String userSearchValue ) { return builder.convertUserSearchValue( userSearchValue ); } /** * Check whether a string contains DB wildcards * * @param dbSearchValue The string with possible DB wildcards * * @return Whether a string contains DB wildcards * * WebDocWf extension * */ public boolean containsWildcards( String dbSearchValue ) { return builder.containsWildcards( dbSearchValue ); } // end of WebDocWf extension for extended wildcard support // WebDocWf extension for query row counter // The following lines have been added: /** * Get the rowcount of the query * If possible, do it without reading all rows * * @return The row count * @exception NonUniqueQueryException * @exception DataObjectException * @exception SQLException * @exception DatabaseManagerException * * WebDocWf extension * */ public int getCount() throws NonUniqueQueryException, DataObjectException, SQLException, DatabaseManagerException { int rowCount=0; if (needToRun && databaseLimit==0) { rowCount = selectCount(); } else { if (needToRun) runQuery(); rowCount = DOs.length; } return rowCount; } /** * Set reference objects. * @param queryRefs Reference objects. */ protected void setRefs(HashMap queryRefs) { refs = queryRefs; } /** * set the current cursor type - overrides default value from dbVendorConf file. * @param resultSetType a result set type; one of ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE. * @param resultSetConcurrency a concurrency type; one of ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE. * @return the current queryTimeout; */ public void set_CursorType(int resultSetType, int resultSetConcurrency) { builder.setCursorType(resultSetType,resultSetConcurrency); } /** * Set fetch size for this query * @param iCurrentFetchSizeIn Query fetch size. */ public void set_FetchSize (int iCurrentFetchSizeIn) { iCurrentFetchSize = iCurrentFetchSizeIn; } /** * reads the current fetchsize for this query * @return the current fetchsize; if -1 the no fetchsize is defined, defaultFetchSize will be use if defined */ public int get_FetchSize() { return (iCurrentFetchSize < 0)? builder.getDefaultFetchSize() : iCurrentFetchSize; } /** * Reads the current queryTimeout for this query. * @return the current queryTimeout; */ public int get_QueryTimeout() { return iCurrentQueryTimeout; } /** * Sets the current queryTimeout for this query. * @param iQueryTimeoutIn current queryTimeout. */ public void set_QueryTimeout(int iQueryTimeoutIn) { iCurrentQueryTimeout = (iCurrentQueryTimeout < 0)? builder.getDefaultQueryTimeout() : iCurrentQueryTimeout; } /** * Get the rowcount of the query by using count(*) in the DB * * @return The row count. * @exception SQLException * @exception DatabaseManagerException * * WebDocWf extension * */ public int selectCount() throws SQLException, DatabaseManagerException { int rowCount=0; String tempClause = builder.getSelectClause(); builder.setSelectClause(" count(*) as \"counter\" "); DBQuery dbQuery; dbQuery = XPDLParticipantProcessDO.createQuery(transaction); dbQuery.query(this); resultSet.next(); rowCount=resultSet.getInt("counter"); // resultSet.close(); // if (transaction == null) // dbQuery.release(); dbQuery.release(); // + builder.close(); resultSet = null; builder.setSelectClause(tempClause); return rowCount; } // end of WebDocWf extension for query row counter /** * Return true if some caching for this table is enabled. * @return (true/false) */ private boolean isCaching() { double cachePercentage = XPDLParticipantProcessDO.cache.getCachePercentage(); double usedPercentage = 0; if(cachePercentage == -1) return false; else if(cachePercentage == 0) return true; else { try { usedPercentage = XPDLParticipantProcessDO.getConfigurationAdministration().getStatistics().getCacheStatistics(CacheConstants.DATA_CACHE).getUsedPercents(); } catch (Exception ex) { return false; } if(usedPercentage > XPDLParticipantProcessDO.cache.getCachePercentage()*100) return true; else return false; } } private static CachedDBTransaction _tr_(DBTransaction dbt) { return (CachedDBTransaction)dbt; } private String fixCaseSensitiveCondition(String cmp_op){ if(XPDLParticipantProcessDO.getConfigurationAdministration().getTableConfiguration().isCaseSensitive()){ if( cmp_op.equals(builder.CASE_INSENSITIVE_CONTAINS) ){ return builder.CASE_SENSITIVE_CONTAINS; }else if( cmp_op.equals( builder.CASE_INSENSITIVE_STARTS_WITH ) ){ return builder.CASE_SENSITIVE_STARTS_WITH; }else if( cmp_op.equals(builder.CASE_INSENSITIVE_ENDS_WITH) ){ return builder.CASE_SENSITIVE_ENDS_WITH; }else if( cmp_op.equals(builder.CASE_INSENSITIVE_EQUAL) ){ return builder.EQUAL; }else if( cmp_op.equals(builder.CASE_INSENSITIVE_MATCH) ){ return builder.CASE_SENSITIVE_MATCH; }else if( cmp_op.equals(builder.USER_CASE_INSENSITIVE_MATCH) ){ return builder.USER_CASE_SENSITIVE_MATCH; } } return cmp_op; } /** * Set the PROCESS_ID to query, with a QueryBuilder comparison operator. * * @param x The PROCESS_ID of the XPDLParticipantProcess to query. * @param cmp_op QueryBuilder comparison operator to use. * * @exception DataObjectException If a database access error occurs. * @exception QueryException If comparison operator is inappropriate * (e.g. CASE_SENSITIVE_CONTAINS on an integer field). */ public void setQueryPROCESS_ID(String x, String cmp_op ) throws DataObjectException, QueryException { String cachePrefix = getLogicalDatabase()+"."; hasNonOidCond = true; cmp_op = fixCaseSensitiveCondition(cmp_op); Condition cond = null; cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PROCESS_ID,x,cmp_op); queryItem.addCond(cond); // WebDocWf extension for extended wildcard support // The following lines have been added: if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) { hitDb = true; } else { // end of WebDocWf extension for extended wildcard support if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) { // Remove from cacheHits any DOs that do not meet this // setQuery requirement. XPDLParticipantProcessDO DO = null; XPDLParticipantProcessDataStruct DS = null; // 12.04.2004 tj // for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();) for ( int i = 0; i < cacheHits.size(); i++ ) { try { boolean findInTransactionCache = false; // DS = (XPDLParticipantProcessDataStruct)iter.next(); DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i ); if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) { DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle()); if(DO != null) findInTransactionCache = true; } if(!findInTransactionCache){ DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction); } }catch (Exception ex) { System.out.println("Error in query member stuff"); } String m = DO.getPROCESS_ID(); if(!QueryBuilder.compare( m, x, cmp_op )) { try { String cacheHandle = DO.get_CacheHandle(); // cacheHits.remove(cacheHandle); cacheHits.removeElementAt( i-- ); } catch (DatabaseManagerException e) { throw new DataObjectException("Error in loading data object's handle."); } } } // for } } // Also prepares the SQL needed to query the database // in case there is no cache, or the query involves other tables. // WebDocWf patch for correct queries in fully cached objects // The following line has been put under comments: // if ( partOrLru || hitDb ) // end of WebDocWf patch for correct queries in fully cached objects builder.addWhere( XPDLParticipantProcessDO.PROCESS_ID, x, cmp_op ); } /** * Set the PROCESS_ID to query, with a QueryBuilder comparison operator. * * @param x The PROCESS_ID of the XPDLParticipantProcess to query. * * @exception DataObjectException If a database access error occurs. * @exception QueryException If comparison operator is inappropriate * (e.g. CASE_SENSITIVE_CONTAINS on an integer field). */ public void setQueryPROCESS_ID(String x) throws DataObjectException, QueryException { setQueryPROCESS_ID(x, QueryBuilder.EQUAL); } /** * Add PROCESS_ID to the ORDER BY clause. * NOTE: The DO cache does not yet support the Order By operation. * Using the addOrderBy method forces the query to hit the database. * * @param direction_flag True for ascending order, false for descending */ public void addOrderByPROCESS_ID(boolean direction_flag) { hitDb = true; builder.addOrderByColumn("PROCESS_ID", (direction_flag) ? "ASC" : "DESC"); } /** * Add PROCESS_ID to the ORDER BY clause. This convenience * method assumes ascending order. * NOTE: The DO cache does not yet support the Order By operation. * Using the addOrderBy method forces the query to hit the database. */ public void addOrderByPROCESS_ID() { hitDb = true; builder.addOrderByColumn("PROCESS_ID","ASC"); } // WebDocWf extension for extended wildcard support // The following lines have been added: /** * Set the PROCESS_ID to query with a user wildcard string * * @param x The PROCESS_ID of the XPDLParticipantProcess to query with user wildcards * * @exception DataObjectException If a database access error occurs. * @exception QueryException If a query error occurs. * * @deprecated Use comparison operators instead * * WebDocWf extension * */ public void setUserMatchPROCESS_ID( String x ) throws DataObjectException, QueryException { String y = convertUserSearchValue( x ); setDBMatchPROCESS_ID( y ); } /** * Set the PROCESS_ID to query with a DB wildcard string * * @param x The PROCESS_ID of the XPDLParticipantProcess to query with DB wildcards * * @exception DataObjectException If a database access error occurs. * @exception QueryException If a query error occurs. * * @deprecated Use comparison operators instead * * WebDocWf extension * */ public void setDBMatchPROCESS_ID(String x ) throws DataObjectException, QueryException { if (containsWildcards(x) || builder.getUserStringAppendWildcard()) { builder.addMatchClause( XPDLParticipantProcessDO.PROCESS_ID, x ); hitDb = true; } else setQueryPROCESS_ID( x, QueryBuilder.EQUAL ); } // end of WebDocWf extension for extended wildcard support /** * Set the PACKAGEOID to query, with a QueryBuilder comparison operator. * * @param x The PACKAGEOID of the XPDLParticipantProcess to query. * @param cmp_op QueryBuilder comparison operator to use. * * @exception DataObjectException If a database access error occurs. * @exception QueryException If comparison operator is inappropriate * (e.g. CASE_SENSITIVE_CONTAINS on an integer field). */ public void setQueryPACKAGEOID(org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO x, String cmp_op ) throws DataObjectException, QueryException { String cachePrefix = getLogicalDatabase()+"."; if(transaction!=null && x!=null && x.get_transaction()!=null) { if(!transaction.equals(x.get_transaction())) throw new DataObjectException("Referenced DO doesn't belong the same transaction."); } if(refs==null) refs = new HashMap(); if(x!=null) refs.put(cachePrefix+x.get_OId(),x); hasNonOidCond = true; cmp_op = fixCaseSensitiveCondition(cmp_op); Condition cond = null; if((x!=null)&& (x instanceof CoreDO)) { CoreDataStruct xDataStruct = (CoreDataStruct)x.get_DataStruct(); cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PACKAGEOID,xDataStruct,cmp_op); } else cond = new Condition(XPDLParticipantProcessDataStruct.COLUMN_PACKAGEOID,x,cmp_op); queryItem.addCond(cond); // WebDocWf extension for extended wildcard support // The following lines have been added: if (cmp_op.equals(QueryBuilder.CASE_INSENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_SENSITIVE_MATCH) || cmp_op.equals(QueryBuilder.USER_CASE_INSENSITIVE_MATCH)) { hitDb = true; } else { // end of WebDocWf extension for extended wildcard support if (XPDLParticipantProcessDO.cache.isFull() && (XPDLParticipantProcessDO.isFullCacheNeeded)) { // Remove from cacheHits any DOs that do not meet this // setQuery requirement. XPDLParticipantProcessDO DO = null; XPDLParticipantProcessDataStruct DS = null; // 12.04.2004 tj // for ( Iterator iter = (new HashSet(cacheHits.values())).iterator(); iter.hasNext();) for ( int i = 0; i < cacheHits.size(); i++ ) { try { boolean findInTransactionCache = false; // DS = (XPDLParticipantProcessDataStruct)iter.next(); DS = (XPDLParticipantProcessDataStruct)cacheHits.elementAt( i ); if(transaction!=null && _tr_(transaction).getTransactionCache()!=null) { DO = (XPDLParticipantProcessDO)_tr_(transaction).getTransactionCache().getDOByHandle(cachePrefix+DS.get_Handle()); if(DO != null) findInTransactionCache = true; } if(!findInTransactionCache){ DO = (XPDLParticipantProcessDO)XPDLParticipantProcessDO.ceInternal(DS.get_OId(), transaction); } }catch (Exception ex) { System.out.println("Error in query member stuff"); } org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO m = DO.getPACKAGEOID(); if(!QueryBuilder.compare( m, x, cmp_op )) { try { String cacheHandle = DO.get_CacheHandle(); // cacheHits.remove(cacheHandle); cacheHits.removeElementAt( i-- ); } catch (DatabaseManagerException e) { throw new DataObjectException("Error in loading data object's handle."); } } } // for } } // Also prepares the SQL needed to query the database // in case there is no cache, or the query involves other tables. // WebDocWf patch for correct queries in fully cached objects // The following line has been put under comments: // if ( partOrLru || hitDb ) // end of WebDocWf patch for correct queries in fully cached objects builder.addWhere( XPDLParticipantProcessDO.PACKAGEOID, x, cmp_op ); } /** * Set the PACKAGEOID to query, with a QueryBuilder comparison operator. * * @param x The PACKAGEOID of the XPDLParticipantProcess to query. * * @exception DataObjectException If a database access error occurs. * @exception QueryException If comparison operator is inappropriate * (e.g. CASE_SENSITIVE_CONTAINS on an integer field). */ public void setQueryPACKAGEOID(org.enhydra.shark.partmappersistence.data.XPDLParticipantPackageDO x) throws DataObjectException, QueryException { setQueryPACKAGEOID(x, QueryBuilder.EQUAL); } /** * Add PACKAGEOID to the ORDER BY clause. * NOTE: The DO cache does not yet support the Order By operation. * Using the addOrderBy method forces the query to hit the database. * * @param direction_flag True for ascending order, false for descending */ public void addOrderByPACKAGEOID(boolean direction_flag) { hitDb = true; builder.addOrderByColumn("PACKAGEOID", (direction_flag) ? "ASC" : "DESC"); } /** * Add PACKAGEOID to the ORDER BY clause. This convenience * method assumes ascending order. * NOTE: The DO cache does not yet support the Order By operation. * Using the addOrderBy method forces the query to hit the database. */ public void addOrderByPACKAGEOID() { hitDb = true; builder.addOrderByColumn("PACKAGEOID","ASC"); } // WebDocWf extension for extended wildcard support // The following lines have been added: // end of WebDocWf extension for extended wildcard support /** * Returns the <code>QueryBuilder</code> that this <code>XPDLParticipantProcessQuery</code> * uses to construct and execute database queries. * <code>XPDLParticipantProcessQuery.setQueryXXX</code> methods use * the <code>QueryBuilder</code> to * append SQL expressions to the <code>"WHERE"</code> clause to be executed. * The <code>QueryBuilder.addEndClause method.</code> can be used to * append freeform SQL expressions to the <code>WHERE</code> clause, * e.g. "ORDER BY name". * * <b>Notes regarding cache-enabled DO classes:</b> * DO classes can be cache-enabled. * If when using a <code>XPDLParticipantProcessQuery</code>, the application developer * <b>does not call</b> <code>getQueryBuilder</code>, * then <code>XPDLParticipantProcessQuery.setQueryXXX</code> methods * simply prune the DO cache and return the remaining results. * However, a <code>QueryBuilder</code> builds * <CODE>SELECT</CODE> statements for execution by the actual database, * and never searches the built-in cache for the DO. * So, if the DO class is cache-enabled, and <code>getQueryBuilder</code> * is called, this <CODE>XPDLParticipantProcessQuery</CODE> object ignores the cache * and hits the actual database. * * @return QueryBuilder that is used to construct and execute database queries. */ public QueryBuilder getQueryBuilder() { hitDb = true; return builder; } /** * Insert an <CODE>OR</CODE> between <CODE>WHERE</CODE> clauses. * Example: find all the persons named Bob or Robert: * <CODE> * PersonQuery pq = new PersonQuery(); * pq.setQueryFirstName( "Bob" ); * pq.or(); * pq.setQueryFirstName( "Robert" ); * </CODE> * * Note: Calls to <CODE>setQueryXxx</CODE> methods * are implicitly <CODE>AND</CODE>ed together, * so the following example will always return nothing: * <CODE> * PersonQuery pq = new PersonQuery(); * pq.setQueryFirstName( "Bob" ); * // AND automatically inserted here. * pq.setQueryFirstName( "Robert" ); * </CODE> * * NOTE: The DO cache does not yet support the OR operator. * Using the or() method forces the query to hit the database. * * @see com.lutris.dods.builder.generator.query.QueryBuilder QueryBuilder to construct more elaborate queries. * author Jay Gunter */ public void or() { hitDb = true; builder.addWhereOr(); } /** * Place an open parenthesis in the <CODE>WHERE</CODE> clause. * Example usage: find all the Bobs and Roberts who are 5 or 50 years old: * <CODE> * PersonQuery pq = new PersonQuery(); * pq.openParen(); * pq.setQueryFirstName( "Bob" ); * pq.or(); * pq.setQueryFirstName( "Robert" ); * pq.closeParen(); * // AND automatically inserted here. * pq.openParen(); * pq.setQueryAge( 5 ); * pq.or(); * pq.setQueryAge( 50 ); * pq.closeParen(); * </CODE> * * NOTE: The DO cache does not yet support the Open Paren operator. * Using the openParen() method forces the query to hit the database. * * @see com.lutris.dods.builder.generator.query.QueryBuilder QueryBuilder to construct more elaborate queries. * author Jay Gunter */ public void openParen() { hitDb = true; builder.addWhereOpenParen(); } /** * Place a closing parenthesis in the <CODE>WHERE</CODE> clause. * * NOTE: The DO cache does not yet support the Close Paren operator. * Using the closeParen() method forces the query to hit the database. * * @see XPDLParticipantProcessQuery#openParen openParen * author Jay Gunter */ public void closeParen() { hitDb = true; builder.addWhereCloseParen(); } }
6bd6348b97d2bb50990f753ed6cbdece77c9b870
f7e6c7070a3ba306d9bd268991c83b7a1acea9c1
/pgpainless-core/src/main/java/org/pgpainless/exception/package-info.java
1d5adbd2b917765bc8b9125e6d03ac80b840e23a
[ "Apache-2.0" ]
permissive
Flowdalic/pgpainless
3f9c77e31193f0629d4b95b4aa87dd8fa7f45313
e9958bc62063be242f6731f88cf4ea0cc3fe01c0
refs/heads/master
2023-08-03T03:32:35.103558
2018-08-03T10:28:25
2018-08-03T10:28:25
139,035,140
0
0
Apache-2.0
2018-06-28T15:13:40
2018-06-28T15:13:40
null
UTF-8
Java
false
false
653
java
/* * Copyright 2018 Paul Schaub. * * 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. */ /** * Exceptions. */ package org.pgpainless.exception;
8a0113e49a89c910917875d48555dd059a50998e
2ff78e0994cb710a619b79659d64d2617cc3e586
/code/RecycleRush/src/frc492/Robot.java
5df4a2ebf49c1a29a9d1f02e84262950bbe6fb4c
[ "MIT" ]
permissive
trc492/Frc2015RecycleRush
d2d662ff8ea653a9f2aad3fe444b98e1800de5e6
302e06aaa89560d20ed34fd89eac05f2d77805bb
refs/heads/master
2021-01-10T01:59:40.009034
2018-05-27T19:32:48
2018-05-27T19:32:48
49,762,591
0
0
null
null
null
null
UTF-8
Java
false
false
19,222
java
package frc492; import com.ni.vision.NIVision; import com.ni.vision.NIVision.*; import edu.wpi.first.wpilibj.BuiltInAccelerometer; import edu.wpi.first.wpilibj.CANTalon; import edu.wpi.first.wpilibj.CameraServer; import edu.wpi.first.wpilibj.Gyro; import edu.wpi.first.wpilibj.SpeedController; import edu.wpi.first.wpilibj.Timer; import frclibj.TrcAnalogInput; import frclibj.TrcDashboard; import frclibj.TrcDbgTrace; import frclibj.TrcDriveBase; import frclibj.TrcKalmanFilter; import frclibj.TrcMotorPosition; import frclibj.TrcPidController; import frclibj.TrcPidDrive; import frclibj.TrcPneumatic; import frclibj.TrcRGBLight; import frclibj.TrcRobot; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the TrcRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the * resource directory. */ public class Robot extends TrcRobot implements TrcMotorPosition, TrcPidController.PidInput { private static final String programName = "RecycleRush"; private static final String moduleName = "Robot"; private static final boolean visionTargetEnabled = false; private static final boolean debugDriveBase = false; private static final boolean debugPidDrive = false; private static final boolean debugPidElevator = false; private static final boolean debugPidSonar = false; private static boolean usbCameraEnabled = false; private TrcDbgTrace dbgTrace = null; // public static boolean competitionRobot = true; // // Sensors // private BuiltInAccelerometer accelerometer; private TrcKalmanFilter accelXFilter; private TrcKalmanFilter accelYFilter; private TrcKalmanFilter accelZFilter; public double robotTilt; // // DriveBase subsystem. // public Gyro gyro; public CANTalon leftFrontMotor; public CANTalon leftRearMotor; public CANTalon rightFrontMotor; public CANTalon rightRearMotor; public TrcDriveBase driveBase; public TrcPidController xPidCtrl; public TrcPidController yPidCtrl; public TrcPidController turnPidCtrl; public TrcPidDrive pidDrive; public TrcPidController sonarPidCtrl; public TrcPidDrive sonarPidDrive; // // Define our subsystems for Auto and TeleOp modes. // public Elevator elevator; public TrcPneumatic lowerGrabber; public TrcPneumatic upperGrabber; public TrcPneumatic pusher; public TrcRGBLight rgbLight; public TrcPneumatic leftHook; public TrcPneumatic rightHook; public Harpoon harpoon; // // Vision target subsystem. // public VisionTarget visionTarget = null; // // Camera subsystem. // private CameraServer cameraServer = null; private int usbCamSession = -1; private Image usbCamImage = null; private double nextCaptureTime = Timer.getFPGATimestamp(); private static final String targetLeftKey = "Target Left"; private static final String targetRightKey = "Target Right"; private static final String targetTopKey = "Target Top"; private static final String targetBottomKey = "TargetBottom"; private static int targetLeft = 170; private static int targetRight = 520; private static int targetTop = 130; private static int targetBottom = 440; private static Rect targetRect = new Rect(targetTop, targetLeft, targetBottom - targetTop, targetRight - targetLeft); // // Robot Modes. // private RobotMode teleOpMode; private RobotMode autoMode; private RobotMode testMode; // // Ultrasonic subsystem (has a dependency on teleOpMode). // public TrcAnalogInput ultrasonic; private TrcKalmanFilter sonarFilter; public double sonarDistance; private static final String dispenserDistanceKey = "Dispenser Distance"; public double dispenserDistance = 26.0; /** * Constructor. */ public Robot() { super(programName); dbgTrace = new TrcDbgTrace( moduleName, false, TrcDbgTrace.TraceLevel.API, TrcDbgTrace.MsgLevel.INFO); } //Robot /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { final String funcName = "robotInit"; // // Sensors. // accelerometer = new BuiltInAccelerometer(); accelXFilter = new TrcKalmanFilter(); accelYFilter = new TrcKalmanFilter(); accelZFilter = new TrcKalmanFilter(); // // DriveBase subsystem. // gyro = new Gyro(RobotInfo.AIN_GYRO); leftFrontMotor = new CANTalon(RobotInfo.CANID_LEFTFRONTMOTOR); leftRearMotor = new CANTalon(RobotInfo.CANID_LEFTREARMOTOR); rightFrontMotor = new CANTalon(RobotInfo.CANID_RIGHTFRONTMOTOR); rightRearMotor = new CANTalon(RobotInfo.CANID_RIGHTREARMOTOR); // // Initialize each drive motor controller. // leftFrontMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); leftRearMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); rightFrontMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); rightRearMotor.setFeedbackDevice(CANTalon.FeedbackDevice.QuadEncoder); leftFrontMotor.reverseSensor(RobotInfo.LEFTFRONTMOTOR_INVERTED); leftRearMotor.reverseSensor(RobotInfo.LEFTREARMOTOR_INVERTED); rightFrontMotor.reverseSensor(RobotInfo.RIGHTFRONTMOTOR_INVERTED); rightRearMotor.reverseSensor(RobotInfo.RIGHTREARMOTOR_INVERTED); // // Reset encoders. // leftFrontMotor.setPosition(0.0); leftRearMotor.setPosition(0.0); rightFrontMotor.setPosition(0.0); rightRearMotor.setPosition(0.0); // // Initialize DriveBase subsystem. // driveBase = new TrcDriveBase( leftFrontMotor, leftRearMotor, rightFrontMotor, rightRearMotor, this, gyro); driveBase.setInvertedMotor( TrcDriveBase.MotorType.kFrontLeft, RobotInfo.LEFTFRONTMOTOR_INVERTED); driveBase.setInvertedMotor( TrcDriveBase.MotorType.kRearLeft, RobotInfo.LEFTREARMOTOR_INVERTED); driveBase.setInvertedMotor( TrcDriveBase.MotorType.kFrontRight, RobotInfo.RIGHTFRONTMOTOR_INVERTED); driveBase.setInvertedMotor( TrcDriveBase.MotorType.kRearRight, RobotInfo.RIGHTREARMOTOR_INVERTED); // // Create PID controllers for DriveBase PID drive. // xPidCtrl = new TrcPidController( "xPidCtrl", RobotInfo.X_KP, RobotInfo.X_KI, RobotInfo.X_KD, RobotInfo.X_KF, RobotInfo.X_TOLERANCE, RobotInfo.X_SETTLING, this, 0); yPidCtrl = new TrcPidController( "yPidCtrl", RobotInfo.Y_KP, RobotInfo.Y_KI, RobotInfo.Y_KD, RobotInfo.Y_KF, RobotInfo.Y_TOLERANCE, RobotInfo.Y_SETTLING, this, 0); turnPidCtrl = new TrcPidController( "turnPidCtrl", RobotInfo.TURN_KP, RobotInfo.TURN_KI, RobotInfo.TURN_KD, RobotInfo.TURN_KF, RobotInfo.TURN_TOLERANCE, RobotInfo.TURN_SETTLING, this, 0); pidDrive = new TrcPidDrive( "pidDrive", driveBase, xPidCtrl, yPidCtrl, turnPidCtrl); sonarPidCtrl = new TrcPidController( "sonarPidCtrl", RobotInfo.SONAR_KP, RobotInfo.SONAR_KI, RobotInfo.SONAR_KD, RobotInfo.SONAR_KF, RobotInfo.SONAR_TOLERANCE, RobotInfo.SONAR_SETTLING, this, (TrcPidController.PIDCTRLO_ABS_SETPT | TrcPidController.PIDCTRLO_INVERTED)); sonarPidDrive = new TrcPidDrive( "sonarPidDrive", driveBase, xPidCtrl, sonarPidCtrl, turnPidCtrl); // // Elevator subsystem. // elevator = new Elevator(); // // Grabber subsystem. // if (RobotInfo.ENABLE_LOWER_GRABBER) { lowerGrabber = new TrcPneumatic( "lowerGrabber", RobotInfo.CANID_PCM, RobotInfo.SOL_LOWERGRABBER_EXTEND, RobotInfo.SOL_LOWERGRABBER_RETRACT); } else { lowerGrabber = null; } if (RobotInfo.ENABLE_UPPER_GRABBER) { upperGrabber = new TrcPneumatic( "upperGrabber", RobotInfo.CANID_PCM, RobotInfo.SOL_UPPERGRABBER_EXTEND, RobotInfo.SOL_UPPERGRABBER_RETRACT); } else { upperGrabber = null; } // // Pusher subsystem. // if (RobotInfo.ENABLE_PUSHER) { pusher = new TrcPneumatic( "pusher", RobotInfo.CANID_PCM, RobotInfo.SOL_PUSHER_EXTEND); } else { pusher = null; } // // RGB LED light // if (RobotInfo.ENABLE_LEDS) { rgbLight = new TrcRGBLight( "rgbLight", RobotInfo.CANID_PCM, RobotInfo.SOL_LED_RED, RobotInfo.SOL_LED_GREEN, RobotInfo.SOL_LED_BLUE); } else { rgbLight = null; } // // Hook subsystem. // if (RobotInfo.ENABLE_CAN_HOOKS) { leftHook = new TrcPneumatic( "leftHook", RobotInfo.CANID_PCM, RobotInfo.SOL_LEFTHOOK_EXTEND, RobotInfo.SOL_LEFTHOOK_RETRACT); rightHook = new TrcPneumatic( "rightHook", RobotInfo.CANID_PCM, RobotInfo.SOL_RIGHTHOOK_EXTEND, RobotInfo.SOL_RIGHTHOOK_RETRACT); } else { leftHook = null; rightHook = null; } // // Harpoon subsystem. // if (RobotInfo.ENABLE_HARPOONS) { harpoon = new Harpoon(); } else { harpoon = null; } // // Vision subsystem. // if (visionTargetEnabled) { visionTarget = new VisionTarget(); } else { visionTarget = null; } // // Camera subsystem for streaming. // if (usbCameraEnabled) { try { usbCamSession = NIVision.IMAQdxOpenCamera( RobotInfo.USB_CAM_NAME, IMAQdxCameraControlMode.CameraControlModeController); NIVision.IMAQdxConfigureGrab(usbCamSession); NIVision.IMAQdxStartAcquisition(usbCamSession); usbCamImage = NIVision.imaqCreateImage(ImageType.IMAGE_RGB, 0); cameraServer = CameraServer.getInstance(); cameraServer.setQuality(30); } catch (Exception e) { usbCameraEnabled = false; dbgTrace.traceWarn( funcName, "Failed to open USB camera, disable it!"); } } // // Robot Modes. // teleOpMode = new TeleOp(this); autoMode = new Autonomous(this); testMode = new Test(); setupRobotModes(teleOpMode, autoMode, testMode, null); ultrasonic = new TrcAnalogInput( "frontSonar", RobotInfo.AIN_ULTRASONIC, RobotInfo.ULTRASONIC_INCHESPERVOLT, dispenserDistance - 1.0, dispenserDistance + 1.0, 0, (TrcAnalogInput.AnalogEventHandler)teleOpMode); sonarFilter = new TrcKalmanFilter(); dispenserDistance = TrcDashboard.getNumber(dispenserDistanceKey, dispenserDistance); } //robotInit public void updateDashboard() { // // Sensor info. // sonarDistance = sonarFilter.filter(ultrasonic.getData()); TrcDashboard.putNumber("Sonar Distance", sonarDistance); double xAccel = accelXFilter.filter(accelerometer.getX()); double yAccel = accelYFilter.filter(accelerometer.getY()); double zAccel = accelZFilter.filter(accelerometer.getZ()); TrcDashboard.putNumber("Accel-X", xAccel); TrcDashboard.putNumber("Accel-Y", yAccel); TrcDashboard.putNumber("Accel-Z", zAccel); robotTilt = zAccel; if (yAccel < 0.0) { robotTilt = -robotTilt; } robotTilt = 180.0*Math.asin(robotTilt)/Math.PI; TrcDashboard.putNumber("Tilt", robotTilt); // // Elevator info. // TrcDashboard.putNumber( "Elevator Height", elevator.getHeight()); TrcDashboard.putBoolean( "LowerLimitSW", !elevator.isLowerLimitSwitchActive()); TrcDashboard.putBoolean( "UpperLimitSW", !elevator.isUpperLimitSwitchActive()); // // USB camera streaming. // if (usbCameraEnabled && Timer.getFPGATimestamp() >= nextCaptureTime) { // // Capture at 10fps. // nextCaptureTime = Timer.getFPGATimestamp() + 0.1; NIVision.IMAQdxGrab(usbCamSession, usbCamImage, 1); targetLeft = (int) TrcDashboard.getNumber(targetLeftKey, targetLeft); targetRight = (int) TrcDashboard.getNumber(targetRightKey, targetRight); targetTop = (int) TrcDashboard.getNumber(targetTopKey, targetTop); targetBottom = (int) TrcDashboard.getNumber(targetBottomKey, targetBottom); targetRect.left = targetLeft; targetRect.top = targetTop; targetRect.width = targetRight - targetLeft; targetRect.height = targetBottom - targetTop; NIVision.imaqDrawShapeOnImage( usbCamImage, usbCamImage, targetRect, DrawMode.DRAW_VALUE, ShapeMode.SHAPE_RECT, (float)0x0); cameraServer.setImage(usbCamImage); } if (debugDriveBase) { // // DriveBase debug info. // TrcDashboard.textPrintf( 1, "LFEnc=%8.0f, RFEnc=%8.0f", leftFrontMotor.getPosition(), rightFrontMotor.getPosition()); TrcDashboard.textPrintf( 2, "LREnc=%8.0f, RREnc=%8.0f", leftRearMotor.getPosition(), rightRearMotor.getPosition()); TrcDashboard.textPrintf( 3, "XPos=%6.1f, YPos=%6.1f, Heading=%6.1f", driveBase.getXPosition()*RobotInfo.XDRIVE_INCHES_PER_CLICK, driveBase.getYPosition()*RobotInfo.YDRIVE_INCHES_PER_CLICK, driveBase.getHeading()); TrcDashboard.textPrintf( 4, "Ultrasonic=%5.1f", sonarDistance); } else if (debugPidDrive) { xPidCtrl.displayPidInfo(1); yPidCtrl.displayPidInfo(3); turnPidCtrl.displayPidInfo(5); } else if (debugPidElevator) { // // Elevator debug info. // TrcDashboard.textPrintf( 1, "ElevatorHeight=%5.1f", elevator.getHeight()); TrcDashboard.textPrintf( 2, "LowerLimit=%s, UpperLimit=%s", Boolean.toString(elevator.isLowerLimitSwitchActive()), Boolean.toString(elevator.isUpperLimitSwitchActive())); elevator.displayDebugInfo(3); } else if (debugPidSonar) { xPidCtrl.displayPidInfo(1); sonarPidCtrl.displayPidInfo(3); turnPidCtrl.displayPidInfo(5); } } //updateDashboard // // Implements TrcDriveBase.MotorPosition. // public double getMotorPosition(SpeedController speedController) { return ((CANTalon)speedController).getPosition(); } //getMotorPosition public double getMotorSpeed(SpeedController speedController) { return ((CANTalon)speedController).getSpeed()*10.0; } //getMotorSpeed public void resetMotorPosition(SpeedController speedController) { ((CANTalon)speedController).setPosition(0.0); } //resetMotorPosition public void reversePositionSensor( SpeedController speedController, boolean flip) { ((CANTalon)speedController).reverseSensor(flip); } //reversePositionSensor public boolean isForwardLimitSwitchActive(SpeedController speedController) { // // There is no limit switches on the DriveBase. // return false; } //isForwardLimitSwitchActive public boolean isReverseLimitSwitchActive(SpeedController speedController) { // // There is no limit switches on the DriveBase. // return false; } //isReverseLimitSwitchActive // // Implements TrcPidController.PidInput. // public double getInput(TrcPidController pidCtrl) { double value = 0.0; if (pidCtrl == xPidCtrl) { value = driveBase.getXPosition()*RobotInfo.XDRIVE_INCHES_PER_CLICK; } else if (pidCtrl == yPidCtrl) { value = driveBase.getYPosition()*RobotInfo.YDRIVE_INCHES_PER_CLICK; } else if (pidCtrl == turnPidCtrl) { value = gyro.getAngle(); } else if (pidCtrl == sonarPidCtrl) { value = sonarDistance; } return value; } //getInput } //class Robot
e2fd56cdbd0ecfc5a6529eb7a9646fb4d7877a80
1ac3fe76f01fbaaa8303d7ce3def6b4d0a8b546c
/Tag_Content_Extractor.java
2e5914d96afdeaed109687e7521f4021488e95a1
[]
no_license
manish160993/HackerrankPrograms
63592eee912ba539e62e2c0ea56c06ce0509ae57
18a87f4ed4e94ba2729b8eb9c6ac32d1ddd3099a
refs/heads/master
2021-05-13T14:34:12.478000
2018-01-22T18:08:38
2018-01-22T18:08:38
116,744,644
0
0
null
null
null
null
UTF-8
Java
false
false
2,411
java
/* In a tag-based language like XML or HTML, contents are enclosed between a start tag and an end tag like <tag>contents</tag>. Note that the corresponding end tag starts with a /. Given a string of text in a tag-based language, parse this text and retrieve the contents enclosed within sequences of well-organized tags meeting the following criterion: The name of the start and end tags must be same. The HTML code <h1>Hello World</h2> is not valid, because the text starts with an h1 tag and ends with a non-matching h2 tag. Tags can be nested, but content between nested tags is considered not valid. For example, in <h1><a>contents</a>invalid</h1>, contents is valid but invalid is not valid. Tags can consist of any printable characters. Input Format The first line of input contains a single integer, (the number of lines). The subsequent lines each contain a line of text. Constraints Each line contains a maximum of printable characters. The total number of characters in all test cases will not exceed . Output Format For each line, print the content enclosed within valid tags. If a line contains multiple instances of valid content, print out each instance of valid content on a new line; if no valid content is found, print None. Sample Input 4 <h1>Nayeem loves counseling</h1> <h1><h1>Sanjay has no watch</h1></h1><par>So wait for a while</par> <Amee>safat codes like a ninja</amee> <SA premium>Imtiaz has a secret crush</SA premium> Sample Output Nayeem loves counseling Sanjay has no watch So wait for a while None Imtiaz has a secret crush */ import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; /* Solution assumes we can't have the symbol "<" as text between tags */ public class Tag_Content_Extractor{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); int testCases = Integer.parseInt(scan.nextLine()); while (testCases-- > 0) { String line = scan.nextLine(); boolean matchFound = false; Pattern r = Pattern.compile("<(.+)>([^<]+)</\\1>"); Matcher m = r.matcher(line); while (m.find()) { System.out.println(m.group(2)); matchFound = true; } if ( ! matchFound) { System.out.println("None"); } } } }
50aae703061fdb87796744350c5924db1e6dcfe3
6e349f85c52df72d9ce48167b3767e84317cf610
/src/main/java/com/expense/manager/web/RegistrationController.java
e1f9541723734e562347a8082e35000241a82ee9
[]
no_license
MichalPietrus/Home-Expense-Manager
6cbf465ef2781aa09879daeae25ec5c03ddfcacc
fe656021e1c069e0624f1a0f4627bcd08bc7b94d
refs/heads/master
2023-01-31T03:25:39.264745
2020-12-14T13:30:16
2020-12-14T13:30:16
295,426,703
0
1
null
2020-09-22T12:12:09
2020-09-14T13:35:30
HTML
UTF-8
Java
false
false
1,544
java
package com.expense.manager.web; import com.expense.manager.model.User; import com.expense.manager.service.UserService; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import javax.validation.Valid; @Controller @RequestMapping("/registration") public class RegistrationController { private final UserService userService; public RegistrationController(UserService userService) { this.userService = userService; } @ModelAttribute("user") public User userRegistrationModel() { return new User(); } @GetMapping public String showRegistrationForm() { return "registration"; } @PostMapping public String registerUserAccount(@ModelAttribute("user") @Valid User user, BindingResult result) { User existingByUserNameOrEmail = userService.findByUsernameOrEmail(user.getUsername(), user.getEmail()); if (existingByUserNameOrEmail != null) result.rejectValue("username", null, "There is already an account registered with that username or email"); if (result.hasErrors()) return "registration"; userService.registerUser(user); return "redirect:/registration?success"; } }
db514262a384ded966ce770bc2daf0a795eb0774
f4dfe52bd506f1508637f23f1d9822c659891c12
/PROFILING/CPUProfiling/src/main/java/com/lowagie/examples/objects/tables/DefaultCell.java
1320f6ef842f01c266295c4786687d0e332803a9
[]
no_license
siddhantaws/LowLatency
5b27b99b8fbe3a98029ca42f636b49d870a0b3bb
f245916fed8bfe5a038dc21098d813bf5accdb1e
refs/heads/master
2021-06-25T19:55:07.994337
2019-09-19T15:39:15
2019-09-19T15:39:15
152,133,438
0
0
null
2020-10-13T16:09:28
2018-10-08T19:17:54
Java
UTF-8
Java
false
false
2,330
java
/* * $Id: DefaultCell.java,v 1.3 2005/05/09 11:52:47 blowagie Exp $ * $Name: $ * * This code is part of the 'iText Tutorial'. * You can find the complete tutorial at the following address: * http://itextdocs.lowagie.com/tutorial/ * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * [email protected] */ package com.lowagie.examples.objects.tables; import java.awt.Color; import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; /** * A very simple PdfPTable example using getDefaultCell(). */ public class DefaultCell { /** * Demonstrates the use of getDefaultCell(). * * @param args * no arguments needed */ public static void main(String[] args) { System.out.println("DefaultCell"); // step 1: creation of a document-object Document document = new Document(); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter.getInstance(document, new FileOutputStream("DefaultCell.pdf")); // step 3: we open the document document.open(); PdfPTable table = new PdfPTable(3); PdfPCell cell = new PdfPCell(new Paragraph("header with colspan 3")); cell.setColspan(3); table.addCell(cell); table.addCell("1.1"); table.addCell("2.1"); table.addCell("3.1"); table.getDefaultCell().setGrayFill(0.8f); table.addCell("1.2"); table.addCell("2.2"); table.addCell("3.2"); table.getDefaultCell().setGrayFill(0f); table.getDefaultCell().setBorderColor(new Color(255, 0, 0)); table.addCell("cell test1"); table.getDefaultCell().setColspan(2); table.getDefaultCell().setBackgroundColor(new Color(0xC0, 0xC0, 0xC0)); table.addCell("cell test2"); document.add(table); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } // step 5: we close the document document.close(); } }
7446dbb5c6b1eb81b285aed1e6835b153e56f826
e1450a329c75a55cf6ccd0ce2d2f3517b3ee51c5
/src/main/java/home/javarush/javaCore/task12/task1228/Solution.java
96fb4c4c65a0a6cb247ad1158a95b9283a4ed43f
[]
no_license
nikolaydmukha/netology-java-base-java-core
afcf0dd190f4c912c5feb2ca8897bc17c09a9ec1
eea55c27bbbab3b317c3ca5b0719b78db7d27375
refs/heads/master
2023-03-18T13:33:24.659489
2021-03-25T17:31:52
2021-03-25T17:31:52
326,259,412
0
0
null
null
null
null
UTF-8
Java
false
false
732
java
package home.javarush.javaCore.task12.task1228; /* Интерфейсы к классу Human */ public class Solution { public static void main(String[] args) { Human human = new Human(); System.out.println(human); } public static interface Worker { public void workLazy(); } public static interface Businessman { public void workHard(); } public static interface Secretary { public void workLazy(); } public static interface Miner { public void workVeryHard(); } public static class Human implements Worker, Secretary, Businessman{ public void workHard() { } public void workLazy() { } } }
705e7ff038c2bbf52bc41c37bb02e164dd4479a4
60f47552491c36429b09fdc8909ff04553503049
/src/com/denghj/jdk_8/stream/stream基本操作/TestStreamApi01.java
783b592f8ba8b3c7657bdf96ea834751c2ac31cc
[]
no_license
denghuaijun/java_se
f5ad737e25b0191fdb358acb166146838e7c63c4
f52cac0506a268328282c922ba5eea8cf1250f6a
refs/heads/master
2023-06-19T01:45:52.152802
2021-07-15T07:24:21
2021-07-15T07:24:21
327,215,887
0
0
null
null
null
null
UTF-8
Java
false
false
1,421
java
package com.denghj.jdk_8.stream.stream基本操作; import com.denghj.jdk_8.lambda.基本语法.Employee; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; /** * 一、Stream 三大操作步骤: * 1. 创建stream * 2.中间操作:即流水线操作 将数据源(集合、数组)的数据经过一系列的中间操作 * 3.终止操作:获取stream流所持有的结果 */ public class TestStreamApi01 { //1、测试 创建stream对象 共四种方式 @Test public void createStream(){ //方式1、通过Collection中的stream()方法创建 List<Employee> employeeList = new ArrayList<>(); //employeeList.parallelStream()创建并行流,默认为串行流 Stream<Employee> stream = employeeList.stream(); //方式2、通过Stream api中的静态方法of() Stream<String> stringStream = Stream.of("a", "b", "c"); stringStream.forEach(System.out::println); //方式3、通过Arrays中的静态方法stream()获取数组流 Stream<Employee> employeeStream = Arrays.stream(new Employee[10]); //方式4、创建无限流 //无限流1:无限迭代 Stream<Integer> iterate = Stream.iterate(0, x -> x + 2); //无线流2:产生数据 Stream<Double> generate = Stream.generate(Math::random); } }
b9fbf4ed61795ef0442ad2e855d388f9611cb091
15fc89df8102eec0af46cb3b1cb0aef95f3a02fe
/app/src/main/java/com/example/jdong/view/IFenLeiView.java
51d7cef38fb4c83c2337c8a1a0935a6850c88c97
[]
no_license
Shenxiaoyang1/JDong
d55bc87228daab946c57278ca4bec10c6a8eaf3e
9b7149198dbb9d58c69dc721ac4f99b7d7c14eda
refs/heads/master
2021-08-31T10:57:53.739933
2017-12-21T03:52:18
2017-12-21T03:52:18
114,960,125
0
0
null
null
null
null
UTF-8
Java
false
false
241
java
package com.example.jdong.view; import com.example.jdong.bean.FenLeiBean; import java.util.List; /** * Created by 刘雅文 on 2017/12/15. */ public interface IFenLeiView { public void show(List<FenLeiBean.DataBean> fenLeiBean); }
f57f00c4712b38766c44bbf4c4e5eae380e34ae9
97cda285663a8bbf751b39321b695d97b6f69474
/Wicket/src/wicket/util/diff/RevisionVisitor.java
175c2c5cafe98fbc76c6cf1232f7a6a00a6eae8e
[]
no_license
clustercompare/clustercompare-data
838c4de68645340546dd5e50b375dcf877591b3e
163d05bdc5f4a03da8155ffb1f922a9421733589
refs/heads/master
2020-12-25T23:10:16.331657
2015-12-11T10:37:43
2015-12-11T10:37:43
39,699,972
0
0
null
null
null
null
UTF-8
Java
false
false
3,257
java
/* * ==================================================================== * * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2003 The Apache Software Foundation. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. The names "The Jakarta Project", "Commons", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package wicket.util.diff; /** * Definition of a Visitor interface for {@link Revision Revisions} See "Design * Patterns" by the Gang of Four */ public interface RevisionVisitor { /** * @param revision */ public void visit(Revision revision); /** * @param delta */ public void visit(DeleteDelta delta); /** * @param delta */ public void visit(ChangeDelta delta); /** * @param delta */ public void visit(AddDelta delta); }
dd5ecea78375c1f885bde40f7b677c97daaf9463
a456b9726eda22e414d0f7ce16206760a7a94f8a
/src/com/example/qrboard/ExploreActivity.java
a62b775741dd6dfc4344393a88f6281b0ad6ad8f
[]
no_license
lorenzoviva/QRBoard
4876a8d31c00b71a4745981d62677d77f4d9e2a5
0519a98ffd854a780a4ac8dd3739b60b44e5ec4d
refs/heads/master
2016-09-10T10:38:05.535477
2015-12-09T23:27:23
2015-12-09T23:27:23
42,772,088
0
0
null
null
null
null
UTF-8
Java
false
false
10,061
java
package com.example.qrboard; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class ExploreActivity extends Activity implements InvalidableAcivity, OnTouchListener { QRExplorer explorer; ActivityInvalidator invalidator; RelativeLayout instructionLayout; private int instructionIndex; private List<TextView> instructions; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT < 16) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_FULLSCREEN); } setContentView(R.layout.activity_explore); explorer = (QRExplorer) findViewById(R.id.qr_explorer); instructionLayout = (RelativeLayout) findViewById(R.id.explore_instruction_layout); invalidator = new ActivityInvalidator(this); explorer.setExploreButton((Button) findViewById(R.id.explorerbutton)); explorer.setEditImageInfo((ImageView) findViewById(R.id.explorereditifoimage)); explorer.setEditTextInfo((TextView) findViewById(R.id.explorereditifo)); explorer.setBackButton((Button) findViewById(R.id.explorequitbutton)); explorer.setReadButton((Button) findViewById(R.id.explorereadbutton)); if (getIntent().hasExtra("response")) { String jsonresponse = getIntent().getStringExtra("response"); setup(jsonresponse); } explorer.setInstructing(true); if (isNotFirstTime()) { instructionLayout.setVisibility(View.INVISIBLE); explorer.setInstructing(false); }else{ // } setupInstructions(); } } private void setupInstructions(){ DisplayMetrics metrics = getResources().getDisplayMetrics(); int width = metrics.widthPixels; int height = metrics.heightPixels; float d = metrics.density; // Log.d("EXPLORER", "bottom: "+ height + " right :" + width + " mw:" + instructionLayout.getMeasuredWidth()); instructionIndex = 1; instructions = new ArrayList<TextView>(); instructions.add((TextView) findViewById(R.id.explorer_instructiontextView0)); instructions.add((TextView) findViewById(R.id.explorer_instructiontextView1)); TextView tv2 = (TextView) findViewById(R.id.explorer_instructiontextView2); Drawable freccia = getResources().getDrawable(R.drawable.arrowright); tv2.measure(0, 0); freccia.setBounds(0, 0, tv2.getMeasuredWidth(), tv2.getMeasuredWidth()); tv2.setCompoundDrawables(null, null, null, freccia); instructions.add(tv2); TextView tv3 = (TextView) findViewById(R.id.explorer_instructiontextView3); RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params1.setMargins((width/5)*2, (width/12), 0, 0); tv3.setLayoutParams(params1); Drawable row = getResources().getDrawable(R.drawable.instructionrow); row.setBounds(0, 0, (width*3)/5, (width*17)/60); tv3.setCompoundDrawables(null, row, null, null); instructions.add(tv3); TextView tv4 = (TextView) findViewById(R.id.explorer_instructiontextView4); RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params2.setMargins((width/5)*4, (width/12), 0, 0); tv4.setLayoutParams(params2); Drawable cell = getResources().getDrawable(R.drawable.instructioncell); cell.setBounds(0, 0, (width)/5, (width*17)/60); tv4.setCompoundDrawables(null, cell, null, null); instructions.add(tv4); TextView tv5 = (TextView) findViewById(R.id.explorer_instructiontextView5); RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params3.setMargins((width/5)*3, (width/12), (width/5), 0); tv5.setLayoutParams(params3); tv5.setCompoundDrawables(null, cell, null, null); instructions.add(tv5); TextView tv6 = (TextView) findViewById(R.id.explorer_instructiontextView6); RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params4.setMargins((width/5), (width/12), (width/5), 0); tv6.setLayoutParams(params4); tv6.setCompoundDrawables(null, cell, null, null); instructions.add(tv6); TextView tv7 = (TextView) findViewById(R.id.explorer_instructiontextView7); RelativeLayout.LayoutParams params5 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params5.setMargins((width/10), (height/10), 0, 0); tv7.setLayoutParams(params5); Drawable focused = getResources().getDrawable(R.drawable.instructionfocused); focused.setBounds(0, 0, (width*17)/60,(width)/5 ); tv7.setCompoundDrawables(focused, null, null, null); instructions.add(tv7); TextView tv8 = (TextView) findViewById(R.id.explorer_instructiontextView8); RelativeLayout.LayoutParams params6 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params6.setMargins((3*width/10), (height/5) + (width/5)+120, 0, 0); tv8.setLayoutParams(params6); Drawable arrowleft = getResources().getDrawable(R.drawable.arrowleft); arrowleft.setBounds(0,0 ,(width/5),(width)/20); tv8.setCompoundDrawables(arrowleft, null, null, null); instructions.add(tv8); TextView tv9 = (TextView) findViewById(R.id.explorer_instructiontextView9); RelativeLayout.LayoutParams params7 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params7.setMargins((3*width/10), (height/5) + (width/5), 0, 0); tv9.setLayoutParams(params7); Drawable arrowleftbig = getResources().getDrawable(R.drawable.arrowleftbig); arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5); tv9.setCompoundDrawables(arrowleftbig, null,null , null); instructions.add(tv9); TextView tv10 = (TextView) findViewById(R.id.explorer_instructiontextView10); RelativeLayout.LayoutParams params8 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params8.setMargins((3*width/10), (height/5) + (width/5), 0, 0); tv10.setLayoutParams(params8); arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5); tv10.setCompoundDrawables(arrowleftbig, null, null, null); instructions.add(tv10); TextView tv11 = (TextView) findViewById(R.id.explorer_instructiontextView11); RelativeLayout.LayoutParams params9 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params9.setMargins((3*width/10), (height/5) + (width/5), 0, 0); tv11.setLayoutParams(params9); arrowleftbig.setBounds(0, 0 ,(width/5),(width)/5); tv11.setCompoundDrawables(arrowleftbig, null, null, null); instructions.add(tv11); TextView tv12 = (TextView) findViewById(R.id.explorer_instructiontextView12); RelativeLayout.LayoutParams param10 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); param10.setMargins((3*width/10), (height/5) + (width/5)+60, 0, 0); tv12.setLayoutParams(param10); // arrowleft.setBounds(0, 0 ,(width/5),(width)/5); tv12.setCompoundDrawables(arrowleft, null, null, null); instructions.add(tv12); TextView tv13 = (TextView) findViewById(R.id.explorer_instructiontextView13); RelativeLayout.LayoutParams param11 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); param11.setMargins((width/10), (height/10), 0, 0); tv13.setLayoutParams(param11); tv13.setCompoundDrawables(focused, null, null, null); instructions.add(tv13); } private void setup(String jsonresponse) { explorer.setup(jsonresponse); } private boolean isNotFirstTime() { SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); boolean ranBefore = preferences.getBoolean("exploreInstruction", false); // if (!ranBefore) { SharedPreferences.Editor editor = preferences.edit(); editor.putBoolean("exploreInstruction", true); editor.commit(); instructionLayout.setVisibility(View.VISIBLE); instructionLayout.setOnTouchListener(this); // } return ranBefore; } @Override public boolean onTouch(View v, MotionEvent event) { instructionIndex++; if(instructionIndex>=instructions.size()){ instructionLayout.setVisibility(View.GONE); explorer.setInstructing(false); }else{ for(int i = 1; i< instructions.size(); i++){ if(i!=instructionIndex){ instructions.get(i).setVisibility(View.INVISIBLE); }else{ instructions.get(i).setVisibility(View.VISIBLE); } } } return false; } @Override public void invalidate() { if (explorer.getArgui().isRefreshExplorer()) { explorer.refresh(); } explorer.postInvalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { if(!explorer.isInstructing()){ explorer.onTouchEvent(event); } return false; } @Override public void onBackPressed() { gotoScanActivity(); } public void gotoScanActivity() { Intent intent = new Intent(getApplicationContext(), ScanActivity.class); intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE"); startActivityForResult(intent, 0); } }
38feb916679b6e122e1baea2ed8505e32d80643e
b92e7c1bbfbf09f74aa32c70d50bdf99b0f5aa20
/RunamicGhent/mobile/src/main/java/com/dp16/runamicghent/Constants.java
b6ab921c6735899095520048fb10817a926cc0a9
[ "MIT" ]
permissive
oSoc17/lopeningent_android
57f44ffdd29448604fb9f17dffb50b49fbb8203e
382278767ed317503945981838024055c020db06
refs/heads/master
2020-12-02T20:55:17.804823
2017-07-26T09:25:11
2017-07-26T09:25:11
96,228,367
3
0
null
null
null
null
UTF-8
Java
false
false
14,831
java
/* * Copyright (c) 2017 Hendrik Depauw * Copyright (c) 2017 Lorenz van Herwaarden * Copyright (c) 2017 Nick Aelterman * Copyright (c) 2017 Olivier Cammaert * Copyright (c) 2017 Maxim Deweirdt * Copyright (c) 2017 Gerwin Dox * Copyright (c) 2017 Simon Neuville * Copyright (c) 2017 Stiaan Uyttersprot * * This software may be modified and distributed under the terms of the MIT license. See the LICENSE file for details. */ package com.dp16.runamicghent; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import java.util.Objects; /** * Class containing public static final constants used throughout the application. * All classes have private constructor, because these classes only contain values. * Created by hendrikdepauw on 01/03/2017. */ public class Constants { // Is this a debug environment? public static final Boolean DEVELOP = true; private static final String UTILITY_CLASS_ERROR = "Utility Class"; /** * Server configuration constants. */ public class Server { public static final String ADDRESS = "groep16.cammaert.me"; public static final String MONGOPORT = "27017"; private Server() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Smoothing toggle. */ public class Smoothing { public static final boolean SMOOTHING_ENABLED = true; private Smoothing() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for setting keys */ public class SettingTypes { public static final String PREF_KEY_DEBUG_LOCATION_MOCK = "pref_key_debug_location_mock"; public static final String PREF_KEY_DEBUG_FAKE_LATLNG_LOCATIONPROVIDER = "pref_key_debug_fake_latlng_locationprovider"; public static final String PREF_KEY_DEBUG_ROUTE_SMOOTHER = "pref_key_debug_route_smoother"; public static final String PREF_KEY_ROUTING_PARK = "pref_key_dynamic_park"; public static final String PREF_KEY_ROUTING_WATER = "pref_key_dynamic_water"; public static final String PREF_KEY_AUDIO_DIRECTIONS = "pref_key_audio_directions"; public static final String PREF_KEY_AUDIO_CUSTOM_SOUND = "pref_key_audio_custom_sound"; public static final String PREF_KEY_AUDIO_LEFT_RIGHT_CHANNEL = "pref_key_audio_left_right_channel"; public static final String USER_WENT_THROUGH_TOURGUIDE_START = "user_went_through_tourguide_start"; public static final String USER_WENT_THROUGH_TOURGUIDE_HISTORY = "user_went_through_tourguide_history"; public static final String USER_WENT_THROUGH_TOURGUIDE_SETTINGS = "user_went_through_tourguide_settings"; private SettingTypes() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for all types of events that are processed by EventBroker. */ public class EventTypes { public static final String LOCATION = "LOCATION"; public static final String LOCATION_ACCURATE = "LOCATION_ACCURATE"; public static final String RAW_LOCATION = "RAW_LOCATION"; public static final String SPEED = "SPEED"; public static final String TRACK = "TRACK"; public static final String TRACK_REQUEST = "TRACK_REQUEST"; public static final String TRACK_LOADED = "TRACK_LOADED"; public static final String RATING = "RATING"; public static final String DISTANCE = "DISTANCE"; public static final String DURATION = "DURATION"; public static final String IS_IN_CITY = "IS_IN_CITY"; public static final String NOT_IN_CITY = "NOT_IN_CITY"; public static final String STATUS_CODE = "STATUS_CODE"; public static final String IN_CITY = "IN_CITY"; // Dynamic routing public static final String OFFROUTE = "OFFROUTE"; public static final String ABNORMAL_HEART_RATE = "ABNORMAL_HEART_RATE"; //Storage public static final String STORE_RUNNINGSTATISTICS = "STORE_RUNNINGSTATISTICS"; public static final String LOAD_RUNNINGSTATISTICS = "LOAD_RUNNINGSTATISTICS"; public static final String LOADED_RUNNINGSTATISTICS = "LOADED_RUNNINGSTATISTICS"; public static final String DELETE_RUNNINGSTATISTICS = "DELETE_RUNNINGSTATISTICS"; public static final String STORE_AGGREGATESTATISTICS = "STORE_AGGREGATESTATISTICS"; public static final String LOAD_AGGREGATESTATISTICS = "LOAD_AGGREGATESTATISTICS"; public static final String LOADED_AGGREGATESTATISTICS = "LOADED_AGGREGATESTATISTICS"; public static final String DELETE_AGGREGATESTATISTICS = "DELETE_AGGREGATESTATISTICS"; public static final String SYNC_WITH_DATABASE = "SYNC_WITH_DATABASE"; //Navigation public static final String NAVIGATION_DIRECTION = "NAVIGATION_DIRECTION"; public static final String SPLIT_POINT = "SPLIT_POINT"; public static final String AUDIO = "AUDIO"; //android wear event types public static final String HEART_RESPONSE = "HEART_RESPONSE"; public static final String START_WEAR = "START_WEAR"; public static final String STOP_WEAR = "STOP_WEAR"; public static final String PAUSE_WEAR = "PAUSE_WEAR"; private EventTypes() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for communication with android wear device */ public class WearMessageTypes { //from wear to mobile public static final String HEART_RATE_MESSAGE_WEAR = "/heartRateMessageWear"; public static final String REQUEST_STATE_MESSAGE_WEAR = "/requestStateMessageWear"; //from mobile to wear public static final String START_RUN_MOBILE = "/startRun"; public static final String STOP_RUN_MOBILE = "/stopRun"; public static final String PAUSE_RUN_MOBILE = "/pauseRun"; //navigation constants public static final String NAVIGATE_LEFT = "/navigateLeft"; public static final String NAVIGATE_RIGHT = "/navigateRight"; public static final String NAVIGATE_STRAIGHT = "/navigateStraight"; public static final String NAVIGATE_UTURN = "/navigateUTurn"; public static final String RUN_STATE_START_MESSAGE_MOBILE = "/runStateStart"; public static final String RUN_STATE_PAUSED_MESSAGE_MOBILE = "/runStateStop"; public static final String TIME_UPDATE_MESSAGE_MOBILE = "/timeUpdate"; public static final String SPEED_UPDATE_MESSAGE_MOBILE = "/speedUpdate"; public static final String DISTANCE_UPDATE_MESSAGE_MOBILE = "/distanceUpdate"; private WearMessageTypes() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for activities (for GuiController) */ public class ActivityTypes { public static final String MAINMENU = "MAINMENU"; public static final String RUNNINGVIEW = "RUNNINGVIEW"; public static final String RESTTEST = "RESTTEST"; public static final String DEBUG = "DEVELOP"; public static final String HISTORYEXPANDED = "HISTORYEXPANDED"; public static final String LOGIN = "LOGIN"; public static final String SETTINGS = "SETTINGS"; public static final String CHANGEPROFILE = "CHANGEPROFILE"; public static final String LICENCES = "LICENCES"; private ActivityTypes() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants used by {@link RouteChecker}. */ public class RouteChecker { // Interval between onRouteChecker messages public static final int INTERVAL = 5000; // Accuracy for onRouteChecker public static final int ACCURACY = 40; private RouteChecker() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for displaying Google Maps. */ public class MapSettings { // Constant used in the location settings dialog. public static final int REQUEST_CHECK_SETTINGS = 0x1; // The desired interval for location updates. Inexact. Updates may be more or less frequent. public static final long UPDATE_INTERVAL = 2000; // The fastest rate for active location updates. Exact. Updates will never be more frequent than this value. public static final long FASTEST_UPDATE_INTERVAL = 1000; // Smallest displacement needed in meters before new location update is received public static final float SMALLEST_DISPLACEMENT = 2.0f; // Max Zoom level for google map public static final float MAX_ZOOM = 19.0f; // Min zoom level for google map public static final float MIN_ZOOM = 10.0f; // Desired zoom level for google map public static final float DESIRED_ZOOM = 17.0f; // Does Google RunningMap need compass public static final boolean COMPASS = true; // Can Google Maps be tilted public static final boolean TILT = false; // Padding to be added (in dp) to the bounding box of the displayed route public static final int ROUTE_PADDING = 20; // Padding to be added (in dp) to left and right side of map public static final int SIDE_MAP_PADDING = 8; // Number of samples for the rolling average public static final int ROLLING_SIZE = 4; // Discount factor is used for rotating map. It determines how much influence the newly calculated bearing has. public static final float DISCOUNT_FACTOR = 0.5f; public static final String STATIC_MAPS_KEY = "AIzaSyAl3P4q7jc4il8jVmGGZk6f-BwsNeC_xyc"; private MapSettings() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constant strings, used for persistence. */ public class Storage { public static final String RUNNINGSTATISTICSDIRECTORY = "runningstatistics"; public static final String RUNNINGSTATISTICSGHOSTDIRECTORY = "runningstatisticsghost"; public static final String AGGREGATERUNNINGSTATISTICSDIRECTORY = "aggregaterunningstatistics"; public static final String RUNNINGSTATISTICSCOLLECTION = "runningStatistics"; public static final String RUNNINGSTATISTICSGHOSTCOLLECTION = "runningStatisticsGhost"; public static final String AGGREGATERUNNINGSTATISTICSCOLLECTION = "aggregateRunningStatistics"; public static final int MINUTES_BETWEEN_SERVER_SYNC_TRIES = 15; public static final String MONGODBNAME = "DRIG_userdata"; public static final String MONGOUSER = "client"; public static final String MONGOPASS = "dynamicrunninginghentSmart"; // Logger name found by decompiling the mongodb java driver jar // Consider this unstable. That is no problem as we would only get a lot of logging messages if this would break. public static final String LOGGERNAME = "org.mongodb.driver.cluster"; public static final boolean TURNOFFLOGGING = true; private Storage() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * All cities the app supports. */ public static class Cities { public static final String GHENT = "GHENT"; protected static final String[] CITY_LIST = {GHENT}; private Cities() { throw new IllegalAccessError("Utility class"); } public static boolean cityIsKnown(String city) { for (String city1 : CITY_LIST) { if (Objects.equals(city1, city)) return true; } return false; } } /** * Bounding boxes containing Ghent. * Used by {@link com.dp16.runamicghent.DataProvider.InCityChecker} */ public static class CityBoundingBoxes { //Coordinate "box" containing the city of Ghent. public static final LatLngBounds latLngBoundGhent = new LatLngBounds(new LatLng(50.8077000, 3.0350000), new LatLng(51.3014000, 4.1858000)); private CityBoundingBoxes() { throw new IllegalAccessError("Utility class"); } } /** * Constants for location updates */ public static class Location { // Constants used to check if the location updates are accurate/inaccurate public static final float MAX_GOOD_ACCURACY = 10.0f; public static final float MIN_BAD_ACCURACY = 14.0f; public static final int COUNTER_MAX = 3; private Location() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants used for route generation. */ public static class RouteGenerator { public static final double MINIMAL_BOUND = 0.5; public static final double MAXIMAL_BOUND = 1.0; public static final double FRACTION_BOUND = 0.1; public static final double FIRST_BORDER = MINIMAL_BOUND / FRACTION_BOUND; public static final double SECOND_BORDER = MAXIMAL_BOUND / FRACTION_BOUND; public static final int MIN_LENGTH = 1; public static final int MAX_LENGTH = 50; public static final int DEFAULT_LENGTH = 5; private RouteGenerator() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } /** * Constants for dynamic routing */ public static class DynamicRouting { // Min and Max values for rangebar public static final int RANGEBAR_LOW = 60; public static final int RANGEBAR_HIGH = 210; // Standard upper and lower heart rate limit public static final int HEART_RATE_LOWER = 130; public static final int HEART_RATE_UPPER = 170; // Min and Max values for slider public static final int SLIDER_LOW = 0; public static final int SLIDER_HIGH = 100; // Default slider position public static final int DEFAULT_SLIDER = 20; // Number of samples for the rolling average public static final int ROLLING_SIZE = 4; // Minimal time that rolling average of heart rate needs to be under lower limit or above upper limit public static final long HEART_RATE_MIN_TIME = 1000 * 60L; // Time to wait after a Abnormal heart rate event has been set public static final long HEART_RATE_WAIT_TIME = 5 * 1000 * 60L; public static final String TAG_LOWER = "LOWER"; public static final String TAG_UPPER = "UPPER"; private DynamicRouting() { throw new IllegalAccessError(UTILITY_CLASS_ERROR); } } }
cf92b1279adb90d443cb17b41f858fedac0c7600
17dfcefb5d4a7527b2ba51f1762cfb62e824d8cc
/src/main/java/com/guyang/dao/BaseDao.java
a82821ff48a6bf765eb78d34b91e5b526d82525d
[]
no_license
guyang66/gy-spring-scoco
f7b71e91dc6941497ba28b729e8625ba5befaf8a
0ff3c558a4f6e73e88e7301be317bc96c3862430
refs/heads/master
2023-06-17T14:06:38.338948
2021-07-13T08:00:27
2021-07-13T08:00:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
428
java
package com.guyang.dao; import java.util.List; import java.util.Map; public interface BaseDao<T> { Integer selectCount(Map<String, ?> param); List<T> select(Map<String, ?> parameters); T selectById(Object id); List<T> selectByIds(Object[] ids); int deleteById(Object id); int deleteByIds(Object[] list); int delete(Map<String, Object> parameters); int insert(T t); int updateById(T t); }
3e4942216774533eef6bc671c438f95a9a2d90f0
16ff6e8ad5d76a3cfcd9ac511f515eba988bf80d
/app/src/main/java/com/example/app_zing/activity/dangnhap.java
14bc24b574abd025997f1dbaa14b1b88537259c1
[]
no_license
caoquocdat12092001/android
27eb0c3e8bc5d68d508096658abf12f50fb46141
85ba835f0019b8a6bf0cac895b40828afe7b4893
refs/heads/master
2022-12-05T02:13:05.432283
2020-08-26T19:13:52
2020-08-26T19:13:52
290,573,661
0
0
null
null
null
null
UTF-8
Java
false
false
4,286
java
package com.example.app_zing.activity; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Toast; import com.example.app_zing.R; import com.google.android.material.textfield.TextInputLayout; public class dangnhap extends AppCompatActivity { Button dangnhap ,btndnchuyendangki; TextInputLayout etuser, etpass; CheckBox cbremember; DatabaseHepper db; SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_dangnhap); // db = new DatabaseHepper(this); db = new DatabaseHepper(this,DatabaseHepper.DBNAME,null,1); anhxa(); sharedPreferences = getSharedPreferences("datalogin",MODE_PRIVATE); String idname = sharedPreferences.getString("taikhoan",""); String idpass = sharedPreferences.getString("matkhau",""); boolean idcheck = sharedPreferences.getBoolean("check", false); // if (idcheck == true){ // Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class); // startActivity(intent); // } btndnchuyendangki.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent1 = new Intent(dangnhap.this,dangki.class); startActivity(intent1); } }); dangnhap.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String user = etuser.getEditText().getText().toString().trim(); String pass = etpass.getEditText().getText().toString().trim(); if (user.equals("") || pass.equals("")) { etuser.setError("Field can't be empty"); etpass.setError("Field can't be empty"); } Boolean checkuserpass = db.checkuserpass(user, pass); if (checkuserpass == true && cbremember.isChecked()){ Toast.makeText(dangnhap.this, "đăng nhập thành công", Toast.LENGTH_SHORT).show(); //cjinhr sửa nội dung file SharedPreferences.Editor editor = sharedPreferences.edit(); //put giá trị vào editor.putString("taikhoan", user); editor.putString("matkhau", pass); editor.putBoolean("check", true); editor.commit(); Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class); intent.putExtra("user",user); startActivity(intent); overridePendingTransition(R.anim.top, R.anim.top); }else if (checkuserpass == true){ SharedPreferences.Editor editor = sharedPreferences.edit(); //put giá trị vào editor.putString("taikhoan", user); editor.putString("matkhau", pass); editor.putBoolean("check", false); editor.commit(); Intent intent = new Intent(dangnhap.this,manhinhgiaodien.class); intent.putExtra("user",user); startActivity(intent); overridePendingTransition(R.anim.top, R.anim.top); }else { Toast.makeText(dangnhap.this, "tân tài khoản hoặc mật khẩu sai", Toast.LENGTH_SHORT).show(); } } }); } private void anhxa() { dangnhap = findViewById(R.id.dangnhap); btndnchuyendangki = findViewById(R.id.btndnchuyendangki); etpass = findViewById(R.id.etpass); etuser = findViewById(R.id.etuser); cbremember = findViewById(R.id.cbremember); } }
b435fa423c7f62e7c6394a1e5f6ffd010d0cfca1
9430bdf488ccab433a3f3578e608d0871f9bb3ed
/app/src/main/java/com/huanpet/huanpet/screen/view/PinyinUtils.java
76ba6b117cf75c2e37cb293a7496e5ea2384463e
[]
no_license
wl19930525/HuanPet
8ac3144fc5282dd9d45b6b5ee6e6ef4746a13b43
026b30772a92b501640d5382485ef3b0de96352a
refs/heads/master
2021-04-15T16:37:48.937039
2018-04-04T01:44:15
2018-04-04T01:44:15
126,459,021
0
0
null
2018-04-02T00:57:17
2018-03-23T08:58:14
Java
UTF-8
Java
false
false
3,711
java
package com.huanpet.huanpet.screen.view; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; public class PinyinUtils { /** * 获得汉语拼音首字母 * * @param chines 汉字 * @return */ public static String getAlpha(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { if (nameChar[i] > 128) { try { pinyinName += PinyinHelper.toHanyuPinyinStringArray( nameChar[i], defaultFormat)[0].charAt(0); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName += nameChar[i]; } } return pinyinName; } /** * 将字符串中的中文转化为拼音,英文字符不变 * * @param inputString 汉字 * @return */ public static String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); String output = ""; if (inputString != null && inputString.length() > 0 && !"null".equals(inputString)) { char[] input = inputString.trim().toCharArray(); try { for (int i = 0; i < input.length; i++) { if (Character.toString(input[i]).matches( "[\\u4E00-\\u9FA5]+")) { String[] temp = PinyinHelper.toHanyuPinyinStringArray( input[i], format); output += temp[0]; } else output += Character.toString(input[i]); } } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { return "*"; } return output; } /** * 汉字转换位汉语拼音首字母,英文字符不变 * * @param chines 汉字 * @return 拼音 */ public static String converterToFirstSpell(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); for (int i = 0; i < nameChar.length; i++) { if (nameChar[i] > 128) { try { pinyinName += PinyinHelper.toHanyuPinyinStringArray( nameChar[i], defaultFormat)[0].charAt(0); } catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } } else { pinyinName += nameChar[i]; } } return pinyinName; } }
b60e331d27fff6e98b878678a9d7478251167fbf
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/google--error-prone/74b237d6c07be0108be1743d4b1d2ad83f7e37a1/after/HardCodedSdCardPath.java
8200b6a673412687127abfb2df46f69bf08d1f20
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
4,085
java
/* * Copyright 2016 Google Inc. 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. */ package com.google.errorprone.bugpatterns.android; import static com.google.errorprone.BugPattern.Category.ANDROID; import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; import static com.sun.source.tree.Tree.Kind.STRING_LITERAL; import com.google.common.collect.ImmutableMap; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.ProvidesFix; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.LiteralTree; import java.util.Map; /** * TODO(avenet): Restrict this check to Android code once the capability is available in Error * Prone. See b/27967984. * * @author [email protected] (Arnaud J. Venet) */ @BugPattern( name = "HardCodedSdCardPath", altNames = {"SdCardPath"}, summary = "Hardcoded reference to /sdcard", category = ANDROID, severity = WARNING, providesFix = ProvidesFix.REQUIRES_HUMAN_ATTENTION ) public class HardCodedSdCardPath extends BugChecker implements LiteralTreeMatcher { // The proper ways of retrieving the "/sdcard" and "/data/data" directories. static final String SDCARD = "Environment.getExternalStorageDirectory().getPath()"; static final String DATA = "Context.getFilesDir().getPath()"; // Maps each platform-dependent way of accessing "/sdcard" or "/data/data" to its // portable equivalent. static final ImmutableMap<String, String> PATH_TABLE = new ImmutableMap.Builder<String, String>() .put("/sdcard", SDCARD) .put("/mnt/sdcard", SDCARD) .put("/system/media/sdcard", SDCARD) .put("file://sdcard", SDCARD) .put("file:///sdcard", SDCARD) .put("/data/data", DATA) .put("/data/user", DATA) .build(); @Override public Description matchLiteral(LiteralTree tree, VisitorState state) { if (tree.getKind() != STRING_LITERAL) { return Description.NO_MATCH; } // Hard-coded paths may come handy when writing tests. Therefore, we suppress the check // for code located under 'javatests'. if (ASTHelpers.isJUnitTestCode(state)) { return Description.NO_MATCH; } String literal = (String) tree.getValue(); if (literal == null) { return Description.NO_MATCH; } for (Map.Entry<String, String> entry : PATH_TABLE.entrySet()) { String hardCodedPath = entry.getKey(); if (!literal.startsWith(hardCodedPath)) { continue; } String correctPath = entry.getValue(); String remainderPath = literal.substring(hardCodedPath.length()); // Replace the hard-coded fragment of the path with a portable expression. SuggestedFix.Builder suggestedFix = SuggestedFix.builder(); if (remainderPath.isEmpty()) { suggestedFix.replace(tree, correctPath); } else { suggestedFix.replace(tree, correctPath + " + \"" + remainderPath + "\""); } // Add the corresponding import statements. if (correctPath.equals(SDCARD)) { suggestedFix.addImport("android.os.Environment"); } else { suggestedFix.addImport("android.content.Context"); } return describeMatch(tree, suggestedFix.build()); } return Description.NO_MATCH; } }
b8c7523a0b38f1a83d830e3d43fcf39ff184edd2
0b20c4a616e17b76fe3c9a048e68b417e35dfaac
/Android/Seed/framework/src/main/java/com/min/framework/ConfigConstants.java
aa0e8cd2d6c2463d6e0fc6ba53b75c9f6788b95e
[]
no_license
minyangcheng/WorkStation
d39fffd3879adeac46d7b1cc1aeb5f56dd16c8dd
efcf62e7295ed8d76ba9de101076d987311dce88
refs/heads/master
2021-01-01T06:10:04.870682
2018-12-06T06:06:35
2018-12-06T06:06:35
97,376,308
1
0
null
null
null
null
UTF-8
Java
false
false
458
java
package com.min.framework; /** * Created by minyangcheng on 2016/10/8. */ public class ConfigConstants { public static final String HTTP_LOG="HttpLog"; public static final int PAGE_SIZE=15; public static String API_SERVER_URL; public static String SOURCE; public static String APP_SECRET; public static boolean DEBUG; public static String VERSION_NAME; public static String SDK_INT; public static String FLAVOR; }
7ba9bb7d4fdb875d9afe8b91e2eb9ed4f956c6de
9df873dbe290776878e612154baa2a4148e17ea2
/src/main/java/com/kenny/fix/definition/MessageDefinition.java
08f30e9334d230e991dbea8465513043b0233d4c
[]
no_license
kennien-ravindran/fixparser
f3978abf63e119f4e4a2caf039791fa3a44bb9e6
2fefbe9d8421e0508a8925f1f5345b311d6ef77c
refs/heads/master
2020-04-25T06:20:20.993209
2019-02-25T22:21:10
2019-02-25T22:21:10
172,577,219
0
0
null
null
null
null
UTF-8
Java
false
false
1,229
java
package com.kenny.fix.definition; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; public class MessageDefinition { private HashMap<Integer, MessageGroupDefinition> groupDefinitionMap = new HashMap<Integer, MessageGroupDefinition>(); public void loadDefinition(int tagId, int firstTag, Set<Integer> required, Set<Integer> optional) { groupDefinitionMap.put(tagId, new MessageGroupDefinition(tagId, firstTag, required, optional )); } public void loadTestDefinition(){ loadDefinition(269, 277, getTreeSet(456), getTreeSet(231, 283)); loadDefinition(123, 786, getTreeSet(398), getTreeSet(567, 496)); loadDefinition(552, 54, getTreeSet(37, 453), getTreeSet(12,13, 58, 528)); loadDefinition(453, 448, getTreeSet(447, 452, 802), getTreeSet()); loadDefinition(802, 523, getTreeSet(803), getTreeSet()); } private TreeSet<Integer> getTreeSet(int... tags){ TreeSet<Integer> set = new TreeSet<Integer>(); for(int tag : tags){ set.add(tag); } return set; } public MessageGroupDefinition getGroupDefinition(int groupId){ return groupDefinitionMap.get(groupId); } }
41187a3f84d6ae55292767ac725d690ce88f8bca
b9fcbdfaf85b16f534c95a41d3a9930ac1683aad
/Server/Tonpose_Kryonet/src/cs309/tonpose/ServerItem.java
eea7273b4077e87c9c0e5eab64c9de941e0816cf
[]
no_license
cbot789/Project-Tonpose
fd33d2de31c17cddb3852f4b05a18255a2de70ca
f2999697ded9279edec40ad8120c46b0d5623a07
refs/heads/master
2021-07-02T03:29:12.480142
2016-12-07T06:59:58
2016-12-07T06:59:58
103,860,474
0
0
null
null
null
null
UTF-8
Java
false
false
114
java
package cs309.tonpose; public class ServerItem { public int typeID; public int uniqueID; public float x, y; }
a909e4b8e2d02c475edb90df09483253d03ef736
c202b1be81c238dc78d62311f785a6b310740d8a
/src/TestNG/GroupingTestcases.java
ad3eb8ac92bca1c4b890a39e4d04e212c583c57c
[]
no_license
Rajno1/SeleniumBasics
7b320efe41b44af96c94c43f8883048f01c1b381
bcabcc1cf877d76e816a7da043613fc48d20c3f6
refs/heads/master
2020-08-04T21:19:24.962815
2019-10-02T07:53:34
2019-10-02T07:53:34
212,282,427
1
0
null
null
null
null
UTF-8
Java
false
false
1,093
java
package TestNG; import org.testng.annotations.Test; public class GroupingTestcases { @Test(priority=1,groups= "Buildacceptance") public void BuildCheck(){ System.out.println("Build acceptacne test"); } //By using 'priority' keyword we can priorities the test cases(@Test) //By using 'groups' keyword we can create the groups @Test(priority=2,groups= "Buildacceptance") public void EnterURL() { System.out.println("Enter URL"); } @Test(priority=3,groups= "Enter Credentials") public void ValidateUserlogin() { System.out.println("Validate user login details"); } @Test(priority=4,groups= "Enter Credentials") public void Enterusername() { System.out.println("Enter user name"); } @Test(priority=5,groups= "Enter Credentials") public void Enterpassword() { System.out.println("Enter password"); } @Test(priority=6,groups= "SubmitButton") public void SubmitStatus() { System.out.println("get the xpath of submit button"); } @Test(priority=7,groups= "SubmitButton") public void Submitbutton() { System.out.println("click submit button"); } }
6c9f1975d19f1f682a29e76bb153959f7eda244b
693d7c5fcbab4f4f12ebc2d7b945311efa4b0ba5
/chatserver/src/main/java/com/project/chat/gameroom/GameMessage.java
829ba27d526ea3f60469bd74c76d77437cc048f3
[ "MIT" ]
permissive
RyuJaeChan/FindSpy
66a098596b02f28cabd533a69625ad42c0aae5f5
cc4aa31121e8b006f7cfdbcb90819be3c61fbfa6
refs/heads/master
2020-04-01T14:00:17.526406
2018-12-18T14:34:14
2018-12-18T14:34:14
153,276,245
0
0
null
null
null
null
UTF-8
Java
false
false
236
java
package com.project.chat.gameroom; import com.project.chat.util.GameState; import lombok.Data; @Data public class GameMessage { private Integer roomId; private GameState gameStep; private String message; private String writer; }
1e31eba465e8c789709567f8b8c80afc11450eab
4117d7a9bd5b987e0111abe59da8371ad7cf3eec
/app/src/main/java/user/com/sg/socialfeeddemo/utils/MockDataParser.java
b1c858a06361db8cf49067fc02f00fa8db26f644
[]
no_license
cian0/SocialFeedDemo
3c74393a87cba2b0dd588d901cbe7b64e6cf6951
dd3d3de17f1be54a80d1409e7f60e2e64f4199c7
refs/heads/master
2021-01-10T13:42:58.732926
2016-02-29T09:58:22
2016-02-29T09:58:22
52,781,258
0
0
null
null
null
null
UTF-8
Java
false
false
2,502
java
package user.com.sg.socialfeeddemo.utils; import android.content.Context; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import user.com.sg.socialfeeddemo.R; import user.com.sg.socialfeeddemo.database.model.Comment; import user.com.sg.socialfeeddemo.database.model.Feed; import user.com.sg.socialfeeddemo.database.model.Profile; /** * Created by ianicasiano on 2/26/16. */ public class MockDataParser { public static void parseData(Context context) { JSONArray profilesJson = FileUtils.rawResourceToJsonArray(context, R.raw.profiles); JSONArray commentsJson = FileUtils.rawResourceToJsonArray(context, R.raw.comments); JSONArray feedsJson = FileUtils.rawResourceToJsonArray(context, R.raw.feeds); JSONObject configJson = FileUtils.rawResourceToJson(context, R.raw.config); ArrayList<Profile> profiles = new ArrayList<>(); ArrayList<Comment> comments = new ArrayList<>(); ArrayList<Feed> feeds = new ArrayList<>(); if (profilesJson == null) { profilesJson = new JSONArray(); } if (commentsJson == null) { commentsJson = new JSONArray(); } if (feedsJson == null) { feedsJson = new JSONArray(); } if (configJson == null) { configJson = new JSONObject(); } int i = 0, j = 0; for (i = 0, j = profilesJson.length(); i < j; i++) { Profile profile = new Profile(); try { profile.parse(profilesJson.getJSONObject(i)); profiles.add(profile); } catch (JSONException e) { // ignore unparseables for now continue; } } for (i = 0, j = commentsJson.length(); i < j; i++) { Comment comment = new Comment(); try { comment.parse(commentsJson.getJSONObject(i)); comments.add(comment); } catch (JSONException e) { // ignore unparseables for now continue; } } for (i = 0, j = feedsJson.length(); i < j; i++) { Feed feed = new Feed(); try { feed.parse(feedsJson.getJSONObject(i)); feeds.add(feed); } catch (JSONException e) { // ignore unparseables for now continue; } } } }
5944da4407298226b233abca7c482b1f44fe3ced
494cf20ddeb8d8924fba7048e6a95bed1386d290
/app/src/main/java/z_aksys/solutions/digiappequitybb/utils/AccountCalculator.java
b4520d325f214cb62a3db08bd489b5b6ad8d3c48
[]
no_license
vaibhav1601/digiTabB2c
c8408aa0249c929dc6eeb6bde889a12844ac8770
52e6e426e25cfe9c447ed7981b66af41d297f7d2
refs/heads/master
2020-04-18T12:02:01.465516
2019-01-24T07:36:02
2019-01-24T07:36:02
null
0
0
null
null
null
null
UTF-8
Java
false
false
301
java
package z_aksys.solutions.digiappequitybb.utils; import android.util.Log; public class AccountCalculator { private final long ACCOUNTOPENINGBROKERAGE = 500; public long calculateAccountOpeningEarning(int numberOfAccounts) { return numberOfAccounts*ACCOUNTOPENINGBROKERAGE; } }
36de460f7776b7e3c0ba3c12fc15ccdb040f2b22
46f14ea3b663fc80701c4f8ad64284a5e04e7adc
/src/cs3500/lecture/mvc/turtledraw/control/SimpleController.java
c5c88d8eeb30eb784a95b7bc0d9338cbc8f360d4
[]
no_license
nzukie-b/Music-Editor
abbd8a30f33e63b2f4357ab9d488fa3676db0cfb
82bdf9d1148f473a5836bc9fd56ab53ccc87f1b4
refs/heads/master
2021-09-09T19:01:47.304799
2017-04-23T22:26:01
2017-04-23T22:26:01
125,789,379
0
0
null
null
null
null
UTF-8
Java
false
false
2,029
java
package cs3500.lecture.mvc.turtledraw.control; import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.Line; import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.SmarterTurtle; import cs3500.lecture.mvc.turtledraw.TracingTurtleModel.TracingTurtleModel; import java.util.InputMismatchException; import java.util.Scanner; /** * Created by blerner on 10/10/16. */ public class SimpleController { public static void main(String[] args) { Scanner s = new Scanner(System.in); TracingTurtleModel m = new SmarterTurtle(); while (s.hasNext()) { String in = s.next(); switch(in) { case "q": case "quit": return; case "show": for (Line l : m.getLines()) { System.out.println(l); } break; case "move": try { double d = s.nextDouble(); m.move(d); } catch (InputMismatchException ime) { System.out.println("Bad length to move"); } break; case "trace": try { double d = s.nextDouble(); m.trace(d); } catch (InputMismatchException ime) { System.out.println("Bad length to trace"); } break; case "turn": try { double d = s.nextDouble(); m.turn(d); } catch (InputMismatchException ime) { System.out.println("Bad length to turn"); } break; case "square": try { double d = s.nextDouble(); m.trace(d); m.turn(90); m.trace(d); m.turn(90); m.trace(d); m.turn(90); m.trace(d); m.turn(90); } catch (InputMismatchException ime) { System.out.println("Bad length to turn"); } break; default: System.out.println(String.format("Unknown command %s", in)); break; } } } }
2e62d0732fb47b7c6eb7cf4b8450e6404ac4faaa
5b9b654e77c1562a367254461c0b6e5933be31c5
/src/LeetCode496_下一个更大元素I.java
e3e5d61677a3cd674b039e76be3d759deea6fb23
[]
no_license
sparkfengbo/LeetcodeSourceJava
865d7328899d09b5e1b7164edb2a6a91b4a48e4a
26b6e5f827822a18a0482623acb24fe363cd9374
refs/heads/master
2022-05-30T15:10:42.561864
2022-05-18T04:56:57
2022-05-18T04:56:57
146,726,852
0
0
null
null
null
null
UTF-8
Java
false
false
4,830
java
import java.util.*; /** * 下一个更大元素 I * 给定两个没有重复元素的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。 * <p> * nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出-1。 * <p> * 示例 1: * <p> * 输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. * 输出: [-1,3,-1] * 解释: * 对于num1中的数字4,你无法在第二个数组中找到下一个更大的数字,因此输出 -1。 * 对于num1中的数字1,第二个数组中数字1右边的下一个较大数字是 3。 * 对于num1中的数字2,第二个数组中没有下一个更大的数字,因此输出 -1。 * 示例 2: * <p> * 输入: nums1 = [2,4], nums2 = [1,2,3,4]. * 输出: [3,-1] * 解释: * 对于num1中的数字2,第二个数组中的下一个较大数字是3。 * 对于num1中的数字4,第二个数组中没有下一个更大的数字,因此输出 -1。 * 注意: * <p> * nums1和nums2中所有元素是唯一的。 * nums1和nums2 的数组大小都不超过1000。 */ public class LeetCode496_下一个更大元素I { public static void main(String[] args) { Solution solution = new Solution(); // System.out.println(Arrays.toString(nextGreaterElement(new int[]{4, 1, 2}, new int[]{1, 3, 4, 2}))); System.out.println(Arrays.toString(solution .nextGreaterElement(new int[]{1,3,5,2,4}, new int[]{6,5,4,3,2,1,7}))); } //暴力 速度太慢 // public static int[] nextGreaterElement(int[] nums1, int[] nums2) { // ArrayList<Integer> list = new ArrayList<>(); // // for (int i = 0; i < nums2.length; i++) { // list.add(nums2[i]); // } // // List<Integer> resultArray = new ArrayList<>(); // for (int i = 0; i < nums1.length; i++) { // int index = list.indexOf(nums1[i]); //// System.out.println(index + " " + nums1[i]); // // boolean isFind = false; // int j = 0; // if (index >= 0) { // for (j = index + 1; j < nums2.length; j++) { // if (nums2[j] > nums1[i]) { // isFind = true; // break; // } // } // } // // if (isFind) { // resultArray.add(nums2[j]); // } else { // resultArray.add(-1); // } // } // // // int[] result = new int[resultArray.size()]; // // for (int i = 0; i < resultArray.size(); i++) { // result[i] = resultArray.get(i); // } // // return result; // } class Solution_leetcode { public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Deque<Integer> stack = new ArrayDeque<Integer>(); for (int i = nums2.length - 1; i >= 0; --i) { int num = nums2[i]; while (!stack.isEmpty() && num >= stack.peek()) { stack.pop(); } map.put(num, stack.isEmpty() ? -1 : stack.peek()); stack.push(num); } int[] res = new int[nums1.length]; for (int i = 0; i < nums1.length; ++i) { res[i] = map.get(nums1[i]); } return res; } } static class Solution { public int[] nextGreaterElement(int[] nums1, int[] nums2) { int l = nums2.length; Deque<Integer> stack = new LinkedList<>(); Map<Integer, Integer> map = new HashMap<>(); map.put(nums2[l - 1], -1); for (int i = 0; i < l - 1; i++) { if (nums2[i + 1] > nums2[i]) { map.put(nums2[i], nums2[i + 1]); while (!stack.isEmpty()) { int n = stack.getLast(); if (n < nums2[i + 1]) { map.put(n, nums2[i + 1]); stack.removeLast(); } else { break; } } } else { stack.offer(nums2[i]); } } while (!stack.isEmpty()) { int n = stack.getLast(); map.put(n, -1); stack.pop(); } int[] res = new int[nums1.length]; for (int i = 0; i < nums1.length; i++) { res[i] = map.containsKey(nums1[i]) ? map.get(nums1[i]) : -1; } return res; } } }
c7c069136d716732f84348f697867ecf783fbea5
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-medium-project/src/main/java/org/gradle/test/performancenull_11/Productionnull_1023.java
cc2b1063cee8e8db0b1233c5270ccbce07f54121
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
585
java
package org.gradle.test.performancenull_11; public class Productionnull_1023 { private final String property; public Productionnull_1023(String param) { this.property = param; } public String getProperty() { return property; } private String prop0; public String getProp0() { return prop0; } public void setProp0(String value) { prop0 = value; } private String prop1; public String getProp1() { return prop1; } public void setProp1(String value) { prop1 = value; } }
1c27cd18946cbc2afe1b0d93bd90e105528e89b9
efb97250b130a55948d3c450fdcd0ec69fec920e
/modbus/src/main/java/com/berrontech/huali/modbus/ip/xa/XaMessageResponse.java
58975e630ea8efe9c73284a224ca11d5a03f9a1c
[]
no_license
levent8421/AlarmCenter
6f24f35bae57dbe179988453fd1b59c7b0d69925
a10921980423ce4741bd16c9747705a2505efdb0
refs/heads/master
2022-12-02T04:44:24.199019
2020-08-13T10:33:52
2020-08-13T10:33:52
286,463,356
0
0
null
null
null
null
UTF-8
Java
false
false
2,285
java
/* * ============================================================================ * GNU General Public License * ============================================================================ * * Copyright (C) 2006-2011 Serotonin Software Technologies Inc. http://serotoninsoftware.com * @author Matthew Lohbihler * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.berrontech.huali.modbus.ip.xa; import com.berrontech.huali.modbus.base.ModbusUtils; import com.berrontech.huali.modbus.exception.ModbusTransportException; import com.berrontech.huali.modbus.ip.IpMessageResponse; import com.berrontech.huali.modbus.msg.ModbusResponse; import com.berrontech.huali.modbus.sero.util.queue.ByteQueue; public class XaMessageResponse extends XaMessage implements IpMessageResponse { static XaMessageResponse createXaMessageResponse(ByteQueue queue) throws ModbusTransportException { // Remove the XA header int transactionId = ModbusUtils.popShort(queue); int protocolId = ModbusUtils.popShort(queue); if (protocolId != ModbusUtils.IP_PROTOCOL_ID) throw new ModbusTransportException("Unsupported IP protocol id: " + protocolId); ModbusUtils.popShort(queue); // Length, which we don't care about. // Create the modbus response. ModbusResponse response = ModbusResponse.createModbusResponse(queue); return new XaMessageResponse(response, transactionId); } public XaMessageResponse(ModbusResponse modbusResponse, int transactionId) { super(modbusResponse, transactionId); } public ModbusResponse getModbusResponse() { return (ModbusResponse) modbusMessage; } }
810084f6a6d477ec38cfc32f7341c3a98996b006
1fb52eff75c7b79d466cd2137be54487113e6058
/src/main/java/com/dev/filarmonic/dao/ShoppingCartDaoImpl.java
29e1ed9573e5c78e36215b35be49a6b3791752cd
[]
no_license
less08/filarmonic-project
663b504ead695c9ef3d4da52b444e0ebe58f18b1
9248d5426107a25b86e532016f27577a32a4a54f
refs/heads/main
2023-03-09T08:58:53.848677
2021-02-26T18:09:04
2021-02-26T18:09:04
333,223,853
0
0
null
2021-02-26T18:09:05
2021-01-26T21:36:45
Java
UTF-8
Java
false
false
2,538
java
package com.dev.filarmonic.dao; import com.dev.filarmonic.exception.DataProcessException; import com.dev.filarmonic.model.ShoppingCart; import com.dev.filarmonic.model.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.stereotype.Repository; @Repository public class ShoppingCartDaoImpl implements ShoppingCartDao { private final SessionFactory sessionFactory; public ShoppingCartDaoImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public ShoppingCart add(ShoppingCart shoppingCart) { Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); session.save(shoppingCart); transaction.commit(); return shoppingCart; } catch (Exception e) { if (transaction != null) { transaction.rollback(); } throw new DataProcessException("Can't add shopping cart " + shoppingCart, e); } finally { if (session != null) { session.close(); } } } @Override public ShoppingCart getByUser(User user) { try (Session session = sessionFactory.openSession()) { Query<ShoppingCart> query = session.createQuery("from ShoppingCart sc " + "left join fetch sc.tickets where sc.user=:user", ShoppingCart.class) .setParameter("user", user); return query.getSingleResult(); } catch (Exception e) { throw new DataProcessException("Can`t find shopping cart by user: " + user, e); } } @Override public void update(ShoppingCart shoppingCart) { Session session = null; Transaction transaction = null; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); session.saveOrUpdate(shoppingCart); transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } throw new DataProcessException("Can't update shopping cart " + shoppingCart, e); } finally { if (session != null) { session.close(); } } } }
3266b3aaa0979343689fc480d12a519cee78f358
1c5e8538f5f500b7f6f2d8a3d792419f2de51b7b
/app/src/main/java/com/example/jiangshujing/keepalivetimingdemo/keepalive/service/DaemonService.java
dd0eda6b53319679a23e3d6ba0756867b6ac6716
[]
no_license
jiangshujing/KeepAliveTimeingDemo
3b002645a6113cdc9c18487cf5a76ae7ca4eb678
961c6fe92d458e050805b5c35f06b21a917066d6
refs/heads/master
2020-04-13T23:10:54.215664
2018-12-29T09:55:46
2018-12-29T09:55:46
163,499,503
0
0
null
null
null
null
UTF-8
Java
false
false
2,660
java
package com.example.jiangshujing.keepalivetimingdemo.keepalive.service; import android.app.Notification; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.os.Build; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import com.example.jiangshujing.keepalivetimingdemo.R; import com.example.jiangshujing.keepalivetimingdemo.keepalive.utils.Contants; /** * 前台Service,使用startForeground * 这个Service尽量要轻,不要占用过多的系统资源,否则 * 系统在资源紧张时,照样会将其杀死 */ public class DaemonService extends Service { private static final String TAG = "DaemonService"; public static final int NOTICE_ID = 100; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); if (Contants.DEBUG) Log.d(TAG, "DaemonService---->onCreate被调用,启动前台service"); //如果API大于18,需要弹出一个可见通知 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { Notification.Builder builder = new Notification.Builder(this); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentTitle("KeepAppAlive"); builder.setContentText("DaemonService is runing..."); startForeground(NOTICE_ID, builder.build()); // 如果觉得常驻通知栏体验不好 // 可以通过启动CancelNoticeService,将通知移除,oom_adj值不变 Intent intent = new Intent(this, CancelNoticeService.class); startService(intent); } else { startForeground(NOTICE_ID, new Notification()); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 如果Service被终止 // 当资源允许情况下,重启service return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); // 如果Service被杀死,干掉通知 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mManager.cancel(NOTICE_ID); } if (Contants.DEBUG) Log.d(TAG, "DaemonService---->onDestroy,前台service被杀死"); // 重启自己 Intent intent = new Intent(getApplicationContext(), DaemonService.class); startService(intent); } }
36db2ca28450b6c6c9ea9061bfc2739ad1f5bf6d
5edeaa8581a929b99d833bcbe10221a951a3ff86
/app/src/main/java/com/nativenote/ejogajogassignment/view/LocationFragment.java
ffa7bd90e99d0f09c792a70f553191d8aa2ac043
[]
no_license
Native-Note/Android-background-service-in-Oreo
c60cc26146612f046fdfd2b3cf0578c3d3f472c7
7ff1f8d7321a82d6a98716b83941eeb3d38659f3
refs/heads/master
2020-03-20T11:40:32.274983
2018-06-14T21:04:38
2018-06-14T21:04:38
137,408,972
0
0
null
null
null
null
UTF-8
Java
false
false
9,933
java
package com.nativenote.ejogajogassignment.view; import android.Manifest; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.Color; import android.location.LocationManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.nativenote.ejogajogassignment.R; import com.nativenote.ejogajogassignment.databinding.FragmentMainBinding; import com.nativenote.ejogajogassignment.listener.SwitchCheckChangeListener; import com.nativenote.ejogajogassignment.service.LocationService; import com.nativenote.ejogajogassignment.utiles.ConnectionDetector; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.List; import pub.devrel.easypermissions.EasyPermissions; import static android.content.Context.LOCATION_SERVICE; import static android.content.Context.POWER_SERVICE; /** * A placeholder fragment containing a simple view. */ public class LocationFragment extends Fragment implements EasyPermissions.PermissionCallbacks { public static final String[] PERMISSION_LIST = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION}; public final static int REQUEST_CODE = 3999; private FragmentActivity mActivity; private FragmentMainBinding binding; private Snackbar snackbarPermissions; private Snackbar snackbarGps; @Override public void onAttach(Context context) { super.onAttach(context); this.mActivity = (FragmentActivity) context; } public LocationFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false); binding.setIsChecked(false); binding.setCallback(listener); return binding.getRoot(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); requestOptimize(); } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onResume() { super.onResume(); if (hasAllPermission()) enableSwitch(); else EasyPermissions.requestPermissions(this, getResources().getString(R.string.permission_txt), REQUEST_CODE, PERMISSION_LIST); } private void requestOptimize() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PowerManager powerManager = (PowerManager) mActivity.getSystemService(Context.POWER_SERVICE); Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); if (powerManager.isIgnoringBatteryOptimizations(mActivity.getApplicationContext().getPackageName())) { intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS); } else { intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName())); startActivity(intent); } } } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) public void onEvent(ContentModel event) { binding.setLocText(event.getData()); } private void enableSwitch() { binding.workingSwitch.setEnabled(true); if (isServiceRunning(LocationService.class, mActivity)) binding.setIsChecked(true); } SwitchCheckChangeListener listener = checked -> { if (checked) { if (!ConnectionDetector.isNetworkPresent(mActivity)) { binding.setIsChecked(false); Snackbar.make(binding.getRoot(), mActivity.getResources().getString(R.string.no_internet), Snackbar.LENGTH_LONG).show(); return; } checkLocationPermission(); } else { if (isServiceRunning(LocationService.class, mActivity)) stopLocationService(); } }; private void checkLocationPermission() { if (!hasAllPermission()) { binding.setIsChecked(false); EasyPermissions.requestPermissions(this, getResources().getString(R.string.permission_txt), REQUEST_CODE, PERMISSION_LIST); } else { checkGpsEnabled(); } } private void checkGpsEnabled() { LocationManager lm = (LocationManager) mActivity.getApplicationContext().getSystemService(LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { reportGpsError(); } else { resolveGpsError(); if (isServiceRunning(LocationService.class, mActivity)) stopLocationService(); startLocationService(); } } public static boolean isServiceRunning(Class<?> serviceClass, Context context) { ActivityManager manager = (ActivityManager) context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } private void reportPermissionsError() { binding.setIsChecked(false); snackbarPermissions = Snackbar .make(binding.getRoot(), getString(R.string.location_permission_required), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.enable, view -> { resolvePermissionsError(); Intent intent = new Intent(Settings .ACTION_APPLICATION_DETAILS_SETTINGS); intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName())); startActivity(intent); }); snackbarPermissions.setActionTextColor(Color.RED); View sbView = snackbarPermissions.getView(); TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.YELLOW); snackbarPermissions.show(); } private void resolvePermissionsError() { if (snackbarPermissions != null) { snackbarPermissions.dismiss(); snackbarPermissions = null; } } private void reportGpsError() { binding.setIsChecked(false); snackbarGps = Snackbar .make(binding.getRoot(), getString(R.string.gps_required), Snackbar.LENGTH_INDEFINITE) .setAction(R.string.enable, view -> { resolveGpsError(); startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); }); snackbarGps.setActionTextColor(Color.RED); View sbView = snackbarGps.getView(); TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text); textView.setTextColor(Color.YELLOW); snackbarGps.show(); } private void resolveGpsError() { if (snackbarGps != null) { snackbarGps.dismiss(); snackbarGps = null; } } private void startLocationService() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PowerManager pm = (PowerManager) mActivity.getApplicationContext().getSystemService(POWER_SERVICE); Intent intent = new Intent(); if (!pm.isIgnoringBatteryOptimizations(mActivity.getApplicationContext().getPackageName())) { intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS); intent.setData(Uri.parse("package:" + mActivity.getApplicationContext().getPackageName())); startActivity(intent); } } Intent intent = new Intent(mActivity, LocationService.class); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { mActivity.startForegroundService(intent); } else { mActivity.startService(intent); } } private void stopLocationService() { Intent intent = new Intent(mActivity, LocationService.class); mActivity.stopService(intent); } private boolean hasAllPermission() { return EasyPermissions.hasPermissions(mActivity, PERMISSION_LIST); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) { enableSwitch(); } @Override public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) { reportPermissionsError(); // mActivity.finish(); } }
d6f4a623c4bacce1eada785c3251e0d1fa5ada49
59d0bce04cb2787d6c09dd60d6081a9596c7df3c
/Maven/src/main/java/com/pages/HomePage.java
2138cf64f890062358d053f62ebe36a1ef152947
[]
no_license
kirantester319/AutomationRepo
bf45f1da505a5b4892f568f5f63d1e41e0944a38
f9795d6b495c0c208c56cd2577622772da9ab7c7
refs/heads/master
2020-12-21T02:13:46.196916
2020-01-27T04:52:06
2020-01-27T04:52:06
236,274,613
0
0
null
2020-10-13T19:04:50
2020-01-26T06:11:44
HTML
UTF-8
Java
false
false
392
java
package com.pages; import java.util.ArrayList; import java.util.Iterator; import java.util.Set; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; public class HomePage { WebDriver driver; HomePage() { this.driver=driver; } }
61aef001db803093923ed0857b7f11d2ff056a9b
ba5d18efd948ffac20ee4bdab369d4e6a67d83ca
/ga_oauth_app/src/main/java/mock/category/MockCategory.java
ce5f8d32ee4a989e783d948ea609adf1f205d732
[]
no_license
atares0223/Google_OAuth2_Springboot_Analytics
b1895fc45801f9a0ed2ed9f5457a6b58669e1006
3093e679f77aa44f5c668ae9f0c80dd3fbed2fa1
refs/heads/master
2020-04-30T15:00:35.029483
2019-03-21T09:15:55
2019-03-21T09:15:55
176,908,059
1
2
null
null
null
null
UTF-8
Java
false
false
837
java
package mock.category; import com.lff.model.product.Category; import mock.seller.MockSeller; public class MockCategory { public static String FRUIT = "fruit"; public static String APPLE = "apple"; public static Category FRUIT_CATEGORY = new Category(null, FRUIT); public static Category APPLE_CATEGORY = new Category(FRUIT_CATEGORY, APPLE); public static String TOY = "toy"; public static String TRANSFORMERS = "transformers"; public static Category TOY_CATEGORY = new Category(null, TOY); public static Category TRANSFORMERS_CATEGORY = new Category(TOY_CATEGORY, TRANSFORMERS); public static Category getCategory(String sellerName){ if(sellerName.equals(MockSeller.FRUIT_HOME)){ return APPLE_CATEGORY; }else if(sellerName.equals(MockSeller.TOY_HOME)){ return TRANSFORMERS_CATEGORY; } return null; } }
49a23e66c1619418d976e72df925938c7db0f0b5
c0985d7d62a09298930cce0d709f03aeda062e85
/app/src/main/java/com/gonztorr/android/tipcalc/fragments/RatingServiceFragmentListener.java
cf5c43c63763cecd8bf493afd868b00043524698
[]
no_license
helijesusg/TipCalc
074d70f88ef81bf8b374936e27f72d4fa2c753e3
da18985c9b5853721cc0019875c94992015d641c
refs/heads/master
2020-07-28T07:22:05.491197
2016-11-22T18:00:00
2016-11-22T18:00:00
73,027,721
0
0
null
null
null
null
UTF-8
Java
false
false
183
java
package com.gonztorr.android.tipcalc.fragments; /** * Created by Heli Gonzalez on 21/11/2016. */ public interface RatingServiceFragmentListener { String getRatingService(); }
195e45708bbf696835b3e962ed25bb98c83ffce1
f885a7ed43d2292ff29d3fc3077cac76c9ebb200
/DA1/telephoned.java
71cd82d1bb745cda3f48ee3c6e08958ca378c883
[]
no_license
shaarangg/Java-Programs
6500999ac6b089989b1599ccc0d4db113d112c63
3b9bccff1912715b8b047ec36118d06a5cdfd687
refs/heads/main
2023-05-27T09:41:38.518406
2021-06-14T16:25:44
2021-06-14T16:25:44
340,027,236
0
0
null
null
null
null
UTF-8
Java
false
false
2,629
java
import java.util.*; abstract class Telephone{ String name; String pno; Telephone(String n, String p){ this.name = n; this.pno = p; } void display(){ System.out.println("Name - "+this.name+"\nPhone Number - "+this.pno); } } class TelephoneIndex extends Telephone { TelephoneIndex(String n, String p){ super(n,p); } void chngname(String sname){ this.name = sname; System.out.println("Name Successfully changed\n"); } void chngpno(String pno){ this.pno = pno; System.out.println("Phone Number Successfully changed\n"); } } class telephoned{ void search(TelephoneIndex[] a, String sname){ int l = sname.length(); int n = a.length; for(int i =0; i<n; i++){ String b = a[i].name.substring(0,l); if(b.equals(sname)){ System.out.println(a[i].name + " "+ a[i].pno); } } } public static void main(String[] args){ System.out.println("Shaarang Singh\n19BCT0215\n"); Scanner sc = new Scanner(System.in); System.out.println("Enter the no. of records"); int n = sc.nextInt(); TelephoneIndex[] a = new TelephoneIndex[n]; String name; String pno; for(int i =0; i<n; i++){ System.out.println("Enter the name"); name = sc.next(); System.out.println("Enter the no."); pno = sc.next(); a[i] = new TelephoneIndex(name, pno); System.out.println(); } System.out.println("PhoneBook"); for(int i=0; i<n; i++){ a[i].display(); System.out.println(); } telephoned obj = new telephoned(); System.out.println("Enter the string to search"); String sname = sc.next(); obj.search(a, sname); System.out.println("\n\n"); System.out.println("Enter the string you want to change"); sname = sc.next(); System.out.println("Enter the new name"); String sname1 = sc.next(); for(int i =0; i<n; i++){ if(a[i].name.equals(sname)){ a[i].chngname(sname1); break; } } System.out.println("Enter the no. you want to change"); pno = sc.next(); System.out.println("Enter the new no."); String pno1 = sc.next(); for(int i =0; i<n; i++){ if(a[i].pno.equals(pno)){ a[i].chngpno(pno1); break; } } sc.close(); } }
0634902a7414b19c3f17b7a6871b724ce933fdab
61f42894a09ad6f97259c81b7edb1419af5cb5bd
/src/com/ystech/aqtp/core/listener/ApplicationListener.java
0a9e1cd0c556871be1a998160cd596968408c186
[]
no_license
shusanzhan/aqtp
59390ce1eaa9d00983c6d40173d8fe1b2b778a35
09f3389e9c8adbd1ca08a74cac39435683e00975
refs/heads/master
2021-01-22T04:41:26.469854
2014-01-04T15:57:27
2014-01-04T15:57:27
10,737,204
1
0
null
null
null
null
UTF-8
Java
false
false
1,518
java
/** * */ package com.ystech.aqtp.core.listener; import javax.annotation.Resource; import javax.servlet.Filter; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.apache.struts2.ServletActionContext; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import com.ystech.aqtp.model.Access; import com.ystech.aqtp.service.AccessManageImpl; /** * @author shusanzhan * @date 2013-11-28 */ public class ApplicationListener implements HttpSessionListener{ @Override public void sessionCreated(HttpSessionEvent arg0) { ApplicationContext applicationContext = (ApplicationContext) ServletActionContext .getServletContext() .getAttribute( WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); //获取spring的环境信息 AccessManageImpl accessManageImpl =(AccessManageImpl)applicationContext.getBean("accessManageImpl"); Access access = accessManageImpl.get(1); int count; count = access.getAccess(); ++count; access.setAccess(count); accessManageImpl.save(access); arg0.getSession().setAttribute("count", count); } @Override public void sessionDestroyed(HttpSessionEvent arg0) { } }
ad7f325ffd7986bbf5e6c5e2a5d25783ec25e2e0
6a0e7ff68b7ed35a774affc8de2343a3f73328bf
/Printing numbers from 30 to 50/Main.java
5df1d95fb77c3542bc3889b755b852977dfea182
[]
no_license
rahulbhatia-rb/Playground
de12837987b1f56ccb349071260e1c552f24b789
b551212c72ebe151d3c341c4f2ce0e1d2c4ea529
refs/heads/master
2020-04-23T16:07:59.765901
2019-07-20T06:41:57
2019-07-20T06:41:57
171,287,541
0
0
null
null
null
null
UTF-8
Java
false
false
110
java
#include <stdio.h> int main() { for(int i=30;i<=50;i++) printf("%d\n",i); //Type your code return 0; }
923d6bcba57a1583ab1ef7622f85ba3e8940c955
e1fd1411965cabe996ac243b00296ed1caae562f
/src/main/java/com/neil/survey/module/SurveyAnswerAllInfo.java
612a44785dcaf92f094cb7cd449d55620f2c5b28
[]
no_license
neilzhao1978/survey
4134ed23b2c8d155c8978856ca5be1574025fe81
e7a6fbc098c621ec47f9a6067530aaa5ea590969
refs/heads/master
2021-09-08T19:53:27.664816
2018-03-12T03:29:58
2018-03-12T03:29:58
103,833,446
0
0
null
null
null
null
UTF-8
Java
false
false
2,264
java
package com.neil.survey.module; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the SURVEY_ANSWER_ALL_INFO database table. * */ @Entity @Table(name="SURVEY_ANSWER_ALL_INFO") @NamedQuery(name="SurveyAnswerAllInfo.findAll", query="SELECT s FROM SurveyAnswerAllInfo s") public class SurveyAnswerAllInfo implements Serializable { private static final long serialVersionUID = 1L; private String brand; @Column(name="IMAGE_ID") private String imageId; @Column(name="IMAGE_NAME") private String imageName; private String model; @Column(name="REPLYER_POSITION") private String replyerPosition; @Column(name="STYLE_KEYWORD") private String styleKeyword; @Id @Column(name="SURVEY_ID") private String surveyId; private String texture; @Column(name="THUMB_URL") private String thumbUrl; private String year; public SurveyAnswerAllInfo() { } public String getBrand() { return this.brand; } public void setBrand(String brand) { this.brand = brand; } public String getImageId() { return this.imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getImageName() { return this.imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public String getModel() { return this.model; } public void setModel(String model) { this.model = model; } public String getReplyerPosition() { return this.replyerPosition; } public void setReplyerPosition(String replyerPosition) { this.replyerPosition = replyerPosition; } public String getStyleKeyword() { return this.styleKeyword; } public void setStyleKeyword(String styleKeyword) { this.styleKeyword = styleKeyword; } public String getSurveyId() { return this.surveyId; } public void setSurveyId(String surveyId) { this.surveyId = surveyId; } public String getTexture() { return this.texture; } public void setTexture(String texture) { this.texture = texture; } public String getThumbUrl() { return this.thumbUrl; } public void setThumbUrl(String thumbUrl) { this.thumbUrl = thumbUrl; } public String getYear() { return this.year; } public void setYear(String year) { this.year = year; } }
4761f34d4959e387a98950910d8368cc8fe78d0e
8f27734dee9e9524055f6ca5c16f38b43aa45db0
/chapter_002/src/test/java/ru/job4j/tracker/ItemTest.java
ec0b111a99e1accff53868e5bd2af71a5f58062d
[ "Apache-2.0" ]
permissive
KirillBelyaev74/job4j_elementary
c0205d677621059128265900295b5fbec3e9a588
d0a335f3e409e24195138d77c2c04b9bb16efc15
refs/heads/master
2023-02-15T01:53:05.015800
2021-01-13T08:08:12
2021-01-13T08:08:12
202,711,977
0
0
Apache-2.0
2020-10-13T17:21:54
2019-08-16T10:57:02
Java
UTF-8
Java
false
false
1,264
java
package ru.job4j.tracker; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class ItemTest { @Test public void whenFirstSecondThenFirstSecond() { Item first = new Item("Petr"); Item second = new Item("Ivan"); Item third = new Item("Artem"); Tracker tracker = new Tracker(); tracker.add(first); tracker.add(second); tracker.add(third); List<Item> result = tracker.findAll(); Collections.sort(result); List<Item> expect = Arrays.asList(third, second, first); assertThat(result, is(expect)); } @Test public void whenFirstSecondThenSecondFirst() { Item first = new Item("Artem"); Item second = new Item("Petr"); Item third = new Item("Ivan"); Tracker tracker = new Tracker(); tracker.add(first); tracker.add(second); tracker.add(third); List<Item> result = tracker.findAll(); Collections.sort(result, Collections.reverseOrder()); List<Item> expect = Arrays.asList(second, third, first); assertThat(result, is(expect)); } }
2945141bc4a46ea13a9ad2e841b622d4f979cae9
575acf52715b95f86a10b4e3c1b354c5cc34248b
/src/main/java/org/demo/data/record/listitem/ReviewListItem.java
de8e44b9a2cebbf3edb7a6af97b19e38c8a99256
[]
no_license
t-soumbou/persistence-with-mongoDB
52a21b507551365f9f88e5adf2b6dd58f9b8ff62
67bfe4425cfe46360606390541b95007952658b0
refs/heads/master
2020-05-21T05:03:53.502360
2017-03-22T16:37:22
2017-03-22T16:37:22
84,574,135
0
0
null
null
null
null
UTF-8
Java
false
false
741
java
/* * Created on 2017-03-22 ( Date ISO 2017-03-22 - Time 17:28:47 ) * Generated by Telosys ( http://www.telosys.org/ ) version 3.0.0 */ package org.demo.data.record.listitem; import org.demo.data.record.ReviewRecord; import org.demo.commons.ListItem; public class ReviewListItem implements ListItem { private final String value ; private final String label ; public ReviewListItem(ReviewRecord review) { super(); this.value = "" + review.getCustomerCode() + "|" + review.getBookId() ; //TODO : Define here the attributes to be displayed as the label this.label = review.toString(); } //@Override public String getValue() { return value; } //@Override public String getLabel() { return label; } }
0e83b0af69e57b7042a698b35e99d99af87cc08b
5858d0e30915568ebddfcac41f6a308a1fd38233
/smarthome-web_lqh/src/main/java/com/biencloud/smarthome/web/wsclient/stub/GetPropertyCompanyInfoResponse.java
57c9ee38f00e179f610ad1eb74a9153158de809e
[]
no_license
CocoaK/java-project-source
303ad9a75ebf499d4ee95048160cd0a573d9f5ec
609f43b9009fedf124c2feef09e10e0d47c2b4b4
refs/heads/master
2020-03-19T07:34:11.395784
2018-06-05T05:52:30
2018-06-05T05:52:30
136,125,854
0
1
null
null
null
null
UTF-8
Java
false
false
1,603
java
package com.biencloud.smarthome.web.wsclient.stub; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getPropertyCompanyInfoResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getPropertyCompanyInfoResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://service.cxfservice.smarthome.biencloud.com/}propertyCompanyInfo" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getPropertyCompanyInfoResponse", propOrder = { "_return" }) public class GetPropertyCompanyInfoResponse { @XmlElement(name = "return") protected PropertyCompanyInfo _return; /** * Gets the value of the return property. * * @return * possible object is * {@link PropertyCompanyInfo } * */ public PropertyCompanyInfo getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link PropertyCompanyInfo } * */ public void setReturn(PropertyCompanyInfo value) { this._return = value; } }
1f1304c2f3c3a724f594b298998cc07e1282bb77
e2a97f336e545c89dbba886889416ee99c3d89a0
/PJ_0306/src/QnAservice/ListQnaAction.java
0363c65aa48fcb6e8b2f7e4112a1ea8b450f4fab
[]
no_license
jongtix/JSP_jongtix
f580d82beaa3a53c9876961af45389527d3832af
ef5aac22eefa6611bdce6647fba645e55d626192
refs/heads/master
2021-05-06T00:38:00.250849
2018-03-18T07:06:06
2018-03-18T07:06:06
114,311,296
0
0
null
null
null
null
UTF-8
Java
false
false
866
java
package QnAservice; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import QnAdao.QnaBoardDao; import QnAdao.SubBoardDao; import QnAdto.Board; import QnAdto.SubBoard; import controller.CommandProcess; import util.Paging; import util.PageBean; public class ListQnaAction implements CommandProcess { @Override public String requestPro(HttpServletRequest request, HttpServletResponse response) throws Throwable { QnaBoardDao dao = QnaBoardDao.getInstance(); int total = dao.getQnaTotal(); Paging pg = new Paging(); PageBean pb = pg.getPaging(request, total); List<Board> list = dao.selectQnaList(pb.getStartRow(), pb.getEndRow()); request.setAttribute("total", total); request.setAttribute("list", list); request.setAttribute("pb", pb); return "QnAboard/listQna.jsp"; } }
0f4ee5b44748e5305196f7e08c3d1e1e6686a402
a46a8fe034b552fdcba31624da4aa2eb73a6ad5b
/LibraryC/src/main/java/ClassC.java
0b6d1658fbda712e144bfcaef9ea6651a9156eab
[]
no_license
jwy411/DependencyConfigurationsTest
98aad1bc7504be2a783a35cd3f2c5515c50f75f2
7b807907ada09e406fdcb3955d6a9029ef9d4b28
refs/heads/master
2022-06-22T02:41:53.577728
2020-05-08T07:01:23
2020-05-08T07:01:23
262,024,987
0
0
null
null
null
null
UTF-8
Java
false
false
87
java
public class ClassC { public String tellMeJoke() { return "You are funny :CC"; } }
e210eb04f16a960399d23606b840cefbd330c0f6
9aef01964e63779f2ed6ad0fcf0d79088a4e9704
/src/main/java/codilitylessons/SummNumbers.java
5cc95fe7dd3104004ff086a8650b60d85cde869c
[]
no_license
KalisiakAdam/Alghoritms
b748b757dbac3e14eada52dac2ea139f48fa3489
52a4b56528ebb725ceb82b65e619452d63ac7dfa
refs/heads/master
2021-08-20T01:03:33.440598
2017-11-27T21:56:07
2017-11-27T21:56:07
112,252,843
0
0
null
null
null
null
UTF-8
Java
false
false
778
java
package codilitylessons; /** * Created by kalisiaczki on 26.11.2017. */ public class SummNumbers { public int sumIt(int[] numberArray){ int totalNumber = 0; for(int i = 0 ; i <numberArray.length ; i++ ){ int number = numberArray[i]; if(number < 10) { totalNumber =+ number; } else{ while(number > 0) { totalNumber += number % 10;; number = number / 10; } } } return totalNumber; } public static void main(String[] args) { int arry[]={9, 21, 3155, 2456}; SummNumbers sumNumber = new SummNumbers(); System.out.println(sumNumber.sumIt(arry)); } }
03c9813d9964839599aaa0f0c8fa6dea43edbd3b
1a759d0b36238e5f6a3d089698bb2cb264a8c873
/app/src/main/java/app/ari/assignment1/activities/TweetActivity.java
32bbc3a51b0f25bd57e48557da43cffae0020779
[]
no_license
ahwwwee/MyTweet-Android
b8ec1f2379d4f5e22433e5d654279fa338ac9979
a1facbf5218cddd27d5e9b295c894346d09b47fd
refs/heads/master
2021-08-23T22:24:27.729505
2017-01-08T20:30:01
2017-01-08T20:30:01
113,368,482
0
0
null
null
null
null
UTF-8
Java
false
false
900
java
package app.ari.assignment1.activities; import android.os.Bundle; import android.app.Fragment; import android.app.FragmentManager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import app.ari.assignment1.R; /** * Created by Ari on 16/12/16. */ public class TweetActivity extends AppCompatActivity { ActionBar actionBar; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_container); actionBar = getSupportActionBar(); FragmentManager manager = getFragmentManager(); Fragment fragment = manager.findFragmentById(R.id.fragmentContainer); if (fragment == null) { fragment = new TweeterFragment(); manager.beginTransaction().add(R.id.fragmentContainer, fragment).commit(); } } }
17e6e75906a5da7cad648a7b0303f5089293bea5
2fe164deaf81b2242a545f622fc9197fd43d6e4f
/src/com/radish/thinking/unit15/ComparablePet.java
a2f905c7f30af535fa3ab357682e624040ed1bf9
[]
no_license
daluoboer/practice
b58488f5f43afb2eb4c06bb0c0c8ce137a917717
6d4eac442dcb8617293982659636dd53bd343643
refs/heads/master
2021-05-23T19:30:02.599615
2020-12-06T12:28:23
2020-12-06T12:28:23
253,434,856
0
0
null
null
null
null
UTF-8
Java
false
false
187
java
package com.radish.thinking.unit15; public class ComparablePet implements Comparable<ComparablePet> { @Override public int compareTo(ComparablePet o) { return 0; } }
88f3dbd306586ab54cf1006a0897df19da0d9e17
6f19edce2f9b8709aa22e6456f043573e00a3bf6
/src/main/java/springbootactuatorlab/rest/SecurityController.java
dfb26cdba092c928f48242afbb61b31b55751b30
[]
no_license
pedro21900/spring-boot-actuator-lab
7d08806a67ddc606f6a58a8516024454178ea196
0ca6db40612baf2aa919725765ffaffb54f74e4a
refs/heads/master
2023-06-10T08:44:18.407662
2021-06-29T16:20:52
2021-06-29T16:20:52
379,643,926
0
0
null
null
null
null
UTF-8
Java
false
false
656
java
package springbootactuatorlab.rest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/auth") public class SecurityController { @GetMapping("/status") public ResponseEntity<String> getStatus() { ResponseEntity<String> responseEntity = new ResponseEntity<>("Resource is fetched", HttpStatus.OK); return responseEntity; } }
[ "pedro.lenonn" ]
pedro.lenonn
7c8de44a05f1b4af9da6bf93cb27f28bd404a569
ed865190ed878874174df0493b4268fccb636a29
/PuridiomRequestForQuotes/src/com/tsa/puridiom/rfq/tasks/RfqSetStatusToBidsReceived.java
900639128e54389df07a9d80d6dd193b7ecdcdc6
[]
no_license
zach-hu/srr_java8
6841936eda9fdcc2e8185b85b4a524b509ea4b1b
9b6096ba76e54da3fe7eba70989978edb5a33d8e
refs/heads/master
2021-01-10T00:57:42.107554
2015-11-06T14:12:56
2015-11-06T14:12:56
45,641,885
0
0
null
null
null
null
UTF-8
Java
false
false
1,014
java
package com.tsa.puridiom.rfq.tasks; import com.tsa.puridiom.common.documents.DocumentStatus; import com.tsa.puridiom.entity.RfqHeader; import com.tsa.puridiom.entity.RfqLine; import com.tsa.puridiom.property.PropertiesManager; import com.tsagate.foundation.processengine.Task; import java.util.List; import java.util.Map; public class RfqSetStatusToBidsReceived extends Task { public Object executeTask(Object object) throws Exception { Map incomingRequest = (Map)object; String userId = (String) incomingRequest.get("userId") ; PropertiesManager propertiesManager = PropertiesManager.getInstance((String)incomingRequest.get("organizationId")) ; RfqHeader rfh = (RfqHeader)incomingRequest.get("rfqHeader") ; List rfqLineList = (List) incomingRequest.get("rfqLineList") ; rfh.setStatus(DocumentStatus.RFQ_PURCHASING); for (int i=0; i < rfqLineList.size(); i++) { RfqLine rfl = (RfqLine) rfqLineList.get(i); rfl.setStatus(DocumentStatus.RFQ_PURCHASING) ; } return null ; } }
[ "brickerz@9227675a-84a3-4efe-bc6c-d7b3a3cf6466" ]
brickerz@9227675a-84a3-4efe-bc6c-d7b3a3cf6466
b747f9050d5859bc7de9fd03770a2d2d8d27c523
0a1e238120665de5b0a723051a537d4498e0caf9
/src/main/java/com/itheima/acl/param/AclModuleParam.java
59a28f0bfb60d861518db0d7b7822264e2b478c2
[]
no_license
shanxf1992/permission_managment_system
cb11192443c37f6b236945a93c22cada60085cbe
045c7adab1610b40a7a7c00c0cb36d1bb78afb26
refs/heads/master
2020-03-28T18:38:36.792837
2018-09-15T11:59:17
2018-09-15T11:59:17
148,897,792
0
0
null
null
null
null
UTF-8
Java
false
false
947
java
package com.itheima.acl.param; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.validator.constraints.Length; import javax.validation.constraints.Max; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; @Setter @Getter @ToString public class AclModuleParam { private Integer id; @Length(min = 2, max = 64, message = "权限模块名称长度需要在2~64个字之间") private String name; private Integer parentId = 0; @NotNull(message = "权限模块展示顺序不能为空") private Integer seq; @NotNull(message = "权限模块状态不能为空") @Min(value = 0, message = "状态最小为值0") @Max(value = 1, message = "状态最大值为1") private Integer status; @Length(min = 0, max = 64, message = "备注长度需要在64个字以内") private String remark; }
04a5933e7002011d26df33aa7dd3a8840c7abdc1
bfe4cc4bb945ab7040652495fbf1e397ae1b72f7
/compute/src/main/java/org/jclouds/compute/predicates/NodeTerminated.java
ce3aee4317ddf55fc22aaae99eab8ba371ab998a
[ "Apache-2.0" ]
permissive
dllllb/jclouds
348d8bebb347a95aa4c1325590c299be69804c7d
fec28774da709e2189ba563fc3e845741acea497
refs/heads/master
2020-12-25T11:42:31.362453
2011-07-30T22:32:07
2011-07-30T22:32:07
1,571,863
2
0
null
null
null
null
UTF-8
Java
false
false
2,047
java
/** * * Copyright (C) 2011 Cloud Conscious, LLC. <[email protected]> * * ==================================================================== * 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.jclouds.compute.predicates; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Resource; import javax.inject.Singleton; import org.jclouds.compute.ComputeService; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeState; import org.jclouds.logging.Logger; import com.google.common.base.Predicate; import com.google.inject.Inject; /** * * Tests to see if a node is deleted * * @author Adrian Cole */ @Singleton public class NodeTerminated implements Predicate<NodeMetadata> { private final ComputeService client; @Resource protected Logger logger = Logger.NULL; @Inject public NodeTerminated(ComputeService client) { this.client = client; } public boolean apply(NodeMetadata node) { logger.trace("looking for state on node %s", checkNotNull(node, "node")); node = refresh(node); if (node == null) return true; logger.trace("%s: looking for node state %s: currently: %s", node.getId(), NodeState.TERMINATED, node.getState()); return node.getState() == NodeState.TERMINATED; } private NodeMetadata refresh(NodeMetadata node) { return client.getNodeMetadata(node.getId()); } }
6946512c55ebe9f8d5a1b4972a44c8daa51cf435
9109586d72344396cdb762497c25c40db276c4fb
/src/main/java/br/com/sismed/mongodb/domain/Login.java
559f75a0ce1e2fb17a44dfbe0cb9a271d2a710c2
[]
no_license
jvrapi/sismed_mongodb
86b82303227f32e9b2d9796e0a9007a0db5401fa
55c2035d1e7be05460f19915a22d22d82adc0382
refs/heads/master
2023-07-10T12:15:17.462904
2020-04-06T14:31:04
2020-04-06T14:31:04
398,935,250
0
0
null
null
null
null
UTF-8
Java
false
false
454
java
package br.com.sismed.mongodb.domain; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class Login { private String senha; private String codigo; public String getSenha() { return senha; } public void setSenha(String senha) { this.senha = new BCryptPasswordEncoder().encode(senha); } public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } }
d2431b4f56645a99d86aac36209ddb340d7a23ba
31c5e85697423b2763d12b0039ec73c92a1441e9
/app/src/main/java/org/meruvian/workshop/fragment/DetailNewsFragment.java
4baccf95ccd13daac11820acccae8b563b5b0f10
[]
no_license
ricodidan/Workshop-Meruvian
ce76449f3a6415c22a5acbc913b0ed5b5f2d4dcb
3ef48d905c6dfcf58df79920923fc5e04fea3757
refs/heads/master
2021-01-13T03:44:02.720472
2016-12-28T00:44:10
2016-12-28T00:44:10
77,271,456
1
0
null
null
null
null
UTF-8
Java
false
false
1,382
java
package org.meruvian.workshop.fragment; import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.meruvian.workshop.R; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Enrico_Didan on 23/12/2016. */ public class DetailNewsFragment extends Fragment { private TextView title, date, content; private DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm"); @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_detail, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { title = (TextView) view.findViewById(R.id.text_title); date = (TextView) view.findViewById(R.id.text_date); content = (TextView) view.findViewById(R.id.text_content); if (getArguments() != null) { title.setText(getArguments().getString("title", "-")); date.setText(dateFormat.format(new Date(getArguments().getLong("date", 0)))); content.setText(getArguments().getString("content", "-")); } } }
ae15bf7c1c99537fa54388aa8351f706b0d6590a
2d16fd9d1b9d57445cf0419ffd1ac710600416aa
/Documents/NetBeansProjects/JavaApplication7/src/HotelPackage/FicheChambres.java
ee552193ca20dadc6296e7e18ef5bbcb1b93ff27
[]
no_license
Yasmine-amrn/HotelLaGazelle
cd415595e60972858b1977acadbda8965a12de06
93e10a24d6690d6dbe87e35ce01b0567d0dce70f
refs/heads/master
2023-04-03T00:02:00.240278
2021-04-09T23:25:07
2021-04-09T23:25:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
22,987
java
/* * 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 HotelPackage; import java.sql.*; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author pc-click */ public class FicheChambres extends javax.swing.JFrame { Connection cnx=null; /** * Creates new form FicheChambres */ public FicheChambres() { setUndecorated(true); setResizable(false); initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel17 = new javax.swing.JLabel(); NumChambre = new javax.swing.JTextField(); jLabel18 = new javax.swing.JLabel(); NumBloc = new javax.swing.JTextField(); jLabel19 = new javax.swing.JLabel(); NumEtage = new javax.swing.JTextField(); jLabel20 = new javax.swing.JLabel(); Categorie = new javax.swing.JTextField(); jLabel21 = new javax.swing.JLabel(); NbrLits = new javax.swing.JTextField(); jLabel22 = new javax.swing.JLabel(); Prix = new javax.swing.JTextField(); Confirme = new javax.swing.JButton(); Annuler = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel1.setBackground(new java.awt.Color(2, 5, 8)); jLabel1.setFont(new java.awt.Font("Bell MT", 1, 28)); // NOI18N jLabel1.setForeground(new java.awt.Color(242, 236, 228)); jLabel1.setText("Fiche Chambre"); jButton1.setBackground(new java.awt.Color(2, 5, 8,0)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/HotelPackage/exitpng.png"))); // NOI18N jButton1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton1MouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { jButton1MousePressed(evt); } }); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 1122, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(111, 111, 111)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(14, 14, 14) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addContainerGap(14, Short.MAX_VALUE)) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1460, 60)); jPanel2.setBackground(new java.awt.Color(250, 249, 248)); jLabel17.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel17.setForeground(new java.awt.Color(2, 5, 8)); jLabel17.setText("N° de chambre"); NumChambre.setBackground(new java.awt.Color(250, 249, 248)); NumChambre.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N NumChambre.setForeground(new java.awt.Color(2, 5, 8)); jLabel18.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel18.setForeground(new java.awt.Color(2, 5, 8)); jLabel18.setText("N° de bloc"); NumBloc.setBackground(new java.awt.Color(250, 249, 248)); NumBloc.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N NumBloc.setForeground(new java.awt.Color(2, 5, 8)); jLabel19.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel19.setForeground(new java.awt.Color(2, 5, 8)); jLabel19.setText("N° de étage"); NumEtage.setBackground(new java.awt.Color(250, 249, 248)); NumEtage.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N NumEtage.setForeground(new java.awt.Color(2, 5, 8)); jLabel20.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel20.setForeground(new java.awt.Color(2, 5, 8)); jLabel20.setText("Catégorie"); Categorie.setBackground(new java.awt.Color(250, 249, 248)); Categorie.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N Categorie.setForeground(new java.awt.Color(2, 5, 8)); jLabel21.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel21.setForeground(new java.awt.Color(2, 5, 8)); jLabel21.setText("Nbr de lits"); NbrLits.setBackground(new java.awt.Color(250, 249, 248)); NbrLits.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N NbrLits.setForeground(new java.awt.Color(2, 5, 8)); jLabel22.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N jLabel22.setForeground(new java.awt.Color(2, 5, 8)); jLabel22.setText("Prix de chambre"); Prix.setBackground(new java.awt.Color(250, 249, 248)); Prix.setFont(new java.awt.Font("Bell MT", 0, 20)); // NOI18N Prix.setForeground(new java.awt.Color(2, 5, 8)); Confirme.setBackground(new java.awt.Color(0, 0, 0)); Confirme.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N Confirme.setForeground(new java.awt.Color(250, 249, 248)); Confirme.setText("Confirmer"); Confirme.setPreferredSize(new java.awt.Dimension(150, 52)); Confirme.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { ConfirmeMouseMoved(evt); } }); Confirme.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { ConfirmeFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { ConfirmeFocusLost(evt); } }); Confirme.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { ConfirmeMouseClicked(evt); } public void mousePressed(java.awt.event.MouseEvent evt) { ConfirmeMousePressed(evt); } }); Confirme.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { ConfirmeActionPerformed(evt); } }); Annuler.setBackground(new java.awt.Color(0, 0, 0)); Annuler.setFont(new java.awt.Font("Bell MT", 0, 22)); // NOI18N Annuler.setForeground(new java.awt.Color(250, 249, 248)); Annuler.setText("Annuler"); Annuler.setPreferredSize(new java.awt.Dimension(150, 52)); Annuler.addFocusListener(new java.awt.event.FocusAdapter() { public void focusGained(java.awt.event.FocusEvent evt) { AnnulerFocusGained(evt); } public void focusLost(java.awt.event.FocusEvent evt) { AnnulerFocusLost(evt); } }); Annuler.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { AnnulerActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(98, 98, 98) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel19) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(NumEtage, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jLabel18)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 87, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(NumChambre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(NumBloc, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(113, 113, 113) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel22) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 77, Short.MAX_VALUE) .addComponent(Prix, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel20) .addComponent(jLabel21)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(Categorie, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(NbrLits, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(261, 261, 261)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(Confirme, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(Annuler, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(177, 177, 177)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(86, 86, 86) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel20) .addComponent(Categorie, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel21) .addComponent(NbrLits, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel22) .addComponent(Prix, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel17) .addComponent(NumChambre, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel18) .addComponent(NumBloc, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(28, 28, 28) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel19) .addComponent(NumEtage, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 359, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(Confirme, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(Annuler, javax.swing.GroupLayout.PREFERRED_SIZE, 43, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(305, 305, 305)) ); getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 60, 1460, 960)); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked }//GEN-LAST:event_jButton1MouseClicked private void jButton1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MousePressed }//GEN-LAST:event_jButton1MousePressed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed new Chambre().setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void ConfirmeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ConfirmeFocusGained Confirme.setBackground(new java.awt.Color(250,249,248)); Confirme.setForeground(new java.awt.Color(2, 5, 8)); }//GEN-LAST:event_ConfirmeFocusGained private void ConfirmeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_ConfirmeFocusLost Confirme.setBackground(new java.awt.Color(0,0,0)); Confirme.setForeground(new java.awt.Color(250,249,248)); }//GEN-LAST:event_ConfirmeFocusLost private void ConfirmeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ConfirmeMouseClicked }//GEN-LAST:event_ConfirmeMouseClicked private void ConfirmeMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ConfirmeMousePressed }//GEN-LAST:event_ConfirmeMousePressed private void ConfirmeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ConfirmeActionPerformed // conditions sur les champs int k=0; String catégorie= Categorie.getText().toString(); try{ Integer.parseInt(NumChambre.getText()); k++; }catch(Exception e){JOptionPane.showMessageDialog(null, "la N° de chambre doit etre un nombre entier !!");;} try{ Integer.parseInt(NumBloc.getText()); k++; }catch(Exception e){JOptionPane.showMessageDialog(null, "la N° de bloc doit etre un nombre entier !!");} try{ Integer.parseInt(NumEtage.getText()); k++; }catch(Exception e){JOptionPane.showMessageDialog(null, "la N° de l'étage doit etre un nombre entier !!");} try{ Integer.parseInt(NbrLits.getText()); k++; }catch(Exception e){JOptionPane.showMessageDialog(null, "le nombre de lits doit etre un nombre entier !!");} try{ Double.parseDouble(Prix.getText()); k++; }catch(Exception e){JOptionPane.showMessageDialog(null, "le prix de chambre doit etre un nombre !!");} //remplir BD if(k==5){ try{ Class.forName("com.mysql.jdbc.Driver"); System.err.println("connected"); Connection cnx =DriverManager.getConnection("jdbc:mysql://localhost:3306/hotellagazelle","root",""); Statement st =cnx.createStatement(); //requete String SQL ="insert into chambre(NumChambre,NumBloc,NumEtage,Categorie,NbrLits,PrixChambre,Disponible)"+ "values("+NumChambre.getText().toString()+","+NumBloc.getText().toString()+","+NumEtage.getText().toString()+","+"\""+Categorie.getText().toString()+"\"" +","+NbrLits.getText().toString()+","+Prix.getText().toString()+","+1+");"; st.executeUpdate(SQL); JOptionPane.showMessageDialog(null, "Oprération réussie"); this.dispose(); new Chambre().setVisible(true); }catch(Exception e){ JOptionPane.showMessageDialog(null, e);}} }//GEN-LAST:event_ConfirmeActionPerformed private void AnnulerFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AnnulerFocusGained Annuler.setBackground(new java.awt.Color(250,249,248)); Annuler.setForeground(new java.awt.Color(2, 5, 8)); }//GEN-LAST:event_AnnulerFocusGained private void AnnulerFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_AnnulerFocusLost Annuler.setBackground(new java.awt.Color(0,0,0)); Annuler.setForeground(new java.awt.Color(250,249,248)); }//GEN-LAST:event_AnnulerFocusLost private void AnnulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AnnulerActionPerformed new Chambre().setVisible(true); this.dispose(); }//GEN-LAST:event_AnnulerActionPerformed private void ConfirmeMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ConfirmeMouseMoved }//GEN-LAST:event_ConfirmeMouseMoved /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FicheChambres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FicheChambres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FicheChambres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FicheChambres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FicheChambres().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton Annuler; private javax.swing.JTextField Categorie; private javax.swing.JButton Confirme; private javax.swing.JTextField NbrLits; private javax.swing.JTextField NumBloc; private javax.swing.JTextField NumChambre; private javax.swing.JTextField NumEtage; private javax.swing.JTextField Prix; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel20; private javax.swing.JLabel jLabel21; private javax.swing.JLabel jLabel22; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; // End of variables declaration//GEN-END:variables }