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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
54c71ed576d1c6f439b2e284080faa59b4cf933f | cdfd2b5409102ee8680ef129740fbb34022a7e24 | /src/application/infra/TestContext.java | 4e6b2545b5a684aff00220f29ce4fca48cf3aa54 | [
"MIT"
] | permissive | Arpit-Shah/ArtosDashboard | fe5ff584a4f9aa920c57d937340b39bdb41d4b84 | aad81ed807db12db99de9b8ca368f4342ec95515 | refs/heads/master | 2022-06-23T10:53:07.342277 | 2021-01-15T19:54:18 | 2021-01-15T19:54:18 | 183,857,112 | 1 | 1 | MIT | 2022-06-21T01:05:43 | 2019-04-28T04:51:49 | Java | UTF-8 | Java | false | false | 1,542 | java | /*******************************************************************************
* Copyright (C) 2018-2019 Arpit Shah and Artos Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package application.infra;
public class TestContext {
private LogWrapper logWrapper;
public LogWrapper getLogWrapper() {
return logWrapper;
}
public void setLogWrapper(LogWrapper logWrapper) {
this.logWrapper = logWrapper;
}
}
| [
"[email protected]"
] | |
99427e65e55e8b08138e0beb8c43ad8a656b56a1 | 226e88235a832617d37e25c61b44088b3ee79735 | /src/octavian/algorithms/Algorithm.java | 968573da3f844422aca6dbcb0a41decc210e1375 | [
"Apache-2.0"
] | permissive | boctavian96/Encrypter | 85152be0655bc6f397e1c0bfc515662494296945 | 6be61f36a775e616c3b5a0dcb4df57493025ec4f | refs/heads/master | 2021-01-19T17:31:01.516662 | 2018-06-26T20:55:56 | 2018-06-26T20:55:56 | 101,066,121 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | 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 octavian.algorithms;
import java.security.PublicKey;
import java.security.PrivateKey;
/**
*
* @author octavian.bodnariu
*/
public interface Algorithm {
public abstract void encrypt();
public abstract void decrypt();
}
| [
"[email protected]"
] | |
1ab41a661a7a5f594d2e22184630931b0a9c52b4 | 3538406360a3ebe52f00e7b53cc06acb58b004a0 | /deegree-core/trunk/src/main/java/org/deegree/feature/persistence/mapping/property/GeometryMapping.java | 46d544750e0bc31d1c38af980a25709517e10888 | [] | no_license | izaslavsky/incf-dai | d563e63aa7cf7147ceb5a60c2b7ade3754f502c8 | 4ba6954720974139388ac0f77040fabe28fb4752 | refs/heads/master | 2016-09-06T11:13:51.903896 | 2013-02-07T02:30:15 | 2013-02-07T02:30:15 | 32,130,589 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,037 | java | //$HeadURL: http://svn.wald.intevation.org/svn/deegree/deegree3/branches/3.0/deegree-core/src/main/java/org/deegree/feature/persistence/mapping/property/GeometryMapping.java $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.feature.persistence.mapping.property;
import org.deegree.cs.CRS;
import org.deegree.feature.persistence.mapping.JoinChain;
import org.deegree.feature.persistence.mapping.MappingExpression;
import org.deegree.feature.types.property.GeometryPropertyType.CoordinateDimension;
import org.deegree.feature.types.property.GeometryPropertyType.GeometryType;
import org.deegree.filter.expression.PropertyName;
/**
* The <code></code> class TODO add class documentation here.
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author: mschneider $
*
* @version $Revision: 27750 $, $Date: 2010-11-03 08:49:44 -0700 (Wed, 03 Nov 2010) $
*/
public class GeometryMapping extends Mapping {
private GeometryType type;
private CoordinateDimension dim;
private CRS crs;
private String srid;
public GeometryMapping( PropertyName path, MappingExpression mapping, GeometryType type, CoordinateDimension dim,
CRS crs, String srid, JoinChain joinedTable ) {
super( path, mapping, joinedTable );
this.type = type;
this.dim = dim;
this.crs = crs;
this.srid = srid;
}
public GeometryType getType() {
return type;
}
public CoordinateDimension getDim() {
return dim;
}
public CRS getCRS() {
return crs;
}
public String getSrid() {
return srid;
}
@Override
public String toString() {
return super.toString() + ",{type=" + type + "}";
}
} | [
"davlit0917@7cbae6f4-d32f-11de-a711-9fae7a67fc1c"
] | davlit0917@7cbae6f4-d32f-11de-a711-9fae7a67fc1c |
da3ce1e4c8b9c4f8bd227e24ce27873211715131 | c4909320f6647fcd3f02279501d1f0c9959b13d5 | /src/com/pep/http/HttpExchangeHandler.java | 62754be245a9f6f95bdd1f47f6f40d502b2d7c6b | [] | no_license | LongHuu100/Tu_Code_Java_Http_Server | a9d6ae6608181389b72994b7ecfcc61e0a034b16 | cca89698799eb439dae339bdbc2d607396a690da | refs/heads/master | 2023-08-02T15:58:47.165254 | 2021-10-03T10:04:48 | 2021-10-03T10:04:48 | 405,921,312 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,142 | java | package com.pep.http;
import com.pep.http.util.MalformedRequestException;
import com.pep.http.util.RoutingException;
import com.pep.http.util.Status;
import java.io.IOException;
/**
* HttpExchangeHandler
*/
public class HttpExchangeHandler implements ExchangeHandler {
private final HttpHandler handler;
public HttpExchangeHandler(HttpHandler handler) {
if (handler == null)
throw new IllegalArgumentException();
this.handler = handler;
}
/* Được gọi từ com.pep.http.Server --> listen */
@Override
public void accept(Exchange exchange) throws IOException {
HttpReader reader = new HttpReader(exchange.in);
HttpWriter writer = new HttpWriter(exchange.out);
try {
handler.accept(reader, writer);
} catch (MalformedRequestException e) {
Status.badRequest().accept(reader, writer);
} catch (RoutingException e) {
Status.notFound().accept(reader, writer);
} catch (Exception e) {
e.printStackTrace();
Status.internalServerError().accept(reader, writer);
}
}
}
| [
"[email protected]"
] | |
f246fbae08d2c1645b39dd03f3435815937b3970 | c69db3b464f024259d588816904a534369c1e4f7 | /kafka-injector-core/src/main/java/com/mikerusoft/kafka/injector/core/properties/Kafka.java | c0ec995f4d129c8e0389ef130e172d26ff2aacfd | [
"Apache-2.0"
] | permissive | grinfeld/kafka-injector | 189aa62007d3526a10dca2071524011ef9aeb9f8 | b2eac90abf5aa44211bc04343818786266d4da05 | refs/heads/master | 2022-11-21T15:11:27.658180 | 2020-10-12T11:18:43 | 2020-10-12T11:18:43 | 193,083,230 | 0 | 1 | Apache-2.0 | 2023-09-05T22:00:11 | 2019-06-21T10:58:32 | Java | UTF-8 | Java | false | false | 397 | java | package com.mikerusoft.kafka.injector.core.properties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Kafka {
private String url;
private String schemaRegistryUrl;
private boolean createTopics;
private Integer batchSize;
private int lingerMs = 1;
private Topic[] topics;
}
| [
"[email protected]"
] | |
cc3d466ecf12b13b7b4f055cbc5a5269d222250c | c62161b99ba63a9322bc2a3971a7617f52b42202 | /src/main/java/estateagency/dto/realtors/NewRealtorForm.java | 1c83d7cd32169c8f9141281e8ee6542a37aede54 | [] | no_license | reisal78/estateagency_2 | 8e7a260828cadcf643f6733f0f57e3e2cac84d83 | dd32acc43b663d2f0a801d76833cd16060cb3ec2 | refs/heads/master | 2021-08-24T09:55:44.458375 | 2017-12-09T03:43:50 | 2017-12-09T03:43:51 | 113,638,866 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,468 | java | package estateagency.dto.realtors;
import estateagency.model.Authority;
import estateagency.validation.Name;
import estateagency.validation.Phone;
import estateagency.validation.UniqueUsername;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.Arrays;
public class NewRealtorForm {
private final Authority[] authorities = Authority.allAuthorities;
private Long id;
@NotEmpty(message = "{message.errors.empty_field}")
@Name
private String fullName;
@NotEmpty(message = "{message.errors.empty_field}")
@Phone
private String phone;
@UniqueUsername
@NotEmpty(message = "{message.errors.empty_field}")
private String username;
@NotEmpty(message = "{message.errors.empty_field}")
private String password;
private boolean enabled;
private Authority authority;
public NewRealtorForm() {
}
@Override
public String toString() {
return "NewRealtorForm{" +
"id=" + id +
", fullName='" + fullName + '\'' +
", phone='" + phone + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", enabled=" + enabled +
", authorities=" + Arrays.toString(authorities) +
", authority=" + authority +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Authority[] getAuthorities() {
return authorities;
}
public Authority getAuthority() {
return authority;
}
public void setAuthority(Authority authority) {
this.authority = authority;
}
}
| [
"[email protected]"
] | |
776df0f40fd156310af07139e6d8ef7935919724 | f05b6cfe969177c897ff485892e583e56ed95e01 | /src/com/cg/address/UI.java | 45122e00490c49290939fca3a511445bbdd4bab1 | [] | no_license | nkneeraj/AddressBookTest | 14637b5600d0d468e596d8a1e5bc0ca5c68ed949 | 147570da3cb29593f0857e576ba48c322ef9172e | refs/heads/master | 2022-12-19T11:28:59.922364 | 2020-09-28T12:30:44 | 2020-09-28T12:30:44 | 299,093,835 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,525 | java | package com.cg.address;
import java.util.*;
public class UI {
public void function(AddressBook book) {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Address Book");
int input = 1;
while(input != 0) {
System.out.println("Input 0 For no action.");
System.out.println("Input 1 to Add a contact.");
System.out.println("Input 2 to update an existing contact");
System.out.println("Input 3 to delete an existing contact");
input = sc.nextInt();sc.nextLine();
switch(input) {
case 1:
System.out.println("Enter first name");
String firstName = sc.nextLine();
if(book.hasContact(firstName))
System.out.println("Enter last name");
String lastName = sc.nextLine();
System.out.println("Enter address line");
String address = sc.nextLine();
System.out.println("Enter city name");
String city = sc.nextLine();
System.out.println("Enter state name");
String state = sc.next();
System.out.println("Enter zip name");
int zipCode = sc.nextInt();
sc.nextLine();
Contact newContact = new Contact(firstName, lastName, address, city, state, zipCode);
book.addContact(newContact);
break;
case 2:
System.out.println("Input first name of person");
String searchName = sc.nextLine();
book.updateContact(searchName);
break;
case 3:
System.out.println("Input first name of the contact you want to delete");
String Name = sc.nextLine();
book.deleteContact(Name);
break;
}
}
}
}
| [
"[email protected]"
] | |
d179b33990fb9114c1fceb78fb81017abd26a881 | f27826af11e6e1c88980603f92311089a2a84f47 | /src/com/clarion/worksys/service/RegionSumService.java | 1aa4e94de39e1537ce6fad50bd028d781478c10f | [] | no_license | yaorong4700/waterInfoSystem | 780fe4e72dab20628f3ee65ff993cff5579c0735 | 98b58c031fe1254973fa214d675391d30f727eb9 | refs/heads/master | 2021-01-20T18:28:52.040293 | 2016-06-16T09:14:10 | 2016-06-16T09:14:10 | 60,671,012 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 540 | java | package com.clarion.worksys.service;
import java.util.List;
import com.clarion.worksys.entity.WaterInfo;
import com.clarion.worksys.httpentity.RegionSumReqParam;
public interface RegionSumService {
List<WaterInfo> searchList(RegionSumReqParam regionSumReqParam);
int totalPageCount(RegionSumReqParam regionSumReqParam);
void deleteByRegionDeviceCollectTime(RegionSumReqParam regionSumReqParam);
List<WaterInfo> downloadregionSumShow();
String downloadRegionSum(List<WaterInfo> regionSumList, String realpathString);
}
| [
"[email protected]"
] | |
4c4207137b9943fcffb5a580ab6b627510e89f6a | 07d5605350374bc7a17ac1c75b3f40b059d07945 | /cayenne-server/src/test/java/org/apache/cayenne/testdo/oneway/auto/_OnewayTable4.java | 388cbdfc3589f8aa93f27571a2dfdfc09566473e | [
"Apache-2.0"
] | permissive | wx930910/cayenne_refactoring | 839521ac1245fd91183312b94b6004b2b6bb115e | b5356d80b9d6a8bb0f763bf4e748c4669f4b1a87 | refs/heads/master | 2023-01-30T04:49:52.767938 | 2020-12-15T07:17:25 | 2020-12-15T07:17:25 | 314,658,092 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,721 | java | package org.apache.cayenne.testdo.oneway.auto;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.cayenne.BaseDataObject;
/**
* Class _OnewayTable4 was generated by Cayenne.
* It is probably a good idea to avoid changing this class manually,
* since it may be overwritten next time code is regenerated.
* If you need to make any customizations, please use subclass.
*/
public abstract class _OnewayTable4 extends BaseDataObject {
private static final long serialVersionUID = 1L;
public static final String ID_PK_COLUMN = "ID";
@Override
public Object readPropertyDirectly(String propName) {
if(propName == null) {
throw new IllegalArgumentException();
}
switch(propName) {
default:
return super.readPropertyDirectly(propName);
}
}
@Override
public void writePropertyDirectly(String propName, Object val) {
if(propName == null) {
throw new IllegalArgumentException();
}
switch (propName) {
default:
super.writePropertyDirectly(propName, val);
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
writeSerialized(out);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
readSerialized(in);
}
@Override
protected void writeState(ObjectOutputStream out) throws IOException {
super.writeState(out);
}
@Override
protected void readState(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.readState(in);
}
}
| [
"[email protected]"
] | |
81202ed3acc20e2c724b4746ad323de10d7c06c6 | 3f5c848b8fe01add732e011a727332abcc30ba6f | /src/controlador/ControladorListaPedidos.java | e8f660658ff0a3a880db3e195bbfd2349c6a377b | [] | no_license | MarianoMarchiaro/repositorioMariano | f9af2cbf34f2b0b58d2014252b7d90b7bacd10ec | 6fc5511b9507ed56c80ff251e49ad2e965162587 | refs/heads/master | 2021-01-08T03:40:18.399358 | 2020-02-20T14:29:48 | 2020-02-20T14:29:48 | 241,901,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,350 | 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 controlador;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import modelo.*;
import vista.*;
/**
*
* @author Mariano
*/
public class ControladorListaPedidos implements ActionListener{
private VentanaListaPedidos vistaPedidos;
private RepositorioPedido repoPedido;
private RepositorioTicket repoTicket = new RepositorioTicket();
public ControladorListaPedidos(){
vistaPedidos = new VentanaListaPedidos();
vistaPedidos.ejecutar();
vistaPedidos.setControlador(this);
repoPedido = new RepositorioPedido();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(vistaPedidos.ESTADO_NOPAGADO)){
EstadoPedido estado = EstadoPedido.NO_PAGADO;
vistaPedidos.cargarTabla(estado);
}
if(e.getActionCommand().equals(vistaPedidos.ESTADO_PAGADO)){
EstadoPedido estado = EstadoPedido.PAGADO;
vistaPedidos.cargarTabla(estado);
}
if(e.getActionCommand().equals(vistaPedidos.ESTADO_ENPROCESO)){
EstadoPedido estado = EstadoPedido.EN_PROCESO;
vistaPedidos.cargarTabla(estado);
}
if(e.getActionCommand().equals(vistaPedidos.ESTADO_PARARETIRAR)){
EstadoPedido estado = EstadoPedido.PARA_RETIRAR;
vistaPedidos.cargarTabla(estado);
}
if(e.getActionCommand().equals(vistaPedidos.ESTADO_FINALIZADO)){
EstadoPedido estado = EstadoPedido.FINALIZADO;
vistaPedidos.cargarTabla(estado);
}
if(e.getActionCommand().equals(vistaPedidos.BOTON_BUSCAR)){
int numero = vistaPedidos.cargarNumero();
vistaPedidos.cargarTabla(numero);
}
if(e.getActionCommand().equals(vistaPedidos.BOTON_INGRESOTRANSPORTE)){
int numero = vistaPedidos.jTable1.getSelectedRow();
Pedido pedido = repoPedido.getPedidos().get(numero);
if(pedido.getEstado().toString().equals(EstadoPedido.PAGADO.toString())){
ControladorGestionIngresoTransporte controlador = new ControladorGestionIngresoTransporte(pedido, vistaPedidos,repoTicket);
}else{
JOptionPane.showMessageDialog(vistaPedidos,"Elija un pedido con estado Pagado");
}
}
if(e.getActionCommand().equals(vistaPedidos.BOTON_EGRESOTRANSPORTE)){
int numero = vistaPedidos.jTable1.getSelectedRow();
Pedido pedido = repoPedido.getPedidos().get(numero);
repoTicket.añadirPedidos(repoPedido);
ControladorGestionarEgresoTransporte controlador = new ControladorGestionarEgresoTransporte(pedido,repoTicket,repoPedido);
}
}
public Ticket conseguirTicket(Pedido pedido,ArrayList<Ticket> tickets){
Ticket ticket = new Ticket();
for(int i=0; i<tickets.size()-1;i++){
if(pedido.getNumero() == tickets.get(i).getPedido().getNumero()){
ticket = tickets.get(i);
}
}
return ticket;
}
}
| [
"Mariano@Mariano-PC"
] | Mariano@Mariano-PC |
4180bbb228e14d37b8dd62834971f2b978338167 | fb14903f50ec711e9732b1b7c3084b2a51fb215f | /myTimer.java | 4b38b2ac0e99cc279434e7af8ac71a27199a4480 | [] | no_license | Draktolli/Timer-Plugin | 302ce6d81aed14bc9d31766ee470bbe578ebdaca | 498bc3ce85fae6cff8fd286c64762e706b66e40d | refs/heads/main | 2023-05-20T06:45:55.941969 | 2021-06-03T02:22:47 | 2021-06-03T02:22:47 | 373,356,215 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 431 | java | import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
public class myTimer extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
JDialog dialog1 = new ourdialog();
dialog1.setVisible(true);
}
}
| [
"[email protected]"
] | |
eb65672a59e8e62eca02a1de26ea056776390b81 | 2049eacdcbb46f3ce1788de29451f7060b2ac02c | /app/src/main/java/com/ninewatt/beacon_collector/BeaconReceiver.java | 5b9d08f29d3537c1f0e83c478930ef68d4e1db1b | [] | no_license | LouieKim/nw_ble_app | 4a0a5cee3c5857d7f1bb0422efc8c85004541846 | 914e61751b70b80ff23553e6f1f99c139f938326 | refs/heads/main | 2023-01-03T08:39:14.541464 | 2020-11-06T04:22:41 | 2020-11-06T04:22:41 | 305,271,802 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,545 | java | package com.ninewatt.beacon_collector;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.bluetooth.le.ScanResult;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.PowerManager;
import android.util.Log;
import com.ninewatt.beacon_collector.beacon.BeaconData;
import com.ninewatt.beacon_collector.beacon.BeaconScanner;
import com.ninewatt.beacon_collector.util.LogUtil;
import com.ninewatt.beacon_collector.util.PrefUtil;
import static android.content.Context.ALARM_SERVICE;
/**
* Alarm 으로 호출
* Beacon 스캔 및 데이터 전송 작업 수행 후 Alarm 재등록
*/
public class BeaconReceiver extends BroadcastReceiver {
private static final String TAG = "!!@@BeaconReceiver";
@Override
public void onReceive(final Context context, Intent intent) {
boolean exist = PrefUtil.hasDevice(context);
final long interval = 1000 * 60 * PrefUtil.getInterval(context);
Log.d(TAG, "onReceive - Exist Device : " + exist + ", Interval : " + interval);
LogUtil.saveLog("D", "!!@@BeaconReceiver", "onReceive - Exist Device : " + exist + ", Interval : " + interval);
// 등록된 디바이스가 있으면 작업 수행
if (exist) {
BeaconScanner scanner = new BeaconScanner(context, new BeaconScanner.OnBleListener() {
@Override
public void onRetry() {
}
@Override
public void onInitFailed() {
}
@Override
public void onAddScanResult(ScanResult result) {
BeaconData data = new BeaconData();
data.convertBeaconData(result);
Log.d(TAG, "onAddScanResult - data : " + data.toString());
LogUtil.saveLog("D", TAG, "onAddScanResult - data : " + data.toString());
TaskManager.getInstance().sendData(PrefUtil.getSiteId(context), String.valueOf(data.getMinor()),
new TaskManager.OnSendListener() {
@Override
public void onSuccess(String data) {
Log.d(TAG, "sendData - onSuccess : " + data);
LogUtil.saveLog("D", "!!@@BeaconReceiver", "sendData - onSuccess : " + data);
startAlarm(context, interval);
}
@Override
public void onFailed() {
Log.e(TAG, "sendData - onFailed");
LogUtil.saveLog("D", "!!@@BeaconReceiver", "sendData - onFailed");
startAlarm(context, interval);
}
});
}
@Override
public void onScanFailed() {
Log.e(TAG, "sendData - onScanFailed");
LogUtil.saveLog("D", "!!@@BeaconReceiver", "sendData - onScanFailed");
startAlarm(context, interval);
}
});
scanner.startScan(PrefUtil.getDeviceAddress(context));
} else {
Log.e(TAG, "등록된 디바이스가 없습니다.");
LogUtil.saveLog("E", "!!@@BeaconReceiver", "등록된 디바이스가 없습니다.");
startAlarm(context, interval);
}
}
public static void startAlarm(Context context, long interval) {
LogUtil.saveLog("E", "!!@@BeaconReceiver", "startAlarm : " + interval);
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm != null) {
boolean isScreenOn = pm.isInteractive();
boolean isIdle = false;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
isIdle = pm.isDeviceIdleMode();
Log.i(TAG, "startAlarm - isScreenOn : " + isScreenOn + ", isIdle : " + isIdle);
if (!isScreenOn || isIdle) {
// PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myApp:notificationLock");
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "myApp:notificationLock");
// PowerManager.WakeLock wl = pm.newWakeLock(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, "myApp:notificationLock");
wl.acquire(interval);
Log.d(TAG, "startAlarm - WakeLock");
}
}
AlarmManager alarmMgr = (AlarmManager) context.getSystemService(ALARM_SERVICE);
Intent alarmIntent = new Intent(context, BeaconReceiver.class);
PendingIntent alarmPendingIntent = PendingIntent.getBroadcast(context, 101, alarmIntent, 0);
alarmMgr.cancel(alarmPendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Log.d(TAG, "startAlarm - setExactAndAllowWhileIdle");
alarmMgr.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, alarmPendingIntent);
} else {
Log.d(TAG, "startAlarm - setExact");
alarmMgr.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, alarmPendingIntent);
}
}
} | [
"[email protected]"
] | |
6d4b7ed14d05903cfecf6ef3bdfcab59ffd447e7 | cd86541e1265fcd206af6436a01d551c393c3ce8 | /src/Viewer/ImageManager.java | cbca25e6ceeb80d8cfbed2d68f48cd05f059a089 | [] | no_license | Moneil97/Image-Tools | 269bb2d7d683fe66cf4d34758d3a3bf01b008af9 | 8c4e248492173336f3b0b8bcedda798d6ff9d610 | refs/heads/master | 2016-09-07T19:04:07.353216 | 2015-02-21T03:32:41 | 2015-02-21T03:32:41 | 31,000,708 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,803 | java | package Viewer;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class ImageManager {
private FileFilter filter;
private String extensions[] = {".jpg", ".png", ".gif", ".jpeg", ".bmp", ".wbmp"};
private List<File> photos = new ArrayList<File>();
private int imageNum = 0;
public ImageManager() {
filter = new FileFilter(){
@Override
public boolean accept(File file) {
for (String extension : extensions)
if (file.getName().toLowerCase().endsWith(extension))
return true;
return false;
}
};
}
public void addImages(File file) {
if (file.isDirectory()){
for (File f : file.listFiles(filter))
photos.add(f);
}
else if (file.isFile()){
if (filter.accept(file))
photos.add(file);
}
System.out.println(photos);
}
public BufferedImage nextImage(){
if (imageNum < photos.size())
imageNum ++;
try {
return ImageIO.read(photos.get(imageNum));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public BufferedImage previousImage(){
if (imageNum > 0)
imageNum --;
try {
return ImageIO.read(photos.get(imageNum));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public BufferedImage getFirstImage() {
try {
return ImageIO.read(photos.get(0));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public void clear() {
photos.clear();
imageNum = 0;
}
public int getImageCount(){
return photos.size();
}
public int getCurrentImageNum(){
return imageNum;
}
}
| [
"[email protected]"
] | |
726c2712b40e7fd9aebe71292684100e120461a3 | 9d923577897bcbeab17c89603a971faa208c1fa0 | /app/src/main/java/creativeLab/samsung/mbf/utils/UserInfo.java | 56a4d0f4b3d515c2c2fbdf90c2d3394e4fdcc53a | [] | no_license | miyoungvkim/MBF | 01825b5963f0d24a900c1d4144c602867790bc68 | 2d4fe10fa1870795d9e9b09adb3d8dfd186fe4a3 | refs/heads/master | 2020-03-21T04:41:44.865439 | 2018-11-24T11:10:39 | 2018-11-24T11:10:39 | 138,118,422 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package creativeLab.samsung.mbf.utils;
public class UserInfo {
public static String USER_DEFAULT_NAME = "친구";
private static String UserName = "친구";
private static int UserAge = 1;
private static int LimitedTime = 10;
public static synchronized String getUserName() {
return UserName;
}
public static synchronized void setUserName(String UserName) {
UserInfo.UserName = UserName;
}
public static synchronized int getUserAge() {
return UserAge;
}
public static synchronized void setUserAge(int UserAge) {
UserInfo.UserAge = UserAge;
}
public static synchronized int getLimitedTime() {
return LimitedTime;
}
public static synchronized void setLimitedTime(int LimitedTime) {
UserInfo.LimitedTime = LimitedTime;
}
}
| [
"[email protected]"
] | |
39057d360794640de5b19a71c7efd5ab2a9b3412 | 6e1877e641316d391fcf98332f1a40b881eea7a4 | /app/src/main/java/com/msfthack/crowdcheck/MapActivity.java | a5e81a9801f0ee9f855bfa0d109c945fb61c9c1d | [] | no_license | asaratik/crowdcheck | 1e95b176e16ddb6bf3f630ba68a022821e3e0f0c | 496d9656108f0d7848449011aad3c1a69f1f0885 | refs/heads/master | 2022-11-24T12:17:43.009132 | 2020-07-30T06:55:34 | 2020-07-30T06:55:34 | 283,094,405 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,025 | java | package com.msfthack.crowdcheck;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
// Bing imports
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.microsoft.maps.CustomTileMapLayer;
import com.microsoft.maps.MapElementTappedEventArgs;
import com.microsoft.maps.MapFlyout;
import com.microsoft.maps.MapImage;
import com.microsoft.maps.MapLayer;
import com.microsoft.maps.MapRenderMode;
import com.microsoft.maps.MapTileBitmapRequestedEventArgs;
import com.microsoft.maps.MapView;
import com.microsoft.maps.Geopoint;
import com.microsoft.maps.MapAnimationKind;
import com.microsoft.maps.MapScene;
import com.microsoft.maps.MapElementLayer;
import com.microsoft.maps.MapIcon;
import com.microsoft.maps.OnBitmapRequestedListener;
import com.microsoft.maps.OnMapElementTappedListener;
import com.msfthack.crowdcheck.helpers.Locations;
import com.msfthack.crowdcheck.helpers.POI;
import com.msfthack.crowdcheck.helpers.Utils;
public class MapActivity extends AppCompatActivity{
private MapView mMapView;
private MapElementLayer mPinLayer;
private List<MapIcon> pins;
List<Locations> locations;
private Geopoint LOCATION;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mMapView = new MapView(this, MapRenderMode.VECTOR);
mPinLayer = new MapElementLayer();
mPinLayer.addOnMapElementTappedListener(new OnMapElementTappedListener() {
@Override
public boolean onMapElementTapped(MapElementTappedEventArgs mapElementTappedEventArgs) {
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(getApplicationContext(),
getLocationDetails((int) mapElementTappedEventArgs.mapElements.get(0).getTag()), duration);
toast.show();
return false;
}
});
mMapView.getLayers().add(mPinLayer);
mMapView.setCredentialsKey(BuildConfig.CREDENTIALS_KEY);
((FrameLayout)findViewById(R.id.map_view)).addView(mMapView);
mMapView.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
//Setup the required data for the map view
Intent intent = getIntent();
setupRequiredData(intent.getStringExtra("location"));
mMapView.setScene(
MapScene.createFromLocationAndZoomLevel(LOCATION, 18),
MapAnimationKind.NONE);
addPinsToLayer(pins);
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
@Override
protected void onStop() {
super.onStop();
mMapView.onStop();
}
@Override
protected void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
private MapIcon getPin(Geopoint geo, String title, int intensity, int uid)
{
MapIcon pushpin = new MapIcon();
pushpin.setLocation(geo);
MapFlyout flyOut = new MapFlyout();
// ImageView iv = new ImageView(getApplicationContext());
// Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
try {
InputStream is;
if(intensity > 75)
{
is = getApplicationContext().getAssets().open("red.png");
flyOut.setDescription("Busy");
}
else if(intensity > 40 && intensity < 75)
{
is = getApplicationContext().getAssets().open("orange.png");
flyOut.setDescription("Moderate");
}
else
{
is = getApplicationContext().getAssets().open("green.png");
flyOut.setDescription("Free");
}
pushpin.setTag(uid);
pushpin.setImage(new MapImage(is));
pushpin.setOpacity(0.5f);
}catch (IOException io)
{
io.printStackTrace();
}
pushpin.setTitle(title);
pushpin.setFlyout(flyOut);
return pushpin;
}
private void addPinsToLayer(List<MapIcon> pins)
{
for(MapIcon pin:pins) {
mPinLayer.getElements().add(pin);
}
}
private void setupRequiredData(String location)
{
String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "data.json");
Gson gson = new Gson();
Type listUserType = new TypeToken<List<Locations>>() { }.getType();
locations = gson.fromJson(jsonFileString, listUserType);
pins = new ArrayList<>();
for (int i = 0; i < locations.size(); i++)
if(locations.get(i).getTitle().equals(location))
{
Log.println(Log.INFO, "TAG", locations.get(i).toString());
LOCATION = new Geopoint(locations.get(i).getLat(), locations.get(i).getLng());
List<POI> list = locations.get(i).getPoi();
for(int j = 0;j<list.size();j++)
pins.add(getPin(new Geopoint(list.get(j).getLat(), list.get(j).getLng()),
list.get(j).getTitle(), list.get(j).getIntensity(), list.get(j).getUid()));
break;
}
}
private String getLocationDetails(int uid)
{
String jsonFileString = Utils.getJsonFromAssets(getApplicationContext(), "data.json");
Gson gson = new Gson();
Type listUserType = new TypeToken<List<Locations>>() { }.getType();
locations = gson.fromJson(jsonFileString, listUserType);
pins = new ArrayList<>();
for (int i = 0; i < locations.size(); i++) {
List<POI> list = locations.get(i).getPoi();
for(int j = 0;j<list.size();j++)
if ((list.get(j).getUid() == uid))
return list.get(j).getTitle();
}
return "default";
}
}
| [
"[email protected]"
] | |
559b5ee8d588278c3f0fa212a8f010c93dcc989d | 10891c4750a12fc08b108afdfbaeb0ab1ceb3958 | /IF01-10118006-Latihan21-RataRataNilai/src/if01/pkg10118006/latihan21/rataratanilai/IF0110118006Latihan21RataRataNilai.java | 191f1385815d7934af588cb307a3e3866404fbb3 | [] | no_license | MrBradabie/IF01-10118006-Latihan21-RataRataNilai | bb4c5621031092559f291b09cc086dfc545b7875 | 1db3e62f87c7f1af6b4e25af8b9a544e31334502 | refs/heads/master | 2020-08-09T17:07:33.169679 | 2019-10-10T08:36:32 | 2019-10-10T08:36:32 | 214,129,498 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 960 | java | package if01.pkg10118006.latihan21.rataratanilai;
import java.util.Scanner;
/*
* NAMA : Alfarizi Rizki Pane
* KELAS : IF-01
* NIM : 10118006
* DESKRIPSI PROGRAM : Program yang dapat menghasilkan rata-rata nilai dari suatu input-an
*/
public class IF0110118006Latihan21RataRataNilai {
public static void main(String[] args) {
int i, totalMahasiswa;
double Total;
double nilai;
Scanner masuk = new Scanner(System.in);
System.out.print("Masukkan Banyaknya Mahasiswa : ");
totalMahasiswa = masuk.nextInt();
i = 1;
Total = 0;
while (i <= totalMahasiswa) {
System.out.print("Nilai Mahasiswa ke-" + i + " : ");
nilai = masuk.nextDouble();
Total += nilai;
i++;
}
System.out.println("\nMaka,Rata-rata Nilainya adalah " + Total / totalMahasiswa);
}
}
| [
"[email protected]"
] | |
1202454e3a54da5d956b9a73c463aa1d648fb588 | b3a79c99e20db39e7e0405c20bedad5a762b903e | /TaskFirebaseDatabase/app/src/main/java/com/example/appinventiv/taskfirebasedatabase/fragment/ChatFragment.java | 2e0f23de6ad07eaa2223ee4bec35e1578fb4462c | [] | no_license | salonibisht/ChatApp | d108459be83beaf26f42a7335d50ac3d8f0215a5 | c78e73c47a345c297e1ba40995304d49f21885f4 | refs/heads/master | 2020-03-07T22:42:50.958932 | 2018-04-02T14:25:41 | 2018-04-02T14:25:41 | 127,761,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,147 | java | package com.example.appinventiv.taskfirebasedatabase.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.appinventiv.taskfirebasedatabase.R;
import com.example.appinventiv.taskfirebasedatabase.activity.ChatActivity;
import com.example.appinventiv.taskfirebasedatabase.activity.LogInActivity;
import com.example.appinventiv.taskfirebasedatabase.interfaces.UserInfoInterface;
import com.example.appinventiv.taskfirebasedatabase.model.UserInfo;
import com.example.appinventiv.taskfirebasedatabase.utility.AppConstants;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
/**
* A simple {@link Fragment} subclass.
*/
public class ChatFragment extends Fragment implements UserInfoInterface {
@BindView(R.id.iv_back)
ImageView ivBack;
@BindView(R.id.toolbar_title)
TextView toolbarTitle;
Unbinder unbinder;
@BindView(R.id.toolbar_profile)
ImageView toolbarProfile;
@BindView(R.id.rv_chat_contacts)
RecyclerView rvChatContacts;
private DatabaseReference mDatabasereference;
private FirebaseUser firebaseUser;
private Query query;
private TextView tvName;
private String name;
private FirebaseRecyclerAdapter<UserInfo,UserViewHolder> firebaseRecyclerAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_chat, container, false);
unbinder = ButterKnife.bind(this, view);
toolbarTitle.setText(R.string.messages);
toolbarProfile.setVisibility(View.VISIBLE);
firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
query = FirebaseDatabase.getInstance()
.getReference()
.child(AppConstants.KEY_USER);
rvChatContacts.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onStart() {
super.onStart();
setChatAdapter();
}
/**
* set Adapter to show User name on inbox....
*/
private void setChatAdapter() {
FirebaseRecyclerOptions<UserInfo> options =
new FirebaseRecyclerOptions.Builder<UserInfo>()
.setQuery(query, UserInfo.class)
.build();
firebaseRecyclerAdapter=new FirebaseRecyclerAdapter<UserInfo, UserViewHolder>(options) {
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_status, parent, false);
return new UserViewHolder(view); }
@Override
protected void onBindViewHolder(@NonNull UserViewHolder holder, int position, @NonNull UserInfo model) {
holder.setName(model.getmFirstName(),model.getmSurname());
}
};
firebaseRecyclerAdapter.startListening();
rvChatContacts.setAdapter(firebaseRecyclerAdapter);
}
@OnClick(R.id.iv_back)
public void onViewClicked() {
}
@Override
public void setOnItemClickListener(View view, int position) {
Intent intent=new Intent(getActivity(),ChatActivity.class);
intent.putExtra("selectedUserId",firebaseRecyclerAdapter.getRef(position).getKey());
intent.putExtra("name",name);
intent.putExtra("type","inboxUser");
startActivity(intent);
}
public class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
tvName=itemView.findViewById(R.id.tv_user_name);
mView=itemView;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setOnItemClickListener(view,getAdapterPosition());
}
});
}
/**
* Set name present in the database to the text view in the inox..
* @param s
* @param s1
*/
public void setName(String s, String s1) {
name=s+" "+s1;
tvName.setText(s+" "+s1);
}
}
}
| [
"[email protected]"
] | |
7750158e0a9624432b19c42ba7010f18cb51fc8a | 32ba22aa2ad08088355b906c4ae75e0308390be7 | /JasonImageUtil/src/main/java/com/jason/jasonimageutil/ReadImage.java | 2ce3e009432e736a1fd4af184f04acbfc6af6f22 | [] | no_license | DonyLi/ImageUtil | 21fcd814ccce21a1bd306b1b5382258ffb15c4dc | e8a61b6305470941178be91c55838ef6dd8aa70c | refs/heads/master | 2020-03-19T23:58:08.631059 | 2019-01-08T06:34:52 | 2019-01-08T06:34:52 | 137,026,929 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 141 | java | package com.jason.jasonimageutil;
public interface ReadImage {
ReadImageResult readImage(String path, int widthLim, boolean isGif);
}
| [
"[email protected]"
] | |
232f6421b059dedba96f0f4dab6274f7ab8d50c2 | 07af209df92e6c247d12f76b91f2f2e2edfb46f0 | /JavaBrains_Courses/JavaBrainsSpringDI/src/org/mzherdev/Triangle.java | 7479aafacc63e062c901d7df44329030972c1bc7 | [] | no_license | michaelzherdev/Java | 7d19bf3358ce5d4cbb4774cdf86488aef9d26bb4 | 5b71e9b42814304d1128d696c91bb97f301a5d99 | refs/heads/master | 2021-01-10T06:31:36.341504 | 2015-10-15T19:31:46 | 2015-10-15T19:31:46 | 44,328,179 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 258 | java | package org.mzherdev;
public class Triangle {
private String type;
public void draw() {
System.out.println(getType() + " Triangle draw");
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| [
"[email protected]"
] | |
cdf60bce52857eeeedd29a6267dd8ed907113296 | eaf69ea473f4f048ff9c445c39ada42e8fde23bb | /src/main/java/cw19/phone/Telefon.java | a06fdee3ad3a145f4de28f4a4ce466c0031b46cb | [] | no_license | Kasad0r/ppj | b0eaae4087e87e7522834321be277d06a2a543b3 | a66a6a5c954f068b3ff301190d105e51cf764fdd | refs/heads/master | 2020-08-20T13:46:20.681503 | 2020-01-21T14:02:26 | 2020-01-21T14:02:26 | 216,029,847 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 438 | java | package cw19.phone;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Telefon implements Funkcional {
String interfejsKomunikacyjny;
String color;
public void zadzwon(String numer) {
System.out.println("Call to " + numer);
}
@Override
public void wyswietlHistoriePolaczen() {
}
}
| [
"[email protected]"
] | |
b7f9073760680dc2c410135ab72611759138d79f | 28a7ede896b98bf6e2630129d94e9e7afd29dc13 | /src/main/java/com/nsb/practice/designpatterns/visitor/Monitor.java | 38d3fd32fc5fd7903e334b6747219039725938b6 | [
"Apache-2.0"
] | permissive | Dorae132/practice | 8a7da9702074608c04d0b5e1a5358a9aad02eccb | d95221c3dea36720df3f0b0019d171a60c60e114 | refs/heads/master | 2022-11-28T10:43:35.461565 | 2020-09-27T00:51:20 | 2020-09-27T00:51:20 | 135,540,001 | 1 | 1 | Apache-2.0 | 2022-10-18T23:20:51 | 2018-05-31T06:14:03 | Java | UTF-8 | Java | false | false | 227 | java | package com.nsb.practice.designpatterns.visitor;
public class Monitor implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
| [
"[email protected]"
] | |
8cd05d37efd811b8cfb9b7a1136cefc73e74e32c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/26/26_940403c7c625d7e4a7073da45784d38e8361b617/InsertReviewFrame/26_940403c7c625d7e4a7073da45784d38e8361b617_InsertReviewFrame_s.java | e9a3b04019843ece8c62b8b1c8eec3af004326b3 | [] | 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,103 | java | import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.*;
/*
* A review frame where a user can insert a review.
*/
public class InsertReviewFrame extends JFrame
{
private static Connection connection;
private static PreparedStatement preparedStatement = null;
JLabel label1, label2, label3, label4;
JComboBox input1, input2, input3, input4;
JButton saveButton, resetButton;
String[] ratingChoices = {"1 - Dishaster!", "2 - Poor", "3 - Meh", "4 - Good", "5 - Great" };
String restid = "";
public InsertReviewFrame(Connection cn, final int userid)
{
connection = cn;
setTitle("Dishaster! - New Review");
setLayout(new GridLayout(5,2));
setSize(new Dimension(400, 250));
label1 = new JLabel(" Restaurant:");
label2 = new JLabel(" Address:");
label3 = new JLabel(" Dish:");
label4 = new JLabel(" Rating:");
ArrayList<String> names = new ArrayList<String>();
try {
names = GUIFrame.readDataBase("distinct name", 1, 1, "");
} catch (Exception e2) {
e2.printStackTrace();
}
input1 = new JComboBox(names.toArray());
input1.setSelectedItem(null);
input2 = new JComboBox();
input3 = new JComboBox();
input4 = new JComboBox();
input1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
try
{
input2.removeAllItems();
input3.removeAllItems();
String name = (String)input1.getSelectedItem();
name = name.replace("'", "\\'");
String where = "name = '" + name + "'";
ArrayList<String> addresses = GUIFrame.readDataBase("address", 1, 1, where);
for (String address : addresses)
input2.addItem(address);
input2.setSelectedItem(null);
ArrayList<String> foods = GUIFrame.readDataBase("distinct food", 1, 3, where);
for (String food : foods)
input3.addItem(food);
input3.setSelectedItem(null);
}
catch(Exception e) {}
}
});
input2.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent event)
{
try
{
String where = "address = '" + input2.getSelectedItem() + "'";
restid = GUIFrame.readDataBase("restaurant_id", 1, 1, where).get(0);
}
catch(Exception e) {}
}
});
input4 = new JComboBox(ratingChoices);
input4.setSelectedItem(null);
saveButton = new JButton("Add");
resetButton = new JButton("Reset");
add(label1);
add(input1);
add(label2);
add(input2);
add(label3);
add(input3);
add(label4);
add(input4);
add(saveButton);
add(resetButton);
// resets all the fields
resetButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
input1.setSelectedItem(null);
input2.setSelectedItem(null);
input3.setSelectedItem(null);
input4.setSelectedItem(null);
}
});
// insert new review
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String value1 = (String) input1.getSelectedItem();
String value2 = (String) input2.getSelectedItem();
String value3 = (String) input3.getSelectedItem();
String value4 = Integer.toString(input4.getSelectedIndex() + 1);
System.out.println(value1 + value2 + value3 + value4);
try
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String statement = "insert into Review(reviewer_id, restaurant_id, food, rating, created) " +
"values(" + userid + ", " + restid + ", '" + input3.getSelectedItem() + "', " + (input4.getSelectedIndex()+1) + ", '" + dateFormat.format(cal.getTime()) + "')";
System.out.println(statement);
preparedStatement = connection.prepareStatement(statement);
preparedStatement.executeUpdate();
JOptionPane.showMessageDialog(saveButton, "Successfully added.");
// update the review frame table
ReviewFrame.updateTable("SELECT name as restaurant, address, food, rating, created as date " +
"FROM Review NATURAL JOIN Restaurant " +
"WHERE reviewer_id = " + userid + " " +
"ORDER BY created DESC;");
try
{
// update the review archive
CallableStatement cStmt = connection.prepareCall("{call UpdateArchive()}");
//cStmt.setString(1, dateFormat.format(cal.getTime()));
cStmt.execute();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(saveButton,"Error archiving.");
}
dispose();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(saveButton,"You have made this review already. If you wish to change the rating, select 'Update Review'.");
}
}
});
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
| [
"[email protected]"
] | |
fa1b8b54d621b68c17bd0fb03464a1b02621a9d4 | aa86f5c41866b66c1cf1c5f11a4af428ddf3c2b0 | /src/main/java/br/com/vetorsistemas/integradorbw/listas/ListaRepository.java | 60e1c4045a23eaa2ec09207102ed27d4d7eb1516 | [] | no_license | evirson/integradorbw | 83091151be615e143f4341aef588ec14eb08470d | 8b7353e14ec44080d7e09bbdc97878909ae0aebd | refs/heads/master | 2021-05-19T19:15:23.113037 | 2020-04-11T23:12:18 | 2020-04-11T23:12:18 | 252,079,293 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 824 | java | package br.com.vetorsistemas.integradorbw.listas;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ListaRepository extends JpaRepository<Lista, Integer> {
default List<Lista> findAll() {
List<Lista> lista = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
Lista x = new Lista();
x.setId(i);
x.setIndice(1);
switch (i) {
case 1:
x.setDescricao("Clientes");
x.setTipo(1);
break;
case 2:
x.setDescricao("Normal");
x.setTipo(2);
break;
case 3:
x.setDescricao("Oferta");
x.setTipo(2);
break;
default:
x.setDescricao("Não Nominado");
x.setTipo(2);
}
lista.add(x);
}
return lista;
}
}
| [
"[email protected]"
] | |
715db68e27b2217cb19276e78849332c0cf00599 | 7229c57245ad7c44a973e5ca12087f6953903e4f | /JavaPractice/src/org/dimigo/oop/SnackTest.java | a4556d84debd0dd8a1402515c0264bb12adb458c | [] | no_license | wp132424/JavaPractice | 0f5070a20bb459147aa7976364448306883e4e53 | b8b07ad80f83b6f72997a9ab945f4fd611b7a0c7 | refs/heads/master | 2020-05-27T08:18:45.931706 | 2015-08-25T08:18:50 | 2015-08-25T08:18:50 | 32,291,359 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 468 | java | package org.dimigo.oop;
public class SnackTest {
public static void main(String[] args) {
Snack[] SnackArr= new Snack[] {
new Snack("새우깡","농심",1100,2),
new Snack("콘칲","크라운",1200,1),
new Snack("허니버터칩","해태",1500,4)
};
int sum= 0;
for (Snack snack : SnackArr) {
sum += snack.calcPrice();
snack.printSnack();
System.out.println();
}
System.out.println("총합 : " + sum);
}
}
| [
"Junghyun@JHPC"
] | Junghyun@JHPC |
63271aacaeecf622c15bf0ff4b4b069dfa81e463 | 2273e9bca8a622ad37f41762fc32fec6e8ed7105 | /heima-leadnews/heima-leadnews-wemedia-gateway/src/main/java/com/heima/wemedia/gateway/WemediaGatewayApplication.java | 9d46ce2acdde3cd4889e5cd3ffe809b7d643b5d2 | [] | no_license | AI96/heima-leadnews | a47652a11d698e2b45f7eaeea63ca9048fac8cfc | 8eadcdd22c248636c8e9eb46108710401026ea64 | refs/heads/master | 2023-05-11T04:38:21.347605 | 2021-05-27T03:13:24 | 2021-05-27T03:13:24 | 370,889,214 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 461 | java | package com.heima.wemedia.gateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient //开启注册中心
public class WemediaGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(WemediaGatewayApplication.class,args);
}
} | [
"[email protected]"
] | |
681cdfb941636186e016a6e0fbc0bfc806e1db16 | dcf729ee06ef88e658be5cdc0568dd617a711856 | /one_to_fifty/Four.java | eb778c2e6145d3ced973324bcb6f4e9623f016ef | [] | no_license | Dendiom/Algorithm | 0ab21298a686d1f2f08dfb77b987833ef1b6e2fe | ca22fe9d2a6226917e28642f8556528c61e0be35 | refs/heads/master | 2021-07-07T11:07:28.992315 | 2019-04-13T08:12:25 | 2019-04-13T08:12:25 | 86,013,289 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,200 | java | package LeetCode.one_to_fifty;
public class Four {
//o(m + n)
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int target1 = 0, target2 = 0;
if ((m + n) % 2 == 0) {
target1 = (m + n) / 2 - 1;
target2 = target1 + 1;
} else {
target1 = (m + n) / 2;
}
int index1 = 0, index2 = 0, count = -1;
while (index1 < m && index2 < n) {
if (nums1[index1] <= nums2[index2]) {
count++;
if (count == target1) {
target1 = nums1[index1];
if (target2 == 0) {
return target1;
} else {
if (index1 + 1 < m) {
target2 = Math.min(nums1[index1 + 1], nums2[index2]);
} else {
target2 = nums2[index2];
}
return (target1 + target2) / 2.0;
}
}
index1++;
} else {
count++;
if (count == target1) {
target1 = nums2[index2];
if (target2 == 0) {
return target1;
} else {
if (index2 + 1 < n) {
target2 = Math.min(nums1[index1], nums2[index2 + 1]);
} else {
target2 = nums1[index1];
}
return (target1 + target2) / 2.0;
}
}
index2++;
}
}
count++;
if (index1 == m) {
while (count < target1) {
count++;
index2++;
}
return target2 == 0? nums2[index2] : (nums2[index2] + nums2[index2 + 1]) / 2.0;
} else {
while (count < target1) {
count++;
index1++;
}
return target2 == 0? nums1[index1] : (nums1[index1] + nums1[index1 + 1]) / 2.0;
}
}
public static double brief(int[] nums1, int[] nums2) {
int m = nums1.length;
int n = nums2.length;
int len = m + n;
int index1 = 0, index2 = 0;
int first = 0, second = 0;
for (int i = 0; i <= len / 2; i++) {
first = second;
if (index1 < m && (index2 >= n || nums1[index1] <= nums2[index2])) {
second = nums1[index1++];
} else {
second = nums2[index2++];
}
}
if (len % 2 == 0) {
return (first + second) / 2.0;
}
return second;
}
public static void main(String[] args) {
System.out.println(findMedianSortedArrays(new int[]{1,3,5}, new int[]{}));
System.out.println(findMedianSortedArrays(new int[]{}, new int[]{1,6}));
System.out.println(brief(new int[]{}, new int[]{1,6}));
System.out.println(brief(new int[]{1, 6, 7 }, new int[]{1,6}));
}
}
| [
"[email protected]"
] | |
00a2feade55fa7cbd468091a6518a6bcfeb1799c | a674a24708c7808d028f4eeffbdb08d64802dfbb | /src/test/java/Training/TrainigDemo/MobileTest.java | 1cbd4915da58984af4c59af93cd839f452543cc9 | [] | no_license | SelvendranAutomation/TraininDemo | 7a3696d187795028df98ea6575ffe817d96ca40a | 8d9f2c1d51e4f1b15f30866f59f4959f9714b11b | refs/heads/master | 2020-04-13T05:10:27.701946 | 2018-12-24T12:00:16 | 2018-12-24T12:00:16 | 162,983,752 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 812 | java | package Training.TrainigDemo;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class MobileTest {
@Test
public void open(){
System.out.println("Mobile Emulator browser..");
System.setProperty("webdriver.chrome.driver", "C:\\Users\\DELL\\Desktop\\BackupDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
//WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.close();
}
}
| [
"[email protected]"
] | |
14feb8349214ba9a3303d8b1af376a8ec5d7c124 | 1eb33cf6cff62ba84359b7b4b39ec121cbe0f72b | /src/main/java/construction/NoArgConstructor.java | 434a2bc4d9e40ea7b501e82fafe17d7fb9d8c621 | [] | no_license | jiuli/java_practice | 6068cedb4b5da41d5346be3d7f9ded5122d058e6 | b3baa327c1ca21415f8666aa76d1ab1bbce87c5f | refs/heads/master | 2021-06-05T17:39:09.249150 | 2021-06-03T08:27:23 | 2021-06-03T08:27:23 | 76,339,391 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 127 | java | package construction;
public class NoArgConstructor {
public NoArgConstructor() {
// Constructor body here
}
} | [
"[email protected]"
] | |
2bb9c560ff2f612034a3e34a6c4877e64fa5bd65 | 36d7ac13d205b9a5b8c3308a27c4605a1cd7ee56 | /others/AndEngine-GLES2-AnchorCenter/src/org/andengine/audio/sound/SoundManager.java | a24468adf18047b6b34d4d9e97ca5ae94a9f8cdc | [
"Apache-2.0"
] | permissive | renanlr/billyadventures | 92103d6208f2e80644fca38c2c8a4ad6f2b5a7ce | f35384d6355dbbdbc5708b370731d1be1e652f39 | refs/heads/master | 2021-01-20T03:39:09.059791 | 2014-12-09T05:03:33 | 2014-12-09T05:03:33 | 23,578,058 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,142 | java | package org.andengine.audio.sound;
import org.andengine.audio.BaseAudioManager;
import org.andengine.audio.sound.exception.SoundException;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.util.SparseArray;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:22:59 - 11.03.2010
*/
public class SoundManager extends BaseAudioManager<Sound> implements OnLoadCompleteListener {
// ===========================================================
// Constants
// ===========================================================
private static final int SOUND_STATUS_OK = 0;
public static final int MAX_SIMULTANEOUS_STREAMS_DEFAULT = 5;
// ===========================================================
// Fields
// ===========================================================
private final SoundPool mSoundPool;
private final SparseArray<Sound> mSoundMap = new SparseArray<Sound>();
// ===========================================================
// Constructors
// ===========================================================
public SoundManager() {
this(MAX_SIMULTANEOUS_STREAMS_DEFAULT);
}
public SoundManager(final int pMaxSimultaneousStreams) {
this.mSoundPool = new SoundPool(pMaxSimultaneousStreams, AudioManager.STREAM_MUSIC, 0);
this.mSoundPool.setOnLoadCompleteListener(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
SoundPool getSoundPool() {
return this.mSoundPool;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void add(final Sound pSound) {
super.add(pSound);
this.mSoundMap.put(pSound.getSoundID(), pSound);
}
@Override
public boolean remove(final Sound pSound) {
final boolean removed = super.remove(pSound);
if (removed) {
this.mSoundMap.remove(pSound.getSoundID());
}
return removed;
}
@Override
public void releaseAll() {
super.releaseAll();
this.mSoundPool.release();
}
@Override
public synchronized void onLoadComplete(final SoundPool pSoundPool, final int pSoundID, final int pStatus) {
if (pStatus == SoundManager.SOUND_STATUS_OK) {
final Sound sound = this.mSoundMap.get(pSoundID);
if (sound == null) {
throw new SoundException("Unexpected soundID: '" + pSoundID + "'.");
} else {
sound.setLoaded(true);
}
}
}
// ===========================================================
// Methods
// ===========================================================
public void onPause() {
this.mSoundPool.autoPause();
}
public void onResume() {
this.mSoundPool.autoResume();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| [
"[email protected]"
] | |
3306cc02362a18f13e5fc6726bd84d97e968701f | 214bdad60d082ede7d3d434afb3f5c9704b9e52e | /StrategyPattern/src/com/agroho/engine/V6CarEngine.java | c6f6b9dd83a16cc7a1a410cf861af55bcad6507c | [] | no_license | aRezaulAlam/DesignPattern | b25a3683215af89102c5b2a7ba45cb97a222e831 | 380fc231caf89cf869e764e25523358926f3569f | refs/heads/master | 2021-01-10T14:41:04.252094 | 2016-03-13T17:57:17 | 2016-03-13T17:57:17 | 53,788,056 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package com.agroho.engine;/*
* Created by rezaul on 2016-03-13.
* Email: [email protected]
*/
public class V6CarEngine implements EngineStyle {
@Override
public void CheckedEngine() {
System.out.println("This is running wit V6 Engine");
}
}
| [
"[email protected]"
] | |
823c53980c4b6d78e9cb4698a76fbe29a85e1b3e | 74f220bb490b8b9e3872a72f4fe0dce747c19b2b | /aws-java-sdk-comprehend/src/main/java/com/amazonaws/services/comprehend/model/StartSentimentDetectionJobRequest.java | a702f5179ad49aa0006320e7541ac0643e12b4aa | [
"Apache-2.0"
] | permissive | eginez/aws-sdk-java | 13f463d2f801b72bf4b65a54f73dc69b69157cce | fc5034d88b02731361ee12cbc34b600c97793557 | refs/heads/master | 2020-05-22T19:44:49.199107 | 2019-05-13T20:29:27 | 2019-05-13T20:29:27 | 186,497,171 | 1 | 0 | Apache-2.0 | 2019-05-13T21:19:19 | 2019-05-13T21:19:19 | null | UTF-8 | Java | false | false | 22,423 | java | /*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.services.comprehend.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/comprehend-2017-11-27/StartSentimentDetectionJob"
* target="_top">AWS API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class StartSentimentDetectionJobRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*/
private InputDataConfig inputDataConfig;
/**
* <p>
* Specifies where to send the output files.
* </p>
*/
private OutputDataConfig outputDataConfig;
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*/
private String dataAccessRoleArn;
/**
* <p>
* The identifier of the job.
* </p>
*/
private String jobName;
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*/
private String languageCode;
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*/
private String clientRequestToken;
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*/
private String volumeKmsKeyId;
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @param inputDataConfig
* Specifies the format and location of the input data for the job.
*/
public void setInputDataConfig(InputDataConfig inputDataConfig) {
this.inputDataConfig = inputDataConfig;
}
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @return Specifies the format and location of the input data for the job.
*/
public InputDataConfig getInputDataConfig() {
return this.inputDataConfig;
}
/**
* <p>
* Specifies the format and location of the input data for the job.
* </p>
*
* @param inputDataConfig
* Specifies the format and location of the input data for the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withInputDataConfig(InputDataConfig inputDataConfig) {
setInputDataConfig(inputDataConfig);
return this;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @param outputDataConfig
* Specifies where to send the output files.
*/
public void setOutputDataConfig(OutputDataConfig outputDataConfig) {
this.outputDataConfig = outputDataConfig;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @return Specifies where to send the output files.
*/
public OutputDataConfig getOutputDataConfig() {
return this.outputDataConfig;
}
/**
* <p>
* Specifies where to send the output files.
* </p>
*
* @param outputDataConfig
* Specifies where to send the output files.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withOutputDataConfig(OutputDataConfig outputDataConfig) {
setOutputDataConfig(outputDataConfig);
return this;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @param dataAccessRoleArn
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
*/
public void setDataAccessRoleArn(String dataAccessRoleArn) {
this.dataAccessRoleArn = dataAccessRoleArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @return The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
*/
public String getDataAccessRoleArn() {
return this.dataAccessRoleArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon Comprehend
* read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions<
* /a>.
* </p>
*
* @param dataAccessRoleArn
* The Amazon Resource Name (ARN) of the AWS Identity and Access Management (IAM) role that grants Amazon
* Comprehend read access to your input data. For more information, see <a href=
* "https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-permissions"
* >https://docs.aws.amazon.com/comprehend/latest/dg/access-control-managing-permissions.html#auth-role-
* permissions</a>.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withDataAccessRoleArn(String dataAccessRoleArn) {
setDataAccessRoleArn(dataAccessRoleArn);
return this;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @param jobName
* The identifier of the job.
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @return The identifier of the job.
*/
public String getJobName() {
return this.jobName;
}
/**
* <p>
* The identifier of the job.
* </p>
*
* @param jobName
* The identifier of the job.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withJobName(String jobName) {
setJobName(jobName);
return this;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @see LanguageCode
*/
public void setLanguageCode(String languageCode) {
this.languageCode = languageCode;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @return The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @see LanguageCode
*/
public String getLanguageCode() {
return this.languageCode;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LanguageCode
*/
public StartSentimentDetectionJobRequest withLanguageCode(String languageCode) {
setLanguageCode(languageCode);
return this;
}
/**
* <p>
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must be in
* the same language.
* </p>
*
* @param languageCode
* The language of the input documents. You can specify English ("en") or Spanish ("es"). All documents must
* be in the same language.
* @return Returns a reference to this object so that method calls can be chained together.
* @see LanguageCode
*/
public StartSentimentDetectionJobRequest withLanguageCode(LanguageCode languageCode) {
this.languageCode = languageCode.toString();
return this;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @param clientRequestToken
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
*/
public void setClientRequestToken(String clientRequestToken) {
this.clientRequestToken = clientRequestToken;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @return A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
*/
public String getClientRequestToken() {
return this.clientRequestToken;
}
/**
* <p>
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend generates one.
* </p>
*
* @param clientRequestToken
* A unique identifier for the request. If you don't set the client request token, Amazon Comprehend
* generates one.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withClientRequestToken(String clientRequestToken) {
setClientRequestToken(clientRequestToken);
return this;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @param volumeKmsKeyId
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage
* volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be
* either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
*/
public void setVolumeKmsKeyId(String volumeKmsKeyId) {
this.volumeKmsKeyId = volumeKmsKeyId;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @return ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the
* storage volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId
* can be either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
*/
public String getVolumeKmsKeyId() {
return this.volumeKmsKeyId;
}
/**
* <p>
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage volume
* attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be either of the
* following formats:
* </p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* </ul>
*
* @param volumeKmsKeyId
* ID for the AWS Key Management Service (KMS) key that Amazon Comprehend uses to encrypt data on the storage
* volume attached to the ML compute instance(s) that process the analysis job. The VolumeKmsKeyId can be
* either of the following formats:</p>
* <ul>
* <li>
* <p>
* KMS Key ID: <code>"1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* <li>
* <p>
* Amazon Resource Name (ARN) of a KMS Key:
* <code>"arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab"</code>
* </p>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public StartSentimentDetectionJobRequest withVolumeKmsKeyId(String volumeKmsKeyId) {
setVolumeKmsKeyId(volumeKmsKeyId);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getInputDataConfig() != null)
sb.append("InputDataConfig: ").append(getInputDataConfig()).append(",");
if (getOutputDataConfig() != null)
sb.append("OutputDataConfig: ").append(getOutputDataConfig()).append(",");
if (getDataAccessRoleArn() != null)
sb.append("DataAccessRoleArn: ").append(getDataAccessRoleArn()).append(",");
if (getJobName() != null)
sb.append("JobName: ").append(getJobName()).append(",");
if (getLanguageCode() != null)
sb.append("LanguageCode: ").append(getLanguageCode()).append(",");
if (getClientRequestToken() != null)
sb.append("ClientRequestToken: ").append(getClientRequestToken()).append(",");
if (getVolumeKmsKeyId() != null)
sb.append("VolumeKmsKeyId: ").append(getVolumeKmsKeyId());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof StartSentimentDetectionJobRequest == false)
return false;
StartSentimentDetectionJobRequest other = (StartSentimentDetectionJobRequest) obj;
if (other.getInputDataConfig() == null ^ this.getInputDataConfig() == null)
return false;
if (other.getInputDataConfig() != null && other.getInputDataConfig().equals(this.getInputDataConfig()) == false)
return false;
if (other.getOutputDataConfig() == null ^ this.getOutputDataConfig() == null)
return false;
if (other.getOutputDataConfig() != null && other.getOutputDataConfig().equals(this.getOutputDataConfig()) == false)
return false;
if (other.getDataAccessRoleArn() == null ^ this.getDataAccessRoleArn() == null)
return false;
if (other.getDataAccessRoleArn() != null && other.getDataAccessRoleArn().equals(this.getDataAccessRoleArn()) == false)
return false;
if (other.getJobName() == null ^ this.getJobName() == null)
return false;
if (other.getJobName() != null && other.getJobName().equals(this.getJobName()) == false)
return false;
if (other.getLanguageCode() == null ^ this.getLanguageCode() == null)
return false;
if (other.getLanguageCode() != null && other.getLanguageCode().equals(this.getLanguageCode()) == false)
return false;
if (other.getClientRequestToken() == null ^ this.getClientRequestToken() == null)
return false;
if (other.getClientRequestToken() != null && other.getClientRequestToken().equals(this.getClientRequestToken()) == false)
return false;
if (other.getVolumeKmsKeyId() == null ^ this.getVolumeKmsKeyId() == null)
return false;
if (other.getVolumeKmsKeyId() != null && other.getVolumeKmsKeyId().equals(this.getVolumeKmsKeyId()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInputDataConfig() == null) ? 0 : getInputDataConfig().hashCode());
hashCode = prime * hashCode + ((getOutputDataConfig() == null) ? 0 : getOutputDataConfig().hashCode());
hashCode = prime * hashCode + ((getDataAccessRoleArn() == null) ? 0 : getDataAccessRoleArn().hashCode());
hashCode = prime * hashCode + ((getJobName() == null) ? 0 : getJobName().hashCode());
hashCode = prime * hashCode + ((getLanguageCode() == null) ? 0 : getLanguageCode().hashCode());
hashCode = prime * hashCode + ((getClientRequestToken() == null) ? 0 : getClientRequestToken().hashCode());
hashCode = prime * hashCode + ((getVolumeKmsKeyId() == null) ? 0 : getVolumeKmsKeyId().hashCode());
return hashCode;
}
@Override
public StartSentimentDetectionJobRequest clone() {
return (StartSentimentDetectionJobRequest) super.clone();
}
}
| [
""
] | |
8340c76029d70edb1f418106b3cc9ab6770486f5 | f05d29ab5093f463a139c8e1db0da0cf754cfa86 | /Android Projects/ThePeoplesKitchen/src/com/example/thepeopleskitchen/ParseFood.java | ff17554146b6dcfdd4ca5bcd3d11ca09af71eaf0 | [] | no_license | skarpath/DevelopmentExamples | 2e2cf8f88a9c7e54320fc4d35a389d7f6c4962f0 | bf2bc615efcc1a7a7238150d84b52a2c4019e68a | refs/heads/master | 2021-01-10T03:22:25.688571 | 2018-10-30T19:58:14 | 2018-10-30T19:58:14 | 42,538,603 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,109 | java | package com.example.thepeopleskitchen;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
public class ParseFood {
public ArrayList<Recipe> ParseJson(String toParse) {
ArrayList<Recipe> recipes_list = new ArrayList<Recipe>();
try {
JSONObject root = new JSONObject(toParse);
JSONArray rarray = root.getJSONArray("recipes");
JSONObject obj;
for (int i = 0; i < rarray.length(); i++) {
{
obj = rarray.getJSONObject(i);
Recipe r = new Recipe();
r.setTitle(obj.getString("title"));
r.setImage_url(obj.getString("image_url"));
r.setRecipe_id(obj.getString("recipe_id"));
r.setPublisher_url(obj.getString("publisher_url"));
r.setPublisher(obj.getString("publisher"));
r.setRecipe_url(obj.getString("f2f_url"));
r.setSource_url(obj.getString("source_url"));
r.setRank(obj.getString("social_rank"));
recipes_list.add(r);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.d("Parser",recipes_list.toString());
return recipes_list;
}
}
| [
"="
] | = |
4600088bbaa1c23a84c32dc5c29c0d7e410ad145 | c234bcc35162f427921b014c4c47d1bda4ba66cc | /Lab/StringCompare.java | 25551cbfa951ed875a9f703b547a84e76e2abb5a | [] | no_license | sharvil1996/DataStructure | f19b27e81235a4bf2279234389b7b8ebb267582a | 612a450a823c8c6e0f6175283dc98a18d310f297 | refs/heads/master | 2021-08-23T21:30:54.055373 | 2017-12-06T16:43:00 | 2017-12-06T16:43:00 | 113,341,586 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 607 | java | import java.util.Scanner;
public class StringCompare {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String str = sc.next();
int cnt = sc.nextInt();
String strTemp[] = new String[50];
String min = "";
String max = "";
int temp = 0;
while (temp != str.length()+1) {
strTemp[temp] = str.substring(temp, temp + cnt);
if (strTemp[temp].compareTo(min) > 0)
min = strTemp[temp];
if (strTemp[temp].compareTo(max) < 0)
max = strTemp[temp];
temp++;
}
System.out.println(min);
System.out.println(max);
}
}
| [
"[email protected]"
] | |
8d93fa37dc361e8594a19db5c703974df0885f22 | 2443d42b6874610071cbddbb28429b2db5b70a4f | /day7/src/main/java/stream/Main.java | 47dd7a56187b430ac1d9c6eb5f81ce0b43d14509 | [] | no_license | callmeislaan/SmartOsc_Study | fd044d98c96d8325bcb942a71fdf088558419f3d | c6b8cdfd7c000d947ca82df75679cf0d955ed9bd | refs/heads/master | 2022-12-23T09:53:43.745871 | 2020-09-25T21:42:05 | 2020-09-25T21:42:05 | 298,684,376 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,603 | java | package stream;
interface itf<T> {
// void bbc(T s1, T s2);
// T get();
T[] a(int size);
}
class MyString {
public MyString() {
System.out.println("day la A");
}
@Override
public String toString() {
return "Day la toString A";
}
// public MyString(String s1, String s2) {
//// return -s1.compareTo(s2);
// System.out.println("a");
// }
public int compareTo(String s1, String s2) {
return -s1.compareTo(s2);
}
}
public class Main {
public static void main(String[] args) {
// MyString myString = new MyString();
// Logger logger = LoggerFactory.getLogger(Main.class);
// logger.error("a", 1);
// logger.info("a", 2);
// logger.info("a", 3);
// logger.info("a", 4);
String[] list = {"Java", "Python", "C#"};
// Stream.of(list).filter(s -> s.startsWith("J")).forEach(s -> System.out.println(s));
// Stream.of(list).filter(s -> s.startsWith("J")).forEach(s -> System.out.println(s));
// streamSupplier.get().forEach(s -> System.out.println(s));
// streamSupplier.get().forEach(s -> System.out.println(s));
// IntStream.of(1, 2, 3).forEach(value -> System.out.println(value));
// DoubleStream.of(1, 2, 3, 4).forEach(value -> System.out.println(value));
// Stream.of(1, 2, 3, 4).forEach(integer -> System.out.println(integer));
// Stream<Integer> stream = Stream.of(new Integer[] {1, 2, 3});
// stream.forEach(integer -> System.out.println(integer));
// Stream stream1 = new ArrayList<Integer>().stream();
// Stream s = Stream.generate(() -> new Date()).limit(10);
//// s.forEach(o -> System.out.println(o));
// Stream.Builder builder = Stream.builder();
// builder.add(1);
// List<String> data = Arrays.asList("Java", "C#", "C++", "PHP", "Javascript");
String[] data = {"Java", "C#", "C++", "PHP", "Javascript", "Java"};
// Integer[] i = {2, 1, 3, 5, 4};
// Stream.of(i).peek(integers -> System.out.println(integers)).count();
// itf compareTo = MyString::compareTo;
// Consumer<String> a = MyString::new;
itf<MyString[]> my = MyString[][]::new;
MyString[][] a = my.a(3);
System.out.println(a.length);
// itf a = MyString::new;
// a.bbc("a", "a");
// Stream.of(data)
//// .peek(System.out::println)
// .sorted()
// .distinct()
//// .toArray();
// .forEach(System.out::println);
}
} | [
"[email protected]"
] | |
ecbdb759f7fa146a122ddcacb7ee5fe5df68b476 | 9fa6c0450f3a190a20223b37097660a6694f35c2 | /Agnus/app/build/generated/source/r/debug/android/support/v4/R.java | ec2f0d58e1f2fb0a336023ac099c4b00e1b10fb0 | [] | no_license | juargore/Agnus | 6ac1f51f15ea3290ba337a9a53699e977a5a4546 | e9b9fc992648cbd6938857f6db0e2d5d431ca566 | refs/heads/master | 2020-08-06T16:09:12.503692 | 2019-10-05T20:35:39 | 2019-10-05T20:35:39 | 213,066,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,685 | java | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* gradle plugin from the resource data it found. It
* should not be modified by hand.
*/
package android.support.v4;
public final class R {
public static final class attr {
public static final int coordinatorLayoutStyle = 0x7f04007e;
public static final int font = 0x7f0400a7;
public static final int fontProviderAuthority = 0x7f0400a9;
public static final int fontProviderCerts = 0x7f0400aa;
public static final int fontProviderFetchStrategy = 0x7f0400ab;
public static final int fontProviderFetchTimeout = 0x7f0400ac;
public static final int fontProviderPackage = 0x7f0400ad;
public static final int fontProviderQuery = 0x7f0400ae;
public static final int fontStyle = 0x7f0400af;
public static final int fontWeight = 0x7f0400b0;
public static final int keylines = 0x7f0400cc;
public static final int layout_anchor = 0x7f0400cf;
public static final int layout_anchorGravity = 0x7f0400d0;
public static final int layout_behavior = 0x7f0400d1;
public static final int layout_dodgeInsetEdges = 0x7f0400fd;
public static final int layout_insetEdge = 0x7f040106;
public static final int layout_keyline = 0x7f040107;
public static final int statusBarBackground = 0x7f040155;
}
public static final class bool {
public static final int abc_action_bar_embed_tabs = 0x7f050000;
}
public static final class color {
public static final int notification_action_color_filter = 0x7f060059;
public static final int notification_icon_bg_color = 0x7f06005a;
public static final int notification_material_background_media_default_color = 0x7f06005b;
public static final int primary_text_default_material_dark = 0x7f060060;
public static final int ripple_material_light = 0x7f060065;
public static final int secondary_text_default_material_dark = 0x7f060066;
public static final int secondary_text_default_material_light = 0x7f060067;
}
public static final class dimen {
public static final int compat_button_inset_horizontal_material = 0x7f07004e;
public static final int compat_button_inset_vertical_material = 0x7f07004f;
public static final int compat_button_padding_horizontal_material = 0x7f070050;
public static final int compat_button_padding_vertical_material = 0x7f070051;
public static final int compat_control_corner_material = 0x7f070052;
public static final int notification_action_icon_size = 0x7f070089;
public static final int notification_action_text_size = 0x7f07008a;
public static final int notification_big_circle_margin = 0x7f07008b;
public static final int notification_content_margin_start = 0x7f07008c;
public static final int notification_large_icon_height = 0x7f07008d;
public static final int notification_large_icon_width = 0x7f07008e;
public static final int notification_main_column_padding_top = 0x7f07008f;
public static final int notification_media_narrow_margin = 0x7f070090;
public static final int notification_right_icon_size = 0x7f070091;
public static final int notification_right_side_padding_top = 0x7f070092;
public static final int notification_small_icon_background_padding = 0x7f070093;
public static final int notification_small_icon_size_as_large = 0x7f070094;
public static final int notification_subtext_size = 0x7f070095;
public static final int notification_top_pad = 0x7f070096;
public static final int notification_top_pad_large_text = 0x7f070097;
}
public static final class drawable {
public static final int notification_action_background = 0x7f080091;
public static final int notification_bg = 0x7f080092;
public static final int notification_bg_low = 0x7f080093;
public static final int notification_bg_low_normal = 0x7f080094;
public static final int notification_bg_low_pressed = 0x7f080095;
public static final int notification_bg_normal = 0x7f080096;
public static final int notification_bg_normal_pressed = 0x7f080097;
public static final int notification_icon_background = 0x7f080098;
public static final int notification_template_icon_bg = 0x7f080099;
public static final int notification_template_icon_low_bg = 0x7f08009a;
public static final int notification_tile_bg = 0x7f08009b;
public static final int notify_panel_notification_icon_bg = 0x7f08009c;
}
public static final class id {
public static final int action0 = 0x7f090007;
public static final int action_container = 0x7f09000f;
public static final int action_divider = 0x7f090011;
public static final int action_image = 0x7f090012;
public static final int action_text = 0x7f090018;
public static final int actions = 0x7f090019;
public static final int async = 0x7f090022;
public static final int blocking = 0x7f090029;
public static final int bottom = 0x7f09002a;
public static final int cancel_action = 0x7f090033;
public static final int chronometer = 0x7f09003b;
public static final int end = 0x7f090052;
public static final int end_padder = 0x7f090053;
public static final int forever = 0x7f09006c;
public static final int icon = 0x7f090074;
public static final int icon_group = 0x7f090075;
public static final int info = 0x7f09008b;
public static final int italic = 0x7f09008d;
public static final int left = 0x7f0900b6;
public static final int line1 = 0x7f0900b8;
public static final int line3 = 0x7f0900b9;
public static final int media_actions = 0x7f0900e1;
public static final int none = 0x7f0900ea;
public static final int normal = 0x7f0900eb;
public static final int notification_background = 0x7f0900ec;
public static final int notification_main_column = 0x7f0900ed;
public static final int notification_main_column_container = 0x7f0900ee;
public static final int right = 0x7f09010a;
public static final int right_icon = 0x7f09010b;
public static final int right_side = 0x7f09010c;
public static final int start = 0x7f090144;
public static final int status_bar_latest_event_content = 0x7f090145;
public static final int tag_transition_group = 0x7f090151;
public static final int text = 0x7f090152;
public static final int text2 = 0x7f090153;
public static final int time = 0x7f090169;
public static final int title = 0x7f09016a;
public static final int top = 0x7f09016e;
}
public static final class integer {
public static final int cancel_button_image_alpha = 0x7f0a0004;
public static final int status_bar_notification_info_maxnum = 0x7f0a000a;
}
public static final class layout {
public static final int notification_action = 0x7f0b0055;
public static final int notification_action_tombstone = 0x7f0b0056;
public static final int notification_media_action = 0x7f0b0057;
public static final int notification_media_cancel_action = 0x7f0b0058;
public static final int notification_template_big_media = 0x7f0b0059;
public static final int notification_template_big_media_custom = 0x7f0b005a;
public static final int notification_template_big_media_narrow = 0x7f0b005b;
public static final int notification_template_big_media_narrow_custom = 0x7f0b005c;
public static final int notification_template_custom_big = 0x7f0b005d;
public static final int notification_template_icon_group = 0x7f0b005e;
public static final int notification_template_lines_media = 0x7f0b005f;
public static final int notification_template_media = 0x7f0b0060;
public static final int notification_template_media_custom = 0x7f0b0061;
public static final int notification_template_part_chronometer = 0x7f0b0062;
public static final int notification_template_part_time = 0x7f0b0063;
}
public static final class string {
public static final int status_bar_notification_info_overflow = 0x7f0f0047;
}
public static final class style {
public static final int TextAppearance_Compat_Notification = 0x7f1000f6;
public static final int TextAppearance_Compat_Notification_Info = 0x7f1000f7;
public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f1000f8;
public static final int TextAppearance_Compat_Notification_Line2 = 0x7f1000f9;
public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f1000fa;
public static final int TextAppearance_Compat_Notification_Media = 0x7f1000fb;
public static final int TextAppearance_Compat_Notification_Time = 0x7f1000fc;
public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f1000fd;
public static final int TextAppearance_Compat_Notification_Title = 0x7f1000fe;
public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f1000ff;
public static final int Widget_Compat_NotificationActionContainer = 0x7f100174;
public static final int Widget_Compat_NotificationActionText = 0x7f100175;
public static final int Widget_Support_CoordinatorLayout = 0x7f100181;
}
public static final class styleable {
public static final int[] CoordinatorLayout = { 0x7f0400cc, 0x7f040155 };
public static final int CoordinatorLayout_keylines = 0;
public static final int CoordinatorLayout_statusBarBackground = 1;
public static final int[] CoordinatorLayout_Layout = { 0x010100b3, 0x7f0400cf, 0x7f0400d0, 0x7f0400d1, 0x7f0400fd, 0x7f040106, 0x7f040107 };
public static final int CoordinatorLayout_Layout_android_layout_gravity = 0;
public static final int CoordinatorLayout_Layout_layout_anchor = 1;
public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2;
public static final int CoordinatorLayout_Layout_layout_behavior = 3;
public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4;
public static final int CoordinatorLayout_Layout_layout_insetEdge = 5;
public static final int CoordinatorLayout_Layout_layout_keyline = 6;
public static final int[] FontFamily = { 0x7f0400a9, 0x7f0400aa, 0x7f0400ab, 0x7f0400ac, 0x7f0400ad, 0x7f0400ae };
public static final int FontFamily_fontProviderAuthority = 0;
public static final int FontFamily_fontProviderCerts = 1;
public static final int FontFamily_fontProviderFetchStrategy = 2;
public static final int FontFamily_fontProviderFetchTimeout = 3;
public static final int FontFamily_fontProviderPackage = 4;
public static final int FontFamily_fontProviderQuery = 5;
public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x7f0400a7, 0x7f0400af, 0x7f0400b0 };
public static final int FontFamilyFont_android_font = 0;
public static final int FontFamilyFont_android_fontWeight = 1;
public static final int FontFamilyFont_android_fontStyle = 2;
public static final int FontFamilyFont_font = 3;
public static final int FontFamilyFont_fontStyle = 4;
public static final int FontFamilyFont_fontWeight = 5;
}
}
| [
"[email protected]"
] | |
8dc2faf830ecb08ab14708be7852fe5542129121 | 519c85c1fc630335d2ffca3fbb3ab141d1d8c784 | /spring_study/study6/src/main/java/inu/appcenter/study6/controller/MemberController.java | 1ac28e699cbd8937547cf8fea5737033f806837e | [] | no_license | wornjs135/Spring_Study | e25829dac43bb68b30a9c42cd7318cd8f07cb0cd | e9ae75a6a23292b7259b74a12ab4b448ac43079d | refs/heads/master | 2023-06-09T12:02:47.739994 | 2021-07-03T13:42:03 | 2021-07-03T13:42:03 | 382,614,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 900 | java | package inu.appcenter.study6.controller;
import inu.appcenter.study6.domain.Member;
import inu.appcenter.study6.model.MemberCreateRequest;
import inu.appcenter.study6.model.MemberResponse;
import inu.appcenter.study6.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequiredArgsConstructor
public class MemberController {
private final MemberService memberService;
@PostMapping("/members")
public ResponseEntity<MemberResponse> saveMember(@RequestBody MemberCreateRequest request){
Member savedMember = memberService.saveMember(request);
return ResponseEntity.ok(MemberResponse.from(savedMember));
}
}
| [
"[email protected]"
] | |
eb54904bebbb67910563cac778e6062b27ef6c9c | 4052a395713dab96453dfb9226c64caa4ec19e0a | /src/main/resources/archetype-resources/core/src/main/java/models/HierarchyPage.java | d5f309927cc8fadbd54f2db20d13bca3864f5fe1 | [
"Apache-2.0"
] | permissive | godanny86/aem-spa-project-archetype | b7597b908ed464766cbcbce7276ebc54ed9de117 | 414f2f61f51d3939ca3242a4cd3bbba7e0c3aac5 | refs/heads/master | 2020-04-11T05:02:11.802717 | 2018-12-07T19:51:59 | 2018-12-07T19:51:59 | 161,535,787 | 1 | 0 | Apache-2.0 | 2018-12-12T19:34:44 | 2018-12-12T19:34:44 | null | UTF-8 | Java | false | false | 1,805 | java | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2018 Adobe Incorporated
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
package ${package}.models;
import javax.annotation.Nullable;
import org.apache.sling.api.resource.Resource;
import org.osgi.annotation.versioning.ProviderType;
import com.adobe.cq.export.json.ContainerExporter;
import com.adobe.cq.export.json.hierarchy.HierarchyNodeExporter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Defines the interface used in conjunction with the Sling Model Exporter to expose the mandatory fields and structure of a page and its child pages.
*/
@ProviderType
public interface HierarchyPage extends HierarchyNodeExporter, ContainerExporter {
/**
* Title of the page. The page title can be the result of multiple fallbacks
*
* @return
*/
@Nullable
@JsonProperty("title")
public String getTitle();
/**
* URL to the root model of the App
*
* @return
*/
@Nullable
@JsonIgnore
public String getRootUrl();
@Nullable
@JsonIgnore
public HierarchyPage getRootModel();
}
| [
"[email protected]"
] | |
34d5492ebc6168d16aeaa3d4714988f8afc58b15 | 70fc691535cd0ab0d1de689401867e26a66fc152 | /Ong_Base/main/com/ong/bean/helpers/BeanHelper.java | b1a3242dc8e4316f8a1abda754271e846973cf28 | [] | no_license | vergil-ong/ong_base | eaf9c83352bd4a4483d60cf2ebefdd1316fa821e | e642f3dc8468c076f057bafcc18af8d5ad5b591e | refs/heads/master | 2022-12-19T20:50:59.861943 | 2019-10-21T23:39:19 | 2019-10-21T23:39:19 | 108,228,845 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 10,711 | java | package com.ong.bean.helpers;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ong.log.helpers.Log;
/**
* 对Bean类的帮助类
* @Description: Bean类的帮助类
* @Author: Ong
* @CreateDate: 2017-05-20 12:00:00
* @E-mail: [email protected]
*/
public class BeanHelper {
private static Log logger = Log.getLog(BeanHelper.class);
private static final String STATICDIR = "D://eclipseworkspace/ong/Ong_Base/STATIC";
private static Class<?> defaultMapClazz = HashMap.class;
private static final String EMPTYSTR = "";
private static final String[] JSONDIR_SUFFIX = {"json","data"};
private static final String[] XML_SUFFIX = {"xml"};
/**
* return if List is null
* @param map
* @return
*/
public static boolean isListNull(List<?> list){
return list == null;
}
/**
* return List is null or empty
* @param map
* @return
*/
public static boolean isListEmpty(List<?> list){
return isListNull(list)||list.isEmpty();
}
/**
* return if map is null
* @param map
* @return
*/
public static boolean isMapNull(Map<?,?> map){
return map == null;
}
/**
* return map is null or empty
* @param map
* @return
*/
public static boolean isMapEmpty(Map<?,?> map){
return isMapNull(map)||map.isEmpty();
}
/**
* get Instance of Map if it`s null
* @param <P>
* @param <T>
* @param map
* @return
*/
public static <T, P> Map<T,P> getInstanceIfNull(Map<T, P> map){
return getInstanceIfNull(map, defaultMapClazz);
}
/**
* get Instance of Map if it`s null
* @param <T>
* @param <P>
* @param map
* @param clazz
* @return
*/
@SuppressWarnings("unchecked")
public static <T, P> Map<T,P> getInstanceIfNull(Map<T, P> map, Class<?> clazz){
Map<T,P> resultMap = null;
/**
* 1. check if map is null
* 1.1 map is not null
* return map
* 1.2 map is null
* return new Instance Class
*/
//1. check if map is null
if(!isMapNull(map)){
//1.1 map is not null return map
return map;
}
//return new Instance Class
try {
resultMap = (Map<T, P>) clazz.newInstance();
} catch (Exception e1) {
logger.error("newInstance the class {0} ,Exception is {1}",clazz,e1.getMessage());
try {
resultMap = (Map<T, P>) defaultMapClazz.newInstance();
} catch (Exception e2) {
logger.error("newInstance the defaultMapClazz {0} ,Exception is {1}",defaultMapClazz,e2.getMessage());
resultMap = new HashMap<T, P>();
}
}
return resultMap;
}
/**
* Object to String
* @param obj
* @return
*/
public static String getStr(Object obj){
String retStr = EMPTYSTR;
if(obj == null){
return retStr;
}
try{
retStr = (String)obj;
}catch(Exception e){
logger.warn("cast the class {0} ,Exception is {1}",obj,e.getMessage());
retStr = obj.toString();
}
return retStr;
}
/**
* get Map from bean
* @param obj
* @return
*/
public static Map<String,Object> bean2Map(Object obj){
Map<String, Object> map = new HashMap<String, Object>();
Method[] declaredMethods = obj.getClass().getDeclaredMethods();
for(Method decMethod : declaredMethods){
Class<?>[] parameterTypes = decMethod.getParameterTypes();
String methodName = decMethod.getName();
if(!methodName.startsWith("get")||parameterTypes.length!=0){
//filter the method is not start with get
//or parameters is not null
continue;
}
try {
Object[] params = {};
Object getValue = decMethod.invoke(obj, params);
String subName = methodName.substring(3);
String firstChar = subName.substring(0, 1);
subName = subName.replaceFirst(firstChar, firstChar.toLowerCase());
map.put(subName, getValue);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
}
return map;
}
/**
* set map to bean<br/>
* 暂时只支持bean类的无参构造函数,如不存在无参构造,则需手动添加<br/>
* 初步构想使用注解来指定构造函数
* @param <T>
* @param map
* @param clazz
* @return
*/
public static <T> T map2Bean(Map<String, Object> map, Class<T> clazz){
if(isMapEmpty(map)){
return null;
}
try {
T bean = clazz.newInstance();
Method[] declaredMethods = clazz.getDeclaredMethods();
for(Method decMethod : declaredMethods){
String methodName = decMethod.getName();
Class<?>[] parameterTypes = decMethod.getParameterTypes();
if(!methodName.startsWith("set") || parameterTypes.length != 1){
continue;
}
String subName = methodName.substring(3, methodName.length());
String firstChar = subName.substring(0, 1);
subName = subName.replaceFirst(firstChar, firstChar.toLowerCase());
Object setValue = map.get(subName);
decMethod.invoke(bean, transferExpectClass(setValue, parameterTypes[0]));
}
return bean;
} catch (InstantiationException e) {
logger.error(e);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
return null;
}
/**
* 将对象转换成期望类型
* @param obj
* @param expectClazz
* @return
*/
public static <T> Object transferExpectClass(Object obj, Class<T> expectClazz){
if(obj.getClass().equals(expectClazz)){
return obj;
}else if(expectClazz.isAssignableFrom(java.lang.String.class)){
return getStr(obj);
}else {
return invokeValueOf(getStr(obj), expectClazz);
}
}
/**
* 执行valueOf 方法
* @param obj
* @param clazz
* @return
*/
public static <T> Object invokeValueOf(Object obj, Class<T> clazz){
try {
Method declaredMethod = clazz.getDeclaredMethod("valueOf", java.lang.String.class);
return declaredMethod.invoke(null, obj);
} catch (NoSuchMethodException e) {
logger.error(e);
} catch (SecurityException e) {
logger.error(e);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
}
return obj;
}
/**
* 将BeanA 转换成 BeanB
* @param a
* @param b
* @return
*/
public static <T, P> P transBeanAToBeanB(T a, P b){
if(a == null){
return null;
}
if(b == null){
return null;
}
Class<? extends Object> clazzA = a.getClass();
Class<? extends Object> classB = b.getClass();
Method[] declaredMethods = clazzA.getDeclaredMethods();
for(Method decMethod : declaredMethods){
String methodName = decMethod.getName();
Class<?>[] parameterTypes = decMethod.getParameterTypes();
if(!methodName.startsWith("get") || parameterTypes.length != 0){
continue;
}
Object[] params = {};
try {
Object getValue = decMethod.invoke(a, params);
String setMethodName = methodName.replaceFirst("get", "set");
String fieldName = lowerFirstCase(methodName.replaceFirst("get", ""));
Field declaredField = classB.getDeclaredField(fieldName);
Class<?> type = declaredField.getType();
Method setMethod = classB.getDeclaredMethod(setMethodName, type);
setMethod.invoke(b, getValue);
} catch (IllegalAccessException e) {
logger.error(e);
} catch (IllegalArgumentException e) {
logger.error(e);
} catch (InvocationTargetException e) {
logger.error(e);
} catch (NoSuchFieldException e) {
logger.info(e);
} catch (SecurityException e) {
logger.error(e);
} catch (NoSuchMethodException e) {
logger.info(e);
}
}
return b;
}
/**
* 将BeanA 转换成 BeanB
* @param a
* @param b
* @return
*/
public static <T, P> P transBeanAToBeanB(T a, Class<P> clazzB){
try {
P b = clazzB.newInstance();
return transBeanAToBeanB(a, b);
} catch (InstantiationException | IllegalAccessException e) {
logger.error(e);
}
return null;
}
public static <T, P> List<P> transAListToBeanB(List<T> a, Class<P> clazzB){
if(a == null){
return null;
}
List<P> resultList = new ArrayList<P>(a.size());
for(T t : a){
resultList.add(transBeanAToBeanB(t, clazzB));
}
return resultList;
}
/**
* 首字母大写
* @param str
* @return
*/
public static String upperFirstCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
return new String(ch);
}
/**
* 首字母小写
* @param str
* @return
*/
public static String lowerFirstCase(String str) {
char[] ch = str.toCharArray();
if (ch[0] >= 'A' && ch[0] <= 'Z') {
ch[0] = (char) (ch[0] + 32);
}
return new String(ch);
}
public static String getStaticFile(String fileName){
if(fileName == null){
return null;
}
for(String jsonSuffix : JSONDIR_SUFFIX){
if(fileName.toLowerCase().endsWith(jsonSuffix)){
return STATICDIR+File.separator+"JSON"+File.separator+fileName;
}
}
for(String xmlSuffix : XML_SUFFIX){
if(fileName.toLowerCase().endsWith(xmlSuffix)){
return STATICDIR+File.separator+"XML"+File.separator+fileName;
}
}
return STATICDIR+File.separator+fileName;
}
/**
* 把对象转成对象数组
* @param obj
* @return
*/
public static Object[] transObj2ObjArray(Object obj){
if(obj == null){
return null;
}
if(obj instanceof Object[]){
return (Object[])obj;
}
if(obj instanceof List){
List<?> list = (List<?>)obj;
return list.toArray();
}
return new Object[]{obj};
}
/**
* 获取对象数组的类型
* @param obj
* @return
*/
public static Class<?>[] getObjClazz(Object[] objs){
if(objs == null){
return null;
}
Class<?>[] clazzArray = new Class<?>[objs.length];
for(int i=0; i<clazzArray.length; i++){
clazzArray[i] = objs[i].getClass();
}
return clazzArray;
}
}
| [
"[email protected]"
] | |
c812495b11d91abe5129dc3adcc899cb69592d1c | 5b82e2f7c720c49dff236970aacd610e7c41a077 | /QueryReformulation-master 2/data/ExampleSourceCodeFiles/CSSPropertyTitleFormsHandler.java | aa781857a41365a7c8cfc57641b0fe99929e3dfe | [] | no_license | shy942/EGITrepoOnlineVersion | 4b157da0f76dc5bbf179437242d2224d782dd267 | f88fb20497dcc30ff1add5fe359cbca772142b09 | refs/heads/master | 2021-01-20T16:04:23.509863 | 2016-07-21T20:43:22 | 2016-07-21T20:43:22 | 63,737,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,345 | java | /Users/user/eclipse.platform.ui/bundles/org.eclipse.ui.forms/src/org/eclipse/ui/internal/forms/css/properties/css2/CSSPropertyTitleFormsHandler.java
org eclipse internal forms css properties css org eclipse css core engine engine org eclipse css swt properties abstract property handler org eclipse swt graphics color org eclipse swt widgets control org eclipse forms widgets section org dom css value property title forms handler abstract property handler string background color gradient titlebar string background color titlebar string border color titlebar override apply property control control string property value string pseudo engine engine exception equals ignore case property control section css value type value color color color engine convert color control display section control set title bar gradient background color css value type value equals ignore case property control section css value type value color color color engine convert color control display section control set title bar background color css value type value equals ignore case property control section css value type value color color color engine convert color control display section control set title bar border color color css value type value override string retrieve property control control string property string pseudo engine engine exception null | [
"[email protected]"
] | |
e11e7b46c6853f760b782f80f689651822708c13 | fae77554a7eda03bf5b6c005c3c42ff15c829d3b | /app/src/main/java/fragment/SendFragment.java | 36b59fba7e0e0952ce5f67de029f6ec6a4d5ffb2 | [] | no_license | food91/Weather | ab9df13046891a683a27abf7e5bfa84a7b8eed56 | 81b08d6b4542045f6f743ff4dc26c2487710003f | refs/heads/master | 2023-03-03T21:08:41.032056 | 2021-02-14T22:28:34 | 2021-02-14T22:28:34 | 338,920,233 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.xiekun.myapplication.R;
public class SendFragment extends Fragment {
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_send, container, false);
final TextView textView = root.findViewById(R.id.text_send);
return root;
}
} | [
"[email protected]"
] | |
fba263791dd4bbc0741afcdc0d9e3f3b6aed9eda | b9942691bc3388795183564e7a32a123aeb5c074 | /src/main/java/ua/iv_fr/lukach/marian/in100gram/security/JWTAuthenticationEntryPoint.java | 45844a82a8db912ba70b0155694ea6e5644bcac7 | [] | no_license | wertyxa/In100gram | e53757085d10c43dd2e0265b1b171b6ab0812ca4 | 6d3ef5573dce5cf7e8a784b808dab48e40a08660 | refs/heads/master | 2023-08-13T17:22:44.062954 | 2021-10-17T21:33:06 | 2021-10-17T21:33:06 | 410,641,942 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,132 | java | package ua.iv_fr.lukach.marian.in100gram.security;
import com.google.gson.Gson;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import ua.iv_fr.lukach.marian.in100gram.payload.response.InvalidLoginResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
InvalidLoginResponse loginResponse = new InvalidLoginResponse();
String jsonLoginResponse = new Gson().toJson(loginResponse);
httpServletResponse.setContentType(SecurityConstants.CONTENT_TYPE);
httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().println(jsonLoginResponse);
}
}
| [
"[email protected]"
] | |
d69c492cd879bd60ddb410edba1f58ae65bf005c | 6492d445e8413e4e820ba16fa1d3cf61e9b8d5ad | /app/src/main/java/com/example/rajayambigms/allnotifications/SimpleNotification.java | 9774e537c1c47f55ce9b7b9d2472ce4b43baf50f | [] | no_license | RajendranEshwaran/ALL_NOTIFICATION_android | 7d87f88c8a9c51d7d1bfc97f94407e580416e27c | c5af104b202201e7d866727ef8b03369feb61784 | refs/heads/master | 2020-05-04T12:47:44.632687 | 2019-04-02T20:03:31 | 2019-04-02T20:03:31 | 179,135,424 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 375 | java | package com.example.rajayambigms.allnotifications;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class SimpleNotification extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_notification);
}
}
| [
"[email protected]"
] | |
4f505d0a25b25c441345ef989a7ade580ebd17d6 | 124cef9be26df75c62ad766bfaebd281f75c8152 | /src/main/java/com/hansoleee/corespringsecurity/domain/dto/AccountDto.java | 261ed70e58a36e10b2fc8752e865133b2bd81781 | [] | no_license | hansoleee/core-spring-security | ad72ec2e15e97e076fe6b0f02a0f9fa77c325955 | 803b1e778ae47e0603d09a84191376ac1734340e | refs/heads/main | 2023-07-15T09:36:48.418674 | 2021-08-16T13:41:11 | 2021-08-16T13:41:11 | 395,935,597 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | package com.hansoleee.corespringsecurity.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
public class AccountDto {
private String id;
private String username;
private String email;
private int age;
private String password;
private List<String> roles;
@Builder
public AccountDto(String id, String username, String email, int age, String password, List<String> roles) {
this.id = id;
this.username = username;
this.email = email;
this.age = age;
this.password = password;
this.roles = roles;
}
}
| [
"[email protected]"
] | |
9427c2174083dd77cea51a65944ec3e1c43f4d92 | dfa85f8e4cda79ba9ad75cc15534253336685818 | /src/main/java/com/example/blogsystem/entity/BlogTagRelation.java | e37aff79918d7c0250c431fc0dde6b87f774930f | [] | no_license | Changri-Liuhen/BlogSystem | 35dd29a4d77b88d0352e926402f5de79b5a7b630 | 7e4c576b329c621e9d1b499e5be31892853afc49 | refs/heads/master | 2023-05-20T22:16:29.842460 | 2021-06-13T16:21:00 | 2021-06-13T16:21:00 | 376,553,653 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,286 | java | package com.example.blogsystem.entity;
import java.util.Date;
public class BlogTagRelation {
private Long relationId;
private Long blogId;
private Integer tagId;
private Date createTime;
public Long getRelationId() {
return relationId;
}
public void setRelationId(Long relationId) {
this.relationId = relationId;
}
public Long getBlogId() {
return blogId;
}
public void setBlogId(Long blogId) {
this.blogId = blogId;
}
public Integer getTagId() {
return tagId;
}
public void setTagId(Integer tagId) {
this.tagId = tagId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", relationId=").append(relationId);
sb.append(", blogId=").append(blogId);
sb.append(", tagId=").append(tagId);
sb.append(", createTime=").append(createTime);
sb.append("]");
return sb.toString();
}
} | [
"[email protected]"
] | |
5c773fac541d7168525312661a1d2bf94179b1ad | f8255c43b11421c4705456e2bc95dcb76ec05cc3 | /Delivery.java | 66bd747b797925dfaac18c5d9e38f74a883296fe | [] | no_license | 9550128249/hcl.ProcessTraining | 943400e3d34b054dc6d142e6b7231e9420213e16 | aa56b1a7c3c29c5a55f20a15dd01842cebbc9e4c | refs/heads/main | 2023-02-07T05:16:37.845974 | 2020-12-28T08:56:27 | 2020-12-28T08:56:27 | 318,253,111 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,255 | java | package hcl.assignmentp7;
public class Delivery {
private long over;
private long ball;
private long runs;
private String batsman;
private String bowler;
private String nonStriker;
public Delivery() {
// TODO Auto-generated constructor stub
}
public Delivery(long over, long ball, long runs, String batsman, String bowler, String nonStriker) {
super();
this.over = over;
this.ball = ball;
this.runs = runs;
this.batsman = batsman;
this.bowler = bowler;
this.nonStriker = nonStriker;
}
public long getOver() {
return over;
}
public void setOver(long over) {
this.over = over;
}
public long getBall() {
return ball;
}
public void setBall(long ball) {
this.ball = ball;
}
public long getRuns() {
return runs;
}
public void setRuns(long runs) {
this.runs = runs;
}
public String getBatsman() {
return batsman;
}
public void setBatsman(String batsman) {
this.batsman = batsman;
}
public String getBowler() {
return bowler;
}
public void setBowler(String bowler) {
this.bowler = bowler;
}
public String getNonStriker() {
return nonStriker;
}
public void setNonStriker(String nonStriker) {
this.nonStriker = nonStriker;
}
}
| [
"[email protected]"
] | |
3ef09c6fd45bcbaf4ce739f97eb3a7157e77216f | 648179f5f66f1ea3db57d3dad53ab313bcf6ddc7 | /Vehicleautomat/src/main/resources/defaultTypes/java/lang/Boolean.java | c51a733035e1b8e15df9cd0c84783d6ab8bdef5e | [] | no_license | dina-25/industrie4.0 | ef670f7b38868277472ad44d0df384dee49e2ebc | 74c7516a7a27cdf5abe42298be1e0ff19a665cca | refs/heads/master | 2020-03-28T10:59:24.002569 | 2018-09-10T14:13:41 | 2018-09-10T14:13:41 | 148,166,255 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 58 | java | package java.lang;
public class Boolean extends Object {
} | [
"[email protected]"
] | |
4a886dda28205906b5e685a763368749c3f71514 | 6578045c16d9560d4ed6d35c3bb99c76717bb3ef | /Invasion/src/com/codeday/invasion/AbstractScreen.java | 89678c8320449955af7b6bf5c04d50f3cf993273 | [] | no_license | TomWerner/Invasion-game | 0b64a5e81dbf64c4f8d7abc50689ce744e829def | 63311e4c76f15c7b6a46e70b76123bbed7ff8e45 | refs/heads/master | 2021-01-22T09:50:37.782130 | 2015-03-10T03:30:11 | 2015-03-10T03:30:11 | 16,967,590 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,792 | java | package com.codeday.invasion;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
/**
* The base class for all game screens.
*/
public abstract class AbstractScreen implements Screen
{
// the fixed viewport dimensions (ratio: 1.6)
public static final int GAME_VIEWPORT_WIDTH = 800,
GAME_VIEWPORT_HEIGHT = 600;
public static final int MENU_VIEWPORT_WIDTH = 800,
MENU_VIEWPORT_HEIGHT = 600;
protected final Invasion game;
protected Stage stage;
private BitmapFont font;
private SpriteBatch batch;
private Skin skin;
private TextureAtlas atlas;
private Table table;
public AbstractScreen(Invasion game)
{
this.game = game;
int width = (isGameScreen() ? GAME_VIEWPORT_WIDTH : MENU_VIEWPORT_WIDTH);
int height = (isGameScreen() ? GAME_VIEWPORT_HEIGHT
: MENU_VIEWPORT_HEIGHT);
this.stage = new Stage(width, height, true);
}
protected String getName()
{
return getClass().getSimpleName();
}
protected boolean isGameScreen()
{
return false;
}
// Lazily loaded collaborators
public BitmapFont getFont()
{
if (font == null)
{
font = new BitmapFont();
}
return font;
}
public SpriteBatch getBatch()
{
if (batch == null)
{
batch = new SpriteBatch();
}
return batch;
}
// public TextureAtlas getAtlas()
// {
// if (atlas == null)
// {
// atlas = new TextureAtlas(
// Gdx.files.internal("image-atlases/pages.atlas"));
// }
// return atlas;
// }
protected Skin getSkin()
{
if (skin == null)
{
FileHandle skinFile = Gdx.files.internal("skin/uiskin.json");
skin = new Skin(skinFile);
}
return skin;
}
protected Table getTable()
{
if (table == null)
{
table = new Table(getSkin());
table.setFillParent(true);
if (Invasion.DEV_MODE)
{
table.debug();
}
stage.addActor(table);
}
return table;
}
// Screen implementation
@Override
public void show()
{
Gdx.app.log(Invasion.LOG, "Showing screen: " + getName());
// set the stage as the input processor
Gdx.input.setInputProcessor(stage);
}
@Override
public void resize(int width, int height)
{
Gdx.app.log(Invasion.LOG, "Resizing screen: " + getName() + " to: " + width
+ " x " + height);
}
@Override
public void render(float delta)
{
// (1) process the game logic
// update the actors
stage.act(delta);
// (2) draw the result
// clear the screen with the given RGB color (black)
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// draw the actors
stage.draw();
// draw the table debug lines
Table.drawDebug(stage);
}
@Override
public void hide()
{
Gdx.app.log(Invasion.LOG, "Hiding screen: " + getName());
// dispose the screen when leaving the screen;
// note that the dipose() method is not called automatically by the
// framework, so we must figure out when it's appropriate to call it
dispose();
}
@Override
public void pause()
{
Gdx.app.log(Invasion.LOG, "Pausing screen: " + getName());
}
@Override
public void resume()
{
Gdx.app.log(Invasion.LOG, "Resuming screen: " + getName());
}
@Override
public void dispose()
{
Gdx.app.log(Invasion.LOG, "Disposing screen: " + getName());
// as the collaborators are lazily loaded, they may be null
if (font != null)
font.dispose();
if (batch != null)
batch.dispose();
if (skin != null)
skin.dispose();
if (atlas != null)
atlas.dispose();
}
} | [
"[email protected]"
] | |
d5b595eb6895924711564f2ad90857fe369516bb | ba7fcd0a28ab1cc9349ccd34a3f00241788026ff | /app/src/main/java/com/lecslt/travelmantics/TravelDeal.java | cadc452ae4c41f802d04d88c58569e58d79cf9cc | [] | no_license | EricMbouwe/Travelmantics | 9be300368918c2ce81b8addc3f14b0115d44fea0 | 597cad28a537ccc110ff93b8cd42491e5a0f6e0b | refs/heads/master | 2020-07-01T11:53:22.376823 | 2020-03-12T11:11:08 | 2020-03-12T11:11:08 | 201,167,377 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,506 | java | package com.lecslt.travelmantics;
import java.io.Serializable;
public class TravelDeal implements Serializable{
private String id;
private String title;
private String description;
private String price;
private String imageUrl;
private String imageName;
public TravelDeal() {
}
public TravelDeal(String title, String description, String price, String imageUrl, String imageName) {
this.setId(id);
this.setTitle(title);
this.setDescription(description);
this.setPrice(price);
this.setImageUrl(imageUrl);
this.setImageUrl(imageName);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
| [
"[email protected]"
] | |
d8073d240fb9c004f0d76a70ef8188dcecbbfa42 | db184b57945a665d617edde42ef0185085c5e322 | /FoodApp/app/src/main/java/com/khmkau/codeu/foodapp/ManualInputActivity.java | 614a19fec535edd262b7644614e37e53f503d163 | [
"MIT"
] | permissive | anthonyuitz/FoodApp | 1236de9cb35ead5d9d7895b07152781a299af197 | a86f8bcf618014257257d332f04232ed39bd26e3 | refs/heads/master | 2021-01-15T16:15:00.857684 | 2015-08-19T01:47:23 | 2015-08-19T01:47:23 | 39,339,698 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 22,344 | java | package com.khmkau.codeu.foodapp;
import android.app.DatePickerDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.Toast;
import com.khmkau.codeu.foodapp.data.FoodContract;
import com.khmkau.codeu.foodapp.data.FoodDbHelper;
import java.util.Calendar;
import java.util.Date;
public class ManualInputActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_input);
}
@Override
protected void onResume() {
super.onResume();
Spinner tableSpinner = (Spinner) findViewById(R.id.tableSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.table_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
tableSpinner.setAdapter(adapter);
tableSpinner.setOnItemSelectedListener(this);
Spinner quantitySpinner = (Spinner) findViewById(R.id.quantitySpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = ArrayAdapter.createFromResource(this,
R.array.quantity_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
quantitySpinner.setAdapter(adapter);
quantitySpinner.setAdapter(adapter);
quantitySpinner.setOnItemSelectedListener(this);
Spinner editFoodGroup = (Spinner) findViewById(R.id.editFoodGroup);
// Create an ArrayAdapter using the string array and a default spinner layout
adapter = ArrayAdapter.createFromResource(this,
R.array.food_groups, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
editFoodGroup.setAdapter(adapter);
EditText purchaseByEditText = (EditText)findViewById(R.id.editPurchasedBy);
purchaseByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog(ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText) findViewById(R.id.editPurchasedBy);
c.setText("" + (selectedmonth + 1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText expiredByEditText = (EditText)findViewById(R.id.editExpiresBy);
expiredByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editExpiresBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText consumedByEditText = (EditText)findViewById(R.id.editConsumedBy);
consumedByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editConsumedBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
EditText thrownByEditText = (EditText)findViewById(R.id.editThrownBy);
thrownByEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mCurrentDate = Calendar.getInstance();
int mYear = mCurrentDate.get(Calendar.YEAR);
int mMonth = mCurrentDate.get(Calendar.MONTH);
int mDay = mCurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker = new DatePickerDialog( ManualInputActivity.
this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
EditText c = (EditText)findViewById(R.id.editThrownBy);
c.setText("" + (selectedmonth+1) + "/" + selectedday + "/" + selectedyear);
}
}, mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show();
}
});
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
switch(parent.getId()) {
case R.id.tableSpinner:
TableRow rowConsumed = (TableRow) findViewById(R.id.rowConsumed);
TableRow rowThrown = (TableRow) findViewById(R.id.rowThrown);
switch (pos) {
case 0:
rowConsumed.setVisibility(View.GONE);
rowThrown.setVisibility(View.GONE);
break;
case 1:
rowConsumed.setVisibility(View.VISIBLE);
rowThrown.setVisibility(View.GONE);
break;
case 2:
rowConsumed.setVisibility(View.GONE);
rowThrown.setVisibility(View.VISIBLE);
break;
}
break;
case R.id.quantitySpinner:
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void inputFood(View view) {
//Toast.makeText(getApplicationContext(), "This feature is not yet implemented. Sorry!",
// Toast.LENGTH_SHORT).show();
ContentValues infoValues = new ContentValues();
ContentValues foodValues = new ContentValues();
EditText nameTextView = (EditText)findViewById(R.id.editName);
EditText quantityTextView = (EditText)findViewById(R.id.editQuantity);
EditText purchasedByTextView = (EditText)findViewById(R.id.editPurchasedBy);
EditText expiredByTextView = (EditText)findViewById(R.id.editExpiresBy);
Spinner foodgroupTextView = (Spinner)findViewById(R.id.editFoodGroup);
EditText totalCostTextView = (EditText)findViewById(R.id.editTotalCost);
EditText caloriesTextView = (EditText)findViewById(R.id.editCalories);
EditText totalFatTextView = (EditText)findViewById(R.id.editTotalFat);
EditText satFatTextView = (EditText)findViewById(R.id.editSatFat);
EditText transFatTextView = (EditText)findViewById(R.id.editTransFat);
EditText cholesterolTextView = (EditText)findViewById(R.id.editCholesterol);
EditText sodiumTextView = (EditText)findViewById(R.id.editSodium);
EditText totalCarbsTextView = (EditText)findViewById(R.id.editTotalCarbs);
EditText sugarTextView = (EditText)findViewById(R.id.editSugar);
EditText proteinTextView = (EditText)findViewById(R.id.editProtein);
Spinner servingTextView = (Spinner)findViewById(R.id.quantitySpinner);
String nameText = nameTextView.getText().toString();
String quantityText = quantityTextView.getText().toString();
String purchasedByText = purchasedByTextView.getText().toString();
String expiredByText = expiredByTextView.getText().toString();
String foodgroupText = foodgroupTextView.getSelectedItem().toString();
String totalCostText = totalCostTextView.getText().toString();
String caloriesText = caloriesTextView.getText().toString();
String totalFatText = totalFatTextView.getText().toString();
String satFatText = satFatTextView.getText().toString();
String transFatText = transFatTextView.getText().toString();
String cholesterolText = cholesterolTextView.getText().toString();
String sodiumText = sodiumTextView.getText().toString();
String totalCarbsText = totalCarbsTextView.getText().toString();
String sugarText = sugarTextView.getText().toString();
String proteinText = proteinTextView.getText().toString();
String servingText = servingTextView.getSelectedItem().toString();
Spinner tableTextView = (Spinner)findViewById(R.id.tableSpinner);
String tableText = tableTextView.getSelectedItem().toString();
String consumedByText = "";
String thrownByText = "";
boolean isValid = true;
if(!Utility.isNumeric(quantityText) || quantityText.equals("")) {
isValid = false;
quantityTextView.setHint(R.string.quantity_error);
quantityTextView.setHintTextColor(Color.RED);
}
int[] purchasedByArray = Utility.validateDate(purchasedByText);
if(purchasedByArray[0] == -1) {
isValid = false;
purchasedByTextView.setHint(R.string.purchased_by_error);
purchasedByTextView.setHintTextColor(Color.RED);
}
int[] expiredByArray = Utility.validateDate(expiredByText);
if(expiredByArray[0] == -1) {
isValid = false;
expiredByTextView.setHint(R.string.expires_by_error);
expiredByTextView.setHintTextColor(Color.RED);
}
if(!totalCarbsText.equals("")) {
if (totalCostText.charAt(0) == '$') {
totalCostText = totalCostText.substring(1);
}
}
if(!Utility.isDouble(totalCostText) || totalCostText.equals("")) {
isValid = false;
totalCostTextView.setHint(R.string.total_cost_error);
totalCostTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(caloriesText) || caloriesText.equals("")) {
isValid = false;
caloriesTextView.setHint(R.string.calories_error);
caloriesTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(totalFatText)) {
isValid = false;
totalFatTextView.setHint(R.string.total_fat_error);
totalFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(satFatText)) {
isValid = false;
satFatTextView.setHint(R.string.saturated_fat_error);
satFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(transFatText)) {
isValid = false;
transFatTextView.setHint(R.string.trans_fat_error);
transFatTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(cholesterolText)) {
isValid = false;
cholesterolTextView.setHint(R.string.cholesterol_error);
cholesterolTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(sodiumText)) {
isValid = false;
sodiumTextView.setHint(R.string.sodium_error);
sodiumTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(totalCarbsText)) {
isValid = false;
totalCarbsTextView.setHint(R.string.total_carbs_error);
totalCarbsTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(sugarText)) {
isValid = false;
sugarTextView.setHint(R.string.sugar_error);
sugarTextView.setHintTextColor(Color.RED);
}
if(!Utility.isNumeric(proteinText)) {
isValid = false;
proteinTextView.setHint(R.string.protein_error);
proteinTextView.setHintTextColor(Color.RED);
}
if(isValid) {
infoValues.put(FoodContract.InfoEntry.COLUMN_FOOD_NAME, nameText);
infoValues.put(FoodContract.InfoEntry.COLUMN_FOOD_GROUP, foodgroupText);
infoValues.put(FoodContract.InfoEntry.COLUMN_SERVING_UNIT, servingText);
infoValues.put(FoodContract.InfoEntry.COLUMN_CALORIES, Integer.parseInt(caloriesText));
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SATURATED_FAT, Integer.parseInt(satFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TRANS_FAT, Integer.parseInt(transFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TOTAL_FAT, Integer.parseInt(totalFatText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_CHOLESTEROL, Integer.parseInt(cholesterolText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SODIUM, Integer.parseInt(sodiumText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_TOTAL_CARBOHYDRATE, Integer.parseInt(totalCarbsText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_SUGAR, Integer.parseInt(sugarText));
}
if(!satFatText.equals("")) {
infoValues.put(FoodContract.InfoEntry.COLUMN_PROTEIN, Integer.parseInt(proteinText));
}
long food_id = ContentUris.parseId(getContentResolver().insert(FoodContract.InfoEntry.CONTENT_URI, infoValues));
//check which table is being inserted to and get relevant fields
if (tableText.equals("Consumed")) {
EditText consumedByTextView = (EditText) findViewById(R.id.editConsumedBy);
consumedByText = consumedByTextView.getText().toString();
int[] consumedDates = Utility.validateDate(consumedByText);
if (consumedDates[0] == -1) {
consumedByTextView.setHintTextColor(Color.RED);
consumedByTextView.setHint(R.string.consumed_by_error);
consumedByTextView.setText("");
isValid = false;
} else {
Date consumedDateTemp = new Date(consumedDates[2], consumedDates[0], consumedDates[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_DATE_CONSUMED, FoodContract.normalizeDate(consumedDateTemp.getTime()));
}
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.ConsumedEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.ConsumedEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.ConsumedEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.ConsumedEntry.CONTENT_URI, foodValues);
}
} else if (tableText.equals("Thrown")) {
EditText thrownByTextView = (EditText) findViewById(R.id.editThrownBy);
thrownByText = thrownByTextView.getText().toString();
int[] thrownDates = Utility.validateDate(thrownByText);
if (thrownDates[0] == -1) {
thrownByTextView.setHintTextColor(Color.RED);
thrownByTextView.setHint(R.string.thrown_by_error);
thrownByTextView.setText("");
isValid = false;
} else {
Date thrownDateTemp = new Date(thrownDates[2], thrownDates[0], thrownDates[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_DATE_THROWN, FoodContract.normalizeDate(thrownDateTemp.getTime()));
}
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.ThrownEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.ThrownEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.ThrownEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.ThrownEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.ThrownEntry.CONTENT_URI, foodValues);
}
} else {
if (isValid) {
Date purchasedByDate = new Date(purchasedByArray[2], purchasedByArray[0], purchasedByArray[1]);
foodValues.put(FoodContract.CurrentEntry.COLUMN_DATE_PURCHASED, FoodContract.normalizeDate(purchasedByDate.getTime()));
Date expiredByDate = new Date(expiredByArray[2], expiredByArray[0], expiredByArray[1]);
foodValues.put(FoodContract.CurrentEntry.COLUMN_EXPIRATION_DATE, FoodContract.normalizeDate(expiredByDate.getTime()));
double totalcost = Double.parseDouble(totalCostText) * 100;
foodValues.put(FoodContract.CurrentEntry.COLUMN_VALUE, (int) totalcost);
foodValues.put(FoodContract.CurrentEntry.COLUMN_QUANTITY, Integer.parseInt(quantityText));
foodValues.put(FoodContract.CurrentEntry.COLUMN_FOOD_KEY, food_id);
getContentResolver().insert(FoodContract.CurrentEntry.CONTENT_URI, foodValues);
}
}
}
if(isValid) {
Toast.makeText(getApplicationContext(), "Food added to " + tableText + ".",
Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(getApplicationContext(), "Failed to add food item.",
Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_manual_input, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
] | |
d186d1acb6ab093149afaca6f24d2772e6163807 | 7eedc3c4520bfd83e534a2bb2c1471d69fc155df | /RSA/Rectangle.java | 28d479f63bbfbdb573d52291a8e36fe22fdc63a4 | [] | no_license | bahkos/Vanko | 46244867d715807621804393b6c67ff4230318ef | b4de93a51b8572301348de3b9bd93ef5bab8d38c | refs/heads/master | 2020-03-12T15:25:50.527181 | 2018-04-30T06:47:36 | 2018-04-30T06:47:36 | 130,690,019 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 533 | java | package oop;
public class Rectangle implements IShape {
private final double width, height;
public Rectangle() {
this(1,1);
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public String getShapeName() {
return "Rectangle";
}
public double getShapeSurface() {
return width * height;
}
public double getShapePerimeter() {
return 2 * (width + height);
}
} | [
"[email protected]"
] | |
132158e475a1f1d6164e17490275502a84586ad1 | f89152960194dbd06bfb94dcd43e08f911288c9c | /Tugas Modul 1/src/com/rohmanbenyr/Suhu/Kelvin.java | 399ba7331ea9730f77f93d27c0dfa0ec039d633f | [] | no_license | RohmanBenyRiyanto/Tugas-Praktikum-PBO | 442a6135bda41475548e8493a2370667919753df | 724e6fe39270c8db48b39e03808461dc548e140d | refs/heads/main | 2023-02-15T14:26:25.079239 | 2020-12-30T02:58:18 | 2020-12-30T02:58:18 | 309,120,403 | 1 | 1 | null | 2020-11-01T15:52:20 | 2020-11-01T15:01:05 | Java | UTF-8 | Java | false | false | 501 | java | /*
* Copyright (c) 2020.This code was written by Rohman Beny R (19104060)
*/
package com.rohmanbenyr.Suhu;
public class Kelvin {
double toFahrenheit(){
//°F = K × 1,8 − 459,67
return (KonversiSuhu.SuhuAwal*1.8-459.67);
}
double toReamur(){
//°Ré = (K − 273,15) × 0,8
return ((KonversiSuhu.SuhuAwal-273.15)*0.8);
}
double toCelcius(){
//°C = K − 273,15
return (KonversiSuhu.SuhuAwal-273.15);
}
} | [
"[email protected]"
] | |
4f8900782aedf172837d5e3f12bb360ce4913037 | 97b46ff38b675d934948ff3731cf1607a1cc0fc9 | /DataPack/dist/game/data/scripts/transformations/AurabirdFalcon.java | 7dc199c05842adc37ee4d53b28755270c287bd6f | [] | no_license | l2brutal/pk-elfo_H5 | a6703d734111e687ad2f1b2ebae769e071a911a4 | 766fa2a92cb3dcde5da6e68a7f3d41603b9c037e | refs/heads/master | 2020-12-28T13:33:46.142303 | 2016-01-20T09:53:10 | 2016-01-20T09:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,067 | java | package transformations;
import pk.elfo.gameserver.instancemanager.TransformationManager;
import pk.elfo.gameserver.model.L2Transformation;
import pk.elfo.gameserver.model.skills.L2Skill;
public class AurabirdFalcon extends L2Transformation
{
private static final int[] SKILLS = new int[]
{
884,
885,
886,
888,
890,
891,
894,
911,
932,
619
};
public AurabirdFalcon()
{
// id, colRadius, colHeight
super(8, 38, 14.25);
}
@Override
public void onTransform()
{
if ((getPlayer().getTransformationId() != 8) || getPlayer().isCursedWeaponEquipped())
{
return;
}
getPlayer().setIsFlyingMounted(true);
transformedSkills();
}
@Override
public void onUntransform()
{
getPlayer().setIsFlyingMounted(false);
removeSkills();
}
public void removeSkills()
{
// Air Blink
getPlayer().removeSkill(L2Skill.valueOf(885, 1), false);
// Exhilarate
getPlayer().removeSkill(L2Skill.valueOf(894, 1), false);
int lvl = getPlayer().getLevel() - 74;
if (lvl > 0)
{
// Air Assault (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(884, lvl), false);
// Air Shock Bomb (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(886, lvl), false);
// Energy Storm (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(888, lvl), false);
// Prodigious Flare (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(890, lvl), false);
// Energy Shot (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(891, lvl), false);
// Energy Burst (up to 11 levels)
getPlayer().removeSkill(L2Skill.valueOf(911, lvl), false);
}
// Transform Dispel
getPlayer().removeSkill(L2Skill.valueOf(619, 1), false);
getPlayer().setTransformAllowedSkills(EMPTY_ARRAY);
}
public void transformedSkills()
{
// Air Blink
if (getPlayer().getLevel() >= 75)
{
getPlayer().addSkill(L2Skill.valueOf(885, 1), false);
}
// Exhilarate
if (getPlayer().getLevel() >= 83)
{
getPlayer().addSkill(L2Skill.valueOf(894, 1), false);
}
int lvl = getPlayer().getLevel() - 74;
if (lvl > 0)
{
// Air Assault (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(884, lvl), false);
// Air Shock Bomb (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(886, lvl), false);
// Energy Storm (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(888, lvl), false);
// Prodigious Flare (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(890, lvl), false);
// Energy Shot (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(891, lvl), false);
// Energy Burst (up to 11 levels)
getPlayer().addSkill(L2Skill.valueOf(911, lvl), false);
}
// Transform Dispel
getPlayer().addSkill(L2Skill.valueOf(619, 1), false);
getPlayer().setTransformAllowedSkills(SKILLS);
}
public static void main(String[] args)
{
TransformationManager.getInstance().registerTransformation(new AurabirdFalcon());
}
} | [
"PkElfo@13720c4f-9a1f-4619-977f-b36a0ac534ba"
] | PkElfo@13720c4f-9a1f-4619-977f-b36a0ac534ba |
92ed94eb4808fb6026c427b76be5ff8896659243 | 9ccd9d652366b633663350466c6b770fed354d42 | /src/main/java/leetcode/GasStation.java | 4cfccd6b5a24fedacf0257b507638aa197dacda7 | [] | no_license | xigui2013/leetcode | e16686661c0b7e8ef52a06ce01c7c6a92f9eb399 | 99c19e25835dde7d90bc51d2618b252fb60bd919 | refs/heads/master | 2021-01-23T08:04:26.023277 | 2018-06-24T03:30:24 | 2018-06-24T03:30:24 | 86,475,009 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,481 | java | package leetcode;
/**
* leetcode
* Created by wjw on 16/05/2017.
*/
public class GasStation {
public int canCompleteCircuit(int[] gas, int[] cost) {
int length = gas.length;
int[] remain = new int[length];
for (int index = 0; index < length; index++) {
remain[index] = gas[index] - cost[index];
}
for (int flag = 0; flag < length; flag++) {
if (remain[flag] < 0) {
continue;
}
int index = flag + 1;
int remainGas = remain[flag];
boolean noway = false;
while (index != flag) {
if (index == length) {
index = 0;
continue;
}
remainGas += remain[index];
if (remainGas < 0) {
noway = true;
break;
}
index++;
}
if (!noway) {
return flag;
}
}
return -1;
}
public int canCompleteCircuit2(int[] gas, int[] cost) {
int sum = 0;
int total = 0;
int j = 0;
for (int i = 0; i < gas.length; ++i) {
sum += gas[i] - cost[i];
total += gas[i] - cost[i];
if (sum < 0) {
j = i + 1;
sum = 0;
}
}
if (total < 0) {
return -1;
}
return j;
}
}
| [
"[email protected]"
] | |
687684be9a30a812931fb31576b994ff68934dfe | 47436699ac32b3b138c53f2c7931b4636ea79eb9 | /server/dictionary-api/src/main/java/com/tsoft/dictionary/util/library/WordCounter.java | 24d1a04904c05bd7da516d617d66e096b9b1bf8e | [] | no_license | knivit/dictionary | 8108f67a9a2c066afa9d02cddec59d5f0d7668e0 | d4285dec0352f124130a43e7a1acff6e053e196d | refs/heads/master | 2021-01-13T02:11:44.807469 | 2015-03-15T13:15:31 | 2015-03-15T13:15:31 | 32,261,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 193 | java | package com.tsoft.library;
public class WordCounter {
private int count;
public int getCount() {
return count;
}
public void inc(int n) {
count += n;
}
}
| [
"[email protected]"
] | |
be4429d61359750fcb538b9ade69eff72f49a064 | 41d767a6d315a908a416c9edaa7dfb7edc8ec752 | /2.JavaCore/src/com/javarush/task/task15/task1515/Solution.java | 03e8daf7725c8d87ec5d7fe59707078510f14e3b | [] | no_license | NSergeyI/JavaRushTasks | a272fa0e8d6c25217c3fdf05c4079dd83724a6e9 | 6e48200d46cd843220e401b3897fb35b624abc32 | refs/heads/master | 2020-03-13T14:47:09.930568 | 2019-03-10T19:59:37 | 2019-03-10T19:59:37 | 100,500,212 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 834 | java | package com.javarush.task.task15.task1515;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/*
Статики-2
*/
public class Solution {
public static int A;
public static int B;
static
{
try {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String sa = read.readLine();
String sb = read.readLine();
read.close();
A = Integer.parseInt(sa);
B = Integer.parseInt(sb);
} catch(Exception ex){
ex.printStackTrace();
}
}
public static final int MIN = min(A, B);
public static void main(String[] args) {
System.out.println(MIN);
}
public static int min(int a, int b) {
return a < b ? a : b;
}
}
| [
"[email protected]"
] | |
6fd511ccfddfc59f2b28f7241743ba4bfd381e93 | fdd9a347189cfee0c13401e7e12585d48ee20577 | /src/main/java/com/github/sunnybat/commoncode/utilities/IPAddress.java | a2340a1adaa8fc2791736514a3c2cf1773b58698 | [] | no_license | SunnyBat/CommonCode | 1a2a4e3f052de54b64ca6a30997e461edb666cca | 30a253d884cb78e5e1c8af7342db3d86478cd39b | refs/heads/development | 2021-01-17T10:06:17.765935 | 2019-05-29T15:13:52 | 2019-05-29T15:14:09 | 30,432,986 | 1 | 4 | null | 2016-05-08T17:24:46 | 2015-02-06T21:05:21 | Java | UTF-8 | Java | false | false | 1,104 | java | package com.github.sunnybat.commoncode.utilities;
import java.io.IOException;
/**
*
* @author SunnyBat
*/
public class IPAddress {
private static final String CHECK_IP_SITE = "http://checkip.amazonaws.com";
/**
* Gets the internal IP address of the given machine.
*
* @return The visible IP address, or [Not Found] if unable to find it
*/
public static String getInternalIP() {
try {
return java.net.Inet4Address.getLocalHost().getHostAddress();
} catch (IOException e) {
return "[Not Found]";
}
}
/**
* Gets the external IP address of the given machine.
*
* @return The visible IP address, or [Not Found] if unable to find it
*/
public static String getExternalIP() {
// Credit to StackOverflow user bakkal
try {
java.net.URL whatismyip = new java.net.URL(CHECK_IP_SITE);
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(whatismyip.openStream()));
return in.readLine(); // Only line returned is the IP
} catch (IOException e) {
return "[Not Found]";
}
}
}
| [
"[email protected]"
] | |
ca00199fcc4b49e17263c5d18b98f711917f1980 | 26d412a165b9d4d3f66908ec8ff65617b93799c0 | /striverSheet/binarySearchTree/predecessorSuccessor/PredecessorSuccessor.java | 4b45e0c57dd3c54e0b72a9f674443e7d819a40d2 | [] | no_license | shanu822486/DSAPreparation | 312c35a326c6d1367c7eb9439cb63769654370a0 | 578cc6bcb0cdaf19f6e1971279de92721c58308d | refs/heads/master | 2023-07-13T12:33:49.943942 | 2021-08-26T17:12:16 | 2021-08-26T17:12:16 | 376,103,371 | 0 | 0 | null | 2021-08-21T18:26:59 | 2021-06-11T17:54:00 | Java | UTF-8 | Java | false | false | 1,098 | java |
// link to Question - https://practice.geeksforgeeks.org/problems/predecessor-and-successor/1#
class GfG
{
public static void findPreSuc(Node root, Res p, Res s, int key)
{
// add your code here
Node pre = null;
Node suc = null;
if(root == null){
return;
}
while(root != null){
if(root.data == key){
if(root.left != null){
pre = root.left;
while(pre.right != null)
pre = pre.right;
}
if(root.right != null){
suc = root.right;
while(suc.left != null)
suc = suc.left;
}
p.pre = pre;
s.succ = suc;
return;
}
if(root.data > key){
suc = root;
root = root.left;
}
else {
pre = root;
root = root.right;
}
}
p.pre = pre;
s.succ = suc;
}
}
| [
"[email protected]"
] | |
d27fc329f19a680198e8631a9d3f63f7be459375 | e1760a1485edbfefa7731a14d87d8604661ee607 | /Data Structures/Project/stage5/src/test/java/edu/yu/cs/com1320/project/professorsTests/stage2/impl/UndoTest.java | 5f66569ee4a1f2ee32f679464e86fef61d9c7ee3 | [] | no_license | azrielb1/Class-Projects | d3ca46e247eae534c81fadd73d1e91e78499842a | 939372d624eadec183d5990acbbc90e79b093c7d | refs/heads/main | 2023-08-21T02:11:25.630993 | 2021-10-13T19:30:13 | 2021-10-13T19:30:13 | 416,867,720 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,889 | java | package edu.yu.cs.com1320.project.professorsTests.stage2.impl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import edu.yu.cs.com1320.project.stage5.Document;
import edu.yu.cs.com1320.project.stage5.DocumentStore;
import edu.yu.cs.com1320.project.stage5.impl.DocumentImpl;
import edu.yu.cs.com1320.project.stage5.impl.DocumentStoreImpl;
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
public class UndoTest {
//variables to hold possible values for doc1
private URI uri1;
private String txt1;
//variables to hold possible values for doc2
private URI uri2;
private String txt2;
//variables to hold possible values for doc2
private URI uri3;
private String txt3;
//variables to hold possible values for doc2
private URI uri4;
private String txt4;
private DocumentStoreImpl createStoreAndPutOne() throws IOException {
DocumentStoreImpl dsi = new DocumentStoreImpl();
ByteArrayInputStream bas1 = new ByteArrayInputStream(this.txt1.getBytes());
dsi.putDocument(bas1,this.uri1, DocumentStore.DocumentFormat.TXT);
return dsi;
}
private DocumentStoreImpl createStoreAndPutAll() throws IOException {
DocumentStoreImpl dsi = new DocumentStoreImpl();
//doc1
ByteArrayInputStream bas = new ByteArrayInputStream(this.txt1.getBytes());
dsi.putDocument(bas,this.uri1, DocumentStore.DocumentFormat.TXT);
//doc2
bas = new ByteArrayInputStream(this.txt2.getBytes());
dsi.putDocument(bas,this.uri2, DocumentStore.DocumentFormat.TXT);
//doc3
bas = new ByteArrayInputStream(this.txt3.getBytes());
dsi.putDocument(bas,this.uri3, DocumentStore.DocumentFormat.TXT);
//doc4
bas = new ByteArrayInputStream(this.txt4.getBytes());
dsi.putDocument(bas,this.uri4, DocumentStore.DocumentFormat.TXT);
return dsi;
}
@BeforeEach
public void init() throws Exception {
//init possible values for doc1
this.uri1 = new URI("http://edu.yu.cs/com1320/project/doc1");
this.txt1 = "This is the text of doc1, in plain text. No fancy file format - just plain old String";
//init possible values for doc2
this.uri2 = new URI("http://edu.yu.cs/com1320/project/doc2");
this.txt2 = "Text for doc2. A plain old String.";
//init possible values for doc1
this.uri3 = new URI("http://edu.yu.cs/com1320/project/doc3");
this.txt3 = "This is the text of doc3 - doc doc goose";
//init possible values for doc2
this.uri4 = new URI("http://edu.yu.cs/com1320/project/doc4");
this.txt4 = "doc4: how much wood would a woodchuck chuck...";
}
@Test
public void undoAfterOnePut() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutOne();
//undo after putting only one doc
Document doc1 = new DocumentImpl(this.uri1, this.txt1);
Document returned1 = dsi.getDocument(this.uri1);
assertNotNull(returned1,"Did not get a document back after putting it in");
assertEquals(doc1.getKey(),returned1.getKey(),"Did not get doc1 back");
dsi.undo();
returned1 = dsi.getDocument(this.uri1);
assertNull(returned1,"Put was undone - should have been null");
try {
dsi.undo();
fail("no documents - should've thrown IllegalStateException");
}catch(IllegalStateException e){}
}
@Test
public void undoWhenEmptyShouldThrow() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutOne();
//undo after putting only one doc
dsi.undo();
assertThrows(IllegalStateException.class,()->{dsi.undo();},"undo should throw an exception when there's nothing to undo");
}
@Test
public void undoByURIWhenEmptyShouldThrow() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutOne();
//undo after putting only one doc
dsi.undo();
assertThrows(IllegalStateException.class,()->{dsi.undo(this.uri1);},"undo should throw an exception when there's nothing to undo");
}
@Test
public void undoAfterMultiplePuts() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutAll();
//undo put 4 - test before and after
Document returned = dsi.getDocument(this.uri4);
assertEquals(this.uri4,returned.getKey(),"should've returned doc with uri4");
dsi.undo();
assertNull(dsi.getDocument(this.uri4),"should've been null - put doc4 was undone");
//undo put 3 - test before and after
returned = dsi.getDocument(this.uri3);
assertEquals(this.uri3,returned.getKey(),"should've returned doc with uri3");
dsi.undo();
assertNull(dsi.getDocument(this.uri3),"should've been null - put doc3 was undone");
//undo put 2 - test before and after
returned = dsi.getDocument(this.uri2);
assertEquals(this.uri2,returned.getKey(),"should've returned doc with uri3");
dsi.undo();
assertNull(dsi.getDocument(this.uri2),"should've been null - put doc2 was undone");
//undo put 1 - test before and after
returned = dsi.getDocument(this.uri1);
assertEquals(this.uri1,returned.getKey(),"should've returned doc with uri1");
dsi.undo();
assertNull(dsi.getDocument(this.uri1),"should've been null - put doc1 was undone");
try {
dsi.undo();
fail("no documents - should've thrown IllegalStateException");
}catch(IllegalStateException e){}
}
@Test
public void undoNthPutByURI() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutAll();
//undo put 2 - test before and after
Document returned = dsi.getDocument(this.uri2);
assertEquals(this.uri2,returned.getKey(),"should've returned doc with uri2");
dsi.undo(this.uri2);
assertNull(dsi.getDocument(this.uri2),"should've returned null - put was undone");
}
@Test
public void undoDelete() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutAll();
assertTrue(dsi.getDocument(this.uri3).getDocumentTxt().equals(this.txt3),"text was not as expected");
dsi.deleteDocument(this.uri3);
assertNull(dsi.getDocument(this.uri3),"doc should've been deleted");
dsi.undo(this.uri3);
assertTrue(dsi.getDocument(this.uri3).getKey().equals(this.uri3),"should return doc3");
}
@Test
public void undoNthDeleteByURI() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutAll();
assertTrue(dsi.getDocument(this.uri3).getDocumentTxt().equals(this.txt3),"text was not as expected");
dsi.deleteDocument(this.uri3);
dsi.deleteDocument(this.uri2);
assertNull(dsi.getDocument(this.uri2),"should've been null");
dsi.undo(this.uri2);
assertTrue(dsi.getDocument(this.uri2).getKey().equals(this.uri2),"should return doc2");
}
@Test
public void undoOverwriteByURI() throws Exception {
DocumentStoreImpl dsi = createStoreAndPutAll();
String replacement = "this is a replacement for txt2";
dsi.putDocument(new ByteArrayInputStream(replacement.getBytes()),this.uri2, DocumentStore.DocumentFormat.TXT);
assertTrue(dsi.getDocument(this.uri2).getDocumentTxt().equals(replacement),"should've returned replacement text");
dsi.undo(this.uri2);
assertTrue(dsi.getDocument(this.uri2).getDocumentTxt().equals(this.txt2),"should've returned original text");
}
} | [
"[email protected]"
] | |
74bdd4948d927934038f714acb41c6f7c45c5aca | 76875917925793ea446a1b1536606633a3272653 | /evo-async-all/src/main/java/com/tazine/evo/async/spring/finish/FinishService.java | 73462a2681e54fec91aca81e63fd59c7ea258854 | [
"MIT"
] | permissive | BookFrank/EVO-World | 01555355c434fac65406e158ffa5f7aebf3ff7dc | 3d27ae414f0281668024838a4c64db4bdd4a6377 | refs/heads/master | 2022-06-22T05:56:43.648597 | 2020-05-05T15:44:32 | 2020-05-05T15:44:32 | 147,456,884 | 1 | 1 | MIT | 2022-06-21T02:58:35 | 2018-09-05T03:54:10 | Java | UTF-8 | Java | false | false | 1,375 | java | package com.tazine.evo.async.spring.finish;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* FinishService
*
* @author frank
* @date 2019/3/5
*/
@Slf4j
@Service
public class FinishService {
@Async
public ListenableFuture<Integer> asyncProcess() {
log.info("执行中");
int sec = new Random().nextInt(3);
System.out.println(sec + " s");
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<>(sec);
}
@Async
public ListenableFuture<Integer> latchProcess(CountDownLatch latch) {
log.info("执行中");
int sec = new Random().nextInt(5);
System.out.println(sec + " s");
try {
TimeUnit.SECONDS.sleep(sec);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
log.info("进行countDown,剩余 {} 个", latch.getCount());
return new AsyncResult<>(sec);
}
}
| [
"[email protected]"
] | |
9163fb379cf73358ab3dbe47348a29d02db5bbb4 | 6f1f272bcf6bed8ec5c3352223b694f21b0e37e4 | /transponder/src/test/java/it/acalabro/transponder/KieLauncher.java | 7c6d8dcb2d191378f3770b6b37f586373d65d6cb | [] | no_license | acalabro/RSW_TH | e543c8ac2a893179b3fb4da749f088efae07c00d | 1290f8d6ed17067ae8d342d4284c11deed0eace2 | refs/heads/master | 2023-07-17T22:45:22.646417 | 2021-09-02T11:11:43 | 2021-09-02T11:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,122 | java | package it.acalabro.transponder;
import it.acalabro.transponder.cep.CepType;
import it.acalabro.transponder.event.ConcernProbeEvent;
public class KieLauncher {
public KieLauncher() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) throws InterruptedException {
DroolsKieTest asd = new DroolsKieTest();
asd.start();
DroolsKieTest.loadRule();
Thread.sleep(1000);
System.out.println("ora mando");
ConcernProbeEvent<String> evt = new ConcernProbeEvent<String>(
System.currentTimeMillis(),
"senderA", "destinationA", "sessionA",
"checksum",
"SLA Alert", "coccole", CepType.DROOLS,"open");
DroolsKieTest.insertEvent(evt);
Thread.sleep(1000);
System.out.println("ora mando altro");
ConcernProbeEvent<String> evt2 = new ConcernProbeEvent<String>(
System.currentTimeMillis(),
"senderA", "destinationA", "sessionA",
"checksum",
"load_one", "coccole", CepType.DROOLS,"open");
DroolsKieTest.insertEvent(evt2);
Thread.sleep(2000);
}
public static void printer(String toprint) {
System.out.println(toprint);
}
}
| [
"[email protected]"
] | |
30fc87fb697228ea328f91df709c57ab66c9888d | 6f33127cadc2226c200045bb98a2ecaebab7cef6 | /WebXslt/src/test/java/com/github/rabid_fish/web/ServletActionTest.java | 5a10a3cd3fce5d4a6a69e4fd8cb5b066aae35b43 | [
"Apache-2.0"
] | permissive | rabid-fish/JavaXslt | b4b949ebcfc8b1de05c9e495a3b62fc0dc1276c8 | 64ad55c3a3332714e7996279f2e7c6e2050242e0 | refs/heads/master | 2020-05-30T18:24:50.711081 | 2014-08-18T04:28:31 | 2014-08-18T04:28:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 961 | java | package com.github.rabid_fish.web;
import static org.junit.Assert.*;
import org.junit.Test;
public class ServletActionTest {
@Test
public void testTranslateFromString() {
ServletAction servletAction = ServletAction.translateFromString(ServletAction.LIST.toString());
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringWithLowercaseActionString() {
ServletAction servletAction = ServletAction.translateFromString(ServletAction.LIST.toString().toLowerCase());
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringCheckForNull() {
ServletAction servletAction = ServletAction.translateFromString(null);
assertEquals(servletAction, ServletAction.LIST);
}
@Test
public void testTranslateFromStringCheckForGibberish() {
ServletAction servletAction = ServletAction.translateFromString("gibberish");
assertEquals(servletAction, null);
}
}
| [
"[email protected]"
] | |
513c5b5129f8fa667063c4cbd34846cbf32cfb44 | a52c82754183ca5cc7550036ec995427001130b2 | /dhruv.java | 472ea786db4e6182e2dacd68a8df11f7477809cf | [] | no_license | mondalraj/financeForKids | ff74ea0521357bae996053775b06874fedb44a09 | bbb9461167fd66a842857e17319e85add42102cf | refs/heads/main | 2023-06-29T21:59:57.200517 | 2021-08-02T14:01:33 | 2021-08-02T14:01:33 | 391,561,455 | 0 | 2 | null | 2021-08-02T14:01:34 | 2021-08-01T07:44:06 | Java | UTF-8 | Java | false | false | 239 | java | public class dhruv{
public static void main(String[] args){
byte age = 30;
byte x = 90;
System.out.println(x+"\n");
System.out.println(age);
System.out.println("thats it!!");
}
} | [
"[email protected]"
] | |
353cf36981edc8e5fa201e752f46bbc08686a537 | 161078e887ecec2d09c1081cdb22f5178c699026 | /Theappfolder/app/src/main/java/com/example/love/solarswitch/CheckNSell.java | 61c192fda9b7aaedc98ce2749c7691bfaa623671 | [
"MIT"
] | permissive | lovepreetsi/hatch-template-project | f79c16c189ee61cdd88bb8867a5ca74ef42cd444 | df3f7d415992305c13014d9a1d12575a0a8d3cfc | refs/heads/master | 2020-04-08T02:23:07.871768 | 2018-11-25T13:20:03 | 2018-11-25T13:20:03 | 158,933,618 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 188 | java | package com.example.love.solarswitch;
public class CheckNSell {
//Add functionality here for the buyer side
//Add a function that checks for the nearest available seller
}
| [
"[email protected]"
] | |
cc3b95bcfba3685d3f5d2e67e0d467408b2103c7 | 889bd5447489a92723db41b40bc368ee3b809500 | /src/com/chariotsolutions/nfc/plugin/NfcPlugin.java | e04f783cc41a5db4392cc4484b52c8612f796dc2 | [] | no_license | fradinni/izitag-mobile | 6e2eae32718d06d1abf0a2c184b807fa5466b963 | 81df05e2073ec48a0a59ca1d3b46948442bb0f5e | refs/heads/master | 2020-04-23T12:17:59.252282 | 2013-05-12T11:36:23 | 2013-05-12T11:36:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,131 | java | package com.chariotsolutions.nfc.plugin;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Parcelable;
import android.util.Log;
public class NfcPlugin extends CordovaPlugin {
private static final String REGISTER_MIME_TYPE = "registerMimeType";
private static final String REGISTER_NDEF = "registerNdef";
private static final String REGISTER_NDEF_FORMATABLE = "registerNdefFormatable";
private static final String REGISTER_DEFAULT_TAG = "registerTag";
private static final String WRITE_TAG = "writeTag";
private static final String ERASE_TAG = "eraseTag";
private static final String SHARE_TAG = "shareTag";
private static final String UNSHARE_TAG = "unshareTag";
private static final String INIT = "init";
private static final String NDEF = "ndef";
private static final String NDEF_MIME = "ndef-mime";
private static final String NDEF_FORMATABLE = "ndef-formatable";
private static final String TAG_DEFAULT = "tag";
private static final String STATUS_NFC_OK = "NFC_OK";
private static final String STATUS_NO_NFC = "NO_NFC";
private static final String STATUS_NFC_DISABLED = "NFC_DISABLED";
private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED";
private static final String TAG = "NfcPlugin";
private final List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
private final ArrayList<String[]> techLists = new ArrayList<String[]>();
private NdefMessage p2pMessage = null;
private PendingIntent pendingIntent = null;
private Intent savedIntent = null;
@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "execute " + action);
if (!getNfcStatus().equals(STATUS_NFC_OK)) {
callbackContext.error(getNfcStatus());
return true; // short circuit
}
createPendingIntent();
if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) {
registerMimeType(data, callbackContext);
} else if (action.equalsIgnoreCase(REGISTER_NDEF)) {
registerNdef(callbackContext);
} else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATABLE)) {
registerNdefFormattable(callbackContext);
} else if (action.equals(REGISTER_DEFAULT_TAG)) {
registerDefaultTag(callbackContext);
} else if (action.equalsIgnoreCase(WRITE_TAG)) {
writeTag(data, callbackContext);
} else if (action.equalsIgnoreCase(ERASE_TAG)) {
eraseTag(callbackContext);
} else if (action.equalsIgnoreCase(SHARE_TAG)) {
shareTag(data, callbackContext);
} else if (action.equalsIgnoreCase(UNSHARE_TAG)) {
unshareTag(callbackContext);
} else if (action.equalsIgnoreCase(INIT)) {
init(callbackContext);
} else {
// invalid action
return false;
}
return true;
}
private String getNfcStatus() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter == null) {
return STATUS_NO_NFC;
} else if (!nfcAdapter.isEnabled()) {
return STATUS_NFC_DISABLED;
} else {
return STATUS_NFC_OK;
}
}
private void registerDefaultTag(CallbackContext callbackContext) {
addTagFilter();
callbackContext.success();
}
private void registerNdefFormattable(CallbackContext callbackContext) {
addTechList(new String[]{NdefFormatable.class.getName()});
callbackContext.success();
}
private void registerNdef(CallbackContext callbackContext) {
addTechList(new String[]{Ndef.class.getName()});
callbackContext.success();
}
private void unshareTag(CallbackContext callbackContext) {
p2pMessage = null;
stopNdefPush();
callbackContext.success();
}
private void init(CallbackContext callbackContext) {
Log.d(TAG, "Enabling plugin " + getIntent());
startNfc();
if (!recycledIntent()) {
parseMessage();
}
callbackContext.success();
}
private void registerMimeType(JSONArray data, CallbackContext callbackContext) throws JSONException {
String mimeType = "";
try {
mimeType = data.getString(0);
intentFilters.add(createIntentFilter(mimeType));
callbackContext.success();
} catch (MalformedMimeTypeException e) {
callbackContext.error("Invalid MIME Type " + mimeType);
}
}
// Cheating and writing an empty record. We may actually be able to erase some tag types.
private void eraseTag(CallbackContext callbackContext) throws JSONException {
Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefRecord[] records = {
new NdefRecord(NdefRecord.TNF_EMPTY, new byte[0], new byte[0], new byte[0])
};
writeNdefMessage(new NdefMessage(records), tag, callbackContext);
}
private void writeTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
if (getIntent() == null) { // TODO remove this and handle LostTag
callbackContext.error("Failed to write tag, received null intent");
}
Tag tag = savedIntent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
writeNdefMessage(new NdefMessage(records), tag, callbackContext);
}
private void writeNdefMessage(final NdefMessage message, final Tag tag, final CallbackContext callbackContext) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (ndef.isWritable()) {
int size = message.toByteArray().length;
if (ndef.getMaxSize() < size) {
callbackContext.error("Tag capacity is " + ndef.getMaxSize() +
" bytes, message is " + size + " bytes.");
} else {
ndef.writeNdefMessage(message);
callbackContext.success();
}
} else {
callbackContext.error("Tag is read only");
}
ndef.close();
} else {
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable != null) {
formatable.connect();
formatable.format(message);
callbackContext.success();
formatable.close();
} else {
callbackContext.error("Tag doesn't support NDEF");
}
}
} catch (FormatException e) {
callbackContext.error(e.getMessage());
} catch (TagLostException e) {
callbackContext.error(e.getMessage());
} catch (IOException e) {
callbackContext.error(e.getMessage());
}
}
});
}
private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException {
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
this.p2pMessage = new NdefMessage(records);
startNdefPush(callbackContext);
}
private void createPendingIntent() {
if (pendingIntent == null) {
Activity activity = getActivity();
Intent intent = new Intent(activity, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0);
}
}
private void addTechList(String[] list) {
this.addTechFilter();
this.addToTechList(list);
}
private void addTechFilter() {
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
}
private void addTagFilter() {
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED));
}
private void startNfc() {
createPendingIntent(); // onResume can call startNfc before execute
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null && getActivity().isFinishing() == false) {
nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
}
}
}
});
}
private void stopNfc() {
Log.d(TAG, "stopNfc");
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
nfcAdapter.disableForegroundDispatch(getActivity());
}
}
});
}
private void startNdefPush(final CallbackContext callbackContext) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter == null) {
callbackContext.error(STATUS_NO_NFC);
// isNdefPushEnabled would be nice, but requires android-17
//} else if (!nfcAdapter.isNdefPushEnabled()) {
// callbackContext.error(STATUS_NDEF_PUSH_DISABLED);
} else {
nfcAdapter.setNdefPushMessage(p2pMessage, getActivity());
callbackContext.success();
}
}
});
}
private void stopNdefPush() {
getActivity().runOnUiThread(new Runnable() {
public void run() {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity());
if (nfcAdapter != null) {
nfcAdapter.setNdefPushMessage(null, getActivity());
}
}
});
}
private void addToTechList(String[] techs) {
techLists.add(techs);
}
private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException {
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
intentFilter.addDataType(mimeType);
return intentFilter;
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
void parseMessage() {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Log.d(TAG, "parseMessage " + getIntent());
Intent intent = getIntent();
String action = intent.getAction();
Log.d(TAG, "action " + action);
if (action == null) {
return;
}
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Parcelable[] messages = intent.getParcelableArrayExtra((NfcAdapter.EXTRA_NDEF_MESSAGES));
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Ndef ndef = Ndef.get(tag);
fireNdefEvent(NDEF_MIME, ndef, messages);
} else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
for (String tagTech : tag.getTechList()) {
Log.d(TAG, tagTech);
if (tagTech.equals(NdefFormatable.class.getName())) {
fireNdefFormatableEvent(tag);
} else if (tagTech.equals(Ndef.class.getName())) { //
Ndef ndef = Ndef.get(tag);
fireNdefEvent(NDEF, ndef, messages);
}
}
}
if (action.equals(NfcAdapter.ACTION_TAG_DISCOVERED)) {
fireTagEvent(tag);
}
setIntent(new Intent());
}
});
}
private void fireNdefEvent(String type, Ndef ndef, Parcelable[] messages) {
JSONObject jsonObject = buildNdefJSON(ndef, messages);
String tag = jsonObject.toString();
String command = MessageFormat.format(javaScriptEventTemplate, type, tag);
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
private void fireNdefFormatableEvent (Tag tag) {
String command = MessageFormat.format(javaScriptEventTemplate, NDEF_FORMATABLE, Util.tagToJSON(tag));
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
private void fireTagEvent (Tag tag) {
String command = MessageFormat.format(javaScriptEventTemplate, TAG_DEFAULT, Util.tagToJSON(tag));
Log.v(TAG, command);
this.webView.sendJavascript(command);
}
JSONObject buildNdefJSON(Ndef ndef, Parcelable[] messages) {
JSONObject json = Util.ndefToJSON(ndef);
// ndef is null for peer-to-peer
// ndef and messages are null for ndef format-able
if (ndef == null && messages != null) {
try {
if (messages.length > 0) {
NdefMessage message = (NdefMessage) messages[0];
json.put("ndefMessage", Util.messageToJSON(message));
// guessing type, would prefer a more definitive way to determine type
json.put("type", "NDEF Push Protocol");
}
if (messages.length > 1) {
Log.wtf(TAG, "Expected one ndefMessage but found " + messages.length);
}
} catch (JSONException e) {
// shouldn't happen
Log.e(Util.TAG, "Failed to convert ndefMessage into json", e);
}
}
return json;
}
private boolean recycledIntent() { // TODO this is a kludge, find real solution
int flags = getIntent().getFlags();
if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) {
Log.i(TAG, "Launched from history, killing recycled intent");
setIntent(new Intent());
return true;
}
return false;
}
@Override
public void onPause(boolean multitasking) {
Log.d(TAG, "onPause " + getIntent());
super.onPause(multitasking);
stopNfc();
}
@Override
public void onResume(boolean multitasking) {
Log.d(TAG, "onResume " + getIntent());
super.onResume(multitasking);
startNfc();
}
@Override
public void onNewIntent(Intent intent) {
Log.d(TAG, "onNewIntent " + intent);
super.onNewIntent(intent);
setIntent(intent);
savedIntent = intent;
parseMessage();
}
private Activity getActivity() {
return this.cordova.getActivity();
}
private Intent getIntent() {
return getActivity().getIntent();
}
private void setIntent(Intent intent) {
getActivity().setIntent(intent);
}
String javaScriptEventTemplate =
"var e = document.createEvent(''Events'');\n" +
"e.initEvent(''{0}'');\n" +
"e.tag = {1};\n" +
"document.dispatchEvent(e);";
}
| [
"[email protected]"
] | |
5bb40ff5193c7eb86d7e5c7f2de34fd914e4378d | 58d037736fe260001cbb82783d75156f7fd3ad0d | /app/src/main/java/com/postterminal/postterminal/OtpSignUpActivity.java | abda1e014fc861068631d83d611943439a8d72df | [] | no_license | AmirNotch/AlphaHumoTerminal_JAVA | cc87c8f1ea4b7b1fac5789ce091da224eeefba86 | 5028c896f2f96e515646d56abb61b09d44e12005 | refs/heads/master | 2023-03-15T20:34:18.442714 | 2021-03-10T10:16:42 | 2021-03-10T10:16:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,852 | java | package com.postterminal.postterminal;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.postterminal.postterminal.JsonObjects.OtpCode;
import com.postterminal.postterminal.JsonObjects.SendSmS;
import com.postterminal.postterminal.PostRequest.APIInterface;
import java.io.IOException;
import java.util.Objects;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.postterminal.postterminal.PhoneActivity.main_auth;
import static com.postterminal.postterminal.PhoneActivity.number1;
public class OtpSignUpActivity extends AppCompatActivity {
TextView otpText,timer;
Button btnOtp,btnSendsms;
private int counter;
APIInterface apiInterface;
/*@SuppressLint("HardwareIds")
public String uniqueId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);*/
public static String access_tok_signUp;
//public static String main_auth1 = main_auth;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.otp_sign_up_activity);
Objects.requireNonNull(getSupportActionBar()).hide();
String ID = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request newRequest = originalRequest.newBuilder()
//.headers()
//.header("Authorization", main_auth)
//.header("uuid_device", ID)*/
.addHeader("Authorization", "Bearer " + main_auth)
.addHeader("uuid", ID)
.build();
return chain.proceed(newRequest);
}
})
.addInterceptor(loggingInterceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.43.26:8080")
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
apiInterface = retrofit.create(APIInterface.class);
//apiInterface = APIClient.getClient().create(APIInterface.class);
otpText = findViewById(R.id.textOtp);
timer = findViewById(R.id.timer);
btnOtp = findViewById(R.id.btnOtp);
btnSendsms = findViewById(R.id.btnSendSMS);
new CountDownTimer(120000, 1000){
@SuppressLint("SetTextI18n")
public void onTick(long millisUntilFinished){
btnSendsms.setEnabled(false);
timer.setText(String.valueOf(120-counter) + " сек.");
counter++;
}
public void onFinish(){
timer.setText("Вы можете получить смс ещё раз");
btnSendsms.setEnabled(true);
}
}.start();
btnOtp.setOnClickListener(new View.OnClickListener() {
//String number = PhoneActivity.number;
@Override
public void onClick(View v) {
Integer sms = Integer.parseInt(otpText.getText().toString());
OtpCode otp = new OtpCode(number1,"signup",sms);
Log.d("error",main_auth + " \n " + number1 +" \n "+ otpText + " ");
Call< OtpCode > call = apiInterface.doCallOtp(/*main_auth,ID,*/otp);
call.enqueue(new Callback< OtpCode >() {
@Override
public void onResponse(Call< OtpCode > call, Response< OtpCode > response) {
OtpCode resource = response.body();
//String result_desc = resource.result_desc;
//String result_code = resource.result_code;
// Log.d("errorCode", result_code + " \n ");
/*if (resource != null) {*/
String access_token = resource.access_token;
String refresh_token = resource.refresh_token;
String result_type = resource.result_code;
access_tok_signUp = access_token;
if (access_token == null || refresh_token == null || result_type == null) {
Toast.makeText(getApplicationContext(), "Повторите процедуру ещё раз", Toast.LENGTH_LONG).show();
}
Log.d("error", access_token + " \n " + refresh_token + " \n "/*+ result_type*/);
if (access_token == null && refresh_token == null && result_type == null) {
Toast.makeText(getApplicationContext(), "Вы ввели не правильно СМС либо перешлите СМС", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_type.equals("1") && !access_token.isEmpty() && !refresh_token.isEmpty()) {
startActivity(new Intent(OtpSignUpActivity.this, SignUpActivity.class));
Toast.makeText(getApplicationContext(), "Придумайте Pin-Code пожалуйста", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_type.equals("0") && access_token.isEmpty() && refresh_token.isEmpty()) {
Toast.makeText(getApplicationContext(), "Попробуйте снова", Toast.LENGTH_LONG).show();
}
/*}
else {
Toast.makeText(getApplicationContext(), "Повторите процедуру ещё раз", Toast.LENGTH_LONG).show();
}*/
}
@Override
public void onFailure(Call< OtpCode > call, Throwable t) {
Toast.makeText(getApplicationContext(),"Извините но произошла ошибка попробуйте снова", Toast.LENGTH_LONG).show();
Log.d("error", call.request().url() + " \n ");
}
});
}
});
btnSendsms.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.setText(0);
new CountDownTimer(120000, 1000){
@SuppressLint("SetTextI18n")
public void onTick(long millisUntilFinished){
btnSendsms.setEnabled(false);
timer.setText(String.valueOf(120 + 120-counter) + " сек.");
counter++;
}
public void onFinish(){
timer.setText("Вы можете получить смс ещё раз");
btnSendsms.setEnabled(true);
}
}.start();
SendSmS SmS = new SendSmS(number1,"signup");
Log.d("error",main_auth + " \n " + number1 +" \n ");
Call< SendSmS> call = apiInterface.doSendSmS(SmS);
call.enqueue(new Callback< SendSmS >() {
@Override
public void onResponse(Call< SendSmS > call, Response< SendSmS > response) {
SendSmS resource = response.body();
String result_code = resource.result_code;
String sign_type = resource.sign_type;
String auth_token = resource.auth_token;
main_auth = auth_token;
if (response.isSuccessful() && result_code.equals("signup") && sign_type.equals("1") && !auth_token.isEmpty()){
Toast.makeText(getApplicationContext(),"Сообщение отправлено подождите.", Toast.LENGTH_LONG).show();
}
if (response.isSuccessful() && result_code.equals("signup") && sign_type.equals("0") && !auth_token.isEmpty()){
Toast.makeText(getApplicationContext(),"Повторите ещё раз.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call< SendSmS > call, Throwable t) {
Toast.makeText(getApplicationContext(),"Проверьте интернет соединение", Toast.LENGTH_LONG).show();
}
});
}
});
}
}
| [
"[email protected]"
] | |
c1573eeff4cb1c5edc92ffa2a268004747337063 | 3e1ae46eaf303db5c7d103a597a3d54dd833f6b3 | /app/src/main/java/com/herokuapp/tastyapp/tasty/DispatchActivity.java | 99ec3de076ce795b29c013fd405fe4f39ac00839 | [] | no_license | kristjin/Tasty-Android | 6d728df7928e1ecba16b1b42eb3019eb42c17ccf | 01ebf726b578c3dc140f5d009f2b718e47b06673 | refs/heads/master | 2021-01-10T08:35:08.691737 | 2015-06-08T15:00:52 | 2015-06-08T15:00:52 | 36,157,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 206 | java | package com.herokuapp.tastyapp.tasty;
public class DispatchActivity extends ParseLoginDispatchActivity {
@Override
protected Class<?> getTargetClass() {
return MainActivity.class;
}
}
| [
"[email protected]"
] | |
70b1e8b8e4d336a65e7eb1ec63c1ca92f72b17f7 | dc5f91cbf5a4dfd0dc45687f9ac25873e3556b6d | /app/src/main/java/com/fm/modules/models/PlatilloSeleccionado.java | 70df28158cb49a229eb509d8dd2a3c61794b9996 | [] | no_license | Bateyss/AppDeliveryFuimonos | 796fdd77ea9bb973aaaf0679f0739d980c6d53c3 | bd04ca8683ad0983804de8609e2ae057288f4aeb | refs/heads/main | 2023-01-20T09:49:48.789362 | 2020-11-27T16:42:02 | 2020-11-27T16:42:02 | 316,553,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,291 | java | package com.fm.modules.models;
public class PlatilloSeleccionado {
private Long platilloSeleccionadoId;
private Platillo platillo;
private Pedido pedido;
private String nombre;
private double precio;
private int cantidad;
public PlatilloSeleccionado() {
}
public PlatilloSeleccionado(Long platilloSeleccionadoId, Platillo platillo, Pedido pedido, String nombre,
double precio, int cantidad) {
this.platilloSeleccionadoId = platilloSeleccionadoId;
this.platillo = platillo;
this.pedido = pedido;
this.nombre = nombre;
this.precio = precio;
this.cantidad = cantidad;
}
public Long getPlatilloSeleccionadoId() {
return platilloSeleccionadoId;
}
public void setPlatilloSeleccionadoId(Long platilloSeleccionadoId) {
this.platilloSeleccionadoId = platilloSeleccionadoId;
}
public Platillo getPlatillo() {
return platillo;
}
public void setPlatillo(Platillo platillo) {
this.platillo = platillo;
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{platilloSeleccionadoId:'");
builder.append(platilloSeleccionadoId);
builder.append("',platillos:'");
builder.append(platillo);
builder.append("',pedidos:'");
builder.append(pedido);
builder.append("',nombre:'");
builder.append(nombre);
builder.append("',precio:'");
builder.append(precio);
builder.append("',cantidad:'");
builder.append(cantidad);
builder.append("'}");
return builder.toString();
}
}
| [
"[email protected]"
] | |
e4c61bcab90ba633745020126e1915d150d8a168 | 88ed30ae68858ad6365357d4b0a95ad07594c430 | /platform/arcus-lib/src/main/java/com/iris/core/dao/cassandra/PersonDAOImpl.java | f242f35d8aeaff5d966c5ca2a2a9f146c16235f6 | [
"Apache-2.0"
] | permissive | Diffblue-benchmarks/arcusplatform | 686f58654d2cdf3ca3c25bc475bf8f04db0c4eb3 | b95cb4886b99548a6c67702e8ba770317df63fe2 | refs/heads/master | 2020-05-23T15:41:39.298441 | 2019-05-01T03:56:47 | 2019-05-01T03:56:47 | 186,830,996 | 0 | 0 | Apache-2.0 | 2019-05-30T11:13:52 | 2019-05-15T13:22:26 | Java | UTF-8 | Java | false | false | 40,400 | java | /*
* Copyright 2019 Arcus Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iris.core.dao.cassandra;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.FAILURE;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.SUCCESS;
import static com.iris.core.dao.PersonDAO.ResetPasswordResult.TOKEN_FAILURE;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.UUID;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterators;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import com.iris.Utils;
import com.iris.bootstrap.ServiceLocator;
import com.iris.capability.util.PhoneNumber;
import com.iris.capability.util.PhoneNumbers;
import com.iris.capability.util.PhoneNumbers.PhoneNumberFormat;
import com.iris.core.dao.PersonDAO;
import com.iris.core.dao.PersonPlaceAssocDAO;
import com.iris.core.dao.exception.EmailInUseException;
import com.iris.core.dao.exception.EmailMismatchException;
import com.iris.core.dao.exception.PinNotUniqueAtPlaceException;
import com.iris.core.dao.metrics.ColumnRepairMetrics;
import com.iris.core.dao.metrics.DaoMetrics;
import com.iris.messages.address.Address;
import com.iris.messages.address.PlatformServiceAddress;
import com.iris.messages.errors.ErrorEventException;
import com.iris.messages.errors.Errors;
import com.iris.messages.errors.NotFoundException;
import com.iris.messages.model.Person;
import com.iris.messages.services.PlatformConstants;
import com.iris.platform.PagedResults;
import com.iris.security.Login;
import com.iris.security.ParsedEmail;
import com.iris.security.credentials.CredentialsHashingStrategy;
import com.iris.security.crypto.AES;
import com.iris.util.TokenUtil;
@Singleton
public class PersonDAOImpl extends BaseCassandraCRUDDao<UUID, Person> implements PersonDAO {
private static final Logger logger = LoggerFactory.getLogger(PersonDAOImpl.class);
private static final Timer findByEmailTimer = DaoMetrics.readTimer(PersonDAO.class, "findByEmail");
private static final Timer updatePasswordTimer = DaoMetrics.updateTimer(PersonDAO.class, "updatePassword");
private static final Timer findLoginTimer = DaoMetrics.readTimer(PersonDAO.class, "findLogin");
private static final Timer generatePasswordResetTokenTimer = DaoMetrics.updateTimer(PersonDAO.class, "generatePasswordResetToken");
private static final Timer resetPasswordTimer = DaoMetrics.updateTimer(PersonDAO.class, "resetPassword");
private static final Timer updatePersonAndEmailTimer = DaoMetrics.upsertTimer(PersonDAO.class, "updatePersonAndEmail");
private static final Timer updatePinAtPlaceTimer = DaoMetrics.updateTimer(PersonDAO.class, "updatePinAtPlace");
private static final Timer setUpdateFlagTimer = DaoMetrics.updateTimer(PersonDAO.class, "setUpdateFlag");
private static final Timer getUpdateFlagTimer = DaoMetrics.readTimer(PersonDAO.class, "getUpdateFlag");
private static final Timer listPersonsTimer = DaoMetrics.readTimer(PersonDAO.class, "listPersons");
private static final Timer listByPlaceIdTimer = DaoMetrics.readTimer(PersonDAO.class, "listByPlaceId");
private static final Timer streamAllTimer = DaoMetrics.readTimer(PersonDAO.class, "streamAll");
static final String TABLE = "person";
private static final String UPDATEFLAG = "updateflag";
private static class LoginColumns {
final static String DOMAIN = "domain";
final static String USER_0_3 = "user_0_3";
final static String USER = "user";
final static String PASSWORD = "password";
final static String PASSWORD_SALT = "password_salt";
final static String USERID = "personid";
final static String RESET_TOKEN = "reset_token";
final static String LAST_PASS_CHANGE = "lastPassChange";
}
static class PersonEntityColumns {
final static String ACCOUNT_ID = "accountId";
final static String FIRST_NAME = "firstName";
final static String LAST_NAME = "lastName";
final static String TERMS_AGREED = "termsAgreed";
final static String PRIVACY_POLICY_AGREED = "privacyPolicyAgreed";
final static String EMAIL = "email";
final static String EMAIL_VERIFIED = "emailVerified";
final static String MOBILE_NUMBER = "mobileNumber";
final static String MOBILE_VERIFIED = "mobileVerified";
final static String MOBILE_NOTIFICATION_ENDPOINTS = "mobileNotificationEndpoints";
final static String CURRENT_PLACE = "currPlace";
final static String CURRENT_PLACE_METHOD = "currPlaceMethod";
final static String CURRENT_LOCATION = "currLocation";
final static String CURRENT_LOCATION_TIME = "currLocationTime";
final static String CURRENT_LOCATION_METHOD = "currLocationMethod";
final static String CONSENT_OFFERSPROMOTIONS = "consentOffersPromotions";
final static String CONSENT_STATEMENT = "consentStatement";
@Deprecated
final static String PIN = "pin";
@Deprecated
final static String PIN2 = "pin2";
final static String PINPERPLACE = "pinPerPlace";
final static String SECURITY_ANSWERS = "securityAnswers";
final static String HAS_LOGIN = "hasLogin";
final static String EMAIL_VERIFICATION_TOKEN = "emailVerificationToken";
};
private static final String[] COLUMN_ORDER = {
PersonEntityColumns.ACCOUNT_ID,
PersonEntityColumns.FIRST_NAME,
PersonEntityColumns.LAST_NAME,
PersonEntityColumns.TERMS_AGREED,
PersonEntityColumns.PRIVACY_POLICY_AGREED,
PersonEntityColumns.EMAIL,
PersonEntityColumns.EMAIL_VERIFIED,
PersonEntityColumns.MOBILE_NUMBER,
PersonEntityColumns.MOBILE_VERIFIED,
PersonEntityColumns.MOBILE_NOTIFICATION_ENDPOINTS,
PersonEntityColumns.CURRENT_PLACE,
PersonEntityColumns.CURRENT_PLACE_METHOD,
PersonEntityColumns.CURRENT_LOCATION,
PersonEntityColumns.CURRENT_LOCATION_TIME,
PersonEntityColumns.CURRENT_LOCATION_METHOD,
PersonEntityColumns.CONSENT_OFFERSPROMOTIONS,
PersonEntityColumns.CONSENT_STATEMENT,
PersonEntityColumns.SECURITY_ANSWERS,
PersonEntityColumns.HAS_LOGIN,
PersonEntityColumns.EMAIL_VERIFICATION_TOKEN
};
private static final String[] READ_ONLY_COLUMN_ORDER = {
PersonEntityColumns.PIN2,
PersonEntityColumns.PINPERPLACE
};
private static final String OPTIMISTIC_UPDATE =
CassandraQueryBuilder
.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(BaseEntityColumns.TAGS)
.addColumn(BaseEntityColumns.IMAGES)
.addColumns(COLUMN_ORDER)
.addWhereColumnEquals(BaseEntityColumns.ID)
.toQuery()
// TODO lightweight transaction support to cassandra query builder
.append(" IF ")
.append(PersonEntityColumns.EMAIL)
.append(" = ?")
.toString();
private PreparedStatement insertLogin;
private PreparedStatement findLoginByEmail;
private PreparedStatement deleteIndex;
private PreparedStatement updatePersonOptimistic;
private PreparedStatement updatePassword;
private PreparedStatement updatePinAtPlace;
private PreparedStatement updatePinAtPlaceAndPin2;
private PreparedStatement initMobileDeviceSequence;
private PreparedStatement deleteMobileDevices;
private PreparedStatement setUpdateFlag;
private PreparedStatement getUpdateFlag;
private PreparedStatement findAllPeople;
private PreparedStatement findAllPeopleLimit;
private final PreparedStatement listPaged;
private final AES aes;
private final PersonPlaceAssocDAO personPlaceAssocDAO;
@Inject(optional = true)
@Named("login.reset.token_ttl_mins")
private int tokenTTLMinutes = 15;
@Inject(optional = true)
@Named("dao.person.asynctimeoutms")
private long asyncTimeoutMs = 30000;
@Inject
@Named("questions.aes.secret")
private String questionsAesSecret;
@Inject
public PersonDAOImpl(Session session, AES aes, PersonPlaceAssocDAO personPlaceAssocDAO) {
super(session, TABLE, COLUMN_ORDER, READ_ONLY_COLUMN_ORDER);
insertLogin = prepareInsertLogin();
findLoginByEmail = prepareFindLoginByEmail();
deleteIndex = prepareDeleteIndex();
updatePersonOptimistic = prepareOptimisticUpdate();
updatePassword = prepareUpdatePassword();
updatePinAtPlace = prepareUpdatePinAtPlace();
updatePinAtPlaceAndPin2 = prepareUpdatePinAtPlaceAndPin2();
initMobileDeviceSequence = prepareInitMobileDeviceSequence();
deleteMobileDevices = prepareDeleteMobileDevices();
setUpdateFlag = prepareSetUpdateFlag();
getUpdateFlag = prepareGetUpdateFlag();
findAllPeople = prepareFindAllPeople();
findAllPeopleLimit = prepareFindAllPeopleLimit();
this.aes = aes;
this.personPlaceAssocDAO = personPlaceAssocDAO;
listPaged = prepareListPaged();
}
@Override
public Person findByAddress(Address addr) {
if(addr == null) {
return null;
}
if(!(addr instanceof PlatformServiceAddress)) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " is not a person");
}
PlatformServiceAddress platAddr = (PlatformServiceAddress) addr;
if(!PlatformConstants.SERVICE_PEOPLE.equals(platAddr.getGroup())) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " is not a person");
}
Object id = addr.getId();
if(id == null || !(id instanceof UUID)) {
throw new ErrorEventException(Errors.CODE_GENERIC, addr.getRepresentation() + " does not contain a valid perosn id");
}
return findById((UUID) id);
}
@Override
protected CassandraQueryBuilder selectNonEntityColumns(CassandraQueryBuilder queryBuilder) {
queryBuilder.addColumns(PersonEntityColumns.PIN);
return super.selectNonEntityColumns(queryBuilder);
}
@Override
protected List<Object> getValues(Person entity) {
List<Object> values = new LinkedList<Object>();
values.add(entity.getAccountId());
values.add(entity.getFirstName());
values.add(entity.getLastName());
values.add(entity.getTermsAgreed());
values.add(entity.getPrivacyPolicyAgreed());
values.add(entity.getEmail());
values.add(entity.getEmailVerified());
values.add(entity.getMobileNumber());
values.add(entity.getMobileVerified());
values.add(entity.getMobileNotificationEndpoints());
values.add(entity.getCurrPlace());
values.add(entity.getCurrPlaceMethod());
values.add(entity.getCurrLocation());
values.add(entity.getCurrLocationTime());
values.add(entity.getCurrLocationMethod());
values.add(entity.getConsentOffersPromotions());
values.add(entity.getConsentStatement());
if(entity.getSecurityAnswers() != null) {
Map<String,String> securityAnswers = new HashMap<>(entity.getSecurityAnswers());
securityAnswers.replaceAll((k,v) -> { return Utils.aesEncrypt(questionsAesSecret, v); });
values.add(securityAnswers);
} else {
values.add(null);
}
values.add(entity.getHasLogin());
values.add(entity.getEmailVerificationToken());
return values;
}
@Override
protected Person createEntity() {
return new Person();
}
@Override
protected void populateEntity(Row row, Person entity) {
entity.setAccountId(row.getUUID(PersonEntityColumns.ACCOUNT_ID));
entity.setCurrLocation(row.getString(PersonEntityColumns.CURRENT_LOCATION));
entity.setCurrLocationMethod(row.getString(PersonEntityColumns.CURRENT_LOCATION_METHOD));
entity.setCurrLocationTime(row.getDate(PersonEntityColumns.CURRENT_LOCATION_TIME));
entity.setCurrPlace(row.getUUID(PersonEntityColumns.CURRENT_PLACE));
entity.setCurrPlaceMethod(row.getString(PersonEntityColumns.CURRENT_PLACE_METHOD));
entity.setEmailVerified(row.getDate(PersonEntityColumns.EMAIL_VERIFIED));
entity.setMobileNotificationEndpoints(row.getList(PersonEntityColumns.MOBILE_NOTIFICATION_ENDPOINTS, String.class));
String mobileNumberStr = row.getString(PersonEntityColumns.MOBILE_NUMBER);
try {
PhoneNumber phone = PhoneNumbers.fromString(mobileNumberStr);
if(phone != null) {
entity.setMobileNumber(PhoneNumbers.format(phone, PhoneNumberFormat.PARENS));
}
}catch(IllegalArgumentException e) {
logger.warn("Error retrieving person's mobile number from DB.", e);
//TODO - what do we with existing invalid phone numbers since we have not validated them until now?
entity.setMobileNumber(mobileNumberStr);
}
entity.setMobileVerified(row.getDate(PersonEntityColumns.MOBILE_VERIFIED));
entity.setFirstName(row.getString(PersonEntityColumns.FIRST_NAME));
entity.setLastName(row.getString(PersonEntityColumns.LAST_NAME));
Map<String,String> pinPerPlace = row.getMap(PersonEntityColumns.PINPERPLACE, String.class, String.class);
if(pinPerPlace != null && !pinPerPlace.isEmpty()) {
Map<String,String> decrypted = new HashMap<>(pinPerPlace);
decrypted.replaceAll((k,v) -> { return aes.decrypt(entity.getId().toString(), v); });
entity.setPinPerPlace(decrypted);
} else {
String pin = row.getString(PersonEntityColumns.PIN2);
if(pin == null) {
pin = row.getString(PersonEntityColumns.PIN);
if(pin != null) {
ColumnRepairMetrics.incPinCounter();
}
}
if(pin != null) {
if(entity.getCurrPlace() == null) {
logger.warn("Unable to determine current place -- can't set pin");
}
else {
entity.setPinAtPlace(entity.getCurrPlace(), aes.decrypt(entity.getId().toString(), pin));
}
}
else {
logger.debug("User [{}] does not have a pin", entity.getId());
}
}
entity.setTermsAgreed(row.getDate(PersonEntityColumns.TERMS_AGREED));
entity.setPrivacyPolicyAgreed(row.getDate(PersonEntityColumns.PRIVACY_POLICY_AGREED));
entity.setConsentOffersPromotions(row.getDate(PersonEntityColumns.CONSENT_OFFERSPROMOTIONS));
entity.setConsentStatement(row.getDate(PersonEntityColumns.CONSENT_STATEMENT));
Map<String,String> securityAnswers = row.getMap(PersonEntityColumns.SECURITY_ANSWERS, String.class, String.class);
if(securityAnswers != null && !securityAnswers.isEmpty()) {
securityAnswers = new HashMap<>(securityAnswers);
securityAnswers.replaceAll((k,v) -> { return Utils.aesDecrypt(questionsAesSecret, v); });
entity.setSecurityAnswers(securityAnswers);
}
entity.setHasLogin(row.getBool(PersonEntityColumns.HAS_LOGIN));
entity.setEmail(row.getString(PersonEntityColumns.EMAIL));
entity.setEmailVerificationToken(row.getString(PersonEntityColumns.EMAIL_VERIFICATION_TOKEN));
}
@Override
protected Person doInsert(UUID id, Person entity) {
Person copy = entity.copy();
copy.setId(id);
copy = super.doInsert(id, copy);
session.execute(new BoundStatement(initMobileDeviceSequence).bind(id));
return copy;
}
protected Person doInsert(UUID id, Person person, String password) {
Person copy = person.copy();
boolean success = false;
insertLoginIndex(person.getEmail(), id, password);
try {
copy.setId(id);
copy.setHasLogin(true);
copy = super.doInsert(id, copy);
success = true;
}
finally {
if(!success) {
deleteLoginIndex(copy.getEmail());
}
}
session.execute(new BoundStatement(initMobileDeviceSequence).bind(id));
return copy;
}
/* (non-Javadoc)
* @see com.iris.core.dao.cassandra.BaseCassandraCRUDDao#doUpdate(com.iris.messages.model.BaseEntity)
*/
@Override
protected Person doUpdate(Person entity) {
if(!entity.getHasLogin()) {
return super.doUpdate(entity);
}
// else need to manage the email index
Person copy = entity.copy();
copy.setModified(new Date());
BoundStatement bs = bindUpdate(copy, copy.getEmail());
ResultSet rs = session.execute(bs);
if(!rs.wasApplied()) {
throw new EmailMismatchException(entity.getEmail());
}
return copy;
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#create(com.iris.messages.model.Person, java.lang.String)
*/
@Override
public Person create(Person person, String password) throws EmailInUseException {
Preconditions.checkArgument(person.getId() == null, "can't create a person with an existing id");
Preconditions.checkNotNull(password, "password may not be null for a credentialed user");
validateAndFormatMobileNumber(person);
UUID id = nextId(person);
return doInsert(id, person, password);
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#createPersonWithNoLogin(com.iris.messages.model.Person)
*/
@Override
public Person createPersonWithNoLogin(Person person) {
Preconditions.checkArgument(person.getId() == null, "can't create a person with an existing id");
Preconditions.checkArgument(person.getCreated() == null, "can't create a person with a created date");
validateAndFormatMobileNumber(person);
Person copy = person.copy();
copy.setHasLogin(false);
return super.save(copy);
}
/* (non-Javadoc)
* @see com.iris.core.dao.PersonDAO#update(com.iris.messages.model.Person)
*/
@Override
public Person update(Person person) {
validateAndFormatMobileNumber(person);
Preconditions.checkNotNull(person.getId(), "can't update a person with no id");
Preconditions.checkNotNull(person.getCreated(), "can't update a non-persisted person");
return super.save(person);
}
@Override
public Person findByEmail(String email) {
if(StringUtils.isBlank(email)) {
return null;
}
try(Context ctxt = findByEmailTimer.time()) {
UUID personId = findIdByEmail(email);
return personId == null ? null : findById(personId);
}
}
@Override
public void delete(Person entity) {
if(entity.getHasLogin()) {
deleteLoginIndex(entity.getEmail());
}
session.execute(new BoundStatement(deleteMobileDevices).bind(entity.getId()));
super.delete(entity);
}
@Override
public boolean updatePassword(String email, String oldPassword, String newPassword) {
Preconditions.checkArgument(!StringUtils.isBlank(email), "email must not be blank");
Preconditions.checkArgument(!StringUtils.isBlank(newPassword), "newPassword must not be blank");
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
ParsedEmail parsed = ParsedEmail.parse(email);
oldPassword = StringUtils.trimToNull(oldPassword);
Login curLogin = findLogin(email);
if(curLogin != null && hashingStrategy.isSalted()) {
oldPassword = hashingStrategy.hashCredentials(oldPassword, hashingStrategy.saltAsBytes(curLogin.getPasswordSalt()));
}
if(!StringUtils.equals(oldPassword, curLogin.getPassword() == null ? null : curLogin.getPassword())) {
return false;
}
try(Context ctxt = updatePasswordTimer.time()) {
return updatePassword(parsed, newPassword);
}
}
@Override
public Login findLogin(String username) {
Row row;
try(Context ctxt = findLoginTimer.time()) {
row = findLoginRowByUsername(username);
}
if(row == null) {
return null;
}
Login login = new Login();
login.setPassword(row.getString(LoginColumns.PASSWORD));
login.setPasswordSalt(row.getString(LoginColumns.PASSWORD_SALT));
login.setUserId(row.getUUID(LoginColumns.USERID));
login.setUsername(username);
login.setLastPasswordChange(row.getDate(LoginColumns.LAST_PASS_CHANGE));
return login;
}
private static final int TOKEN_LENGTH = 6;
@Override
public String generatePasswordResetToken(String email) {
Preconditions.checkNotNull(email, "Email must be provided");
try(Context ctxt = generatePasswordResetTokenTimer.time()) {
String token = TokenUtil.randomTokenString(TOKEN_LENGTH);
ParsedEmail parsed = ParsedEmail.parse(email);
Statement stmt = QueryBuilder.update("login")
.using(QueryBuilder.ttl(tokenTTLMinutes * 60))
.with(QueryBuilder.set(LoginColumns.RESET_TOKEN, token))
.where(QueryBuilder.eq(LoginColumns.DOMAIN, parsed.getDomain()))
.and(QueryBuilder.eq(LoginColumns.USER_0_3, parsed.getUser_0_3()))
.and(QueryBuilder.eq(LoginColumns.USER, parsed.getUser()));
session.execute(stmt);
return token.toString();
}
}
@Override
public ResetPasswordResult resetPassword(String email, String token, String password) {
if(StringUtils.isBlank(email)) {
return FAILURE;
}
if(StringUtils.isBlank(token)) {
return FAILURE;
}
if(StringUtils.isBlank(password)) {
return FAILURE;
}
ParsedEmail parsed = ParsedEmail.parse(email);
try(Context ctxt = resetPasswordTimer.time()) {
BoundStatement boundStatement = new BoundStatement(findLoginByEmail);
Row row = session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser())).one();
if(row == null) {
return FAILURE;
}
if(!Objects.equal(token, row.getString(LoginColumns.RESET_TOKEN))) {
return TOKEN_FAILURE;
}
boolean succeeded = updatePassword(parsed, password);
if(succeeded) {
Statement stmt = QueryBuilder.update("login")
.with(QueryBuilder.set(LoginColumns.RESET_TOKEN, null))
.where(QueryBuilder.eq(LoginColumns.DOMAIN, parsed.getDomain()))
.and(QueryBuilder.eq(LoginColumns.USER_0_3, parsed.getUser_0_3()))
.and(QueryBuilder.eq(LoginColumns.USER, parsed.getUser()));
session.execute(stmt);
}
return succeeded ? SUCCESS : FAILURE;
}
}
@Override
public Person updatePinAtPlace(Person person, UUID placeId, String newPin) throws PinNotUniqueAtPlaceException
{
Preconditions.checkArgument(person != null, "person cannot be null");
Preconditions.checkArgument(placeId != null, "placeId cannot be null");
Preconditions.checkArgument(StringUtils.isNotBlank(newPin), "newPin cannot be blank");
try (Context timerContext = updatePinAtPlaceTimer.time())
{
List<Person> personsAtPlace = listByPlaceId(placeId);
verifyNewPinUniqueness(personsAtPlace, placeId, newPin);
Date modified = new Date();
String encryptedNewPin = aes.encrypt(person.getId().toString(), newPin);
boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);
Statement updateStatement = isCurrentPlace ?
new BoundStatement(updatePinAtPlaceAndPin2)
.bind(modified, placeId.toString(), encryptedNewPin, encryptedNewPin, person.getId()) :
new BoundStatement(updatePinAtPlace)
.bind(modified, placeId.toString(), encryptedNewPin, person.getId());
session.execute(updateStatement);
Person copy = person.copy();
copy.setModified(modified);
copy.setPinAtPlace(placeId, newPin);
return copy;
}
}
private List<Person> listByPlaceId(UUID placeId)
{
try (Context timerContext = listByPlaceIdTimer.time())
{
Set<UUID> personIds = personPlaceAssocDAO.findPersonIdsByPlace(placeId);
Function<ResultSet, Person> entityTransform =
resultSet -> buildEntity(resultSet.one());
return listByIdsAsync(personIds, entityTransform, asyncTimeoutMs);
}
}
private void verifyNewPinUniqueness(List<Person> personsAtPlace, UUID placeId, String newPin)
throws PinNotUniqueAtPlaceException
{
for (Person personAtPlace : personsAtPlace)
{
if (personAtPlace.hasPinAtPlace(placeId))
{
String pinAtPlace = personAtPlace.getPinAtPlace(placeId);
if (StringUtils.equals(pinAtPlace, newPin))
{
throw new PinNotUniqueAtPlaceException();
}
}
}
}
@Override
public Person deletePinAtPlace(Person person, UUID placeId)
{
Preconditions.checkArgument(person != null, "person cannot be null");
Preconditions.checkArgument(placeId != null, "placeId cannot be null");
try (Context timerContext = updatePinAtPlaceTimer.time())
{
Date modified = new Date();
boolean isCurrentPlace = Objects.equal(person.getCurrPlace(), placeId);
Statement deleteStatement = isCurrentPlace ?
new BoundStatement(updatePinAtPlaceAndPin2).bind(modified, placeId.toString(), null, null, person.getId()) :
new BoundStatement(updatePinAtPlace).bind(modified, placeId.toString(), null, person.getId());
session.execute(deleteStatement);
Person copy = person.copy();
copy.setModified(modified);
copy.clearPin(placeId);
return copy;
}
}
@Override
public Person updatePersonAndEmail(Person person, String currentLoginEmail) {
if(!person.getHasLogin()) {
return update(person);
}
String newLoginEmail = person.getEmail();
ParsedEmail oldParsedEmail = ParsedEmail.parse(person.getEmail());
if (!oldParsedEmail.isValid()) {
throw new IllegalArgumentException("Old email address is not valid: " + currentLoginEmail);
}
ParsedEmail newParsedEmail = ParsedEmail.parse(newLoginEmail);
if (!newParsedEmail.isValid()) {
throw new IllegalArgumentException("New email address is not valid: " + newLoginEmail);
}
Row row = findLoginRowByUsername(currentLoginEmail);
if (row == null) {
throw new NotFoundException(Address.fromString(person.getAddress()));
}
String password = row.getString(LoginColumns.PASSWORD);
String password_salt = row.getString(LoginColumns.PASSWORD_SALT);
UUID userId = row.getUUID(LoginColumns.USERID);
Date lastPassChange = row.getDate(LoginColumns.LAST_PASS_CHANGE);
BoundStatement insert = new BoundStatement(insertLogin)
.setString(LoginColumns.DOMAIN, newParsedEmail.getDomain())
.setString(LoginColumns.USER_0_3, newParsedEmail.getUser_0_3())
.setString(LoginColumns.USER, newParsedEmail.getUser())
.setString(LoginColumns.PASSWORD, password)
.setString(LoginColumns.PASSWORD_SALT, password_salt)
.setUUID(LoginColumns.USERID, userId)
// changing the email invalidates the reset token
.setString(LoginColumns.RESET_TOKEN, null)
.setDate(LoginColumns.LAST_PASS_CHANGE, lastPassChange);
Person copy = person.copy();
copy.setModified(new Date());
copy.setEmailVerificationToken(null);
copy.setEmailVerified(null); //clear emailverified date and token
BoundStatement update = bindUpdate(copy, currentLoginEmail);
try(Context ctxt = updatePersonAndEmailTimer.time()) {
ResultSet rs = session.execute(insert);
if(!rs.wasApplied()) {
throw new EmailInUseException(newLoginEmail);
}
boolean success = false;
try {
ResultSet updateRs = session.execute(update);
if(!updateRs.wasApplied()) {
throw new EmailMismatchException(currentLoginEmail);
}
success = true;
}
finally {
if(!success) {
deleteLoginIndex(newLoginEmail);
}
}
deleteLoginIndex(currentLoginEmail);
}
return copy;
}
@Override
public void setUpdateFlag(UUID personId, boolean updateFlag) {
Preconditions.checkArgument(personId != null, "The person id cannot be null");
BoundStatement statement = new BoundStatement(setUpdateFlag);
try(Context ctxt = setUpdateFlagTimer.time()) {
session.execute(statement.bind(updateFlag, personId));
}
}
@Override
public boolean getUpdateFlag(UUID personId) {
Preconditions.checkArgument(personId != null, "The person id cannot be null");
BoundStatement statement = new BoundStatement(getUpdateFlag);
ResultSet resultSet;
try(Context ctxt = getUpdateFlagTimer.time()) {
resultSet = session.execute(statement.bind(personId));
}
Row row = resultSet.one();
return row.getBool(UPDATEFLAG);
}
private BoundStatement bindUpdate(Person person, String currentEmail) {
List<Object> values = new ArrayList<Object>(COLUMN_ORDER.length + 5);
values.add(person.getModified());
values.add(person.getTags());
values.add(person.getImages());
values.addAll(getValues(person));
values.add(person.getId());
values.add(currentEmail);
// use an optimistic update to prevent inadvertently changing the
// email address and corrupting the index
BoundStatement bs = new BoundStatement(updatePersonOptimistic);
return bs.bind(values.toArray());
}
private BoundStatement bindDeleteLogin(ParsedEmail parsed) {
return
new BoundStatement(deleteIndex)
.setString(LoginColumns.DOMAIN, parsed.getDomain())
.setString(LoginColumns.USER_0_3, parsed.getUser_0_3())
.setString(LoginColumns.USER, parsed.getUser()); }
private boolean updatePassword(ParsedEmail parsed, String password) {
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
List<String> hashAndSalt = generateHashAndSalt(password);
BoundStatement update = new BoundStatement(updatePassword);
ResultSet rs = session.execute(update.bind(hashAndSalt.get(0), hashAndSalt.get(1), new Date(), parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser()));
return rs.wasApplied();
}
private List<String> generateHashAndSalt(String password) {
CredentialsHashingStrategy hashingStrategy = ServiceLocator.getInstance(CredentialsHashingStrategy.class);
if(hashingStrategy == null) {
throw new IllegalStateException("No credentials hashing strategy has been found, please be sure that a concrete implementation of CredentialsHashingStrategy has been injected.");
}
String hashedPassword = password;
String salt = null;
if(hashingStrategy.isSalted()) {
ByteSource saltBytes = hashingStrategy.generateSalt();
salt = saltBytes.toBase64();
hashedPassword = hashingStrategy.hashCredentials(password, saltBytes);
}
return ImmutableList.of(hashedPassword, salt);
}
@Override
protected UUID getIdFromRow(Row row) {
return row.getUUID(BaseEntityColumns.ID);
}
@Override
protected UUID nextId(Person person) {
return UUID.randomUUID();
}
private Row findLoginRowByUsername(String username) {
ParsedEmail parsed = ParsedEmail.parse(username);
BoundStatement boundStatement = new BoundStatement(findLoginByEmail);
return session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser())).one();
}
private void insertLoginIndex(String email, UUID id, String password) {
ParsedEmail parsed = ParsedEmail.parse(email);
List<String> hashAndSalt = generateHashAndSalt(password);
BoundStatement boundStatement = new BoundStatement(insertLogin);
ResultSet rs = session.execute(boundStatement.bind(parsed.getDomain(), parsed.getUser_0_3(), parsed.getUser(), hashAndSalt.get(0), hashAndSalt.get(1), id, null, new Date()));
if(!rs.wasApplied()) {
throw new EmailInUseException(email);
}
}
private void deleteLoginIndex(String email) {
ParsedEmail parsed = ParsedEmail.parse(email);
BoundStatement boundStatement = bindDeleteLogin(parsed);
session.execute(boundStatement);
}
private UUID findIdByEmail(String email) {
Login login = findLogin(email);
return login == null ? null : login.getUserId();
}
@Override
public PagedResults<Person> listPersons(PersonQuery query) {
BoundStatement bs = null;
if (query.getToken() != null) {
bs = listPaged.bind(UUID.fromString(query.getToken()), query.getLimit() + 1);
} else {
bs = findAllPeopleLimit.bind(query.getLimit() + 1);
}
try(Context ctxt = listPersonsTimer.time()) {
return doList(bs, query.getLimit());
}
}
@Override
public Stream<Person> streamAll() {
try(Context ctxt = streamAllTimer.time()) {
Iterator<Row> rows = session.execute(new BoundStatement(findAllPeople)).iterator();
Iterator<Person> result = Iterators.transform(rows, (row) -> buildEntity(row));
Spliterator<Person> stream = Spliterators.spliteratorUnknownSize(result, Spliterator.IMMUTABLE | Spliterator.NONNULL);
return StreamSupport.stream(stream, false);
}
}
private PreparedStatement prepareOptimisticUpdate() {
PreparedStatement stmt = session.prepare(OPTIMISTIC_UPDATE);
stmt.setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
return stmt;
}
private PreparedStatement prepareInsertLogin() {
return CassandraQueryBuilder.insert(Tables.LOGIN)
.addColumn(LoginColumns.DOMAIN)
.addColumn(LoginColumns.USER_0_3)
.addColumn(LoginColumns.USER)
.addColumn(LoginColumns.PASSWORD)
.addColumn(LoginColumns.PASSWORD_SALT)
.addColumn(LoginColumns.USERID)
.addColumn(LoginColumns.RESET_TOKEN)
.addColumn(LoginColumns.LAST_PASS_CHANGE)
.ifNotExists()
.prepare(session);
}
private PreparedStatement prepareFindLoginByEmail() {
return CassandraQueryBuilder.select(Tables.LOGIN)
.addColumns(LoginColumns.DOMAIN, LoginColumns.USER_0_3, LoginColumns.USER, LoginColumns.PASSWORD, LoginColumns.PASSWORD_SALT, LoginColumns.USERID, LoginColumns.RESET_TOKEN, LoginColumns.LAST_PASS_CHANGE)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareDeleteIndex() {
return CassandraQueryBuilder.delete(Tables.LOGIN)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareUpdatePassword() {
return CassandraQueryBuilder.update(Tables.LOGIN)
.addColumn(LoginColumns.PASSWORD)
.addColumn(LoginColumns.PASSWORD_SALT)
.addColumn(LoginColumns.LAST_PASS_CHANGE)
.addWhereColumnEquals(LoginColumns.DOMAIN)
.addWhereColumnEquals(LoginColumns.USER_0_3)
.addWhereColumnEquals(LoginColumns.USER)
.prepare(session);
}
private PreparedStatement prepareUpdatePinAtPlace() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(PersonEntityColumns.PINPERPLACE + "[?]")
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareUpdatePinAtPlaceAndPin2() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(BaseEntityColumns.MODIFIED)
.addColumn(PersonEntityColumns.PINPERPLACE + "[?]")
.addColumn(PersonEntityColumns.PIN2)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareDeleteMobileDevices() {
return CassandraQueryBuilder.delete(Tables.MOBILE_DEVICES)
.addWhereColumnEquals(Tables.MobileDevicesCols.PERSON_ID)
.prepare(session);
}
private PreparedStatement prepareInitMobileDeviceSequence() {
return CassandraQueryBuilder.update(TABLE)
.set("mobileDeviceSequence=0")
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareSetUpdateFlag() {
return CassandraQueryBuilder.update(TABLE)
.addColumn(UPDATEFLAG)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareGetUpdateFlag() {
return CassandraQueryBuilder.select(TABLE)
.addColumn(UPDATEFLAG)
.addWhereColumnEquals(BaseEntityColumns.ID)
.prepare(session);
}
private PreparedStatement prepareFindAllPeople() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE);
return addAllColumns(queryBuilder).prepare(session);
}
private PreparedStatement prepareFindAllPeopleLimit() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE)
.boundLimit();
return addAllColumns(queryBuilder).prepare(session);
}
private PreparedStatement prepareListPaged() {
CassandraQueryBuilder queryBuilder = CassandraQueryBuilder.select(TABLE)
.where("token(" + BaseEntityColumns.ID + ") >= token(?) LIMIT ?");
return addAllColumns(queryBuilder).prepare(session);
}
private CassandraQueryBuilder addAllColumns(CassandraQueryBuilder queryBuilder) {
queryBuilder.addColumns(BASE_COLUMN_ORDER).addColumns(COLUMN_ORDER).addColumns(READ_ONLY_COLUMN_ORDER);
return selectNonEntityColumns(queryBuilder);
}
private void validateAndFormatMobileNumber(Person person) {
//Validate and format phone number
PhoneNumber phone1 = PhoneNumbers.fromString(person.getMobileNumber());
if(phone1 != null) {
person.setMobileNumber(PhoneNumbers.format(phone1, PhoneNumberFormat.PARENS));
}
}
}
| [
"[email protected]"
] | |
f22db35474ef20fa9afddfbdf29f5d3ed41bd30e | b2321d70021f9662d20c77728db888cb278d54e4 | /src/flowMap/model/OS.java | 303ec021175f15f6b6246beb86bb54ac9f5cabf3 | [] | no_license | 51mon/flowMap | 64a86d833a4811d503ccb4131963b3e875f56676 | 6005c5e984c0f44230da208143ca009208a6eb0b | refs/heads/master | 2020-04-05T23:31:52.877474 | 2013-11-20T00:00:52 | 2013-11-20T00:00:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,487 | java | package flowMap.model;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "oses")
public class OS extends NamedIntId {
public static final String STAGE_ID_COL = "stage_id";
@DatabaseField(columnName = STAGE_ID_COL, foreign = true)
Stage stage;
public static final String VERSION_COL = "version";
@DatabaseField(columnName = VERSION_COL)
private String version;
public static final String ARCHITECTURE_COL = "architecture";
@DatabaseField(columnName = ARCHITECTURE_COL)
private String architecture;
public static final String HOST_NAME_COL = "host_name";
@DatabaseField(columnName = HOST_NAME_COL)
private String hostName;
public OS() {}
public OS(String hostName) {
this.hostName = hostName;
}
public OS(String arch, String name, String version) {
super(name);
this.architecture = arch;
this.version = version;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Stage getStage() {
return stage;
}
public void setStage(Stage stage) {
this.stage = stage;
}
}
| [
"[email protected]"
] | |
0aa4012f159f2dd7a7325e0a0bbb0dbd440ea9e2 | 4c7ab60f25fb91f5b3222750316b9e09ce46c954 | /book/src/main/java/com/pc/composite/IBranch.java | e5ea07f75994943a63b4240b55e884a7f7d60b66 | [] | no_license | chad0204/design-pattern | 9f8c7a98f05fb873ad90156437fe80cd23f81689 | 29009e7b39f948bdd50679763a51c7b1ba7d6875 | refs/heads/master | 2023-03-08T09:38:17.931451 | 2023-03-01T14:37:15 | 2023-03-01T14:37:15 | 205,509,612 | 0 | 0 | null | 2022-08-11T09:44:18 | 2019-08-31T07:08:40 | Java | UTF-8 | Java | false | false | 230 | java | package com.pc.composite;
import java.util.List;
/**
* 领导职位
*
* @author pengchao
* @since 2023/1/31 14:01
*/
public interface IBranch extends ICrop {
void addCrop(ICrop iCrop);
List<ICrop> getChildes();
}
| [
"[email protected]"
] | |
dbedf0705e36b25e070d7b93b010b6b23a82de9e | d2c586de0f0b5b28f11a102afb80b42a0cbc655b | /src/HaksaStudent.java | 30ebb2f2f4bd80685d6633d3770cd91d8eecbfff | [] | no_license | meloning/HaksaManagerProgramGUI | 2630e34adc228dd5f4ee577f01f2cb90546e5f6f | 0247edd70797a082a5a52a87910ecf66895b6a95 | refs/heads/master | 2020-05-22T03:36:06.862194 | 2019-05-23T16:00:33 | 2019-05-23T16:00:33 | 186,215,369 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 8,079 | java | import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import DAO.StudentDAO;
import DTO.StudentDTO;
public class HaksaStudent extends JPanel{
//컴포넌트 그룹.
JTextField nameInput;
JTextField hakgwaInput;
JTextField addressInput;
JTextField hakbunInput;
JButton insertBtn;
JButton selectBtn;
JButton updateBtn;
JButton deleteBtn;
JButton searchBtn;
DefaultTableModel model;
JTable table;
//DAO 데이터접근 객체
StudentDAO stdDAO = new StudentDAO();
public HaksaStudent() {
this.setLayout(new FlowLayout());
hakbunInput = new JTextField(14);
nameInput = new JTextField(20);
hakgwaInput = new JTextField("컴퓨터공학과",20);
addressInput = new JTextField("서울시...",20);
insertBtn = new JButton("등록");
selectBtn = new JButton("목록");
updateBtn = new JButton("수정");
deleteBtn = new JButton("삭제");
searchBtn = new JButton("검색");
//입력 폼 추가.
this.add(new JLabel("학번 "));this.add(hakbunInput);this.add(searchBtn);//검색추가(Layout매니저적용되었기에..)
this.add(new JLabel("이름 "));this.add(nameInput);
this.add(new JLabel("학과 "));this.add(hakgwaInput);
this.add(new JLabel("주소 "));this.add(addressInput);
//출력 폼 추가(Table형태)
String colName[]={"학번","이름","학과","주소"};//Table 필드명
model=new DefaultTableModel(colName,0);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(270,120));
this.add(table);
this.add(new JScrollPane(table));
//버튼 추가.
this.add(insertBtn);this.add(selectBtn);this.add(updateBtn);this.add(deleteBtn);
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
StudentDTO stdTemp = null;
stdTemp=stdDAO.SelectById(hakbunInput.getText());
hakbunInput.setText(stdTemp.getId());
nameInput.setText(stdTemp.getName());
hakgwaInput.setText(stdTemp.getDepartmentId());
addressInput.setText(stdTemp.getAddress());
}
});
insertBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//필수입력체크
if(nameInput.getText().length()==0||hakbunInput.getText().length()==0||
hakgwaInput.getText().length()==0||addressInput.getText().length()==0) {
JOptionPane.showMessageDialog(null, "빈칸이 있습니다. 전부입력해주세요.","Message"
,JOptionPane.ERROR_MESSAGE);
}else {
StudentDTO stdTemp = new StudentDTO();
stdTemp.setId(hakbunInput.getText());
stdTemp.setName(nameInput.getText());
stdTemp.setDepartmentId(hakgwaInput.getText());
stdTemp.setAddress(addressInput.getText());
int result = stdDAO.Insert(stdTemp);
if(result>0) {
JOptionPane.showMessageDialog(null, "입력성공.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "입력실패.","Fail",JOptionPane.ERROR_MESSAGE);
}
//출력 메소드 호출
ShowList();
}
}
});
selectBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//출력 메소드 호출
ShowList();
}
});
updateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String id="";
StudentDTO stdTemp = null;
//수정할 목록을 출력하는 부분.
/*if(IsUpdate==false) {
id=JOptionPane.showInputDialog("변경할 id 입력(7글자):");
//취소한경우,
if(id==null) return;
stdTemp=dbm.SelectById(id);
if(stdTemp==null) {
JOptionPane.showMessageDialog(null, "존재하지 않는 id입니다."+id,"Message",JOptionPane.ERROR_MESSAGE);
}
hakbunInput.setText(stdTemp.getId());
nameInput.setText(stdTemp.getName());
hakgwaInput.setText(stdTemp.getDept());
addressInput.setText(stdTemp.getAddress());
updateBtn.setText("완료");
IsUpdate=true;
}else {*/
//실질적인 수정을 적용하는 부분.
stdTemp=new StudentDTO();
stdTemp.setId(hakbunInput.getText());
stdTemp.setName(nameInput.getText());
stdTemp.setDepartmentId(hakgwaInput.getText());
stdTemp.setAddress(addressInput.getText());
int result = stdDAO.Update(stdTemp);
if(result>0) {
JOptionPane.showMessageDialog(null, "수정되었습니다.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "수정하지 못했습니다.:"+id,"Fail",JOptionPane.ERROR_MESSAGE);
}
ShowList();
//updateBtn.setText("수정");
//IsUpdate=false;
//}
}
});
deleteBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = JOptionPane.showConfirmDialog(null, "삭제할것입니까?","Confirm",JOptionPane.YES_NO_OPTION);
//YES이면,
if(result==JOptionPane.YES_OPTION) {
//String id=JOptionPane.showInputDialog("삭제할 id 입력(7글자):");
//취소한경우,
//if(id==null) return;
if(hakbunInput.getText()==null) {
JOptionPane.showMessageDialog(null, "삭제할 학번을 입력해주세요.","Success",JOptionPane.INFORMATION_MESSAGE);
}
int result2 = stdDAO.Delete(hakbunInput.getText());
if(result2>0) {
JOptionPane.showMessageDialog(null, "삭제되었습니다.","Success",JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, "삭제하지 못했습니다.:","Fail",JOptionPane.ERROR_MESSAGE);
}
//출력 메소드 호출
ShowList();
}
//NO라면 없음.
}
});
table.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
table=(JTable)e.getComponent();//클릭한 테이블 구하기
model=(DefaultTableModel)table.getModel();
String id = (String) model.getValueAt(table.getSelectedRow(), 0);
hakbunInput.setText(id);
String name = (String) model.getValueAt(table.getSelectedRow(), 1);
nameInput.setText(name);
String dept = (String) model.getValueAt(table.getSelectedRow(), 2);
hakgwaInput.setText(dept);
String address = (String) model.getValueAt(table.getSelectedRow(), 3);
addressInput.setText(address);
}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
//this.setResizable(false);
this.setSize(290, 350);
this.setVisible(true);
}
//출력(Table) 메소드
public void ShowList() {
//입력폼 초기화
hakbunInput.setText("");
nameInput.setText("");
hakgwaInput.setText("");
addressInput.setText("");
//Table 초기화
model.setNumRows(0);
ArrayList<StudentDTO> arrStd = null;
arrStd=stdDAO.SelectAll();
if(arrStd==null) {
JOptionPane.showMessageDialog(null, "출력실패.","Fail",JOptionPane.ERROR_MESSAGE);
}
//컬럼의 갯수=> 4
String[] row=new String[4];
for(StudentDTO stdTemp:arrStd) {
//jta.append(stdTemp+"\n");
row[0]=stdTemp.getId();
row[1]=stdTemp.getName();
row[2]=stdTemp.getDepartmentId();
row[3]=stdTemp.getAddress();
model.addRow(row);
}
}
/*public static void main(String[] args) {
new NewHaksa();
}*/
}
| [
"[email protected]"
] | |
7c3bceafc6c60a3e94122d6262ce3c2fe8d6494f | 91bac731a3ca26af7011e67602f73a3427195104 | /L8.2.2/src/main/java/ru/otus/l822/NioMain.java | a8cabee246b8a5e9459605599d09c7f97f3ff173 | [
"MIT"
] | permissive | kundzi/otus_java_2017_04 | 80ae01c6449e60fe31b1147b775794d0886747e7 | 417929594f9c6ffd401d088c74b1acded67e2ade | refs/heads/master | 2020-12-03T00:32:54.085415 | 2017-08-16T20:32:36 | 2017-08-16T20:32:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 877 | java | package ru.otus.l822;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NioMain {
public static void main(String[] args) throws Exception {
try (RandomAccessFile aFile = new RandomAccessFile("data/data.txt", "rw")) {
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(64);
int bytesRead = inChannel.read(buf);
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
System.out.print("\n");
buf.clear();
bytesRead = inChannel.read(buf);
}
}
}
}
| [
"[email protected]"
] | |
ba6a89d2f4491ebba22b2bba79aac0dc1f7272d3 | 05eef6968dbbc5d8d08c48f44d50827a63a790a6 | /bank/src/com/neusoft/po/CreditCardBill.java | 9fc5c2a1950deb5b5fa8ea9a73d11552948ff390 | [] | no_license | NEU-ORG/bank | 087169a3ce5b41a3d6adf31c02ad163204081041 | 352dd5d63f17e3bf2f9967718b591459c7957d7d | refs/heads/master | 2020-04-06T08:53:32.339197 | 2016-09-05T10:48:22 | 2016-09-05T10:48:22 | 64,071,261 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,695 | java | package com.neusoft.po;
import java.util.Date;
/**
* CreditCardBill entity. @author MyEclipse Persistence Tools
*/
public class CreditCardBill implements java.io.Serializable {
// Fields
private Integer id;
private CreditCard creditCard;
private Date statementDate;
private double dueDate;
private String currency;
private long statementBalance;
private long minPayment;
private long lastStatementBalance;
private long amountPayment;
private long amountReceived;
// Constructors
/** default constructor */
public CreditCardBill() {
}
/** full constructor */
public CreditCardBill(CreditCard creditCard, Date statementDate,
double dueDate, String currency, long statementBalance,
long minPayment, long lastStatementBalance, long amountPayment,
long amountReceived) {
this.creditCard = creditCard;
this.statementDate = statementDate;
this.dueDate = dueDate;
this.currency = currency;
this.statementBalance = statementBalance;
this.minPayment = minPayment;
this.lastStatementBalance = lastStatementBalance;
this.amountPayment = amountPayment;
this.amountReceived = amountReceived;
}
// Property accessors
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public CreditCard getCreditCard() {
return this.creditCard;
}
public void setCreditCard(CreditCard creditCard) {
this.creditCard = creditCard;
}
public Date getStatementDate() {
return this.statementDate;
}
public void setStatementDate(Date statementDate) {
this.statementDate = statementDate;
}
public double getDueDate() {
return this.dueDate;
}
public void setDueDate(double dueDate) {
this.dueDate = dueDate;
}
public String getCurrency() {
return this.currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public long getStatementBalance() {
return this.statementBalance;
}
public void setStatementBalance(long statementBalance) {
this.statementBalance = statementBalance;
}
public long getMinPayment() {
return this.minPayment;
}
public void setMinPayment(long minPayment) {
this.minPayment = minPayment;
}
public long getLastStatementBalance() {
return this.lastStatementBalance;
}
public void setLastStatementBalance(long lastStatementBalance) {
this.lastStatementBalance = lastStatementBalance;
}
public long getAmountPayment() {
return this.amountPayment;
}
public void setAmountPayment(long amountPayment) {
this.amountPayment = amountPayment;
}
public long getAmountReceived() {
return this.amountReceived;
}
public void setAmountReceived(long amountReceived) {
this.amountReceived = amountReceived;
}
} | [
"[email protected]"
] | |
f64812b7e02dbd92f8764223e215c148d1be4490 | d57473533fe009c46f835ca372b82c7ecfd1ceea | /src/DatabaseManager.java | 223a90b43cc13dfbf2099977bfe2cf936d32427e | [] | no_license | Tuna0128/Database | aa7987d1adfe67d2825a63c9c9092ea470386b11 | 85c7833931db185a4c8c1ccd7693e9e599e03649 | refs/heads/master | 2021-04-12T09:56:46.634648 | 2017-06-16T15:21:09 | 2017-06-16T15:21:09 | 94,524,986 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,700 | java | import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseManager {
Connection db;
Statement state;
PreparedStatement pState;
DatabaseManager() {
init();
}
private void init() {
try {
db = DriverManager.getConnection("jdbc:mariadb://140.127.74.210/410477013", "410477013", "e853w");
state = db.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addMovie(String title, String genres, int year, int price, String company, String url)
throws SQLException {
int mv_id = 0;
pState = db.prepareStatement(
"INSERT INTO `movie` " + "(`mv_id`, `title`, `genres`, `released_year`, `price`, `company`, `url`) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)");
pState.setInt(1, mv_id);
pState.setString(2, title);
pState.setString(3, genres);
pState.setInt(4, year);
pState.setInt(5, price);
pState.setString(6, company);
pState.setString(7, url);
pState.execute();
}
public void updateMovie(int mv_id, String title, String genres, int year, int price, String company, String url)
throws SQLException {
ResultSet result = state.executeQuery("SELECT * FROM `movie` WHERE `mv_id` = 0 ");
result.next();
if (mv_id == -1)
mv_id = result.getInt("mv_id");
if (title == null)
title = result.getString("title");
if (genres == null)
genres = result.getString("genres");
if (year == -1)
year = result.getInt("released_year");
if (price == -1)
price = result.getInt("price");
if (company == null)
company = result.getString("company");
if (url == null)
url = result.getString("url");
pState = db.prepareStatement("UPDATE `movie` "
+ "SET `title` = ?, `genres` = ?, `released_year` = ?, `price` = ?, `company` = ?, `url` = ? "
+ "WHERE `movie`.`mv_id` = ? ");
pState.setString(1, title);
pState.setString(2, genres);
pState.setInt(3, year);
pState.setInt(4, price);
pState.setString(5, company);
pState.setString(6, url);
pState.setInt(7, mv_id);
pState.execute();
}
public void removeMovie(int mv_id) throws SQLException {
pState = db.prepareStatement("DELETE FROM `movie` " + "WHERE mv_id = ?");
pState.setInt(1, mv_id);
pState.execute();
}
public int getDownloads(int mv_id) throws SQLException {
pState = db
.prepareStatement("SELECT COUNT(`b_id`) " + "FROM `bill` natural join `movie` " + "WHERE `mv_id` = ? ");
pState.setInt(1, mv_id);
ResultSet result = pState.executeQuery();
result.next();
int i = result.getInt(1);
return i;
}
}
| [
"[email protected]"
] | |
e86ff35356cca4543678777b88d03fd2e2f1acab | 588208f2b8c6a4b45108a712812c07267d49f796 | /keg-MrDAP/mrdapPlatform/src/edu/thu/keg/link/client2/TaskLib.java | 34d3563839a3bc95956e5a720371a6043fabf4e7 | [] | no_license | Ariesnix/KEG | ce50fdbd87f1ad1b848a280ad232656019e1ecc5 | 643e0a58118e3b90a006c0dc621b8cd6afc9462a | refs/heads/master | 2021-01-01T20:05:33.893308 | 2014-12-07T11:34:25 | 2014-12-07T11:34:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 687 | java | package edu.thu.keg.link.client2;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import edu.thu.keg.link.client.env.Default;
import edu.thu.keg.link.common.request.Request;
public class TaskLib
{
public static void main(String[] args) throws JSONException
{
System.out.println(list());
}
public static JSONArray list() throws JSONException
{
List<String[]> list = new ArrayList<String[]>();
String app_submit_url = Default.getValue("APPLICATION_SUBMIT_URL");
String info= Request.post(app_submit_url + "TaskJarCollection2", list);
return new JSONArray(info);
}
}
| [
"[email protected]"
] | |
d6ebc129144645ba03bf08ca8296a26b37ab07d1 | f0b7aba39aed384415ce6b375db6157635922847 | /erp_dao/src/main/java/cn/feituo/erp/dao/impl/InventoryDao.java | 1b4322843d78768cafcedea6759202e33a1349e1 | [] | no_license | qiuxr/ERP | 104ac9a83b09bdf4209b9ef354f2571f763d33b9 | 567ab36de4f52ed47219973ddec6f4ed57b5be4d | refs/heads/master | 2018-12-25T02:08:55.960561 | 2018-10-25T01:52:50 | 2018-10-25T01:52:50 | 103,376,934 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,256 | java | package cn.feituo.erp.dao.impl;
import java.util.Calendar;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import cn.feituo.erp.dao.IInventoryDao;
import cn.feituo.erp.entity.Inventory;
/**
* 盘盈盘亏数据访问类
* @author Administrator
*
*/
public class InventoryDao extends BaseDao<Inventory> implements IInventoryDao {
/**
* 构建查询条件
* @param dep1
* @param dep2
* @param param
* @return
*/
public DetachedCriteria getDetachedCriteria(Inventory inventory1,Inventory inventory2,Object param){
DetachedCriteria dc=DetachedCriteria.forClass(Inventory.class);
if(inventory1!=null){
if(null != inventory1.getType() && inventory1.getType().trim().length()>0){
dc.add(Restrictions.like("type", inventory1.getType(), MatchMode.ANYWHERE));
}
if(null != inventory1.getState() && inventory1.getState().trim().length()>0){
dc.add(Restrictions.like("state", inventory1.getState(), MatchMode.ANYWHERE));
}
if(null != inventory1.getRemark() && inventory1.getRemark().trim().length()>0){
dc.add(Restrictions.like("remark", inventory1.getRemark(), MatchMode.ANYWHERE));
}
//提交日期
if(null != inventory1.getCreatetime()){
dc.add(Restrictions.ge("opertime",inventory1.getCreatetime()));
}
if(null != inventory1.getChecktime()){
dc.add(Restrictions.ge("opertime",inventory1.getChecktime()));
}
}
if(null != inventory2){
//结束日期
if(null != inventory2.getCreatetime()){
Calendar car = Calendar.getInstance();
car.setTime(inventory2.getCreatetime());
car.set(Calendar.HOUR, 23);//23点
car.set(Calendar.MINUTE, 59);//59分
car.set(Calendar.SECOND, 59);//秒
car.set(Calendar.MILLISECOND, 999);//毫秒
dc.add(Restrictions.le("createtime", car.getTime()));
}
if(null != inventory2.getChecktime()){
Calendar car = Calendar.getInstance();
car.setTime(inventory2.getChecktime());
car.set(Calendar.HOUR, 23);//23点
car.set(Calendar.MINUTE, 59);//59分
car.set(Calendar.SECOND, 59);//秒
car.set(Calendar.MILLISECOND, 999);//毫秒
dc.add(Restrictions.le("checktime", car.getTime()));
}
}
return dc;
}
}
| [
"[email protected]"
] | |
b4ca4275ec07d0cc507d9669d32918239ea69eae | cef95dbe9ac9dd71b179d715f7d4d2ff8c659921 | /SupportSpeed/src/main/java/com/titannet/service/IServicioService.java | 0a1dec0a38a78f29311429dc73ff0d5269565221 | [] | no_license | victoralbertosg/sysSupportSpeed | 216a09960a571b22aa0974ca75c9f306c9d03c7e | d7966db5f9aa5ebf3c8304134343ad6b7181e0e1 | refs/heads/master | 2022-06-30T07:35:19.662379 | 2019-09-05T05:28:35 | 2019-09-05T05:28:35 | 196,319,041 | 0 | 0 | null | 2022-06-21T01:26:12 | 2019-07-11T04:20:45 | Java | UTF-8 | Java | false | false | 862 | java | package com.titannet.service;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import com.titannet.entity.ControlServicio;
import com.titannet.entity.EstadoServicio;
import com.titannet.entity.Persona;
import com.titannet.entity.Servicio;
public interface IServicioService {
public List<Servicio> findAll();
public Page<Servicio> findAll(Pageable pageable);
public void save(Servicio servicio);
public Servicio findById(Long id);
public void delete(Servicio servicio);
public List<Servicio> servicioEstado1(EstadoServicio es);
public List<Servicio> servicioTrabajador (Persona persona);
public List<Servicio> servicioTrabajadorEstado (Persona persona,EstadoServicio es);
public List<Servicio> servicioClienteEstado (Persona persona,EstadoServicio es);
}
| [
"[email protected]"
] | |
22c01f2470817c17528780a77a442377b4f0daac | 9d3809c721d5f7d6a6f2f0e0139f1f32ea20c02e | /java10/DB연결/반환값연습.java | 0f23338bae902944ab086fa198c57b528fe76f58 | [
"MIT"
] | permissive | emiho4870/androidJava | 3c25c04a0a7987633f91d3e948d85176a9228b63 | b9af626f5379b84a0837539000705921d59863a1 | refs/heads/master | 2023-01-05T21:49:19.463234 | 2020-10-06T09:15:23 | 2020-10-06T09:15:23 | 288,410,809 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 818 | java | package DB연결;
import java.util.Date;
import java.util.Random;
public class 반환값연습 {
public int add( int x , int y ) {
return x + y ;
}
public double add( double x , int y ) { //하나라도 double 이면 double
return x + y ;
}
public double add( int x , double y ) { //하나라도 double 이면 double
return x + y ;
}
public int[] add( int x ) { // 기본형 ,int
int[] num = { 1 , 2 , x };
return num ;
}
public String add( String x , int y ) { // 하나라도 String 이면 String
return x + y ;
}
public Date add() { // return Date
Date date = new Date();
return date;
}
public boolean add(boolean x) { // 기본형 boolean
Random r = new Random(); //랜덤
return r.nextBoolean(); //랜덤 : boolean : return
}
}
| [
"[email protected]"
] | |
c116e9637b3e01349a6ee79bffada9c39c701c70 | ceca9162a8b8a2653620a1eb2b5362e06c8f0b63 | /srcM/javaconcurrent/Semaphore/SemaphoreExample.java | 1bdd6c11f86dbf919710487013c1959e4c37716f | [] | no_license | jal285/study_1 | 762c933b443e481b4d618ebb69dfd29d6214bc5e | 60b4d4aa08813bbb841e310b4d163c003eed375a | refs/heads/master | 2023-08-17T03:31:55.435983 | 2021-09-15T14:25:58 | 2021-09-15T14:25:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package javaconcurrent.Semaphore;
public class SemaphoreExample {
public static void main(String[] args) {
PrinteQueue printerQueue = new PrinteQueue();
Thread thread[]=new Thread[10];
for (int i=0; i<10;i++){
thread[i] = new Thread(new PrintingJob(printerQueue),"Thread"+i);
}
for (int i=0;i<10;i++){
thread[i].start();
}
}
}
| [
"[email protected]"
] | |
a23d14295837320637ae65b4a457cbc802de98f7 | 7378e110798a847629bf16d18104ba7e18b53917 | /app/src/main/java/com/rhaghis/quranproject/MainActivity.java | 2719c05569215e444ffe75acd065604e35fc4ca9 | [] | no_license | RHAghis/AlquranAppsUAS | e1b13ebcaf22f44c566f55095dfc7c0dee5f3fa1 | 162d95328cda896c591f2920329d084daedc09f9 | refs/heads/master | 2021-09-06T03:58:49.487758 | 2018-02-02T07:03:24 | 2018-02-02T07:03:24 | 119,938,280 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,709 | java | package com.rhaghis.quranproject;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import com.rhaghis.quranproject.adapter.QuranAdapter;
import com.rhaghis.quranproject.generator.ServiceGenerator;
import com.rhaghis.quranproject.models.Quran;
import com.rhaghis.quranproject.models.Surah;
import com.rhaghis.quranproject.services.QuranService;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
QuranService service;
RecyclerView rvSursh;
QuranAdapter quranAdapter;
List<Surah> surahList = new ArrayList<>();
RecyclerView.LayoutManager layoutManager;
ProgressDialog pr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
service = ServiceGenerator.createService(QuranService.class);
reloadData();
quranAdapter = new QuranAdapter(getApplicationContext(), surahList);
layoutManager = new LinearLayoutManager(this);
rvSursh = findViewById(R.id.rvSurah);
rvSursh.setLayoutManager(layoutManager);
rvSursh.setAdapter(quranAdapter);
}
private void reloadData() {
pr = ProgressDialog.show(this, "List Surah", "Silahkan Tunggu Sebentar....", true, false);
Call<Quran> call = service.getQuran();
call.enqueue(new Callback<Quran>() {
@Override
public void onResponse(Call<Quran> call, Response<Quran> response) {
if(response.isSuccessful()){
pr.dismiss();
Log.d("Suk", "Sukses !!! ");
surahList.clear();
surahList.addAll(response.body().getData().getSurahs());
quranAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Data Telah Tampil", Toast.LENGTH_SHORT).show();
}else {
pr.dismiss();
Toast.makeText(MainActivity.this, "Gagal Memuat Data", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<Quran> call, Throwable t) {
Log.d(String.valueOf(t), "Error : "+t);
Toast.makeText(MainActivity.this, "Harap Periksa Koneksi anda", Toast.LENGTH_SHORT).show();
}
});
}
}
| [
"[email protected]"
] | |
b20817b90fd8fd43aeebcda5c442f22c72498592 | f6a693800d563581c576d94dd6b02dc030774d85 | /app/src/main/java/id/sch/smktelkom_mlg/learn/recyclerview3/model/Hotel.java | 04b1e97dcda15b8d8007c02d26780bc6fc888b33 | [] | no_license | fadhilikhsann/RecyclerView3 | 0c71abc89af127c1d1b4af8974e3bf1c543f87cf | 548e6828cd8844ceed6a0c01106140185a69d97a | refs/heads/master | 2021-06-07T03:28:51.520207 | 2016-11-05T08:25:09 | 2016-11-05T08:25:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 567 | java | package id.sch.smktelkom_mlg.learn.recyclerview3.model;
import java.io.Serializable;
/**
* Created by Fadhil Ikhsan on 03/11/2016.
*/
public class Hotel implements Serializable {
public String judul;
public String deskripsi;
public String detail;
public String lokasi;
public String foto;
public Hotel(String judul, String deskripsi, String detail, String lokasi, String foto) {
this.judul = judul;
this.deskripsi = deskripsi;
this.detail = detail;
this.lokasi = lokasi;
this.foto = foto;
}
}
| [
"[email protected]"
] | |
4e904b8a2b42d86eec3ed34b987833e9f15eeb9d | bb2114897acd90dbeeab38b886a308a5826d7bf3 | /atmosphere-springboot-server/src/test/java/com/harshild/SampleAtmosphereServerTests.java | 9657a461545fc2aaeaddb0b41f0b25b1e8f3fa78 | [
"MIT"
] | permissive | harshild/atmosphere-all-clients | ced03c10452be395c974c7c5f056529710d524e2 | d1e6319b610ca831b9856227ee3d9e9bf657c827 | refs/heads/master | 2021-05-03T04:51:16.447817 | 2018-02-22T14:41:02 | 2018-02-22T14:41:02 | 120,627,704 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,772 | java | /*
* Copyright 2008-2018-2008-2018 the original author or authors.
*
* 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.harshild;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AtmosphereServer.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class SampleAtmosphereServerTests {
private static Log logger = LogFactory.getLog(SampleAtmosphereServerTests.class);
@Value("${local.server.port}")
private int port = 1234;
@Test
public void chatEndpoint() throws Exception {
ConfigurableApplicationContext context = new SpringApplicationBuilder(
ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class)
.properties(
"websocket.uri:ws://localhost:" + this.port + "/chat/websocket")
.run("--spring.main.web_environment=false");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
AtomicReference<String> messagePayloadReference = context
.getBean(ClientConfiguration.class).messagePayload;
context.close();
assertThat(count, equalTo(0L));
assertThat(messagePayloadReference.get(),
containsString("{\"message\":\"test\",\"author\":\"test\",\"time\":"));
}
@Configuration
static class ClientConfiguration implements CommandLineRunner {
@Value("${websocket.uri}")
private String webSocketUri;
private final CountDownLatch latch = new CountDownLatch(1);
private final AtomicReference<String> messagePayload = new AtomicReference<String>();
@Override
public void run(String... args) throws Exception {
logger.info("Waiting for response: latch=" + this.latch.getCount());
if (this.latch.await(10, TimeUnit.SECONDS)) {
logger.info("Got response: " + this.messagePayload.get());
}
else {
logger.info("Response not received: latch=" + this.latch.getCount());
}
}
@Bean
public WebSocketConnectionManager wsConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(),
handler(), this.webSocketUri);
manager.setAutoStartup(true);
return manager;
}
@Bean
public StandardWebSocketClient client() {
return new StandardWebSocketClient();
}
@Bean
public TextWebSocketHandler handler() {
return new TextWebSocketHandler() {
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
session.sendMessage(new TextMessage(
"{\"author\":\"test\",\"message\":\"test\"}"));
}
@Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message) throws Exception {
logger.info("Received: " + message + " ("
+ ClientConfiguration.this.latch.getCount() + ")");
session.close();
ClientConfiguration.this.messagePayload.set(message.getPayload());
ClientConfiguration.this.latch.countDown();
}
};
}
}
}
| [
"[email protected]"
] | |
ce980b7e035214b590d61b51f0deaa05e30d9e9a | d04da34e2bd704c45136c06605a7d6598b17030f | /weekly-core/src/main/java/com/weekly/framework/datasource/DynamicDataSource.java | 1322673b54f6991157c92fc62692ef4e49ffa0ff | [] | no_license | peiweipan/weeklySchedule | 427e7cab8d2c4a854b14b72e7ecf5108be9ca84b | a28f41436bedd5db1ba1fed9078f1338340c1fd1 | refs/heads/master | 2023-04-14T21:16:40.174340 | 2020-09-02T02:12:32 | 2020-09-02T02:12:32 | 361,801,579 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 705 | java | package com.weekly.framework.datasource;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
* 动态数据源
*
* @author weekly
*/
public class DynamicDataSource extends AbstractRoutingDataSource
{
public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources)
{
super.setDefaultTargetDataSource(defaultTargetDataSource);
super.setTargetDataSources(targetDataSources);
super.afterPropertiesSet();
}
@Override
protected Object determineCurrentLookupKey()
{
return DynamicDataSourceContextHolder.getDataSourceType();
}
} | [
"[email protected]"
] | |
ff433620367e358da1fd67d816c20315caf51f6a | 7f9e87256e62771a6ec72d1c9546a3d1e4f41281 | /src/day53/Ex4.java | c851a1e2cc2de051aebb85009029272eb93b929d | [] | no_license | jeonseojin/Java | df7c670cfc28706ab0207a5035d3bcf347d35bb2 | a5fd3b5ed7b219d9f24dd8619fbf9ab327c0c5d1 | refs/heads/master | 2022-11-22T15:13:53.090180 | 2020-07-09T00:48:05 | 2020-07-09T00:48:10 | 257,480,244 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 228 | java | package day53;
public class Ex4 {
public static void main(String[] args) {
// while문 9단
int num=9;
int n=1;
while(n<=9) {
System.out.printf("%d X %d = %d\n",num,n,num*n);
n++;
}
}
}
| [
"[email protected]"
] | |
00ebf7edd551dec1ee82b3203a0f548747e280c3 | 29482a8cd1a75b33f043a28e5ade29f96bc79605 | /doji-practice/src/main/java/com/dayton/doji/practice/concurrentPrograming/chap01/demo01/ConcurrencyTest.java | f6d2c34aad9aa9dc46fda393cc26deefd6beb8d0 | [
"Apache-2.0"
] | permissive | dym3093/doji | ced52b7a05391f12c53b60d8312b73982d0d79a2 | 057047bd323540bc818d48687d256208e2494d81 | refs/heads/master | 2023-01-30T07:56:42.712146 | 2020-12-15T14:25:41 | 2020-12-15T14:25:41 | 285,522,700 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,264 | java | package com.dayton.doji.practice.concurrentPrograming.chap01.demo01;
/**
* @author Martin Deng
* @since 2020-11-16 20:58
*/
public class ConcurrencyTest {
private static final long COUNT = 10000*10000L;
public static void main(String[] args) throws InterruptedException {
concurrency();
serial();
}
/**
* 并发执行
* @return void
* @author Martin Deng
* @since 2020/11/16 21:05
*/
private static void concurrency() throws InterruptedException {
long start = System.currentTimeMillis();
Thread thread = new Thread(() -> {
int a = 0;
for (int i = 0; i < COUNT; i++) {
a += 5;
}
});
thread.start();
int b = 0;
for (int i = 0; i < COUNT; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
thread.join();
System.out.println("concurrency : " + time + " ms, b=" + b );
}
/**
* 串行执行
* @return void
* @author Martin Deng
* @since 2020/11/16 21:05
*/
private static void serial(){
long start = System.currentTimeMillis();
int a = 0;
for (int i = 0; i < COUNT; i++) {
a += 5;
}
int b = 0;
for (int i = 0; i < COUNT; i++) {
b--;
}
long time = System.currentTimeMillis() - start;
System.out.println("serial : " + time + " ms, b=" + b + ", a=" + a);
}
}
| [
"[email protected]"
] | |
f95727b5a4d736e89ea79da90eb38e014761eef3 | 71cc9418e03e0f88b2b2468a6374856d3e77255d | /test/java/com/example/kids0806/ExampleUnitTest.java | 915dd524e6f105375e1c20b453e7cb093e588105 | [] | no_license | 2021-SMHRD-KDT-AI-1/JamMinWorld | aad233eb26aa0d9d26199ccc5396aba62a52abe4 | a9dc4460f0b9308ccaaadf800aaa8ca4d700a659 | refs/heads/master | 2023-07-15T16:49:46.750230 | 2021-08-10T00:30:11 | 2021-08-10T00:30:11 | 388,303,720 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 397 | java | package com.example.kids0806;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
639d42526134c96f6400414ad9a2c7b046513af6 | 7454db1033695b233820e2c0d8071028451e5b42 | /FTPServer.java | 85cc41633f906c3e8f3673058026ecbb95168377 | [] | no_license | shahzain/Java-Projects | a5c8e781d49d09d1e7e974f7b92d15a177d29c4c | 9d3009aa402da33cc5040fd28b48d303bc5babfa | refs/heads/master | 2021-01-24T18:37:37.848326 | 2017-03-09T15:31:02 | 2017-03-09T15:31:02 | 84,456,125 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,824 | java | package ftpserver;
import java.net.*;
import java.io.*;
import java.util.*;
public class FTPServer {
public static void main(String[] args) throws UnsupportedEncodingException, FileNotFoundException, IOException {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("server.txt"), "utf-8"))) {
writer.write("from server");
}
ServerSocket soc=new ServerSocket(5217);
System.out.println("FTP Server Started on Port Number 5217");
while(true)
{
System.out.println("Waiting for Connection ...");
transferfile t=new transferfile(soc.accept());
}}
}
class transferfile extends Thread
{
Socket ClientSoc;
DataInputStream din;
DataOutputStream dout;
transferfile(Socket soc)
{
try
{
ClientSoc=soc;
din=new DataInputStream(ClientSoc.getInputStream());
dout=new DataOutputStream(ClientSoc.getOutputStream());
System.out.println("FTP Client Connected ...");
start();
}
catch(Exception ex)
{
}
}
void SendFile() throws Exception
{
String filename=din.readUTF();
File f=new File(filename);
if(!f.exists())
{
dout.writeUTF("File Not Found");
return;
}
else
{
dout.writeUTF("READY");
FileInputStream fin=new FileInputStream(f);
int ch;
do
{
ch=fin.read();
dout.writeUTF(String.valueOf(ch));
}
while(ch!=-1);
fin.close();
dout.writeUTF("File Receive Successfully");
}
}
void ReceiveFile() throws Exception
{
String filename=din.readUTF();
if(filename.compareTo("File not found")==0)
{
return;
}
File f=new File(filename);
String option;
if(f.exists())
{
dout.writeUTF("File Already Exists");
option=din.readUTF();
}
else
{
dout.writeUTF("SendFile");
option="Y";
}
if(option.compareTo("Y")==0)
{
FileOutputStream fout=new FileOutputStream(f);
int ch;
String temp;
do
{
temp=din.readUTF();
ch=Integer.parseInt(temp);
if(ch!=-1)
{
fout.write(ch);
}
}while(ch!=-1);
fout.close();
dout.writeUTF("File Send Successfully");
}
else
{
return;
}
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for Command ...");
String Command=din.readUTF();
if(Command.compareTo("GET")==0)
{
System.out.println("\tGET Command Received ...");
SendFile();
continue;
}
else if(Command.compareTo("SEND")==0)
{
System.out.println("\tSEND Command Receiced ...");
ReceiveFile();
continue;
}
else if(Command.compareTo("DISCONNECT")==0)
{
System.out.println("\tDisconnect Command Received ...");
System.exit(1);
}
}
catch(Exception ex)
{
}
}
}
}
| [
"[email protected]"
] | |
52f66eac5009ce2de1abc88e2c6980a731ae9a69 | 2d5aa15ce0f39e6f02e24c013c9405b8a3261617 | /src/main/java/com/kaytech/bugtracker/domain/User.java | 72819b9eaab5e3437995aae00048870a761e052e | [] | no_license | driscol/BugTrackerJHipster | 82c6defbbe38d862f954b80a01ab052241ab8997 | f532aa8c85a356fae3e019248a54c67441c05fc8 | refs/heads/main | 2023-03-10T21:05:38.051449 | 2021-02-22T23:51:51 | 2021-02-22T23:51:51 | 341,370,917 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,536 | java | package com.kaytech.bugtracker.domain;
import com.kaytech.bugtracker.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
return 31;
}
// prettier-ignore
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
| [
"/"
] | / |
8895b2bcd1dae57b7e637c4bcd412c27fb2addde | b4cf19d02b4300b11daab82fc9c5445aaf11191b | /src/main/java/com/example/sweater/domain/User.java | e46b50c1dc9ceae43f2c8747fe499a93136284ac | [
"MIT"
] | permissive | IMozgg/sweater | c602ca39b3d49227d18690d3addb9488e684a337 | aeba870dd29b041b355fa43cf5c35b9ae7e04ebe | refs/heads/master | 2020-04-24T12:58:09.968214 | 2019-03-05T20:32:59 | 2019-03-05T20:32:59 | 171,972,108 | 0 | 0 | MIT | 2019-03-05T22:03:36 | 2019-02-22T01:22:28 | Java | UTF-8 | Java | false | false | 1,869 | java | package com.example.sweater.domain;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Set;
@Entity
@Table(name = "usr")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean isActive;
@ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
@CollectionTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"))
@Enumerated(EnumType.STRING)
private Set<Role> roles;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return getRoles();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return isActive;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
| [
"[email protected]"
] | |
ce242588be81174c01fd68b0a26fa9b49b41a117 | 6d620667c6df8acf05e79bbaa86643655e0ef339 | /src/main/java/expression/Expression.java | 7675da4edd7469fc4cab2d1df3dd8b9573992f9b | [] | no_license | saimonsaret/ExpressionGenerator | 5170d6bdff4dacfbaf4c7e5a38ce8522baf45244 | d98eaed189b7100ee37bd08c644c01ec2bdeab46 | refs/heads/master | 2021-01-20T09:14:20.263070 | 2017-08-27T23:19:05 | 2017-08-27T23:19:05 | 101,586,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package expression;
import expression.token.Token;
import java.util.List;
public class Expression {
private final List<Token> tokens;
public Expression(List<Token> tokens) {
this.tokens = tokens;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Token token : tokens) {
builder.append(token.getValue());
}
return builder.toString();
}
public List<Token> getTokens() {
return tokens;
}
}
| [
"[email protected]"
] | |
7d6c10e01da2a437586a07e7024d188ba0b4ee88 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/27/27_f3a1e317e1e2e56da5febe80fcec91a24a90888e/NetController/27_f3a1e317e1e2e56da5febe80fcec91a24a90888e_NetController_s.java | 28adfabcfc8e1f291a5b22d7545621b7cfc0851e | [] | 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 | 32,044 | java | package com.game.rania.net;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.game.rania.Config;
import com.game.rania.controller.CommandController;
import com.game.rania.controller.Controllers;
import com.game.rania.controller.command.AddLocationCommand;
import com.game.rania.controller.command.AddPlanetCommand;
import com.game.rania.controller.command.AddUserCommand;
import com.game.rania.controller.command.AttackCommand;
import com.game.rania.controller.command.ChatNewMessageCommand;
import com.game.rania.controller.command.RemoveUserCommand;
import com.game.rania.controller.command.RepairCommand;
import com.game.rania.controller.command.SetTargetCommand;
import com.game.rania.controller.command.SwitchScreenCommand;
import com.game.rania.model.Domain;
import com.game.rania.model.Nebula;
import com.game.rania.model.Player;
import com.game.rania.model.Target;
import com.game.rania.model.User;
import com.game.rania.model.Location;
import com.game.rania.model.Planet;
import com.game.rania.model.items.Consumable;
import com.game.rania.model.items.Device;
import com.game.rania.model.items.RepairKit;
import com.game.rania.model.items.Engine;
import com.game.rania.model.items.Equip;
import com.game.rania.model.items.Fuelbag;
import com.game.rania.model.items.Hyper;
import com.game.rania.model.items.Item;
import com.game.rania.model.items.ItemCollection;
import com.game.rania.model.items.Radar;
import com.game.rania.model.items.Shield;
import com.game.rania.model.items.Body;
import com.game.rania.model.items.Weapon;
import com.game.rania.screen.MainMenu;
import com.game.rania.userdata.Command;
import com.game.rania.userdata.Client;
import com.game.rania.userdata.IOStream;
import com.game.rania.utils.Condition;
public class NetController
{
private Receiver receiver = null;
private CommandController cController = null;
private Client mClient = null;
private int ProtocolVersion = 10;
public NetController(CommandController commandController)
{
cController = commandController;
}
public void dispose()
{
if (receiver != null)
receiver.stopThread();
}
public void sendTouchPoint(int x, int y, int currentX, int currentY, boolean stop)
{
byte[] data = new byte[8];
byte[] userxArr = intToByteArray(x);
byte[] useryArr = intToByteArray(y);
System.arraycopy(userxArr, 0, data, 0, 4);
System.arraycopy(useryArr, 0, data, 4, 4);
try
{
mClient.stream.sendCommand(Command.touchPlayer, data);
} catch (Exception ex)
{
}
}
public void sendTarget(Target target)
{
byte[] data = new byte[8];
byte[] targetTypeArr = intToByteArray(target.type);
byte[] targetArr = intToByteArray(target.id);
System.arraycopy(targetTypeArr, 0, data, 0, 4);
System.arraycopy(targetArr, 0, data, 4, 4);
try
{
mClient.stream.sendCommand(Command.setTarget, data);
} catch (Exception ex)
{
}
}
public void sendUseEquip(int equip_id)
{
byte[] data = new byte[4];
byte[] useEquipArr = intToByteArray(equip_id);
System.arraycopy(useEquipArr, 0, data, 0, 4);
try
{
mClient.stream.sendCommand(Command.useEquips, data);
} catch (Exception ex)
{
}
}
public int getServerTime()
{
return mClient.serverTime;
}
public boolean login(String Login, String Password)
{
mClient = new Client();
mClient.login = Login;
mClient.socket = null;
mClient.isLogin = false;
try
{
mClient.socket = new Socket(InetAddress.getByName(Config.serverAddress), Config.serverPort);
if (mClient.socket.isConnected())
{
mClient.stream = new IOStream(mClient.socket.getInputStream(), mClient.socket.getOutputStream());
byte[] LoginArr = Login.getBytes("UTF-16LE");
byte[] LoginLenArr = intToByteArray(LoginArr.length);
byte[] ProtocolVersionArr = intToByteArray(ProtocolVersion);
byte[] data = new byte[LoginArr.length + LoginLenArr.length + ProtocolVersionArr.length];
System.arraycopy(ProtocolVersionArr, 0, data, 0, 4);
System.arraycopy(LoginLenArr, 0, data, 4, 4);
System.arraycopy(LoginArr, 0, data, 8, LoginArr.length);
mClient.stream.sendCommand(Command.login, data);
byte[] PasswordArr = Password.getBytes("UTF-16LE");
byte[] PasswordLenArr = intToByteArray(PasswordArr.length);
data = new byte[PasswordArr.length + PasswordLenArr.length];
System.arraycopy(PasswordLenArr, 0, data, 0, 4);
System.arraycopy(PasswordArr, 0, data, 4, PasswordArr.length);
mClient.stream.sendCommand(Command.password, data);
// Command command = waitCommand();
Command command = mClient.stream.readCommand();
if (command.idCommand == Command.login)
{
CommandReader cr = new CommandReader(command);
mClient.isLogin = true;
mClient.serverTime = cr.getInt();
receiver = new Receiver(mClient, this);
receiver.start();
checkCRC(command, cr);
return true;
}
if (command.idCommand == Command.faillogin)
{
// CommandReader ArrPtr = new CommandReader(command.data);
mClient.isLogin = false;
}
if (command.idCommand == Command.failversion)
{
// CommandReader ArrPtr = new CommandReader(command.data);
mClient.isLogin = false;
}
}
} catch (Exception ex)
{
return false;
}
return false;
}
public boolean checkCRC(Command command, CommandReader cr)
{
if (command.controlCRC != cr.crc)
{
Gdx.app.log("CRC error", "Login");
return false;
}
return true;
}
public void disconnect()
{
try
{
if (mClient != null && mClient.socket.isConnected() && mClient.isLogin)
{
mClient.stream.sendCommand(Command.disconnect);
receiver.stopThread();
mClient.socket.shutdownInput();
mClient.socket.shutdownOutput();
mClient.socket.close();
}
} catch (Exception ex)
{
}
}
public void sendChatMessage(String Message, int channel)
{
String toPilot = "";
if (Message.isEmpty())
return;
try
{
byte[] ChannelArr = intToByteArray(channel);
byte[] MessageArr = Message.getBytes("UTF-16LE");
byte[] MessageLenArr = intToByteArray(MessageArr.length);
byte[] toPilotArr = toPilot.getBytes("UTF-16LE");
byte[] toPilotLenArr = intToByteArray(toPilotArr.length);
byte[] data = new byte[ChannelArr.length + MessageArr.length + MessageLenArr.length + toPilotArr.length + toPilotLenArr.length];
System.arraycopy(ChannelArr, 0, data, 0, 4);
System.arraycopy(MessageLenArr, 0, data, 4, 4);
System.arraycopy(MessageArr, 0, data, 8, MessageArr.length);
System.arraycopy(toPilotLenArr, 0, data, 8 + MessageArr.length, 4);
System.arraycopy(toPilotArr, 0, data, 8 + MessageArr.length + 4, toPilotArr.length);
mClient.stream.sendCommand(Command.message, data);
} catch (Exception ex)
{
}
}
public void clientRelogin()
{
// mClient.relogin
}
public void loadComplite()
{
try
{
mClient.stream.sendCommand(Command.loadComplite);
} catch (Exception ex)
{
}
}
public ItemCollection getItems()
{
ItemCollection iCollect = new ItemCollection();
try
{
mClient.stream.sendCommand(Command.items);
Command command = waitCommand(Command.items);
CommandReader cr = new CommandReader(command);
int listItemsCount = cr.getInt();
for (int i = 0; i < listItemsCount; i++)
{
int itemsCount = cr.getInt();
for (int j = 0; j < itemsCount; j++)
{
int item_id = cr.getInt();
int item_itemType = cr.getInt();
String item_description = cr.getString();
int item_volume = cr.getInt();
int item_region_id = cr.getInt();
int item_use_only = cr.getInt();
int item_price = cr.getInt();
if (item_itemType == 1)
{
String device_vendorStr = cr.getString();
int device_deviceType = cr.getInt();
int device_durability = cr.getInt();
switch (device_deviceType)
{
case Device.Type.body:
{
int body_slot_weapons = cr.getInt();
int body_slot_droids = cr.getInt();
int body_slot_shield = cr.getInt();
int body_slot_hyper = cr.getInt();
Body body = new Body();
body.id = item_id;
body.itemType = item_itemType;
body.description = item_description;
body.volume = item_volume;
body.region_id = item_region_id;
body.vendorStr = device_vendorStr;
body.deviceType = device_deviceType;
body.durability = device_durability;
body.use_only = item_use_only;
body.price = item_price;
body.slot_weapons = body_slot_weapons;
body.slot_droids = body_slot_droids;
body.slot_shield = body_slot_shield;
body.slot_hyper = body_slot_hyper;
iCollect.bodies.put(body.id, body);
break;
}
case Device.Type.engine:
{
int engine_power = cr.getInt();
int engine_economic = cr.getInt();
Engine engine = new Engine();
engine.id = item_id;
engine.itemType = item_itemType;
engine.description = item_description;
engine.volume = item_volume;
engine.region_id = item_region_id;
engine.vendorStr = device_vendorStr;
engine.deviceType = device_deviceType;
engine.durability = device_durability;
engine.use_only = item_use_only;
engine.price = item_price;
engine.power = engine_power;
engine.economic = engine_economic;
iCollect.engines.put(engine.id, engine);
break;
}
case Device.Type.fuelbag:
{
int fuelbag_compress = cr.getInt();
Fuelbag fuelbag = new Fuelbag();
fuelbag.id = item_id;
fuelbag.itemType = item_itemType;
fuelbag.description = item_description;
fuelbag.volume = item_volume;
fuelbag.region_id = item_region_id;
fuelbag.vendorStr = device_vendorStr;
fuelbag.deviceType = device_deviceType;
fuelbag.durability = device_durability;
fuelbag.use_only = item_use_only;
fuelbag.price = item_price;
fuelbag.compress = fuelbag_compress;
iCollect.fuelbags.put(fuelbag.id, fuelbag);
break;
}
case Device.Type.droid:
{
int droid_power = cr.getInt();
int droid_time_reload = cr.getInt();
int radius = cr.getInt();
RepairKit droid = new RepairKit();
droid.id = item_id;
droid.itemType = item_itemType;
droid.description = item_description;
droid.volume = item_volume;
droid.region_id = item_region_id;
droid.vendorStr = device_vendorStr;
droid.deviceType = device_deviceType;
droid.durability = device_durability;
droid.use_only = item_use_only;
droid.price = item_price;
droid.power = droid_power;
droid.time_reload = radius;
droid.radius = droid_time_reload;
iCollect.droids.put(droid.id, droid);
break;
}
case Device.Type.shield:
{
int shield_power = cr.getInt();
Shield shield = new Shield();
shield.id = item_id;
shield.itemType = item_itemType;
shield.description = item_description;
shield.volume = item_volume;
shield.region_id = item_region_id;
shield.vendorStr = device_vendorStr;
shield.deviceType = device_deviceType;
shield.durability = device_durability;
shield.use_only = item_use_only;
shield.price = item_price;
shield.power = shield_power;
iCollect.shields.put(shield.id, shield);
break;
}
case Device.Type.hyper:
{
int hyper_radius = cr.getInt();
int hyper_time_start = cr.getInt();
int hyper_time_reload = cr.getInt();
Hyper hyper = new Hyper();
hyper.id = item_id;
hyper.itemType = item_itemType;
hyper.description = item_description;
hyper.volume = item_volume;
hyper.region_id = item_region_id;
hyper.vendorStr = device_vendorStr;
hyper.deviceType = device_deviceType;
hyper.durability = device_durability;
hyper.use_only = item_use_only;
hyper.price = item_price;
hyper.radius = hyper_radius;
hyper.time_start = hyper_time_start;
hyper.time_reload = hyper_time_reload;
iCollect.hypers.put(hyper.id, hyper);
break;
}
case Device.Type.radar:
{
int radar_radius = cr.getInt();
int radar_defense = cr.getInt();
int big_radius = cr.getInt();
Radar radar = new Radar();
radar.id = item_id;
radar.itemType = item_itemType;
radar.description = item_description;
radar.volume = item_volume;
radar.region_id = item_region_id;
radar.vendorStr = device_vendorStr;
radar.deviceType = device_deviceType;
radar.durability = device_durability;
radar.use_only = item_use_only;
radar.price = item_price;
radar.radius = radar_radius;
radar.defense = radar_defense;
radar.big_radius = big_radius;
iCollect.radars.put(radar.id, radar);
break;
}
case Device.Type.weapon:
{
int weapon_weaponType = cr.getInt();
int weapon_radius = cr.getInt();
int weapon_power = cr.getInt();
int weapon_time_start = cr.getInt();
int weapon_time_reload = cr.getInt();
Weapon weapon = new Weapon();
weapon.id = item_id;
weapon.itemType = item_itemType;
weapon.description = item_description;
weapon.volume = item_volume;
weapon.region_id = item_region_id;
weapon.vendorStr = device_vendorStr;
weapon.deviceType = device_deviceType;
weapon.durability = device_durability;
weapon.use_only = item_use_only;
weapon.price = item_price;
weapon.weaponType = weapon_weaponType;
weapon.radius = weapon_radius;
weapon.power = weapon_power;
weapon.time_start = weapon_time_start;
weapon.time_reload = weapon_time_reload;
iCollect.weapons.put(weapon.id, weapon);
break;
}
}
}
if (item_itemType == 2)
{
Consumable item = new Consumable();
item.id = item_id;
item.itemType = item_itemType;
item.description = item_description;
item.volume = item_volume;
item.region_id = item_region_id;
iCollect.consumables.put(item.id, item);
}
}
}
checkCRC(command, cr);
} catch (Exception ex)
{
}
return iCollect;
}
public HashMap<Integer, Planet> getPlanets(int idLocation, boolean wait)
{
HashMap<Integer, Planet> planets = new HashMap<Integer, Planet>();
try
{
mClient.stream.sendCommand(Command.planets, intToByteArray(idLocation));
if (!wait)
return null;
Command command = waitCommand(Command.planets);
CommandReader cr = new CommandReader(command);
cr.delta(4);
int PlanetsCount = cr.getInt();
for (int i = 0; i < PlanetsCount; i++)
{
int PlanetId = cr.getInt();
String PlanetName = cr.getString();
int PlanetType = cr.getInt();
int PlanetSpeed = cr.getInt();
int PlanetOrbit = cr.getInt();
int PlanetRadius = cr.getInt();
Color color = cr.getColor();
Color atmColor = cr.getColor();
int PlanetDomain = cr.getInt();
int PlanetAtmosphere_speedX = cr.getInt();
int PlanetAtmosphere_speedY = cr.getInt();
int PlanetPrice_coef = cr.getInt();
Planet planet = new Planet(PlanetId, PlanetName, PlanetType, PlanetRadius, PlanetSpeed, PlanetOrbit, idLocation, PlanetDomain, PlanetAtmosphere_speedX, PlanetAtmosphere_speedY);
planet.color = color;
planet.price_coef = PlanetPrice_coef;
planet.atmophereColor = atmColor;
planets.put(PlanetId, planet);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return planets;
}
public HashMap<Integer, Nebula> getAllNebulas()
{
HashMap<Integer, Nebula> nebulas = new HashMap<Integer, Nebula>();
try
{
mClient.stream.sendCommand(Command.nebulas);
Command command = waitCommand(Command.nebulas);
CommandReader cr = new CommandReader(command);
int NebulasCount = cr.getInt();
for (int i = 0; i < NebulasCount; i++)
{
int NebId = cr.getInt();
int NebType = cr.getInt();
int NebX = cr.getInt();
int NebY = cr.getInt();
int NebScale = cr.getInt();
int NebAngle = cr.getInt();
Nebula Neb = new Nebula(NebId, NebType, NebX, NebY, NebAngle, NebScale);
nebulas.put(Neb.id, Neb);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return nebulas;
}
public HashMap<Integer, Domain> getAllDomains()
{
HashMap<Integer, Domain> domains = new HashMap<Integer, Domain>();
try
{
mClient.stream.sendCommand(Command.domains);
Command command = waitCommand(Command.domains);
CommandReader cr = new CommandReader(command);
int DomainsCount = cr.getInt();
for (int i = 0; i < DomainsCount; i++)
{
Domain domain = new Domain();
domain.id = cr.getInt();
domain.color = cr.getColor();
domain.domainName = cr.getString();
domain.x = cr.getInt();
domain.y = cr.getInt();
int enemyCount = cr.getInt();
domain.enemy = new int[enemyCount];
for (int j = 0; j < enemyCount; j++)
{
domain.enemy[j] = cr.getInt();
}
domains.put(domain.id, domain);
}
checkCRC(command, cr);
} catch (Exception ex)
{
clientRelogin();
}
return domains;
}
public Player getUserData()
{
try
{
mClient.stream.sendCommand(Command.player);
Command command = waitCommand(Command.player);
CommandReader cr = new CommandReader(command);
int UserId = cr.getInt();
int UserX = cr.getInt();
int UserY = cr.getInt();
int UserDomain = cr.getInt();
int UserInPlanet = cr.getInt();
String PName = cr.getString();
String SName = cr.getString();
Player player = new Player(UserId, UserX, UserY, PName, SName, UserDomain, UserInPlanet);
player.setEquips(getEquips(cr));
checkCRC(command, cr);
return player;
} catch (Exception ex)
{
clientRelogin();
}
return null;
}
public static int byteArrayToInt(byte[] b)
{
return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24;
}
public static double byteArrayToDouble(byte[] b)
{
long longBits = ((b[7] & 0xFFL) << 56) |
((b[6] & 0xFFL) << 48) |
((b[5] & 0xFFL) << 40) |
((b[4] & 0xFFL) << 32) |
((b[3] & 0xFFL) << 24) |
((b[2] & 0xFFL) << 16) |
((b[1] & 0xFFL) << 8) |
((b[0] & 0xFFL) << 0);
return Double.longBitsToDouble(longBits);
}
public static byte[] intToByteArray(int a)
{
return new byte[] { (byte) ((a >> 24) & 0xFF), (byte) ((a >> 16) & 0xFF), (byte) ((a >> 8) & 0xFF), (byte) (a & 0xFF) };
}
// commands
private Condition cWaitCommand = new Condition(), cCopyCommand = new Condition();
private volatile int idWaitCommand = Command.none;
private volatile Command currentCommand = null;
public Command waitCommand(int idCommand) throws InterruptedException
{
idWaitCommand = idCommand;
cWaitCommand.signalWait();
Command command = currentCommand;
cCopyCommand.signal();
return command;
}
public void processingCommand(Command command) throws InterruptedException, UnsupportedEncodingException
{
if (idWaitCommand != Command.none && idWaitCommand == command.idCommand)
{
idWaitCommand = Command.none;
currentCommand = command;
cWaitCommand.signal();
cCopyCommand.signalWait();
return;
}
CommandReader cr = new CommandReader(command);
switch (command.idCommand)
{
case Command.addUser:
{
int UserId = cr.getInt();
String ShipName = cr.getString();
int UserX = cr.getInt();
int UserY = cr.getInt();
int TargetX = cr.getInt();
int TargetY = cr.getInt();
int UserDomain = cr.getInt();
User user = new User(UserId, UserX, UserY, ShipName, "", UserDomain);
//user.setPositionTarget(TargetX, TargetY);
user.setEquips(getEquips(cr));
cController.addCommand(new AddUserCommand(user));
break;
}
case Command.touchUser:
{
int UserId = cr.getInt();
int UserTouchX = cr.getInt();
int UserTouchY = cr.getInt();
int flyTime = cr.getInt();
int fuel = cr.getInt();
cController.addCommand(new SetTargetCommand(UserId, UserTouchX, UserTouchY, flyTime * 0.001f, fuel));
break;
}
case Command.removeUser:
{
int UserId = cr.getInt();
cController.addCommand(new RemoveUserCommand(UserId));
break;
}
case Command.disconnect:
{
try
{
receiver.stopThread();
mClient.socket.shutdownInput();
mClient.socket.shutdownOutput();
mClient.socket.close();
cController.addCommand(new SwitchScreenCommand(new MainMenu()));
} catch (Exception ex)
{
}
}
case Command.message:
{
int channel = cr.getInt();
String message = cr.getString();
String userName = cr.getString();
String toPilot = cr.getString();
cController.addCommand(new ChatNewMessageCommand(userName, channel, message, toPilot));
break;
}
case Command.userAction:
{
int equipID = cr.getInt();
int userID = cr.getInt();
int targetID = cr.getInt();
int action = cr.getInt();
switch (action)
{
case User.Action.attack:
{
int dmg = cr.getInt();
cController.addCommand(new AttackCommand(userID, targetID, equipID, dmg));
break;
}
case User.Action.repair:
{
int rapair = cr.getInt();
cController.addCommand(new RepairCommand(userID, targetID, equipID, rapair));
break;
}
}
break;
}
case Command.planets:
{
int locID = cr.getInt();
int PlanetsCount = cr.getInt();
for (int i = 0; i < PlanetsCount; i++)
{
int PlanetId = cr.getInt();
String PlanetName = cr.getString();
int PlanetType = cr.getInt();
int PlanetSpeed = cr.getInt();
int PlanetOrbit = cr.getInt();
int PlanetRadius = cr.getInt();
Color PlanetColor = cr.getColor();
Color AtmColor = cr.getColor();
int PlanetDomain = cr.getInt();
int PlanetAtmosphere_speedX = cr.getInt();
int PlanetAtmosphere_speedY = cr.getInt();
int PlanetPrice_coef = cr.getInt();
Planet planet = new Planet(PlanetId, PlanetName, PlanetType, PlanetRadius, PlanetSpeed, PlanetOrbit, locID, PlanetDomain, PlanetAtmosphere_speedX, PlanetAtmosphere_speedY);
planet.color = PlanetColor;
planet.atmophereColor = AtmColor;
planet.price_coef = PlanetPrice_coef;
cController.addCommand(new AddPlanetCommand(planet));
}
break;
}
case Command.location:
{
int LocationsCount = cr.getInt();
for (int i = 0; i < LocationsCount; i++)
{
Location location = new Location();
location.id = cr.getInt();
location.starName = cr.getString();
location.starType = cr.getInt();
location.x = cr.getInt();
location.y = cr.getInt();
location.starRadius = cr.getInt();
location.domain = cr.getInt();
cController.addCommand(new AddLocationCommand(location));
}
break;
}
default:
break;
}
checkCRC(command, cr);
}
private List<Equip<Item>> getEquips(CommandReader cr)
{
ItemCollection items = Controllers.locController.getItems();
if (items == null)
return null;
List<Equip<Item>> equip = new ArrayList<Equip<Item>>();
int eqCount = cr.getInt();
for (int j = 0; j < eqCount; j++)
{
int equip_id = cr.getInt();
int item_id = cr.getInt();
int iType = cr.getInt();
int dType = cr.getInt();
int in_use = cr.getInt();
int wear = cr.getInt();
int in_planet = cr.getInt();
int num = cr.getInt();
Equip<Item> eq = new Equip<Item>();
eq.id = equip_id;
eq.in_use = in_use == 1 ? true : false;
eq.wear = wear;
eq.in_planet = in_planet;
eq.num = num;
eq.item = null;
if (iType == Item.Type.device)
{
switch (dType)
{
case Device.Type.droid:
{
eq.item = items.droids.get(item_id);
break;
}
case Device.Type.engine:
{
eq.item = items.engines.get(item_id);
break;
}
case Device.Type.fuelbag:
{
eq.item = items.fuelbags.get(item_id);
break;
}
case Device.Type.hyper:
{
eq.item = items.hypers.get(item_id);
break;
}
case Device.Type.radar:
{
eq.item = items.radars.get(item_id);
break;
}
case Device.Type.shield:
{
eq.item = items.shields.get(item_id);
break;
}
case Device.Type.body:
{
eq.item = items.bodies.get(item_id);
break;
}
case Device.Type.weapon:
{
eq.item = items.weapons.get(item_id);
break;
}
}
}
else if (iType == Item.Type.consumable)
{
eq.item = items.consumables.get(item_id);
}
equip.add(eq);
}
return equip;
}
class CommandReader
{
public int address;
public byte[] data;
public int crc;
public boolean endOfData;
public CommandReader()
{
this.data = null;
this.address = 0;
this.crc = 0;
this.endOfData = false;
}
public CommandReader(Command cmd)
{
this.data = cmd.data;
this.address = 0;
this.crc = 0;
this.endOfData = false;
}
public void delta(int delta)
{
for (int i = 0; i < delta; i++)
{
char b = (char) (this.data[this.address + i] & 0xFF);
this.crc = this.crc + b * (this.address + i);
}
this.address += delta;
if (this.address == data.length)
{
this.endOfData = true;
}
}
public int getInt()
{
int Res = 0;
if (!this.endOfData)
{
byte[] Arr = new byte[4];
System.arraycopy(this.data, this.address, Arr, 0, 4);
delta(4);
Res = byteArrayToInt(Arr);
}
else
{
Gdx.app.log("Read Data error", "getIntValue");
}
return Res;
}
public double getDbl()
{
double Res = 0.0f;
if (!this.endOfData)
{
byte[] Arr = new byte[8];
System.arraycopy(this.data, this.address, Arr, 0, 8);
delta(8);
Res = byteArrayToDouble(Arr);
}
else
{
Gdx.app.log("Read Data error", "getDoubleValue");
}
return Res;
}
public String getString()
{
String Res = "";
if (!this.endOfData)
{
int SL = this.getInt();
byte[] Arr = new byte[SL];
System.arraycopy(this.data, this.address, Arr, 0, SL);
delta(SL);
try
{
Res = new String(Arr, "UTF-16LE");
} catch (UnsupportedEncodingException e)
{
Gdx.app.log(" ", ": " + e.getMessage());
}
}
else
{
Gdx.app.log("Read Data error", "getStringValue");
}
return Res;
}
private Color getColor()
{
Color Res = null;
if (!this.endOfData)
{
byte[] Arr = new byte[4];
System.arraycopy(this.data, this.address, Arr, 0, 4);
delta(4);
char R = (char) (Arr[0] & 0xFF);
char G = (char) (Arr[1] & 0xFF);
char B = (char) (Arr[2] & 0xFF);
char A = (char) (Arr[3] & 0xFF);
Res = new Color(R / 255.0f, G / 255.0f, B / 255.0f, A / 255.0f);
}
else
{
Gdx.app.log("Read Data error", "getColorValue");
}
return Res;
}
}
}
| [
"[email protected]"
] | |
8f319b84e4101a2739146ae7408e715832b93a9c | b733c258761e7d91a7ef0e15ca0e01427618dc33 | /cards/src/main/java/org/rnd/jmagic/cards/LoneMissionary.java | d075bd955858c5f0967e684e9019c90ae88c78f1 | [] | no_license | jmagicdev/jmagic | d43aa3d2288f46a5fa950152486235614c6783e6 | 40e573f8e6d1cf42603fd05928f42e7080ce0f0d | refs/heads/master | 2021-01-20T06:57:51.007411 | 2014-10-22T03:03:34 | 2014-10-22T03:03:34 | 9,589,102 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 878 | java | package org.rnd.jmagic.cards;
import static org.rnd.jmagic.Convenience.*;
import org.rnd.jmagic.engine.*;
import org.rnd.jmagic.engine.generators.*;
@Name("Lone Missionary")
@Types({Type.CREATURE})
@SubTypes({SubType.KOR, SubType.MONK})
@ManaCost("1W")
@ColorIdentity({Color.WHITE})
public final class LoneMissionary extends Card
{
public static final class ETBGainLife extends EventTriggeredAbility
{
public ETBGainLife(GameState state)
{
super(state, "When Lone Missionary enters the battlefield, you gain 4 life.");
this.addPattern(whenThisEntersTheBattlefield());
this.addEffect(gainLife(You.instance(), 4, "You gain 4 life."));
}
}
public LoneMissionary(GameState state)
{
super(state);
this.setPower(2);
this.setToughness(1);
// When Lone Missionary enters the battlefield, you gain 4 life.
this.addAbility(new ETBGainLife(state));
}
}
| [
"robyter@gmail"
] | robyter@gmail |
c27c3bc70edcff5a7a8796f3d74ab075822e066f | 9d50774b302b61c58639ce25586dd7f26f8dac9f | /GamerLobby3/app/src/main/java/com/example/jewishbear/gamerlobby/SignupActivity.java | baf0aac208506d93708c156c8040e213721e37f0 | [] | no_license | mindvortex/proje | 53e8bfc7e0512eb23029ff236314dd7d29ce4e9f | 4dcd3c05afac92ba56502d730578b956cfa8f31a | refs/heads/master | 2020-01-23T21:29:15.515276 | 2016-11-24T20:08:34 | 2016-11-24T20:08:34 | 74,702,094 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 926 | java | package com.example.jewishbear.gamerlobby;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
/**
* Created by jewishbear on 11/20/2016.
*/
public class SignupActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup_activity);
Button signupbtn = (Button) findViewById(R.id.signup_button);
signupbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(SignupActivity.this,HomeActivity.class);
startActivity(intent);
}
});
}
}
| [
"[email protected]"
] | |
5eaf8ff430617a526e300944a35175c83be7ddbf | 274facced4421d2f54d3630eb223fd4e40620375 | /src/fr/seijuro/PvP/Main.java | 5bd3405ba2b030553f890854b1cde7468284c7a4 | [] | no_license | Gwenzy/1vs1-BlastFight | 8923ceccd059d8a6253949da2a1f5ca31b5aa84f | 059d398a60bf5765ed4b9379246d07d1ded4b112 | refs/heads/master | 2021-01-10T17:44:12.937574 | 2016-01-31T12:09:45 | 2016-01-31T12:09:45 | 50,740,038 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,012 | java | package fr.seijuro.PvP;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
public class Main
extends JavaPlugin
{
private DuelManager duelManager;
private DuelManagerRanked duelManagerRanked;
private List<WaitingPlayer> waitingPlayers;
public void onEnable()
{
this.duelManager = new DuelManager(this);
getServer().getPluginManager().registerEvents(new GameListener(this), this);
this.waitingPlayers = new ArrayList<WaitingPlayer>();
final Main main = this;
//SQLITE INIT
try
{
Connection con;
Statement state;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:plugins/1vs1-Blastfight/data.db");
state = con.createStatement();
state.executeUpdate("CREATE TABLE IF NOT EXISTS Ranked " +
"(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +
" pseudo VARCHAR(16) NOT NULL, " +
" elo INT NOT NULL, " +
" win INT NOT NULL, " +
" lose INT NOT NULL)");
con.close();
}
//Test commentary
catch(Exception e){e.printStackTrace();}
//SQLITE INIT END
Bukkit.getServer().getScheduler().runTaskTimerAsynchronously(this, new Runnable(){
@Override
public void run() {
duelManagerRanked = new DuelManagerRanked(main);
// Chaque seconde, on v�rifie les joueurs en file d'attente
//On add une seconde dans leur timer
for(WaitingPlayer wp : waitingPlayers)
{
wp.addSecond();
}
//On check si un joueur dans la plage d'elo 75-125% existe |
for(WaitingPlayer wp : waitingPlayers)
{
//if(wp.)
}
//Si oui, on lance des confirmations aux deux joueurs
//Si les deux acceptent, on les enl�ve de la liste d'attente et on les fait combattre
//On start un duel classique
//Quand un des deux meurt, on effectue le calcul du nouvel elo en fonction de la fonction dans la config
//Si un des deux refuse, on enl�ve celui qui a refus� de la file et on remet l'autre
}
}, 0, 20);
}
public void onDisable() {}
public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args)
{
if (cmdLabel.equalsIgnoreCase("setlobby"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permissions de faire ca.");
return true;
}
if (args.length <= 0)
{
getConfig().set("Lobby.world", p.getLocation().getWorld().getName());
getConfig().set("Lobby.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Lobby.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Lobby.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Lobby.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Lobby.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Lobby du serveur training bien enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setlobby'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setfirst"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("First.world", p.getLocation().getWorld().getName());
getConfig().set("First.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("First.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("First.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("First.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("First.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Premi�re place du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setfirst'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setsecond")) {
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "You don't have permission.");
return true;
}
getConfig().set("Second.world", p.getLocation().getWorld().getName());
getConfig().set("Second.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Second.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Second.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Second.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Second.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Deuxi�me position du combat enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setsecond'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setArena"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Arena.world", p.getLocation().getWorld().getName());
getConfig().set("Arena.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Arena.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Arena.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Arena.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Arena.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Place de combat du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setarena'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setdeath"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Death.world", p.getLocation().getWorld().getName());
getConfig().set("Death.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Death.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Death.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Death.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Death.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Place de mort du combat d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setdeath'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
} else if (cmdLabel.equalsIgnoreCase("setrankedfirst"))
{
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "Vous n'avez pas la permission de faire �a.");
return true;
}
getConfig().set("Rankedfirst.world", p.getLocation().getWorld().getName());
getConfig().set("Rankedfirst.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Rankedfirst.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Rankedfirst.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Rankedfirst.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Rankedfirst.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Premi�re place du combat ranked d�fini.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setrankedfirst'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
else if (cmdLabel.equalsIgnoreCase("setrankedsecond")) {
if ((sender instanceof Player))
{
Player p = (Player)sender;
if (args.length <= 0)
{
if (!p.isOp())
{
p.sendMessage(ChatColor.RED + "You don't have permission.");
return true;
}
getConfig().set("Rankedsecond.world", p.getLocation().getWorld().getName());
getConfig().set("Rankedsecond.x", Double.valueOf(p.getLocation().getX()));
getConfig().set("Rankedsecond.y", Double.valueOf(p.getLocation().getY()));
getConfig().set("Rankedsecond.z", Double.valueOf(p.getLocation().getZ()));
getConfig().set("Rankedsecond.yaw", Float.valueOf(p.getLocation().getYaw()));
getConfig().set("Rankedsecond.pitch", Float.valueOf(p.getLocation().getPitch()));
p.sendMessage(ChatColor.GREEN + "Deuxi�me position du combat ranked enregistr�.");
saveConfig();
}
else
{
p.sendMessage(ChatColor.RED + "Probl�me de syntaxe essayez :" + ChatColor.AQUA + "'/setrankedsecond'.");
}
}
else
{
sender.sendMessage(ChatColor.RED + "Commande uniquement executable dans le jeu ! (Naruhiko wsh, tu fais quoi)");
}
}
return true;
}
public Location getLobby()
{
Location loc = null;
String world = getConfig().getString("Lobby.world");
double x = getConfig().getDouble("Lobby.x");
double y = getConfig().getDouble("Lobby.y");
double z = getConfig().getDouble("Lobby.z");
float yaw = (float)getConfig().getDouble("Lobby.yaw");
float pitch = (float)getConfig().getDouble("Lobby.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getDeath()
{
Location loc = null;
String world = getConfig().getString("Death.world");
double x = getConfig().getDouble("Death.x");
double y = getConfig().getDouble("Death.y");
double z = getConfig().getDouble("Death.z");
float yaw = (float)getConfig().getDouble("Death.yaw");
float pitch = (float)getConfig().getDouble("Death.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getArena()
{
Location loc = null;
String world = getConfig().getString("Arena.world");
double x = getConfig().getDouble("Arena.x");
double y = getConfig().getDouble("Arena.y");
double z = getConfig().getDouble("Arena.z");
float yaw = (float)getConfig().getDouble("Arena.yaw");
float pitch = (float)getConfig().getDouble("Arena.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getFirst()
{
Location loc = null;
String world = getConfig().getString("First.world");
double x = getConfig().getDouble("First.x");
double y = getConfig().getDouble("First.y");
double z = getConfig().getDouble("First.z");
float yaw = (float)getConfig().getDouble("First.yaw");
float pitch = (float)getConfig().getDouble("First.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public Location getSecond()
{
Location loc = null;
String world = getConfig().getString("Second.world");
double x = getConfig().getDouble("Second.x");
double y = getConfig().getDouble("Second.y");
double z = getConfig().getDouble("Second.z");
float yaw = (float)getConfig().getDouble("Second.yaw");
float pitch = (float)getConfig().getDouble("Second.pitch");
loc = new Location(Bukkit.getWorld(world), x, y, z, yaw, pitch);
return loc;
}
public DuelManager getDuelManager()
{
return this.duelManager;
}
public boolean addWaitingPlayer(Player p)
{
if(isPlayerWaiting(p))
return false;
else
{
this.waitingPlayers.add(new WaitingPlayer(p.getUniqueId()));
return true;
}
}
public boolean isPlayerWaiting(Player p)
{
for(WaitingPlayer wp : this.waitingPlayers)
{
if(wp.getUUID().equals(p.getUniqueId()))
return true;
}
return false;
}
public boolean removeWaitingPlayer(Player p)
{
if(isPlayerWaiting(p))
{
for(WaitingPlayer wp : this.waitingPlayers)
{
if(wp.getUUID().equals(p.getUniqueId()))
{
this.waitingPlayers.remove(wp);
return true;
}
}
}
else
return false;
return false;
}
public void clearPlayer(Player p1)
{
p1.getInventory().clear();
p1.getInventory().setArmorContents(null);
for (PotionEffect pe : p1.getActivePotionEffects()) {
p1.removePotionEffect(pe.getType());
}
}
}
| [
"[email protected]"
] | |
bc266b6bd1ca95864bbd89138b14b1505c10fba0 | 2fa0fcd8afb9b9905f94ff46b9fe989e39e66000 | /accesibilitymodifiers in java/src/pak2/Three.java | 02c9009d9d9a621c9749bdbe194ef0dabf27f9d3 | [] | no_license | nerdseeker365/Core-java | dea9bb5b30500a4cc5827d2777fea57b4ce65b22 | 7823877cef124749da1c6d7c1d90bbbabfd67768 | refs/heads/master | 2022-04-08T14:21:11.553451 | 2020-03-17T04:20:22 | 2020-03-17T04:20:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 507 | java | package pak2;
import access.One;
public class Three extends One {
public static void main(String args[]) {
One o=new One();
Three t=new Three();
//System.out.println(o.a);// error because of private variable not allowed to access another class
//System.out.println(o.b);//package level or default variable not allowed to access another package
System.out.println(Three.c);
//System.out.println(One.c);
//System.out.println(t.c);
System.out.println(o.d);
}
}
| [
"[email protected]"
] | |
bea178d68d8c71cc6ed7873c1f5ae324a293a169 | 6511f9cd8fbd37499294e5a9f50a4bc73b75ed8e | /lib/lib-beans/src/test/java/com/gainmatrix/lib/paging/pager/impl/ForecastPagerTest.java | a0553142aa4793c3165e537bb0ae275e892e7d1f | [
"Apache-2.0"
] | permissive | mazurkin/gainmatrix | 736cce1e97d83c987ac0a4fab96bd5ac31cba952 | 296766e8516035275287954ffe85dcecbcd9bebe | refs/heads/master | 2021-03-12T23:39:23.105356 | 2015-09-30T15:29:44 | 2015-09-30T15:29:44 | 41,808,921 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,682 | java | package com.gainmatrix.lib.paging.pager.impl;
import com.gainmatrix.lib.paging.Extraction;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ForecastPagerTest {
@Test
public void testAll() {
ForecastPager pager = new ForecastPager();
pager.setPageSize(10);
pager.setForecast(2);
pager.setPageLimit(100);
Extraction extraction;
List<String> list;
//
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(0, pager.getPageCount());
//
extraction = pager.getExtraction();
Assert.assertEquals(0, extraction.getOffset());
Assert.assertEquals(21, extraction.getCount());
//
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(3, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(2, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(2, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(1, pager.getPage());
Assert.assertEquals(1, pager.getPageCount());
Assert.assertEquals(0, list.size());
//
pager.setPage(0);
Assert.assertEquals(1, pager.getPage());
pager.setPage(10000000);
Assert.assertEquals(100, pager.getPage());
//
pager.setPage(12);
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(14, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(13, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(13, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(12, pager.getPage());
Assert.assertEquals(12, pager.getPageCount());
Assert.assertEquals(0, list.size());
//
pager.setPage(99);
list = new ArrayList<String>(Collections.nCopies(21, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(20, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(16, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(100, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(10, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(10, list.size());
list = new ArrayList<String>(Collections.nCopies(7, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(7, list.size());
list = new ArrayList<String>(Collections.nCopies(0, "aaa"));
list = pager.analyse(list);
Assert.assertEquals(99, pager.getPage());
Assert.assertEquals(99, pager.getPageCount());
Assert.assertEquals(0, list.size());
}
}
| [
"[email protected]"
] | |
080d7cba61e3edc5a96e27d9c6686d2dae40e405 | 4e828f3aec1018c7cdf9ccc9d9f5e6148502e10f | /chapter7-rpc/rpc-transporter/client-api/src/main/java/com/wuhulala/rpc/client/exception/TimeoutException.java | 438dcb35af3f8192004b740065dbc1627a2e02a0 | [] | no_license | Anthony-byte/netty-action | 03b92f3eb3adc3dff868190235f601dd1c88d222 | 787421ca46655d2ee20bd5c206374b14d20d62e3 | refs/heads/master | 2023-03-10T07:44:22.990100 | 2021-02-18T06:24:45 | 2021-02-18T06:24:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,970 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wuhulala.rpc.client.exception;
import io.netty.channel.Channel;
import java.net.InetSocketAddress;
/**
* TimeoutException. (API, Prototype, ThreadSafe)
*
* @export
* @see org.apache.dubbo.remoting.exchange.support.DefaultFuture#get()
*/
public class TimeoutException extends RemotingException {
public static final int CLIENT_SIDE = 0;
public static final int SERVER_SIDE = 1;
private static final long serialVersionUID = 3122966731958222692L;
private final int phase;
public TimeoutException(boolean serverSide, Channel channel, String message) {
super(channel, message);
this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE;
}
public TimeoutException(boolean serverSide, InetSocketAddress localAddress,
InetSocketAddress remoteAddress, String message) {
super(localAddress, remoteAddress, message);
this.phase = serverSide ? SERVER_SIDE : CLIENT_SIDE;
}
public int getPhase() {
return phase;
}
public boolean isServerSide() {
return phase == 1;
}
public boolean isClientSide() {
return phase == 0;
}
} | [
"[email protected]"
] | |
88f853e6abd03be0c0f1f41c3b4affeca39c9ba0 | 45a2b5462cfde59821b73def5a527233a64f51f4 | /app/src/main/java/com/linksu/videofeed/demo/VisibilePercentsUtils.java | faca22c3de5b2782393555d8140d91aed9d432a5 | [
"MIT"
] | permissive | DevAlliances/VideoFeed | 455c869b1eb91167a4f6b9d806f98ed839707950 | 0071e7252dc990a6dd73f8e76599da167eb0ba34 | refs/heads/master | 2021-01-15T22:10:15.459053 | 2017-08-09T11:00:33 | 2017-08-09T11:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,657 | java | package com.linksu.videofeed.demo;
import android.graphics.Rect;
import android.view.View;
/**
* ================================================
* 作 者:linksus
* 版 本:1.0
* 创建日期:7/27 0027
* 描 述:
* 修订历史:
* ================================================
*/
public class VisibilePercentsUtils {
private static VisibilePercentsUtils mVisibilePercentsUtils = null;
private VisibilePercentsUtils() {
}
public static VisibilePercentsUtils getInstance() {
if (mVisibilePercentsUtils == null) {
synchronized (VisibilePercentsUtils.class) {
if (mVisibilePercentsUtils == null) {
mVisibilePercentsUtils = new VisibilePercentsUtils();
}
}
}
return mVisibilePercentsUtils;
}
private final Rect mCurrentViewRect = new Rect();
public int getVisibilityPercents(View view) {
int percents = 100;
view.getLocalVisibleRect(mCurrentViewRect);
int height = view.getHeight();
if (viewIsPartiallyHiddenTop()) {
// view is partially hidden behind the top edge
percents = (height - mCurrentViewRect.top) * 100 / height;
} else if (viewIsPartiallyHiddenBottom(height)) {
percents = mCurrentViewRect.bottom * 100 / height;
}
return percents;
}
private boolean viewIsPartiallyHiddenBottom(int height) {
return mCurrentViewRect.bottom > 0 && mCurrentViewRect.bottom < height;
}
private boolean viewIsPartiallyHiddenTop() {
return mCurrentViewRect.top > 0;
}
}
| [
"[email protected]"
] | |
768203c52c56512ab2cd7570bb2cdd14bb986ac3 | c157633108584c813e4c27bca00a766900561abf | /h2o-algos/src/main/java/hex/deeplearning/Dropout.java | 0cb4c1c2d45c1bd966854ea2a43ec67bf75aacdc | [
"Apache-2.0"
] | permissive | voltek62/h2o-3 | 18ef87f6e1cfa5ce4eabcfec59c651c58ed7546f | d581245120bf0cb6fab2bc7e8273b4f41f461448 | refs/heads/master | 2021-01-14T14:02:10.771288 | 2016-05-02T01:28:14 | 2016-05-02T01:28:14 | 57,887,717 | 0 | 0 | Apache-2.0 | 2019-10-13T20:52:43 | 2016-05-02T12:10:05 | Java | UTF-8 | Java | false | false | 2,415 | java | package hex.deeplearning;
import water.util.RandomUtils;
import java.util.Arrays;
import java.util.Random;
/**
* Helper class for dropout training of Neural Nets
*/
public class Dropout {
private transient Random _rand;
private transient byte[] _bits;
private transient double _rate;
public byte[] bits() { return _bits; }
// public Dropout() {
// _rate = 0.5;
// }
@Override
public String toString() {
String s = "Dropout: " + super.toString();
s += "\nRandom: " + _rand.toString();
s += "\nDropout rate: " + _rate;
s += "\nbits: ";
for (int i=0; i< _bits.length*8; ++i) s += unit_active(i) ? "1":"0";
s += "\n";
return s;
}
Dropout(int units) {
_bits = new byte[(units+7)/8];
_rand = RandomUtils.getRNG(0);
_rate = 0.5;
}
Dropout(int units, double rate) {
this(units);
_rate = rate;
}
public void randomlySparsifyActivation(Storage.Vector a, long seed) {
if (a instanceof Storage.DenseVector)
randomlySparsifyActivation((Storage.DenseVector) a, seed);
else if (a instanceof Storage.SparseVector)
randomlySparsifyActivation((Storage.SparseVector)a, seed);
else throw new UnsupportedOperationException("randomlySparsifyActivation not implemented for this type: " + a.getClass().getSimpleName());
}
// for input layer
private void randomlySparsifyActivation(Storage.DenseVector a, long seed) {
if (_rate == 0) return;
setSeed(seed);
for( int i = 0; i < a.size(); i++ )
if (_rand.nextFloat() < _rate) a.set(i, 0);
}
private void randomlySparsifyActivation(Storage.SparseVector a, long seed) {
if (_rate == 0) return;
setSeed(seed);
for (Storage.SparseVector.Iterator it=a.begin(); !it.equals(a.end()); it.next())
if (_rand.nextFloat() < _rate) it.setValue(0f);
}
// for hidden layers
public void fillBytes(long seed) {
setSeed(seed);
if (_rate == 0.5) _rand.nextBytes(_bits);
else {
Arrays.fill(_bits, (byte)0);
for (int i=0;i<_bits.length*8;++i)
if (_rand.nextFloat() > _rate) _bits[i / 8] |= 1 << (i % 8);
}
}
public boolean unit_active(int o) {
return (_bits[o / 8] & (1 << (o % 8))) != 0;
}
private void setSeed(long seed) {
if ((seed >>> 32) < 0x0000ffffL) seed |= 0x5b93000000000000L;
if (((seed << 32) >>> 32) < 0x0000ffffL) seed |= 0xdb910000L;
_rand.setSeed(seed);
}
}
| [
"[email protected]"
] | |
724194728fcfdc8886fc98c13f26262a9e5332da | 4a04de6d4bb9972e0e2e30082d58f68a33c5e1c4 | /src/br/com/trainee_tqi/modelo/Cliente.java | 9a1c0d717af6aa76e7d0dab13d306b0ecd9e5870 | [] | no_license | alexandrecvf/Trainee_TQI | e6638c3ca086bb3c0d1d9863af2ffa6d48c3c0f2 | 770402b77ebaf9ab5ad7e87b8ec42524a7ead4ed | refs/heads/master | 2022-12-07T21:17:59.761913 | 2020-09-01T02:35:43 | 2020-09-01T02:35:43 | 290,641,185 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,360 | java | package br.com.trainee_tqi.modelo;
/**
* <h1>Classe Modelo Cliente</h1>
* Modelo de cliente da aplicação. Possui todos os atributos do cliente e ainda seus getters e setters.
*
* @author Alexandre Vilarinho
*/
public class Cliente {
/** Id do cliente*/
Long id;
/** Nome do cliente*/
String nome;
/** CPF do cliente*/
String cpf;
/** RG do cliente*/
String rg;
/** Telefone do cliente*/
String telefone;
/** E-mail do cliente*/
String email;
/** Senha do cliente*/
String senha;
/** Endereço do cliente*/
String endereco;
/** CEP do cliente*/
String cep;
/** Renda mensal do cliente*/
float renda_mensal;
/** Recebe o id
* @return id id do cliente
* */
public Long getId() {
return id;
}
/**Define o id do cliente.
*
* @param id Id do cliente
* */
public void setId(Long id) {
this.id = id;
}
/** Recebe o nome do cliente.
* @return nome Nome do cliente
* */
public String getNome() {
return nome;
}
/**Define o nome do cliente.
*
* @param nome Nome do cliente.
* */
public void setNome(String nome) {
this.nome = nome;
}
/** Recebe o CPF do cliente
* @return cpf CPF do cliente
* */
public String getCpf() {
return cpf;
}
/**Define o CPF do cliente
*
* @param cpf CPF do cliente.
* */
public void setCpf(String cpf) {
this.cpf = cpf;
}
/** Recebe o RG do cliente
* @return rg RG do cliente
* */
public String getRg() {
return rg;
}
/**Define o RG do cliente.
*
* @param rg RG do cliente.
* */
public void setRg(String rg) {
this.rg = rg;
}
/** Recebe o telefone do cliente.
* @return telefone Telefone do cliente.
* */
public String getTelefone() {
return telefone;
}
/**Define o telefone do cliente.
*
* @param telefone Telefone do cliente.
* */
public void setTelefone(String telefone) {
this.telefone = telefone;
}
/** Recebe o e-mail do cliente.
* @return email E-mail do cliente.
* */
public String getEmail() {
return email;
}
/**
* Define o e-mail do cliente.
*
* @param email E-mail do cliente.
* */
public void setEmail(String email) {
this.email = email;
}
/** Recebe o endereço do cliente
* @return endereco Endereço do cliente.
* */
public String getEndereco() {
return endereco;
}
/**Define o endereço do cliente.
*
* @param endereco Endereço do cliente.
* */
public void setEndereco(String endereco) {
this.endereco = endereco;
}
/** Recebe o CEP do cliente.
* @return cep CEP do cliente.
* */
public String getCep() {
return cep;
}
/** Define o CEP do cliente
*
* @param cep CEP do cliente
* */
public void setCep(String cep) {
this.cep = cep;
}
/** Recebe a renda mensal do cliente.
* @return renda_mensal Renda mensal do cliente.
* */
public float getRenda_mensal() {
return renda_mensal;
}
/** Define a renda mensal do cliente
*
* @param renda_mensal Renda mensal do cliente.
* */
public void setRenda_mensal(float renda_mensal) {
this.renda_mensal = renda_mensal;
}
/** Recebe a senha do cliente
* @return senha Senha do cliente.
* */
public String getSenha() {
return senha;
}
/** Define a senha do cliente
*
* @param senha Senha do cliente.
* */
public void setSenha(String senha) {
this.senha = senha;
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.