blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
sequencelengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ea10e583c26771946997de619cd5760d8e4ef0cb | 1102e6e2fe8b5520660c0ed0df0fb8f2c5c32a9d | /kris91268/lbd/Tileentity/LightTile.java | e89d148d0e9ea6f6bf0f0214a8d43dbb99f4a32e | [] | no_license | BasaltSigma/lbd-mod | b09c6e393a97d01fee677cccc262cfe170c37622 | 5b8d2efe12a1737b8dfc30eabf521832d90605c1 | refs/heads/master | 2021-06-28T13:34:34.355118 | 2017-09-20T02:32:59 | 2017-09-20T02:32:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 456 | java | package kris91268.lbd.Tileentity;
import net.minecraft.world.World;
/**
* Interface to define the guidelines of most tile entities in this mod. Must be used <br />
* by every tile entity representing a light device for that matter. Not to be used on other tile
* entities that do not have that purpose.
* @author Arbiter
*/
public interface LightTile
{
/**
* Called when the bridge has finished activating/deactivating
*/
void onFinished();
} | [
"[email protected]"
] | |
9b68c7c456ae8457a31f543b3a162af0bb07e73b | 01d6b951ce24b3d2c89b1ffa18fd79aaa9c4599c | /src/com/google/android/gms/internal/fa$2.java | ebb3d155d8c17a44b27d883dc2a5d0f513e6030e | [] | no_license | mohsenuss91/KGBANDROID | 1a5cc246bf17b85dae4733c10a48cc2c34f978fd | a2906e3de617b66c5927a4d1fd85f6a3c6ed89d0 | refs/heads/master | 2016-09-03T06:45:38.912322 | 2015-03-08T12:03:35 | 2015-03-08T12:03:35 | 31,847,141 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 582 | java | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.android.gms.internal;
import android.content.DialogInterface;
import android.webkit.JsResult;
final class sM
implements android.content.gInterface.OnClickListener
{
final JsResult sM;
public final void onClick(DialogInterface dialoginterface, int i)
{
sM.cancel();
}
ckListener(JsResult jsresult)
{
sM = jsresult;
super();
}
}
| [
"[email protected]"
] | |
4d99d3db3b54f326b34b94f40648cc0ff2b3a83d | 0c2785d3c5915b9a9dd493dd28351cc26d1f49a8 | /app/src/main/java/com/example/rohan/docpatient/DocActivity.java | f1db42c1860ca7fd4b81344247479779aea3a25b | [] | no_license | saisuresh1999/docpatient | a331de77a444fd46af4fce4fb590bdf68d18448c | 561d6bd9b1ad9333138be3e913b5f623c7f51d30 | refs/heads/master | 2020-04-14T05:48:23.819937 | 2018-12-31T09:00:27 | 2018-12-31T09:00:27 | 163,669,399 | 1 | 0 | null | 2018-12-31T13:00:32 | 2018-12-31T13:00:32 | null | UTF-8 | Java | false | false | 2,541 | java | package com.example.rohan.docpatient;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class DocActivity extends AppCompatActivity {
Button bute;
TextView nametext,destext,spltext;
ImageView imgProfile;
ArrayList<profile> listofdes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doc);
DatabaseReference dbref;
listofdes=new ArrayList<profile>();
Intent intent=getIntent();
String s=intent.getStringExtra("val");
String s1=intent.getStringExtra("nam");
bute=(Button) findViewById(R.id.button);
bute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(DocActivity.this,LoginActivity.class);
startActivity(i);
}
});
nametext=(TextView) findViewById(R.id.nameq);
destext=(TextView) findViewById(R.id.description);
spltext=(TextView) findViewById(R.id.spl);
imgProfile=(ImageView) findViewById(R.id.profilepicture);
dbref=FirebaseDatabase.getInstance().getReference().child("Profile").child(s1);
dbref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
profile p=dataSnapshot.getValue(profile.class);
nametext.setText(p.getName());
destext.setText(p.getDes());
spltext.setText(p.getEmail());
// Picasso.with(this).load(p.getProfilePic()).into(imgProfile);
Picasso.get().load(p.getProfilePic()).into(imgProfile);
Toast.makeText(DocActivity.this,p.getEmail(),Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
| [
"[email protected]"
] | |
96b577d7ba657776b5b6e9786d5fded6aec555ec | ad0acb2015513b190327b2e98c76c6bef43b5736 | /merriew-core/src/main/java/org/merriew/core/dao/impl/ProjectDaoImpl.java | e2b996d3221f38b7a178a1e120719d56f4f336c8 | [] | no_license | javierarrieta/Merriew | 223e03dde346b2737119783923b57e4dd82be5e0 | 831e12e51e4df528569616772edf3af3517b986e | refs/heads/master | 2021-01-25T07:34:11.378293 | 2011-12-07T11:29:55 | 2011-12-07T11:29:55 | 2,754,487 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,556 | java | package org.merriew.core.dao.impl;
import java.util.List;
import java.util.UUID;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.merriew.core.dao.ProjectDao;
import org.merriew.core.entity.Environment;
import org.merriew.core.entity.Project;
import org.merriew.core.entity.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
public class ProjectDaoImpl implements ProjectDao {
private EntityManager em;
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED)
public void create(Project project) {
project.setId( UUID.randomUUID().toString() );
em.persist(project);
}
@PersistenceContext
public void setEm(EntityManager em) {
this.em = em;
}
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=true)
public Project[] findAllProjects() {
TypedQuery<Project> q = em.createNamedQuery("Project.findAll", Project.class);
List<Project> projects = q.getResultList();
return projects.toArray(new Project[projects.size()]);
}
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=true)
public Project getProject( String id ) {
return em.find(Project.class, id);
}
public void create(Repository repo) {
repo.setId( UUID.randomUUID().toString() );
em.persist(repo);
}
public Repository getRepository(String id) {
return em.find(Repository.class, id);
}
public Repository[] getRepositories(Project project) {
TypedQuery<Repository> q = em.createNamedQuery("Repository.findByProjectId", Repository.class);
q.setParameter("projectId", project.getId() );
List<Repository> repos = q.getResultList();
return repos.toArray( new Repository[ repos.size() ]);
}
public void create(Environment environment) {
environment.setId( UUID.randomUUID().toString() );
em.persist(environment);
}
public Environment getEnvironment(String id) {
return em.find(Environment.class, id);
}
public Environment[] findAllEnvironments() {
TypedQuery<Environment> q = em.createNamedQuery(Environment.FIND_ALL, Environment.class);
List<Environment> envs = q.getResultList();
return envs.toArray( new Environment[envs.size() ] );
}
}
| [
"[email protected]"
] | |
cf96d67b08d71d27acfe6a7764e70d547e988fa0 | f2fc99363e1c3ca61aa0e18cdacfd91f95642fb5 | /commons/src/main/java/interview/xiaomi/AddOne.java | 08343875e12b61437f732cb420036fe993ef2128 | [
"Apache-2.0"
] | permissive | zeroro88/pinenut | 3faf22ac3d4902d4539431ac8c9f4b0e8598dfc7 | 65300af11ac1ce4431df64e24f3fc0fd71b7742a | refs/heads/master | 2021-01-15T23:21:23.103042 | 2017-07-20T02:12:05 | 2017-07-20T02:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 849 | java | package interview.xiaomi;
import java.util.Arrays;
/**
* 用一个数组表示一个整数,每一位表示整数的一位。
* 实现一个整数 +1 的方法
* Created by why on 2017/5/18.
*/
public class AddOne {
public static int[] addOne(int[] array) {
int len = array.length;
for (int i = len - 1; i >= 0; i--) {
if (array[i] == 9) {
array[i] = 0;
} else {
array[i]++;
break;
}
}
if (array[0] == 0) {
int[] result = new int[len + 1];
result[0] = 1;
return result;
} else {
return array;
}
}
public static void main(String[] args) {
int[] a = {4, 1, 3, 4, 5, 6, 8, 2};
System.out.println(Arrays.toString(addOne(a)));
}
}
| [
"[email protected]"
] | |
1ef6021a11b2cc49cb4538831e445536887575a6 | aeef0c8dea8cadfc42e3bcca37fbf460656c2600 | /DesafioConversao.java | 798c9d5a46aee47aae3a11481f67f973ae4c133f | [] | no_license | mateuscajun/Projeto-curso-java-fundamentos | 9180d1ebc2e201af2feb1811d2880630574d9de0 | 1c7eea4afd550c007117f8f10f812f3a35864fdf | refs/heads/main | 2023-06-12T05:42:48.817765 | 2021-07-01T16:36:06 | 2021-07-01T16:36:06 | 382,087,969 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 950 | java | package fundamentos;
import java.util.Scanner;
public class DesafioConversao {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Digite seus três últmos salários");
System.out.println("Digite o último salário :");
String Salario1 = entrada.next().replace(",", ".");
System.out.println("Digite o penúltimo salário :");
String Salario2 = entrada.next().replace(",", ".");
System.out.println("Digite o antepenúltimo salário :");
String Salario3 = entrada.next().replace(",", ".");
float numero1 = Float.parseFloat(Salario1);
float numero2 = Float.parseFloat(Salario2);
float numero3 = Float.parseFloat(Salario3);
float soma = numero1 + numero2 + numero3;
System.out.println("A soma dos últimos três salários é : " + soma);
System.out.println("A média dos últimos três salários é : " + soma / 3);
entrada.close();
}
}
| [
"[email protected]"
] | |
07933832eff773cc109ffdd734699da59acf2f1a | c71b1e896bd774470ba05e391ab93b0fbdbc4524 | /flashsale/src/main/java/com/saurav/flashsale/service/OrderServiceImpl.java | 5ccd83ac6d342b2f57452a37a069ba9a0b439573 | [] | no_license | saurav744/flashSale | b32e454df448c0c6729c13ecc1cc08f16b742003 | 7eaf41ba3fa34d80eec5e8a43219f66c7c7adb12 | refs/heads/master | 2022-06-21T08:10:31.736527 | 2020-05-14T06:56:03 | 2020-05-14T06:56:03 | 262,867,280 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,147 | java | package com.saurav.flashsale.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.saurav.flashsale.entities.enums.FlashSaleStatus;
import com.saurav.flashsale.entities.enums.OrderStatus;
import com.saurav.flashsale.entity.FlashSale;
import com.saurav.flashsale.entity.Inventory;
import com.saurav.flashsale.entity.SaleOrder;
import com.saurav.flashsale.entity.Product;
import com.saurav.flashsale.entity.SaleRegistration;
import com.saurav.flashsale.entity.User;
import com.saurav.flashsale.entity.request_response.OrderRequest;
import com.saurav.flashsale.entity.request_response.OrderResponse;
import com.saurav.flashsale.exception.EmptyStockException;
import com.saurav.flashsale.exception.MultiOrderNotAllowedException;
import com.saurav.flashsale.exception.NotRegisteredException;
import com.saurav.flashsale.exception.OrderNotProcessedException;
import com.saurav.flashsale.exception.ResourceNotFoundException;
import com.saurav.flashsale.exception.SaleNotOnException;
import com.saurav.flashsale.repository.FlashSaleRepository;
import com.saurav.flashsale.repository.InventoryRepository;
import com.saurav.flashsale.repository.OrderRepository;
import com.saurav.flashsale.repository.SaleRegistrationRepository;
import com.saurav.flashsale.repository.UserRepository;
@Service("orderService")
@Transactional
public class OrderServiceImpl implements OrderService{
@Autowired
private OrderRepository orderRepository;
@Autowired
private InventoryRepository inventoryRepository;
@Autowired
private FlashSaleRepository flashSaleRepository;
@Autowired
private SaleRegistrationRepository saleRegistrationRepository;
@Autowired
private UserRepository userRepository;
@Override
public OrderResponse placeOrder(OrderRequest orderRequest) {
FlashSale flashSale = flashSaleRepository.getOne(orderRequest.getFlashSaleId());
if(flashSale.getStatus() != FlashSaleStatus.ONGOING) {
throw new SaleNotOnException();
}
User user = userRepository.getOne(orderRequest.getUserId());
Optional<SaleRegistration> opSaleRegistration = saleRegistrationRepository
.findByUserAndFlashSale(user, flashSale);
if(!opSaleRegistration.isPresent()) {
throw new NotRegisteredException();
}
Product product = flashSale.getProduct();
Optional<SaleOrder> opOrder = orderRepository.findByUserAndProduct(user, product);
if(opOrder.isPresent() && opOrder.get().getStatus() != OrderStatus.CANCELLED) {
throw new MultiOrderNotAllowedException();
}
boolean purchaseSuccessful = false;
synchronized (this) {
Inventory inventory = inventoryRepository.findByProductId(product.getId());
int count = inventory.getCount();
if (count > 0) {
inventory.setCount(count - 1);
inventoryRepository.save(inventory);
purchaseSuccessful = true;
} else {
throw new EmptyStockException();
}
}
if(purchaseSuccessful) {
SaleOrder saleOrder = new SaleOrder();
saleOrder.setProduct(product);
saleOrder.setUser(user);
saleOrder.setStatus(OrderStatus.CONFIRMED);
saleOrder = orderRepository.save(saleOrder);
OrderResponse response = new OrderResponse();
response.setOrderId(saleOrder.getId());
response.setProduct(saleOrder.getProduct().getName());
response.setStatus(saleOrder.getStatus());
response.setCreatedAt(saleOrder.getCreatedAt());
return response;
} else {
throw new OrderNotProcessedException();
}
}
@Override
public OrderResponse updateStatus(Long orderId, OrderStatus status) {
Optional<SaleOrder> opOrder = orderRepository.findById(orderId);
if(!opOrder.isPresent()) {
throw new ResourceNotFoundException(Long.toString(orderId), "Order not found");
}
SaleOrder saleOrder = opOrder.get();
saleOrder.setStatus(status);
saleOrder = orderRepository.save(saleOrder);
OrderResponse orderResponse = new OrderResponse(saleOrder.getId(), saleOrder.getProduct().getName(),
saleOrder.getCreatedAt(), saleOrder.getStatus());
return orderResponse;
}
}
| [
"[email protected]"
] | |
a080422ce16bbe8913be6d35f46493c6c486905f | 5c45572083327fe6635ebfe49944310469db768c | /Pell_series.java | c413362d8ab9870abadfe4ad8d97b85cf4ea0073 | [] | no_license | tskalyan17/java_assignment | fb7dd465bd8628f2777816cd2ff5ba96d5c52840 | adac9dd32fe051b98d8bf3b4683f20a6f182a7a0 | refs/heads/master | 2023-04-11T13:44:41.217489 | 2021-04-04T07:58:34 | 2021-04-04T07:58:34 | 352,902,240 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 335 | java | /*35. Implement a Java program to print the first 15 numbers of the Pell series
-- each number = 2*prev number + pre to prev number*/
class Pell_series{
public static void main(String args[]){
int i=0,a=0,b=1,num=0;
for(i=0;i<15;i++){
num=2*a+b;
b=a;
a=num;
System.out.println(num);
}
}
} | [
"[email protected]"
] | |
10128a332a38bf4890e885a2e010f09f2a66ebf0 | 78c6c1153209368e07187aeb3cb3f3d710458f35 | /src/test/java/com/caiya/serialization/fastjson/GenericFastjson2JsonSerializerTest.java | aa9f31a45c42059a4597161bebda1328e5d0c73c | [] | no_license | wnjustdoit/serialization | 94daed75f0d1015062d90eec978b82455abe368b | 551b68ea8fa69929f504ca33724b59c7f21a5a64 | refs/heads/master | 2022-07-07T14:58:24.316175 | 2019-08-28T09:06:52 | 2019-08-28T09:06:52 | 180,546,230 | 0 | 0 | null | 2022-02-01T00:59:21 | 2019-04-10T09:16:47 | Java | UTF-8 | Java | false | false | 785 | java | package com.caiya.serialization.fastjson;
import com.alibaba.fastjson.JSON;
import com.caiya.serialization.Serializer;
import com.caiya.serialization.User;
import org.junit.Assert;
import org.junit.Test;
public class GenericFastjson2JsonSerializerTest {
private Serializer<Object> jsonSerializer = Serializer.json();
@Test
public void testSerializeAndDeserialize() {
User user = new User();
user.setName("我是tom");
byte[] outPut = jsonSerializer.serialize(user);
Assert.assertNotNull(outPut);
Assert.assertTrue(outPut.length > 0);
User result = (User) jsonSerializer.deserialize(outPut);
Assert.assertNotNull(result);
Assert.assertEquals(JSON.toJSONString(result), JSON.toJSONString(user));
}
}
| [
"[email protected]"
] | |
a5909634e91e9fd3808284908e3210cf6f33794a | 6f1e4052a57ac98c2b5ec6febaaa38962d54017f | /src/main/java/com/sample/swagger/config/SwaggerConfig.java | 49bf359b4cf410c4ebb3883015b7de77136a8a29 | [] | no_license | sejinjja/SwaggerSample | ac514d8312da7993cf0e166abce4e405dd2bc2b4 | 3fc7160af88c54fd941e3ac080d9be66877aaeb4 | refs/heads/master | 2020-03-26T07:54:58.630161 | 2018-08-14T06:27:24 | 2018-08-14T06:27:24 | 144,677,572 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,947 | java | package com.sample.swagger.config;
import com.fasterxml.classmate.TypeResolver;
import com.sample.swagger.dto.TestDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Autowired
private TypeResolver typeResolver;
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sample.swagger.controller"))
.build()
.apiInfo(this.getApiInfo("tester123", "1.0.0"));
// return new Docket(DocumentationType.SWAGGER_2)
// .additionalModels(typeResolver.resolve(TestDTO.class));
}
private ApiInfo getApiInfo(String title, String version) {
return new ApiInfoBuilder()
.title(title)
.version(version)
.build();
}
@Bean
public Docket testApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sample.swagger.controller"))
.paths(PathSelectors.regex("/user.*"))
.build()
.groupName("user");
// return new Docket(DocumentationType.SWAGGER_2)
// .groupName("test");
}
}
| [
"[email protected]"
] | |
5545548f8c24599efb56584189e749befae0ea73 | 85724683c49a3ff6c4908f7bebbf03792aab0374 | /com/matyas/game/BetadomServer/ServerMain.java | dd1a2b8df5084154bdfbc642e5d1098fdffe650c | [
"CC-BY-3.0"
] | permissive | coreymatyas/Betadom | d5a35ab0493015953cf1cd1442f68a690bb7dab8 | 4e41e5bc54bf164bbfe33a40c2425283fb479e7b | refs/heads/master | 2020-07-08T13:14:12.902431 | 2012-05-27T20:35:20 | 2012-05-27T20:35:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,516 | java | package com.matyas.game.BetadomServer;
import com.matyas.game.Betadom.ResourceManager;
import com.matyas.game.Betadom.util.Packet;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ServerMain extends Thread{
private short serverPort = 21220;
private ServerSocket serverSocket = null;
private ConsoleCommandListener consoleListener = null;
private GameThread gameThread = null;
private static ArrayList<ClientHandler> users = new ArrayList<ClientHandler>();
private boolean running = true;
private int pingInterval = 10000;
private byte[][] mapTiles = new byte[10000][10000];
public ServerMain(){
gameThread = new GameThread(this, mapTiles);
gameThread.start();
consoleListener = new ConsoleCommandListener();
ResourceManager.getInstance().loadFromIndex();
try {
serverSocket = new ServerSocket(serverPort);
BetadomLogger.log("Server started on port: "+serverPort);
}catch (Exception ex) {
BetadomLogger.log("Could not listen on port: "+serverPort);
System.exit(-1);
}
start();
}
public void run(){
Socket clientSocket = null;
while(running){
try {
clientSocket = serverSocket.accept();
ClientHandler newClient = new ClientHandler(clientSocket, pingInterval);
users.add(newClient);
newClient.start();
BetadomLogger.log("Got new client from "+clientSocket.getInetAddress());
}catch (Exception ex) {
if(running){
BetadomLogger.log("Couldn't accept client on: "+serverPort);
System.exit(-1);
}
}
}
}
public void stopServer(){
running = false;
for(ClientHandler client : users){
client.disconnect();
}
try{
serverSocket.close();
BetadomLogger.log("Server socket closed. Shutting down...");
BetadomLogger.close();
System.exit(0);
}catch(Exception ex){
BetadomLogger.log("Unable to close server socket.");
System.exit(-1);
}
}
public static void sendToAll(Packet packet){
for(ClientHandler client : users){
client.addPacket(packet);
}
}
}
| [
"[email protected]"
] | |
fd243ad0b8f9db7c2f16c103d87566264a650fc3 | db644b7703504ce1fee1856689bc6109440f5453 | /p3/src/aula6/ex1/Fish.java | f72ddf1ea468a8c521abbf29d6ce373d77fb1d0f | [] | no_license | jok1n9/P3 | 506a13cc6c93a10616223505e93c88f96da4174b | f54e38dd89dca5c17e751ebb97a47d0cedb6dbb0 | refs/heads/master | 2023-03-09T01:52:11.654620 | 2021-03-03T00:15:00 | 2021-03-03T00:15:00 | 303,205,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,118 | java | package aula6.ex1;
public class Fish implements Alimento{
enum TYPE {CONGELADO,FRESCO};
private TYPE type;
private double proteins;
private double calories;
private double weight;
public Fish(TYPE t, double p, double c, double w) {
this.type = t;
this.proteins = p;
this.calories = c;
this.weight = w;
}
public TYPE getType() {
return this.type;
}
public double getProteins() {
return this.proteins;
}
public double getCalories() {
return this.calories;
}
public double getWeight() {
return this.weight;
}
@Override
public String toString() {
return "Fish Type: "+this.type+
", Proteins: "+this.proteins+
", Calories: "+this.calories+
", Weight: "+this.weight;
}
public boolean equals(Fish f) {
if(this == f)
return true;
if(f == null)
return false;
if(this.getClass() != f.getClass())
return false;
if(this.type != f.getType())
return false;
if(this.proteins != f.getProteins())
return false;
if(this.calories != f.getCalories())
return false;
if(this.weight != f.getWeight())
return false;
return true;
}
}
| [
"[email protected]"
] | |
dfdfb8ce1085178f06eb04f11fd8b835fb61d99e | 7043d651e3d00ca9a2ad87381757100ed80a5c66 | /src/main/java/com/elementall/eps/backend/crewplanner/models/Employee.java | d3383ea984dbc2afbe87f346341f5a7317f0c3f1 | [] | no_license | codefink2020/eps-crew-planner | e62c484b60ac2463904aa5f9d3b58738935bf662 | d42311b2399f56b913b53e0281363dc76724fb9e | refs/heads/master | 2023-02-13T14:29:50.756266 | 2021-01-19T15:17:11 | 2021-01-19T15:17:11 | 331,021,524 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 731 | java | package com.elementall.eps.backend.crewplanner.models;
import lombok.Data;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@Data
@Entity
public class Employee extends Person{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private LocalDate employedDate;
private LocalDate terminationDate;
@ManyToMany
private List<Job> plannedJobs;
public Employee() {
this.plannedJobs = new ArrayList<>();
}
public void setName(String first, String last) {
super.setFirstName(first);
super.setLastName(last);
}
public void addJob(Job job) {
this.plannedJobs.add(job);
}
}
| [
"[email protected]"
] | |
1ca9d76054fe297cedf7f68cc307678b17f7276b | 3de2e0a42554e819bfef56d5d39cb353200d2867 | /app/src/main/java/com/vivekvishwanath/bitters/login/LoginActivity.java | e433dd1bdef2a1cf92c1d391a823bacfb7aa61f9 | [] | no_license | VivekV95/Bitters | 202a0fe3dbb3fd61a082069f78884c93607d654c | f0fe130d4ef3356b6823839d6e572ecfc249698f | refs/heads/master | 2020-05-24T13:43:23.839944 | 2019-09-23T19:05:12 | 2019-09-23T19:05:12 | 187,293,731 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,471 | java | package com.vivekvishwanath.bitters.login;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.vivekvishwanath.bitters.R;
import com.vivekvishwanath.bitters.apis.FirebaseAuthDao;
import com.vivekvishwanath.bitters.views.MainActivity;
public class LoginActivity extends AppCompatActivity
implements RegisterFragment.OnFragmentInteractionListener {
FirebaseAuth mAuth;
FirebaseUser firebaseUser;
private Context context;
public static final String REGISTER_FRAGMENT_TAG = "register_fragment";
private static final String PREFS_NAME = "Bitters_prefs";
private static final String PREFS_EMAIL_KEY = "Prefs_email";
private static final String PREFS_PASSWORD_KEY = "Prefs_password";
private static SharedPreferences preferences;
private static final int LOGIN_REQUEST_CODE = 12;
private TextView textViewRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private Button buttonSignIn;
private CheckBox checkBoxRemember;
private ProgressBar loginProgressBar;
private boolean startMain = true;
private View.OnClickListener textViewRegisterListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
textViewRegisterClicked();
}
};
private void textViewRegisterClicked() {
RegisterFragment fragment = new RegisterFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.register_fragment_container
, fragment , REGISTER_FRAGMENT_TAG);
transaction.addToBackStack(null);
transaction.commit();
}
private View.OnClickListener buttonSignInListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
buttonSignInClicked();
}
};
private void buttonSignInClicked() {
if (checkFields()) {
loginProgressBar.setVisibility(View.VISIBLE);
handleLoginInfo();
FirebaseAuthDao.signIn(editTextEmail.getText().toString()
, editTextPassword.getText().toString(), new FirebaseAuthDao.SignInCallback() {
@Override
public void onSignInResult(boolean result, String message) {
if (result) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, LOGIN_REQUEST_CODE);
finish();
loginProgressBar.setVisibility(View.GONE);
} else {
loginProgressBar.setVisibility(View.GONE);
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.app_bar_title);
context = this;
preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
textViewRegister = findViewById(R.id.text_view_register);
textViewRegister.setOnClickListener(textViewRegisterListener);
editTextEmail = findViewById(R.id.edit_text_email);
editTextPassword = findViewById(R.id.edit_text_password);
loginProgressBar = findViewById(R.id.login_progress_bar);
checkBoxRemember = findViewById(R.id.check_box_remember);
buttonSignIn = findViewById(R.id.button_sign_in);
buttonSignIn.setOnClickListener(buttonSignInListener);
mAuth = FirebaseAuth.getInstance();
FirebaseAuthDao.initializeInstance(context);
if (!getSharedPreferences("bitters", Context.MODE_PRIVATE)
.getBoolean("night_mode", false)) {
}
}
@Override
protected void onStart() {
super.onStart();
firebaseUser = mAuth.getCurrentUser();
if (firebaseUser != null) {
if (startMain) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, LOGIN_REQUEST_CODE);
}
}
/* String email = preferences.getString(PREFS_EMAIL_KEY, null);
String pass = preferences.getString(PREFS_PASSWORD_KEY, null);
if (email != null && pass != null) {
FirebaseAuthDao.signIn(email, pass, new FirebaseAuthDao.SignInCallback() {
@Override
public void onSignInResult(boolean result) {
if (result) {
Intent intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} else {
Toast.makeText(context, "Sign in unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
} */
}
@Override
public void onFragmentInteraction(Uri uri) {
}
private boolean checkFields() {
if (TextUtils.isEmpty(editTextEmail.getText().toString())
|| TextUtils.isEmpty(editTextPassword.getText().toString())) {
return false;
}
return true;
}
private void handleLoginInfo() {
SharedPreferences.Editor editor = preferences.edit();
if (checkBoxRemember.isChecked()) {
editor.putString(PREFS_EMAIL_KEY, editTextEmail.getText().toString());
editor.putString(PREFS_PASSWORD_KEY, editTextPassword.getText().toString());
editor.apply();
} else {
editor.clear();
editor.apply();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LOGIN_REQUEST_CODE && resultCode == RESULT_OK) {
startMain = false;
onBackPressed();
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
| [
"[email protected]"
] | |
4c644ffcb0eb1a92f0cdc429f47b80548afefaac | 48ed940b768bc248b86b7864a1e6aedd0919bb71 | /src/main/java/com/newpay/webauth/dal/model/RepayMentCity.java | e1875882cbb93661c9098705af0455fbb8edc829 | [] | no_license | wanruome/mchtAppUserApi | d136ab662711bf610842341898a2c1ca24a88678 | 07a7b95827d34031736e4bc16f37031f18cbaa60 | refs/heads/master | 2020-03-21T04:29:18.856973 | 2018-07-31T04:27:23 | 2018-07-31T04:27:23 | 138,110,670 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 549 | java | /**
* @copyright wanruome-2018
* @author wanruome
* @create 2018年6月22日 下午10:19:01
*/
package com.newpay.webauth.dal.model;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
@Data
@Table(name = "TBL_REPAYMENT_CITYS")
public class RepayMentCity {
@Id
@Column(name = "ID")
private String id;
@Column(name = "PROVINCE")
private String province;
@Column(name = "CITY")
private String city;
@Column(name = "CODE")
private String code;
}
| [
"[email protected]"
] | |
e0daf29e65f76fad13e9fb0241bf142e927e1682 | 574914f8232c2fa7626e9d48baa10ed4086e2816 | /common/src/main/java/org/jboss/demos/run/DemosRunner.java | f5f2181f91330e8627bc35767c4a1000013130be | [
"Apache-2.0"
] | permissive | gaol/demos | 47cd293e157e371dc8373e308473ea1d96d183e5 | ce64ce7dcdee7f8eac52559078125a7c662fe430 | refs/heads/master | 2016-08-04T07:00:50.280884 | 2014-04-11T08:08:14 | 2014-04-11T08:08:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,304 | java | /**
*
*/
package org.jboss.demos.run;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.jboss.demos.run.Demos.Demo;
/**
* @author lgao
*
*/
public class DemosRunner {
private static DemosRunner singleRuner;
public static DemosRunner getSingleRunner () {
if (singleRuner == null) {
singleRuner = new DemosRunner(Demos.scanCurrentJar());
}
return singleRuner;
}
private final Demos demos;
public DemosRunner(Demos demos) {
this.demos = demos;
}
public Demos getDemos() {
return this.demos;
}
public void run(String demoName) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
Demo demo = demos.getDemo(demoName);
if (demo == null) {
throw new IllegalArgumentException("Demo: " + demoName + " does not exist!");
}
Method method = demo.getMethod();
Class<?> cls = method.getDeclaringClass();
Object obj = cls.newInstance(); //TODO check constructor.
Class<?> paramsTypes[] = method.getParameterTypes();
Object params[] = new Object[paramsTypes.length];
int i = 0;
for (Class<?> pType: paramsTypes) {
Object param = pType.newInstance(); //TODO check constructor.
params[i] = param;
i ++;
}
method.invoke(obj, params);
}
}
| [
"[email protected]"
] | |
e83843e69fd96d7c0ba443ca2ebfc0bbef45d7b2 | a8839ef997eb5383c933b2a45755b1a4d5b2b784 | /src/main/java/com/openix/prueba23/config/Constants.java | fcd29b427ab4dfdfa311f656fc5b23eb2886f96e | [] | no_license | GWP-SMN/jhipster-sample-application23 | fc854d62805ddc55ec76e9a9c0b0d8556acaf0dd | b72108550bcb4a479839c9d7e4c2575d9504523b | refs/heads/master | 2020-04-05T08:37:57.407722 | 2018-11-08T14:49:47 | 2018-11-08T14:49:47 | 156,722,044 | 1 | 0 | null | 2018-11-08T14:51:12 | 2018-11-08T14:49:39 | Java | UTF-8 | Java | false | false | 424 | java | package com.openix.prueba23.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String ANONYMOUS_USER = "anonymoususer";
public static final String DEFAULT_LANGUAGE = "en";
private Constants() {
}
}
| [
"[email protected]"
] | |
252ca98a000985f4ee42fb6b7d5539d39b48cf6d | 1a3085906549c248618ccc6bda52c513f30243ae | /Day1/Solution2.java | 6a4f4b68f05da9fdba2451f9938a0679858b2daa | [] | no_license | ankur2811/October-Leetcode-Challenge | c611dec0bd348852d3d5325d28543f6a98994231 | 699f57f1beca85d770953f11c2ce7327b01bebd3 | refs/heads/master | 2023-01-08T09:24:51.205724 | 2020-10-31T14:09:41 | 2020-10-31T14:09:41 | 301,178,111 | 0 | 3 | null | 2020-10-27T09:21:16 | 2020-10-04T16:48:03 | Java | UTF-8 | Java | false | false | 439 | java | class RecentCounter {
ArrayDeque<Integer> q;
public RecentCounter() {
q = new ArrayDeque<>();
}
public int ping(int t) {
while( !q.isEmpty() && q.peek() < t-3000 )
q.remove();
q.add(t);
return q.size();
}
}
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter obj = new RecentCounter();
* int param_1 = obj.ping(t);
*/
| [
"[email protected]"
] | |
334cc91039747012371d149a3878a24f6e1738bc | 64c1d93610f7e7564f4046271af185d51c848713 | /app/src/main/java/com/gooten/core/GTN.java | af5ae023a6548b2e498727b67692c89327905f89 | [] | no_license | printdotio/gooten-android-core | 72de9ed2abbefd966e32f875a81911dd396947d6 | 672672396e8c7265ce81f85912d9d38eda4b87c1 | refs/heads/master | 2020-04-12T22:21:25.350191 | 2016-06-30T10:45:56 | 2016-09-08T12:34:20 | 62,303,056 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,589 | java | package com.gooten.core;
import android.content.Context;
import com.gooten.core.persistence.GTNConfigPersistence;
import com.gooten.core.types.Environment;
import com.gooten.core.utils.Logger;
import com.gooten.core.utils.StringUtils;
/**
* Gooten Core SDK entry point.
*/
public class GTN {
private GTN() {
// NOP
}
/**
* @return SDK version in format MAJOR.MINOR.PATCH
*/
public static String getVersion() {
return Version.BUILD_VERSION;
}
/**
* Holds SDK configuration.
*/
private static GTNConfig config;
/**
* Returns current {@code GTNConfig} instance.
* Reference could change in runtime if application gets restarted, in which case the {@link GTNConfig} is restored from permanent storage.
*
* @return {@link GTNConfig} instance, or null if current application instance was killed and restarted.
*/
public static GTNConfig getConfig() {
return config;
}
/**
* Returns restored {@link GTNConfig} if needed.
*/
public static GTNConfig getRestoredConfig(Context context) {
if (config == null) {
config = GTNConfigPersistence.load(context);
}
return config;
}
/**
* Sets the Gooten SDK configuration without validation.
*
* @param context The {@code Context} of your application.
* @param config The {@code GTNConfig} holding the configuration for Gooten SDK.
*/
public static void setConfigNoValidation(Context context, GTNConfig config) {
if (context == null) {
throw new IllegalArgumentException("Failed to set Gooten SDK Config. Context can not be null.");
}
GTN.config = config;
GTNConfigPersistence.store(context, config);
}
/**
* Sets the Gooten SDK configuration.
*
* @param context The {@code Context} of your application.
* @param config The {@code GTNConfig} holding the configuration for Gooten SDK.
* @throws GTNException If the configuration is invalid.
*/
public static void setConfig(Context context, GTNConfig config) throws GTNException {
if (context == null) {
throw new GTNException("Failed to set Gooten SDK Config. Context can not be null.");
}
if (config == null) {
throw new GTNException("Failed to set Gooten SDK Config. GTNConfig can not be null.");
}
// Validate configuration
GTNException validationException = validateConfig(config);
if (validationException != null) {
GTN.config = null;
Logger.e(GTN.class, "Failed to set Gooten SDK Config. GTNConfig is not valid.");
throw validationException;
}
// Set and store GTN config
GTN.config = config;
GTNConfigPersistence.store(context, config);
}
/**
* Performs sanity checks to supplied {@code GTNConfig} object.
*
* @param config {@link GTNConfig} object to validate
* @return {@link GTNException} describing the issue in configuration, or null if {@link GTNConfig} is valid.
*/
private static GTNException validateConfig(GTNConfig config) {
if (StringUtils.isBlank(config.getRecipeId())) {
return new GTNException("GTNConfig is not valid. RecipeId must be set.");
}
if (config.getEnvironment() == null) {
config.setEnvironment(Environment.LIVE);
Logger.e(GTN.class, "Environment not set. Using LIVE environment...");
}
return null;
}
}
| [
"[email protected]"
] | |
0d63b149a30fdf9045b1fa066d5c75b654a5f815 | aabceb41593153c77467180bd4c749b34457a6b2 | /app/src/main/java/com/scitech/codegram/Signup_page.java | 1814f165ea94afed5bcbee7bbad3af3a16a69f89 | [] | no_license | Panda2498/Codegram | 81b54b4d528e04d330eb3f2bc089b825f03c5b2f | 092854bd6e8100b2e072b216c6dffc6189387e1a | refs/heads/main | 2023-01-28T10:49:33.863823 | 2020-12-11T14:09:07 | 2020-12-11T14:09:07 | 320,587,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,860 | java | package com.scitech.codegram;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
public class Signup_page extends AppCompatActivity {
FirebaseAuth firebaseAuth;
TextInputLayout rpass, rcpass, remail;
MaterialButton register;
TextView loginLink;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_page);
loginLink = (TextView)findViewById(R.id.login_link);
loginLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Signup_page.this, login_page.class));
finish();
}
});
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
remail = findViewById(R.id.remail);
rpass = findViewById(R.id.rpassword);
rcpass = findViewById(R.id.rcpassword);
register = findViewById(R.id.register_button);
register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UserSignup();
}
});
}
private void UserSignup()
{
String email, pass, cpass;
email = remail.getEditText().getText().toString();
pass = rpass.getEditText().getText().toString();
cpass = rcpass.getEditText().getText().toString();
if(TextUtils.isEmpty(email))
{
Toast.makeText(Signup_page.this, "Please enter the Email !!!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(pass))
{
Toast.makeText(Signup_page.this, "Password field cannot be kept blank!!!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(cpass))
{
Toast.makeText(Signup_page.this, "Confirm password field cannot be kept blank!!!", Toast.LENGTH_SHORT).show();
}
else if(pass.equals(cpass))
{
progressDialog.setMessage("Signing up...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, cpass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
DatabaseReference reqDatabase = FirebaseDatabase.getInstance().getReference("Follow_Requests");
List<String> list = new ArrayList<>();
list.add(user.getUid());
reqDatabase.child(user.getUid()).setValue(new Follow_Request(list));
}
else {
Toast.makeText(Signup_page.this, "trip", Toast.LENGTH_SHORT).show();
}
Toast.makeText(Signup_page.this, "Registration Successful !!!", Toast.LENGTH_SHORT).show();
progressDialog.hide();
startActivity(new Intent(Signup_page.this, edit_profile.class).putExtra("Intent","Signup"));
finish();
}
else {
FirebaseAuthException e = (FirebaseAuthException)task.getException();
Toast.makeText(Signup_page.this, "Registration Failed !!! " + e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.hide();
}
}
});
}
else{
Toast.makeText(Signup_page.this, "Password match failed !!!", Toast.LENGTH_SHORT).show();
}
}
}
| [
"[email protected]"
] | |
d4e51b49cfc4b4c790a01772d4d96d9974a6569b | 2f92dfff9b9929b64e645fdc254815d06bf2b8d2 | /src/main/lee/code/code_443__String_Compression/C443_MainClass.java | e612a7c647b1691acb79fed61c0055029173196a | [
"MIT"
] | permissive | code543/leetcodequestions | fc5036d63e4c3e1b622fe73552fb33c039e63fb0 | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | refs/heads/master | 2020-04-05T19:43:15.530768 | 2018-12-07T04:09:07 | 2018-12-07T04:09:07 | 157,147,529 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 529 | java | package lee.code.code_443__String_Compression;
import java.util.*;
import lee.util.*;
import java.io.*;
import com.eclipsesource.json.*;
import java.text.*;
public class C443_MainClass {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader("no MAIN"));
String line;
while ((line = in.readLine()) != null) {
System.out.print(line);
}
}
}
| [
"[email protected]"
] | |
cba4b04144224df07940350e1900228563bbfbb6 | 533d15375254a16bde29b034c1f0664e1fc413dc | /app/src/main/java/rikka/akashitoolkit/event/EventAdapter.java | 0c37948774b2071c6d4627b2722e017728797155 | [] | no_license | HeroinThemirror/Akashi-Toolkit | 6bff357a0851e98fa82ef0ade7ea46f280d21542 | 9e213cffb6b5c57c3581f2909a6d826288542750 | refs/heads/master | 2021-01-17T14:17:04.192765 | 2016-09-04T09:47:02 | 2016-09-04T09:47:02 | 67,379,526 | 0 | 0 | null | 2017-10-18T09:55:25 | 2016-09-05T01:54:23 | Java | UTF-8 | Java | false | false | 1,786 | java | package rikka.akashitoolkit.event;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import rikka.akashitoolkit.R;
import rikka.akashitoolkit.adapter.BaseRecyclerAdapter;
/**
* Created by Rikka on 2016/8/12.
*/
public class EventAdapter extends BaseRecyclerAdapter<RecyclerView.ViewHolder, Object> {
private static final String TAG = "EventAdapter";
public static final int TYPE_TITLE = 0;
public static final int TYPE_GALLERY = 1;
public static final int TYPE_CONTENT = 2;
public static final int TYPE_MAPS = 3;
public static final int TYPE_URL = 4;
public EventAdapter() {
}
@Override
public void rebuildDataList() {
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_TITLE:
return new TitleSummaryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_seansonal_title, parent, false));
case TYPE_GALLERY:
return new GalleryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_seansonal_gallery, parent, false));
case TYPE_CONTENT:
return new TitleSummaryViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_seansonal_text, parent, false));
case TYPE_MAPS:
return new EventMapViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_seansonal_voice, parent, false));
case TYPE_URL:
return new TitleSummaryButtonViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_event_action, parent, false));
}
return null;
}
}
| [
"[email protected]"
] | |
82ae9eb0202f7b681abb512d3c21261f171bcc81 | 5c377b9049336fa368f47986cebe241d16d7f576 | /web/src/main/java/net/ruixin/controller/qbyp/XqbMapping.java | c8948bed8a00aa50aa9d2c9fe3e9167ad17e5029 | [] | no_license | yucheng0407/asdfkgzpt | 0961968b9f13aff4c1f7e50a4ab44097de172c1b | 05b2f2f2c912a78fb554aef6e1a42c2d448635bb | refs/heads/master | 2020-05-17T00:31:47.036082 | 2019-04-24T10:16:29 | 2019-04-24T10:16:29 | 182,956,882 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 662 | java | package net.ruixin.controller.qbyp;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*巡区表 路径跳转
*/
@Controller
@RequestMapping("/qbyp")
public class XqbMapping {
/**
* 巡区表列表
*/
@RequestMapping("/xqbList")
public String xqbList() { return "asdfkgzpt/qbyp/xqbList";}
/**
* 巡区表表单
*/
@RequestMapping("/xqbEdit")
public String xqbEdit() { return "asdfkgzpt/qbyp/xqbEdit";}
/**
* 巡区表查看表单
*/
@RequestMapping("/xqbView")
public String xqbView() { return "asdfkgzpt/qbyp/xqbView";}
}
| [
"[email protected]"
] | |
ac52853bbd492c40485191168ee57efa01c6c67b | 93176f66e0f0d0bf403cdc9af1e65473085dbaf9 | /PedidoVenda/src/main/java/com/bioformula/pedidovenda/model/StatusPedido.java | 8e32c9943cd86c7dc6696617396e97cd22aef1ad | [] | no_license | mktbioformula/Bioformula | cb511564dca07f1bdc0ca05a5f0f7b495f1af509 | aa5275c2caf2068aa1997872bba0fda3861c29a1 | refs/heads/master | 2021-07-13T13:16:30.044835 | 2017-10-13T20:16:46 | 2017-10-13T20:16:46 | 106,863,166 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | package com.bioformula.pedidovenda.model;
public enum StatusPedido {
ORCAMENTO, EMITIDO, CANCELADO
}
| [
"[email protected]"
] | |
0032d2c73f692e8965d44d38381012d5c3aa05e4 | 9972099a9985b36007e014448317cb6c31999ada | /src/main/java/utils/RandomGenerator.java | 2c22d7efaea0dc9af3bd2c85d74e9c1927c70601 | [] | no_license | rada5346/testAddition | 09b9e1dea2a4669bf4b233d7d6c2446e3ac6cbfe | 1452ed48cc5f0b76cd30412362bc579df9f5bb75 | refs/heads/master | 2021-08-23T22:13:06.970303 | 2017-12-06T20:16:33 | 2017-12-06T20:16:33 | 113,086,438 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 576 | java | package utils;
import java.util.Random;
public class RandomGenerator {
private final static Random random = new Random();
public static String randStr(int length){
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxy";
char[] symbols = new char[length];
for(int i = 0; i< length; i++){
symbols[i] = letters.toCharArray()[random.nextInt(length)];
}
return new String(symbols);
}
public static int generateInt(int maxExpectedValue){
return random.nextInt(maxExpectedValue);
}
}
| [
"[email protected]"
] | |
b086ac76fcdd156f069547efdca8a6c6c63e7f36 | 3c023e00d44b5a35e8e7fba1c0dfa72cb4e59201 | /spring-security-core/src/main/java/com/security/core/properties/ImageCodeProperties.java | 7bbc20989ccf4dba5f15dd5eaaabf4d3d484bb0a | [] | no_license | eistert/spring_security | 1eddf06e79637104c9f1bee126164504b5d468fc | 11ddee9f80927d7727d36db09570ca7d49d2c0f1 | refs/heads/master | 2022-07-05T18:41:04.643553 | 2020-06-05T07:12:27 | 2020-06-05T07:12:27 | 212,506,454 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 998 | java | /**
*
*/
package com.security.core.properties;
/**
* @author zhailiang
* 默认配置
*/
public class ImageCodeProperties {
// 基本参数可配置
private int width = 67;
private int height = 23;
private int length = 4;
private int expireIn = 60;
// url可配置
private String url;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getLength() {
return length;
}
public void setLength(int lenght) {
this.length = lenght;
}
public int getExpireIn() {
return expireIn;
}
public void setExpireIn(int expireIn) {
this.expireIn = expireIn;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| [
"[email protected]"
] | |
6b8e06f5e9bc7e130a82687dd006671a84b8822e | f165441bfc263972467ad192831b07988a7a9453 | /app/src/main/java/corpode21/com/br/corpod21/fragments/DuvidasFrequentesFragment.java | 940bc6d761203cc81ab16d046fc5e2f4c108256d | [] | no_license | fgomescg/CorpoD21 | 6fc951f6ec99a8e9b61bc64f5af235ea0bea1a87 | 00d50787cde1823c89fab3acff4d8eb3578e39c2 | refs/heads/master | 2016-09-05T12:52:02.478349 | 2015-12-03T23:40:37 | 2015-12-03T23:40:37 | 34,695,847 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,326 | java | package corpode21.com.br.corpod21.fragments;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import corpode21.com.br.corpod21.R;
/**
* Created by Fabio on 14/05/2015.
*/
public class DuvidasFrequentesFragment extends Fragment implements
View.OnClickListener {
private TextView pergunta1;
private TextView pergunta2;
private TextView pergunta3;
public final String TAG = "DuvidasFrequentesFragment";
private FragmentActivity myContext;
public DuvidasFrequentesFragment() {
// Required empty public constructor
}
@Override
public void onAttach(Activity activity) {
myContext=(FragmentActivity) activity;
super.onAttach(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_duvidas, container, false);
pergunta1 = (TextView) v.findViewById(R.id.pergunta1);
pergunta1.setOnClickListener(this);
pergunta2 = (TextView) v.findViewById(R.id.pergunta2);
pergunta2.setOnClickListener(this);
pergunta3 = (TextView) v.findViewById(R.id.pergunta3);
pergunta3.setOnClickListener(this);
// Inflate the layout for this fragment
return v;
}
@Override
public void onClick(View v) {
final String perguntaId = v.getTag().toString();
openFragment(new RespostaDuvidasFragment(), perguntaId);
}
private void openFragment(final Fragment fragment, String perguntaId) {
myContext.getSupportFragmentManager()
.beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_from_left,R.anim.enter_from_left,R.anim.exit_from_right)
.replace(R.id.content_frame, fragment)
.addToBackStack(TAG)
.commit();
//Passando parametros para o Fragment
Bundle args = new Bundle();
args.putString("PERGUNTAID", perguntaId);
fragment.setArguments(args);
}
}
| [
"[email protected]"
] | |
3671fa0f7233abdd5bab8ae05b55e43e823d1b6a | c7dddef4b5308a77bc017cb4b23d624ef6546ce9 | /src/test/java/com/example/fivefivemm/service/SendSmsTest.java | 296ac84e10dea397e05d2046a182bb45d03cf148 | [] | no_license | iiap/55mm-back | 85f1f706137544f5f8d1d9565077f9a8171fa303 | 702b5f24a55252a76b4318a7b238be74a3432b45 | refs/heads/master | 2020-05-29T16:18:05.479332 | 2019-05-29T15:20:19 | 2019-05-29T15:20:19 | 187,812,942 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,001 | java | package com.example.fivefivemm.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.example.fivefivemm.service.Implements.SendSmsImplements;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SendSmsTest {
@Autowired
public SendSmsImplements sendSmsImplements;
@Test
public void sendSmsTest() {
SendSmsResponse response = sendSmsImplements.sendSmsForInform("15320225720", "12345");
System.out.println("短信接口返回的数据----------------");
System.out.println("Code=" + response.getCode());
System.out.println("Message=" + response.getMessage());
System.out.println("RequestId=" + response.getRequestId());
System.out.println("BizId=" + response.getBizId());
}
}
| [
"[email protected]"
] | |
1e3dd20a44e6a56e16d41f7eb43a9cc67471dd12 | 01b7af545cff6bc9c69e3b813148b7484449f104 | /MODEL/PROGRAM/JPO/fpdm/excelreport/diversity/EBOMUtil_mxJPO.java | a85f18871fb5d6c4e51d4d51fae06bd5aa2a0f09 | [] | no_license | rgarbhe-processia/Tiger-DEV | c674b417935076ef41e8cb99a60ba423f51a89a1 | 75d8ad323df5cbb309e52ae4017cc2d00f6d1f0e | refs/heads/master | 2020-04-14T10:57:45.934483 | 2020-01-10T09:55:41 | 2020-01-10T09:55:41 | 163,800,729 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,069 | java | package fpdm.excelreport.diversity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import matrix.db.BusinessObject;
import matrix.db.Context;
import matrix.util.MatrixException;
import matrix.util.SelectList;
public class EBOMUtil_mxJPO {
/**
* Return a ResolvedEBOM object containing the consolidated EBOM
* @param context
* @param objectId
* @return the object containing the resolved EBOM
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, String objectId) throws MatrixException {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOMWithQuantity(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM who contain elements selected from object in a SelectList
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param slInfos
* the SelectList element containing attributes to select on elements
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, String objectId, SelectList slInfos) throws MatrixException {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOMWithQuantity(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM corresponding to a ProductConfiguration
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param pc
* The ProductConfiguration object
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, String objectId, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc) throws MatrixException {
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOMWithQuantity(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM corresponding to a ProductConfiguration, who contain elements selected from object in a SelectList
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param pc
* The ProductConfiguration object
* @param slInfos
* the SelectList element containing attributes to select on elements
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, String objectId, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc, SelectList slInfos)
throws MatrixException {
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOMWithQuantity(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM
* @param context
* @param boRoot
* The BusinessObject to expand
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, BusinessObject boRoot) {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
return getEBOMWithQuantity(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM who contain elements selected from object in a SelectList
* @param context
* @param boRoot
* The BusinessObject to expand
* @param slInfos
* The SelectList element containing attributes to select on elements
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, BusinessObject boRoot, SelectList slInfos) {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
return getEBOMWithQuantity(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM corresponding to a ProductConfiguration
* @param context
* @param boRoot
* The BusinessObject to expand
* @param pc
* The ProductConfiguration object
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, BusinessObject boRoot, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc) {
fpdm.excelreport.diversity.ResolvedEBOM_mxJPO rebom = fpdm.excelreport.diversity.EBOMUtil_mxJPO.getEBOM(context, boRoot, pc);
System.out.println("REBOM : " + rebom);
fpdm.excelreport.diversity.ResolvedEBOM_mxJPO resultBOM = fpdm.excelreport.diversity.EBOMUtil_mxJPO.consolidateEBOM(rebom);
return resultBOM;
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM corresponding to a ProductConfiguration, who contain elements selected from object in a SelectList
* @param context
* @param boRoot
* The BusinessObject to expand
* @param pc
* The ProductConfiguration object
* @param slInfos
* The SelectList element containing attributes to select on elements
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOMWithQuantity(Context context, BusinessObject boRoot, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc,
SelectList slInfos) {
fpdm.excelreport.diversity.ResolvedEBOM_mxJPO rebom = fpdm.excelreport.diversity.EBOMUtil_mxJPO.getEBOM(context, boRoot, pc, slInfos);
fpdm.excelreport.diversity.ResolvedEBOM_mxJPO resultBOM = fpdm.excelreport.diversity.EBOMUtil_mxJPO.consolidateEBOM(rebom);
return resultBOM;
}
/**
* Consolidate a bom from a ResolvedEBOM object
* @param rebom
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO consolidateEBOM(fpdm.excelreport.diversity.ResolvedEBOM_mxJPO rebom) {
HashMap<String, fpdm.excelreport.diversity.ResolvedPart_mxJPO> hmParts = rebom.hmBOM;
for (Entry<String, fpdm.excelreport.diversity.ResolvedPart_mxJPO> entry : hmParts.entrySet()) {
try {
fpdm.excelreport.diversity.ResolvedPart_mxJPO aPart = entry.getValue();
System.out.println(aPart.sId + " -> " + aPart.uom);
ArrayList<fpdm.excelreport.diversity.Children_mxJPO> alChildren = aPart.children;
HashMap<String, Integer> hmIDChildrenAlreadyKnown = new HashMap<String, Integer>();
ArrayList<Integer> alToDelete = new ArrayList<Integer>();
for (int x = 0; x < alChildren.size(); x++) {
fpdm.excelreport.diversity.Children_mxJPO thisChildren = alChildren.get(x);
if (!hmIDChildrenAlreadyKnown.containsKey(thisChildren.id)) {
hmIDChildrenAlreadyKnown.put(thisChildren.id, x);
} else {
if (!fpdm.excelreport.diversity.ResolvedPart_mxJPO.slRangePart.contains(thisChildren.uom)) {
int intFNExisting = Integer.parseInt(alChildren.get(hmIDChildrenAlreadyKnown.get(thisChildren.id)).fn);
int intFNNew = Integer.parseInt(thisChildren.fn);
float intQuantityExisting = Float.parseFloat(alChildren.get(hmIDChildrenAlreadyKnown.get(thisChildren.id)).quantity);
float intQuantityNew = Float.parseFloat(thisChildren.quantity);
float newQuantity = intQuantityExisting + intQuantityNew;
if (intFNExisting < intFNNew) {
alChildren.get(hmIDChildrenAlreadyKnown.get(thisChildren.id)).quantity = "" + newQuantity;
alChildren.get(x).quantity = "0";
alToDelete.add(x);
} else {
alChildren.get(hmIDChildrenAlreadyKnown.get(thisChildren.id)).quantity = "0";
alChildren.get(x).quantity = "" + newQuantity;
alToDelete.add(hmIDChildrenAlreadyKnown.get(thisChildren.id));
}
}
}
}
for (int x = alChildren.size() - 1; x > 0; x--) {
float floatQuantity = Float.parseFloat(alChildren.get(x).quantity);
if (0 == floatQuantity) {
alChildren.remove(x);
}
}
aPart.children = alChildren;
} catch (Exception e) {
e.printStackTrace();
}
}
rebom.hmBOM = hmParts;
return rebom;
}
/**
* Return a ResolvedEBOM object containing the EBOM
* @param context
* @param objectId
* @return the object containing the resolved EBOM
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, String objectId) throws MatrixException {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOM(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the EBOM who contain elements selected from object in a SelectList
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param slInfos
* the SelectList element containing attributes to select on elements
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, String objectId, SelectList slInfos) throws MatrixException {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOM(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the EBOM corresponding to a ProductConfiguration
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param pc
* The ProductConfiguration object
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, String objectId, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc) throws MatrixException {
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOM(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the EBOM corresponding to a ProductConfiguration, who contain elements selected from object in a SelectList
* @param context
* @param objectId
* the object containing the resolved EBOM
* @param pc
* The ProductConfiguration object
* @param slInfos
* the SelectList element containing attributes to select on elements
* @return
* @throws MatrixException
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, String objectId, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc, SelectList slInfos)
throws MatrixException {
BusinessObject boRoot = new BusinessObject(objectId);
return getEBOM(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the EBOM
* @param context
* @param boRoot
* The BusinessObject to expand
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, BusinessObject boRoot) {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
return getEBOM(context, boRoot, pc);
}
/**
* Return a ResolvedEBOM object containing the EBOM who contain elements selected from object in a SelectList
* @param context
* @param boRoot
* The BusinessObject to expand
* @param slInfos
* The SelectList element containing attributes to select on elements
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, BusinessObject boRoot, SelectList slInfos) {
fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc = new fpdm.excelreport.diversity.ProductConfiguration_mxJPO("", new ArrayList<String>(), "");
return getEBOM(context, boRoot, pc, slInfos);
}
/**
* Return a ResolvedEBOM object containing the EBOM corresponding to a ProductConfiguration
* @param context
* @param boRoot
* The BusinessObject to expand
* @param pc
* The ProductConfiguration object
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, BusinessObject boRoot, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc) {
// ResolvedEBOM rebom = new ResolvedEBOM(boRoot.getObjectId(), pc);
return getEBOM(context, boRoot, pc, new SelectList());
}
/**
* Return a ResolvedEBOM object containing the consolidated EBOM corresponding to a ProductConfiguration, who contain elements selected from object in a SelectList
* @param context
* @param boRoot
* The BusinessObject to expand
* @param pc
* The ProductConfiguration object
* @param slInfos
* The SelectList element containing attributes to select on elements
* @return
*/
public static fpdm.excelreport.diversity.ResolvedEBOM_mxJPO getEBOM(Context context, BusinessObject boRoot, fpdm.excelreport.diversity.ProductConfiguration_mxJPO pc, SelectList slInfos) {
fpdm.excelreport.diversity.ResolvedEBOM_mxJPO rebom = new fpdm.excelreport.diversity.ResolvedEBOM_mxJPO(boRoot.getObjectId(), pc, slInfos);
rebom.builtResolvedEBOM(context);
return rebom;
}
}
| [
"[email protected]"
] | |
537c875ef820c3edc78180dd3358d321037bcd76 | 1a5fc61e8c41dde9f9b42ea6f5ca3605d62e6d99 | /OpsTracker/repository/CustomerBankRepository.java | 8482a7788db3f04690b35a1605a59e8e7586c44e | [] | no_license | deepakm14/OpsTracker | f8ca760249bcc854956d8c150be5cf2d58f678f8 | 5ce4a9e71e25454e2e5187c3cadeb009f0dac21b | refs/heads/master | 2020-03-26T14:05:19.750411 | 2018-09-17T11:26:03 | 2018-09-17T11:26:03 | 144,971,372 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 232 | java | package com.jallikattu.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.jallikattu.entity.CustomerBank;
public interface CustomerBankRepository extends JpaRepository<CustomerBank, String>{
}
| [
"[email protected]"
] | |
122afcd61386d4bbe0d07252ba733aeadd7b07fb | 2c6280e2821581c72d0255993b301c4b2ed8face | /example/src/main/java/io/redstone/example/SmaStrategyExample.java | 0611ef1fe79f3809fd84e7329ff069b4fa36ae33 | [
"Apache-2.0"
] | permissive | bigbigbigfish/redstone | 2bb8d70bcc90f971b3a80c85fdb3ef062fafc733 | 2508da38cf9a5dd59c9246f292ac0b88b273fe16 | refs/heads/master | 2020-11-23T19:29:18.043315 | 2019-12-12T05:59:23 | 2019-12-12T05:59:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,453 | java | package io.redstone.example;
import io.polaris.financial.instrument.Instrument;
import io.polaris.financial.market.impl.BasicMarketData;
import io.polaris.indicator.events.SmaEvent;
import io.polaris.indicator.impl.ma.SmaPoint;
import io.redstone.core.adaptor.impl.OutboundAdaptor;
import io.redstone.engine.specific.strategy.IndicatorStrategy;
public class SmaStrategyExample extends IndicatorStrategy<BasicMarketData> implements SmaEvent {
public SmaStrategyExample(int strategyId, int subAccountId, Instrument instrument) {
super(strategyId, subAccountId, instrument);
}
@Override
public void onMarketData(BasicMarketData marketData) {
// TODO Auto-generated method stub
}
@Override
public void onCurrentPointAvgPriceChanged(SmaPoint point) {
// TODO Auto-generated method stub
}
@Override
public void onStartSmaPoint(SmaPoint point) {
// TODO Auto-generated method stub
}
@Override
public void onEndSmaPoint(SmaPoint point) {
// TODO Auto-generated method stub
}
@Override
protected void handleMarketData(BasicMarketData marketData) {
// TODO Auto-generated method stub
}
@Override
protected OutboundAdaptor getOutboundAdaptor(Instrument instrument) {
// TODO Auto-generated method stub
return null;
}
@Override
public String strategyName() {
// TODO Auto-generated method stub
return null;
}
@Override
public String eventName() {
// TODO Auto-generated method stub
return null;
}
}
| [
"[email protected]"
] | |
ebd1a9d278d809df7cc4ef9f9fd2270e28ed4a0c | adc03b3ffcd9c4640888aa79a9b3e067a02fbc03 | /app/src/test/java/neb/com/asuspc/demoapplication/ExampleUnitTest.java | 8a473784ccadc2ef7b3f2789d607a87bad0c39eb | [] | no_license | Mrinangk/demo | cb005375ffe268b6cad9fea88d604474528b0899 | cda0ea2bcd60307cbd7c370bf930c51a86adfb81 | refs/heads/master | 2023-03-07T01:27:01.328730 | 2021-02-19T10:07:24 | 2021-02-19T10:07:24 | 340,329,627 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 391 | java | package neb.com.asuspc.demoapplication;
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]"
] | |
d7548afd2ba0f655ec276212d0da026877f7ec6f | 362da3d4fe627493faae37e40f061c369fb4e887 | /fna.algos.practice/src.main.java/com/epi/sorting/RenderACalendar.java | 7be7718f0e3f3c27b66685d60f0ce55f9fd06e7c | [] | no_license | faisal-nazir/practice_repo | ed1cd49504781349136789f838df400d9ae9629c | 4d0b7866afcff173c545fc45a1273150df362359 | refs/heads/master | 2022-08-07T19:13:55.598542 | 2022-07-25T20:09:32 | 2022-07-25T20:09:32 | 147,714,677 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,467 | java | package com.epi.sorting;
import java.util.*;
public class RenderACalendar {
// EPI-14.4: Render a calendar
// same as MeetingRoom_II (search for this class in the workspace)
// https://leetcode.com/problems/meeting-rooms-ii/discuss/67857/AC-Java-solution-using-min-heap
// https://leetcode.com/problems/meeting-rooms-ii/discuss/67855/Explanation-of-%22Super-Easy-Java-Solution-Beats-98.8%22-from-%40pinkfloyda
private static class Event {
int startTime;
int endTime;
Event(int s, int e) {
this.startTime = s;
this.endTime = e;
}
}
private static class EndPoint implements Comparable<EndPoint> {
int time;
boolean isStartTime;
EndPoint(int t, boolean isStart) {
this.time = t;
this.isStartTime = isStart;
}
@Override
public int compareTo(EndPoint o) {
if(this.time == o.time) {
return (this.isStartTime && !o.isStartTime)? -1 : (!this.isStartTime && o.isStartTime)? 1 : 0;
}
return Integer.compare(this.time, o.time);
}
}
public static int computeConcurrentEvents(List<Event> events) {
List<EndPoint> endPoints = new ArrayList<>();
for(Event e : events) {
endPoints.add(new EndPoint(e.startTime, true));
endPoints.add(new EndPoint(e.endTime, false));
}
Collections.sort(endPoints);
int max = 0, count = 0;
for(EndPoint p : endPoints) {
if(p.isStartTime) {
++count;
max = Math.max(max, count);
} else {
--count;
}
}
return max;
}
}
| [
"[email protected]"
] | |
ff6e3cdd2e110ad449badd27024f18e57be9423e | a1206b142ff7fdb490f10afa83bd103d642ec7dd | /src/main/java/test/Video.java | 66168ec1a3855e45fee9ae637fb87f0758b9b03e | [] | no_license | matthewshine/java-learning-example | d7e4babacd8dc4404fe9ed2c0449083e7dd7be60 | 9a4d6c056e8d05ea1be10b5e489b2979fbef7e00 | refs/heads/master | 2023-07-12T00:11:09.946088 | 2020-04-26T09:53:52 | 2020-04-26T09:53:52 | 258,995,196 | 0 | 0 | null | 2021-08-13T15:36:25 | 2020-04-26T09:53:41 | Java | UTF-8 | Java | false | false | 2,027 | java | package test;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class Video {
public static void main(String[] args) {
String url = null;
try {
url = getRealSrcBvid("h0851061duv");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(url);
}
static String getRealSrcBvid(String vid) throws UnsupportedEncodingException, IOException {
String url ="http://vv.video.qq.com/getinfo?vids="+vid+"&platform=101001&charge=0&otype=json&defn=shd";
String line = "";
StringBuffer sb = new StringBuffer();
HttpURLConnection urlConnection = (HttpURLConnection)new URL(url).openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200) {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line);// 网页传回的只有一行
}
}
String json = sb.toString();
System.out.println(json);
int fvkey_index = json.indexOf("\"fvkey\":\"")+9;
int endIndex = json.indexOf("\"",fvkey_index);
String fvkey = json.substring(fvkey_index,endIndex);//获取到fvkey
int fn_index = json.indexOf("\"fn\":\"")+6;
int fn_end = json.indexOf("\"",fn_index);
String fn = json.substring(fn_index,fn_end);//获取到视频文件名
String head = "http://ugcws.video.gtimg.com/";
StringBuffer real_url = new StringBuffer();
real_url.append(head);//加入头部
real_url.append(fn+"?");//加入文件名
real_url.append("vkey="+fvkey);//加入解锁码
/*构造成功*/
return real_url.toString();
}
}
| [
"[email protected]"
] | |
c34ebff81800d3c486f6884cd817b772102fb43e | eadb2c413a121477eab92875f734b84b187bfdbb | /ZuulServer/src/main/java/com/roots/cacaopay/zuul/SwaggerConfig.java | 0f6a233742467d912a9ebe94432766e408515455 | [] | no_license | jram97/fintpay | 84fa48d1db7c8f8010ad74fd941bf8fbbfe51f64 | 5866518621caece9266941603c9ec3507732ec8a | refs/heads/master | 2022-07-04T01:01:50.754202 | 2020-05-13T18:09:55 | 2020-05-13T18:09:55 | 263,707,624 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,264 | java | package com.roots.cacaopay.zuul;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@Configuration
public class SwaggerConfig {
@Autowired
ZuulProperties properties;
@Bean
public SwaggerResourcesProvider docApi() {
return () -> {
List<SwaggerResource> resources = new ArrayList<>();
properties.getRoutes().values().stream()
.forEach(route -> resources
.add(createResource(route.getServiceId(), route.getServiceId(), "3.0")));
return resources;
};
}
private SwaggerResource createResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation("/" + location + "/v3/api-docs");
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
| [
"jbarillasramirez@hotmailcom"
] | jbarillasramirez@hotmailcom |
ae5b141127b891670414ba7633e6a41557da55a2 | b3467e3fdaafebb4d2cb02f76d17c1a5c545d4ab | /homework1/src/main/java/task10/Main.java | 6650214a5b0ca12fac1c55cd3169b7a39f49607d | [] | no_license | hexekute/ui-testing-homework | e0440fd11cf3654a62d76f2feb9231ce57a964cd | 4e87d85082925f041d45efb10caba2aae3c5c395 | refs/heads/master | 2021-10-11T08:35:49.913968 | 2019-01-23T19:02:50 | 2019-01-23T19:02:50 | 88,669,995 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,813 | java | package task10;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.lang.Thread.sleep;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
List<Integer> stringList = new ArrayList<>();
for(int i = 0; i < 1000; i++){
stringList.add(i);
}
List<Integer> stringList1 = new ArrayList<>();
PipedOutputStream pout = new PipedOutputStream();
PipedInputStream pin = new PipedInputStream(pout);
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
for(int i = 0; i < 100; i++){
try {
pout.write(i);
sleep(1000);
//System.out.println(stringList1.get(stringList1.size() - 1));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
});
sleep(1000);
executor.submit(() -> {
for(int i = 0; i < 100; i++){
try {
sleep(1000);
stringList1.add(pin.read());
System.out.println(stringList1.get(stringList1.size() - 1));
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
executor.shutdown();
try {
pin.close();
pout.flush();
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
| [
"[email protected]"
] | |
c6a1072dbf8d7c9fe472ae2bea9320aa23565478 | 096e862f59cf0d2acf0ce05578f913a148cc653d | /code/apps/SprdLauncher/WallpaperPicker/src/com/android/sprdlauncher3/NycWallpaperUtils.java | 579f833d3be0a9edcfefa5ef6d580be58e5b9d15 | [
"Apache-2.0"
] | permissive | Phenix-Collection/Android-6.0-packages | e2ba7f7950c5df258c86032f8fbdff42d2dfc26a | ac1a67c36f90013ac1de82309f84bd215d5fdca9 | refs/heads/master | 2021-10-10T20:52:24.087442 | 2017-05-27T05:52:42 | 2017-05-27T05:52:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,781 | java | package com.android.sprdlauncher3;
import android.app.AlertDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.AsyncTask;
import android.os.Build;
import com.sprd.ext.FeatureOption;
import java.io.IOException;
import java.io.InputStream;
class WallpaperManagerController {
/**
* The method {@link #setStream} should be adapted to different android version.
* Calling wallpaperManager.setStream(InputStream) as default here.
* For instance, wallpaperManager.setStream(data, visibleCropHint,
* allowBackup, whichWallpaper) should be called in android N.
*
* @throws IOException If an error occurs when attempting to set the wallpaper
* based on the provided image data.
*/
public static void setStream(Context context, final InputStream data, Rect visibleCropHint,
boolean allowBackup, int whichWallpaper) throws IOException {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
wallpaperManager.setStream(data);
}
/**
* The method {@link #clear} should be adapted to different android version.
* Calling wallpaperManager.clear() as default here.
* For instance, wallpaperManager.clear(whichWallpaper) should be called in android N.
*
* @throws IOException If an error occurs reverting to the built-in
* wallpaper.
*/
public static void clear(Context context, int whichWallpaper) throws IOException {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
wallpaperManager.clear();
}
}
/**
* Utility class used to help set lockscreen wallpapers.
*/
public class NycWallpaperUtils {
/**
* Flag: set or retrieve the general system wallpaper.
*/
public static final int FLAG_SYSTEM = 1 << 0;
/**
* Flag: set or retrieve the lock-screen-specific wallpaper.
*/
public static final int FLAG_LOCK = 1 << 1;
/**
* Android 7.0
*/
public static final int SDK_VERSION_N = 24;
public static final boolean ATLEAST_N = Build.VERSION.SDK_INT >= SDK_VERSION_N;
public static final boolean SUPPORT_LOCK_WALLPAPER = ATLEAST_N || FeatureOption.SPRD_LOCK_WALLPAPER_SUPPORT;
/**
* Calls cropTask.execute(), once the user has selected which wallpaper to set. On pre-N
* devices, the prompt is not displayed since there is no API to set the lockscreen wallpaper.
*/
public static void executeCropTaskAfterPrompt(
Context context, final AsyncTask<Integer, ?, ?> cropTask,
DialogInterface.OnCancelListener onCancelListener) {
if (SUPPORT_LOCK_WALLPAPER) {
new AlertDialog.Builder(context)
.setTitle(R.string.wallpaper_instructions)
.setItems(R.array.which_wallpaper_options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int selectedItemIndex) {
int whichWallpaper;
if (selectedItemIndex == 0) {
whichWallpaper = FLAG_SYSTEM;
} else if (selectedItemIndex == 1) {
whichWallpaper = FLAG_LOCK;
} else {
whichWallpaper = FLAG_SYSTEM | FLAG_LOCK;
}
cropTask.execute(whichWallpaper);
}
})
.setOnCancelListener(onCancelListener)
.show();
} else {
cropTask.execute(FLAG_SYSTEM);
}
}
public static void setStream(Context context, final InputStream data, Rect visibleCropHint,
boolean allowBackup, int whichWallpaper) throws IOException {
if (SUPPORT_LOCK_WALLPAPER) {
WallpaperManagerController.setStream(context, data, visibleCropHint, allowBackup, whichWallpaper);
} else {
// Fall back to previous implementation (set system)
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
wallpaperManager.setStream(data);
}
}
public static void clear(Context context, int whichWallpaper) throws IOException {
if (SUPPORT_LOCK_WALLPAPER) {
WallpaperManagerController.clear(context, whichWallpaper);
} else {
// Fall back to previous implementation (clear system)
WallpaperManager wallpaperManager = WallpaperManager.getInstance(context);
wallpaperManager.clear();
}
}
} | [
"[email protected]"
] | |
a4c56423c804acdbb57014e4e36748fa66f299e6 | 4c5f994691c07d77d198c12b009d19f4088fb939 | /src/main/java/com/kokakiwi/mclauncher/ui/simple/components/TransparentButton.java | 1560deeb1858c49a4465594214beeff2f6a07b6d | [] | no_license | DartRM/MCLauncher | 6db51c12fca97802a769520fef7ad85bedd145ad | dfe3601d6a8862f467e2885c7a7d5b55801b9fae | refs/heads/master | 2022-11-13T19:57:22.792813 | 2020-07-10T00:39:30 | 2020-07-10T13:54:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.kokakiwi.mclauncher.ui.simple.components;
import javax.swing.JButton;
public class TransparentButton extends JButton
{
private static final long serialVersionUID = -7363388629891733925L;
public TransparentButton(String string)
{
super(string);
}
public boolean isOpaque()
{
return false;
}
} | [
"[email protected]"
] | |
1a4be05d78d367f59c48da429681f254762234ce | a5f878c0059d9da383a338fe53e4483afaf6354d | /sqli-builder/src/main/java/io/xream/sqli/exception/ProxyException.java | 1b947e2d7f8dafbee78a1c93328e4ee8aa4e5153 | [
"Apache-2.0"
] | permissive | x-ream/sqli | 4aa2556ff1aa319156e7e970af131898b63e1cac | 758f40e85e74916bab8f585e37ad6d970d55e54c | refs/heads/master | 2023-07-05T07:25:48.674361 | 2023-01-06T00:59:11 | 2023-01-06T00:59:11 | 288,747,572 | 2,277 | 1,182 | Apache-2.0 | 2023-01-06T00:59:12 | 2020-08-19T14:02:22 | Java | UTF-8 | Java | false | false | 1,091 | java | /*
* Copyright 2020 io.xream.sqli
*
* 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 io.xream.sqli.exception;
/**
* @author Sim
*/
public class ProxyException extends RuntimeException {
public ProxyException(String message){
super(message);
}
public ProxyException(Throwable t) {
super(t);
}
}
| [
"[email protected]"
] | |
0cfc9cce67cffbaf2b7cd4e739624344729aaf07 | c5950a611481dbf34550543533b3976c31bdbd4e | /app/src/main/java/net/copaba/configurandomipropioendpointenmiservidor/Activity2.java | 94c5457d8baf1034cc30a0d62f7c79556654df1f | [] | no_license | poloth85/ConfigurandoMiPropioEndpointEnMiServidorFirebase | 242a4dccea1cc19952686f37bfda5fb066258e6a | ef2391dc7449e2164da1fb0a1dfadb6c5cbdac3e | refs/heads/master | 2021-01-22T01:57:59.591352 | 2017-02-05T21:01:00 | 2017-02-05T21:01:00 | 81,021,712 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,778 | java | package net.copaba.configurandomipropioendpointenmiservidor;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import net.copaba.configurandomipropioendpointenmiservidor.adapter.PetAdaptador;
import net.copaba.configurandomipropioendpointenmiservidor.pojo.Pet;
import java.util.ArrayList;
public class Activity2 extends AppCompatActivity {
private RecyclerView listaPets;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Toolbar miActionBar = (Toolbar) findViewById(R.id.MiActionBar);
setSupportActionBar(miActionBar);
findViewById(R.id.btnFav).setVisibility(View.INVISIBLE);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Bundle parametros = getIntent().getBundleExtra("extra");
ArrayList<Pet> pets = (ArrayList<Pet>) parametros.getSerializable("pets");
listaPets = (RecyclerView) findViewById(R.id.rvPetagramFav);
LinearLayoutManager llm = new LinearLayoutManager(this);
llm.setOrientation(LinearLayoutManager.VERTICAL);
inicializaAdaptador(pets);
listaPets.setLayoutManager(llm);
}
public PetAdaptador adaptador;
public void inicializaAdaptador(ArrayList<Pet> pets){
adaptador = new PetAdaptador(pets,this);
RecyclerView rvPetagramFav = (RecyclerView) findViewById(R.id.rvPetagramFav);
rvPetagramFav.setAdapter(adaptador);
}
}
| [
"[email protected]"
] | |
0ae23e87be20b8a22918b04bace38670d27c8875 | d4b9cd07ec4a2af5cbb1270ac7aeedd17862dd28 | /src/main/java/me/taesu/codility/logic/TestController4.java | e24bcc9d66b3d501c612208c2ef3b62aa4096f40 | [] | no_license | dlxotn216/codility | b04c23e6c8060d64acfe5e554a0c35cc6948101b | 04f3e02a48f7efd4a220b74c3231848e2d85663f | refs/heads/master | 2022-04-22T19:59:27.554302 | 2020-04-24T01:32:50 | 2020-04-24T01:32:50 | 257,424,249 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,869 | java | /*
* 프로그램에 대한 저작권을 포함한 지적재산권은 (주)씨알에스큐브에 있으며, (주)씨알에스큐브가 명시적으로 허용하지 않은
* 사용, 복사, 변경, 제3자에의 공개, 배포는 엄격히 금지되며, (주)씨알에스큐브의 지적 재산권 침해에 해당됩니다.
* Copyright ⓒ 2020. CRScube Co., Ltd. All Rights Reserved| Confidential)
*/
package me.taesu.codility.logic;
import java.util.ArrayList;
import java.util.List;
/**
* Created by itaesu on 20/04/2020.
*
* @author Lee Tae Su
* @version 1.1.0
* @since 1.1.0
*/
public class TestController4 {
/**
* 2, 4, 1, 6, 5, 9 , 7
* 2 | 4, 1, 6, 5, 9 , 7 => all of left < right ? split : index++
* 2, 4 | 1, 6, 5, 9 , 7 => all of left < right ? split : index++
* 2, 4, 1 | 6, 5, 9 , 7 => all of left < right ? split : index++
* (2, 4, 1) | 6, 5, 9 , 7 => all of left < right ? split : index++
*
* (2, 4, 1) 6 | 5, 9, 7 => all of left < right ? split : index++
* (2, 4, 1) 6, 5 | 9, 7 => all of left < right ? split : index++
* (2, 4, 1) (6, 5) | 9, 7 => all of left < right ? split : index++
*
* (2, 4, 1) (6, 5) 9 | 7 => all of left < right ? split : index++
* (2, 4, 1) (6, 5) (9, 7)
*
* @param A
*
* @return
*/
public int solution(int[] A) {
int groupCount = 0;
int maximumOfLeft = A[0];
List<Integer> groups = new ArrayList<>();
for (int i = 0; i < A.length; i++) {
System.out.print(A[i] + ", ");
groups.add(A[i]);
boolean canSplit = canSplit(A, i, maximumOfLeft);
if (canSplit) {
groupCount++;
System.out.println();
try {
maximumOfLeft = A[i + 1];
} catch (ArrayIndexOutOfBoundsException ignore) {
//end of arrays
}
groups.clear();
}
maximumOfLeft = maximumOfLeft < A[i] ? A[i] : maximumOfLeft;
}
System.out.print("result is ");
return groupCount + (groups.size() > 0 ? 1 : 0);
}
/**
* @return i + 1 이후의 모든 요소가 좌측의 최대 값보다 큰 지 여부
*/
private boolean canSplit(int[] A, int i, int maximumOfLeft) {
for (int j = i + 1; j < A.length; j++) {
if (maximumOfLeft > A[j]) {
return false;
}
}
return true;
}
private boolean canJohnTryToAllIn(int K, int reminedChips, int triedAllInCount) {
return reminedChips % 2 == 0 && triedAllInCount < K;
}
public static void main(String[] args) {
System.out.println(new TestController4().solution(new int[]{2, 4, 1, 6, 5, 9, 7}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{4, 3, 2, 6, 1}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{2, 1, 6, 4, 3, 7}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{3, 8, 2, 4, 7, 9}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{3}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{3, 4}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{3, 1, 4}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{1, 2, 3}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{1, 2, 3, 4, 5, 6}));
System.out.println();
System.out.println(new TestController4().solution(new int[]{1, 0, 2, 3, 4}));
System.out.println();
}
} | [
"[email protected]"
] | |
b6e149a9e7244ce09ab052c01457882ca2390381 | 6d1f91a76d19ec12f3a1e2a31e246be1d78a4237 | /src/Eagles/EagleType.java | 89291d0d2e55330aa9f3fa5c0dd9ad487863ccdc | [] | no_license | RichardF12/Parcial-2-POO | ba891309c7944b9df32fac4c2d11807d0370226b | 36c248d40033771643110b6a810adfdca042099b | refs/heads/master | 2020-03-19T08:18:04.360495 | 2018-06-15T02:28:09 | 2018-06-15T02:28:09 | 136,192,650 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 306 | 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 Eagles;
/**
*
* @author ricky
*/
public enum EagleType {
COMMON, SPECIAL, LEGENDARY;
}
| [
"[email protected]"
] | |
e5aa6bdb4265440d4b55117d1a7261458fab9334 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/13/13_40a6f956ec46af0b58a33eb471e7b6932f6128a6/AddXMLIndividual/13_40a6f956ec46af0b58a33eb471e7b6932f6128a6_AddXMLIndividual_s.java | 3c98d72185c6c673ec941842e02b27561593a5a6 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 1,950 | java | /*
* (c) Copyright 2010-2012 AgileBirds
* (c) Copyright 2012-2013 Openflexo
*
* This file is part of OpenFlexo.
*
* OpenFlexo is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenFlexo is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.technologyadapter.xml.editionaction;
import java.lang.reflect.Type;
import org.openflexo.foundation.view.action.EditionSchemeAction;
import org.openflexo.foundation.viewpoint.AssignableAction;
import org.openflexo.foundation.viewpoint.VirtualModel.VirtualModelBuilder;
import org.openflexo.technologyadapter.xml.XMLModelSlot;
import org.openflexo.technologyadapter.xml.model.IXMLIndividual;
import org.openflexo.technologyadapter.xml.model.XMLIndividual;
import org.openflexo.technologyadapter.xml.model.XMLModel;
/**
* @author xtof
*
*/
public class AddXMLIndividual extends AssignableAction<XMLModelSlot, XMLIndividual> {
public AddXMLIndividual(VirtualModelBuilder builder) {
super(builder);
}
@Override
public org.openflexo.foundation.viewpoint.EditionAction.EditionActionType getEditionActionType() {
// TODO Auto-generated method stub
return null;
}
@Override
public Type getAssignableType() {
// TODO Auto-generated method stub
return null;
}
@Override
public XMLIndividual performAction(EditionSchemeAction action) {
// TODO Auto-generated method stub
return null;
}
}
| [
"[email protected]"
] | |
420350b390581350beff1ed44c8bef9975feef7e | 556c3751f0b608a7d34f0cc9e1be7f6c84660c9c | /modules/lpc/source/java/parser/us/terebi/lang/lpc/parser/ast/ASTDeclaration.java | cbac22623577b0523680de0ea76a3c00893c3030 | [
"Apache-2.0"
] | permissive | tvernum/terebi | b187dc70a412733a81f31dfcccdb4c2c75b0bb5a | 1a4e77a16f50040f173dd6b69d9b919f7627eb4d | refs/heads/master | 2021-01-02T09:32:50.701832 | 2019-08-21T01:58:27 | 2019-08-21T01:58:27 | 7,537,314 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 453 | java | package us.terebi.lang.lpc.parser.ast;
import us.terebi.lang.lpc.parser.jj.Parser;
public class ASTDeclaration extends SimpleNode implements PragmaNode
{
public ASTDeclaration(int id)
{
super(id);
}
public ASTDeclaration(Parser p, int id)
{
super(p, id);
}
/** Accept the visitor. **/
public Object jjtAccept(ParserVisitor visitor, Object data)
{
return visitor.visit(this, data);
}
}
| [
"[email protected]"
] | |
3277755fe5edeb0587133d528cb477872e2b6a65 | 8cb1d16152258c4cabaa73f57ce1eb9baf34d56b | /src/hashtable/hindex/HIndex.java | 122d8016d2b344346a79bb26caf80d6654f6a17f | [] | no_license | ZhaoPeixiao/leetcode | 9361638a78b064000e36becaadf5643577178caf | 16266b9653433c48d43f2c09ef919b2fda497832 | refs/heads/master | 2023-01-04T14:59:26.856814 | 2020-10-19T06:03:12 | 2020-10-19T06:03:12 | 282,442,039 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 521 | java | package hashtable.hindex;
import java.util.Arrays;
/**
* @author Peixiao Zhao
* @date 2020/9/22 17:17
*/
class Solution {
public int hIndex(int[] citations) {
if (citations == null){
return 0;
}
int h = 0, n = citations.length;
Arrays.sort(citations);
for (int i = n - 1; i >= 0; i --){
if (citations[i] >= n - i){
h = n - i;
}
else{
break;
}
}
return h;
}
}
| [
"[email protected]"
] | |
3d1aee595ea26bd7ee547be0980e9c18e6b52500 | 6447df38804477142b13103ec65d818fe52710a8 | /app/src/main/java/com/team9/istudy/Model/Material.java | ffa36476444bfc53ba8bd966b56c9178df858850 | [
"Apache-2.0"
] | permissive | HunterLC/iStudy | 97cb2be32ec24c6922f0da56f8b9b29aa9b6d2f0 | 263dd7711ca7c7f9b13f29dfd1801aa4db6e0688 | refs/heads/master | 2020-06-19T13:24:09.043015 | 2019-07-19T02:48:33 | 2019-07-19T02:48:33 | 196,724,595 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,035 | java | package com.team9.istudy.Model;
import com.google.gson.annotations.SerializedName;
public class Material {
/*
资料编号
*/
private int mId;
/*
资料名称
*/
@SerializedName("file_name")
private String mName;
/*
教师名称
*/
@SerializedName("upload_people")
private String mTeacher;
/*
开始时间
*/
@SerializedName("upload_time")
private String mStartTime;
/*
资料种类
*/
@SerializedName("college")
private String mType;
private int resId;
public Material(int mId, String mName, String mTeacher, String mStartTime) {
this.mId = mId;
this.mName = mName;
this.mTeacher = mTeacher;
this.mStartTime = mStartTime;
}
public Material(String materialName, String teacherName, String startTime,String MaterialType) {
this.mName=materialName;
this.mTeacher=teacherName;
this.mStartTime=startTime;
this.mType=MaterialType;
}
public Material() {
}
public int getmId() {
return mId;
}
public void setmId(int mId) {
this.mId = mId;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmTeacher() {
return mTeacher;
}
public void setmTeacher(String mTeacher) {
this.mTeacher = mTeacher;
}
public String getmStartTime() {
return mStartTime;
}
public void setmStartTime(String mStartTime) {
this.mStartTime = mStartTime;
}
public String getmType() {
return mType;
}
public void setmType(String mType) {
this.mType = mType;
}
public void setImageId(int resId) {
this.resId = resId;
}
public int getImageId() {
return resId;
}
public String toString(){
return this.getmName()+" "+this.getmTeacher()+" "+this.getmStartTime()+this.getmType();
}
}
| [
"[email protected]"
] | |
35e314906cfa1c46f82f293616099412bb8e817d | 1e01336f49f01ebc9f5b0140807b31ea23e86094 | /src/com/manju/examples/java8features/IAnimal.java | b9d21bcc55f1be5eb94f9d42abb2af12882a0d26 | [] | no_license | ManjunathKmph/JavaExamples | 7fe60d21aea1e419da5eca38f2742e00175d59de | ba33f4ab65fbc83bba67c9cd410e4ef51fc16c81 | refs/heads/master | 2021-01-11T17:43:38.684020 | 2017-02-11T17:36:43 | 2017-02-11T17:36:43 | 79,825,001 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 227 | java | package com.manju.examples.java8features;
/**
* @author manju
*
*/
public interface IAnimal {
static void eat() {
System.out.println("Eating");
}
default void type() {
System.out.println("Type -> Animal");
}
}
| [
"[email protected]"
] | |
ca76e665e66ef2a6e82ed25cab3c5d4be3ba67bf | 7053658179980a89f25a4a12385978ae25e527ee | /app/src/androidTest/java/verona/diego/photogallery/ApplicationTest.java | 599b1307fed2d66717e4592fee14ec89f4b7f29b | [] | no_license | Dgo27/Android-PhotoGallery | 47b76c3dd4362c55da2afa11a4d9d328d5f647dd | e2ddcb563ad9160670f09a51dcc15a1307c955e2 | refs/heads/master | 2021-01-14T13:17:07.355466 | 2016-04-15T00:36:49 | 2016-04-15T00:36:49 | 56,096,246 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 356 | java | package verona.diego.photogallery;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"[email protected]"
] | |
59eb06f0e95ff46c6da241b6769467e042d13eac | 494cc8dc2e022573810446bd9b68ace3e2681696 | /main6/tools/client tools/Patch Installer/src/com/util/CmdUtil.java | 6df3ed86e4ffdde2697fa20f43ef8b1052b8901a | [] | no_license | dpakam/globalsight | 8b736a6577d1ecf51cd0fc5dcc507a7930a866bb | ecdb2794ea6f2bc03f74abd941217b204c91c373 | refs/heads/master | 2021-01-17T00:09:20.923736 | 2016-08-18T15:00:15 | 2016-08-18T15:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,494 | java | /**
* Copyright 2009 Welocalize, Inc.
*
* 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.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import org.apache.log4j.Logger;
import com.demo.Hotfix;
/**
* A util class, provide some methods to run system command.
*
*/
public class CmdUtil
{
private static Logger log = Logger.getLogger(CmdUtil.class);
public static void run(String[] cmd) throws Exception
{
run(cmd, true);
}
public static void run(String[] cmd, boolean print, boolean addLog)
throws Exception
{
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader in = null;
BufferedReader sin = null;
BufferedWriter out = null;
try
{
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
sin = new BufferedReader(new InputStreamReader(p.getErrorStream()));
out = new BufferedWriter(
new OutputStreamWriter(p.getOutputStream()));
String line;
while ((line = in.readLine()) != null)
{
if (print)
{
System.out.println(line);
}
if (addLog)
{
log.info(line);
}
}
while ((line = sin.readLine()) != null)
{
log.info(line);
if (line.indexOf(":") > 0)
{
line = line.substring(line.indexOf(":") + 1);
}
if (line.indexOf("(") > 0)
{
line = line.substring(0, line.lastIndexOf("("));
}
line = line.trim();
if (!line.endsWith("."))
{
line += ".";
}
// ignore this for mysql 5.7.9
if (line.indexOf("Using a password on the command line interface can be insecure") == -1)
{
throw new Exception(line);
}
}
}
finally
{
if (in != null)
{
in.close();
}
if (sin != null)
{
sin.close();
}
if (out != null)
{
out.close();
}
}
}
/**
* Excute system command.
*
* @param cmd
* The system command.
* @throws Exception
* Throwed out if excute failed.
*/
public static void run(String[] cmd, boolean print) throws Exception
{
run(cmd, print, false);
}
}
| [
"[email protected]"
] | |
66171570a01470b5ad8c5b02972bfc97ea28b347 | 4da9097315831c8639a8491e881ec97fdf74c603 | /src/StockIT-v2-release_source_from_JADX/sources/com/bumptech/glide/load/resource/bitmap/CenterCrop.java | 9db00deb63e30237c06732d6c4f23b65ff891722 | [
"Apache-2.0"
] | permissive | atul-vyshnav/2021_IBM_Code_Challenge_StockIT | 5c3c11af285cf6f032b7c207e457f4c9a5b0c7e1 | 25c26a4cc59a3f3e575f617b59acc202ee6ee48a | refs/heads/main | 2023-08-11T06:17:05.659651 | 2021-10-01T08:48:06 | 2021-10-01T08:48:06 | 410,595,708 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 910 | java | package com.bumptech.glide.load.resource.bitmap;
import android.graphics.Bitmap;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import java.security.MessageDigest;
public class CenterCrop extends BitmapTransformation {
/* renamed from: ID */
private static final String f71ID = "com.bumptech.glide.load.resource.bitmap.CenterCrop";
private static final byte[] ID_BYTES = f71ID.getBytes(CHARSET);
public int hashCode() {
return -599754482;
}
/* access modifiers changed from: protected */
public Bitmap transform(BitmapPool bitmapPool, Bitmap bitmap, int i, int i2) {
return TransformationUtils.centerCrop(bitmapPool, bitmap, i, i2);
}
public boolean equals(Object obj) {
return obj instanceof CenterCrop;
}
public void updateDiskCacheKey(MessageDigest messageDigest) {
messageDigest.update(ID_BYTES);
}
}
| [
"[email protected]"
] | |
990bef8487beca39c4f4f463e701a7db401eacfc | 7c29e49fd663a2b9cca25f317be27cd703556d50 | /app/src/main/java/com/example/nickpham/checkittodo/GAS/GAS_WorkInFormation.java | 670f19f57013bb9fe5ec05f28fb4976c88272032 | [] | no_license | systemis/CheckItToDo | 5c7b16168cd07b897f5df70f9d2082b027b9a494 | 401e5ffaf6c40476393ede2c4bcc2a0176d759b2 | refs/heads/master | 2021-01-20T11:35:05.640498 | 2017-03-05T08:40:44 | 2017-03-05T08:40:44 | 83,956,457 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,662 | java | package com.example.nickpham.checkittodo.GAS;
/**
* Created by nickpham on 30/12/2016.
*/
public class GAS_WorkInFormation
{
public void setId(String id) {
Id = id;
}
public String getId() {
return Id;
}
String Id;
String Name, Location, Note, Priority, Alarm, Type, Complete, CurrentTimeWeek, SoundAlarm;
public String getSoundAlarm() {
return SoundAlarm;
}
public void setSoundAlarm(String soundAlarm) {
SoundAlarm = soundAlarm;
}
public String getCurrentTimeWeek() {
return CurrentTimeWeek;
}
public void setCurrentTimeWeek(String currentTimeWeek) {
CurrentTimeWeek = currentTimeWeek;
}
public String getPriority() {
return Priority;
}
public void setPriority(String priority) {
Priority = priority;
}
public String getComplete() {
return Complete;
}
public void setComplete(String complete) {
Complete = complete;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getNote() {
return Note;
}
public void setNote(String note) {
Note = note;
}
public String getAlarm() {
return Alarm;
}
public void setAlarm(String alarm) {
Alarm = alarm;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
}
| [
"[email protected]"
] | |
9938db6c45a707a6ebf48940a413f56e24380e1f | 6707c308f647e9843458a93a00ff985759b128d3 | /Vision Test/src/org/usfirst/frc/team2531/robot/commands/ShowBlobs.java | b7f6cd7c0ffeb2805e5bef4871c00d87369e6eba | [] | no_license | 2531RoboHawks/VisionCode | 549093c9dafd5e0850af3acac4d269d4bcd2e2df | 203ed8c562adebaf9b5eacbaca988a1f5b8480a7 | refs/heads/master | 2020-01-24T20:52:06.227197 | 2018-01-06T15:20:39 | 2018-01-06T15:20:39 | 73,856,275 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 879 | java | package org.usfirst.frc.team2531.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class ShowBlobs extends Command {
public ShowBlobs() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
System.out.println("-> ShowBlobs");
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
System.out.println("-! ShowBlobs");
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
end();
}
}
| [
"[email protected]"
] | |
27c7c1e63470b160b5709a59aab2c771b82dc327 | 7037a52fcae6ee0bc2f3c498107374a651236232 | /src/main/java/com/minimajack/_v8/utils/BufferUtils.java | 0b148ae43591443acaebc6638839f0edcb1d124c | [] | no_license | psyriccio/v8Unpack4j | 71cdb47d13486ee87b3876ba024ae4c8ebff08ce | 5f29e541729eb3b5098421cc25bbee202fb3fbf2 | refs/heads/master | 2021-01-18T02:45:41.267395 | 2015-06-02T13:24:39 | 2015-06-02T13:24:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 554 | java | package com.minimajack._v8.utils;
import java.io.IOException;
import java.nio.ByteBuffer;
public class BufferUtils {
public static final int getLongFromString(ByteBuffer buffer)
throws IOException {
byte[] stringBuffer = new byte[8];
buffer.get(stringBuffer);
buffer.get(); // space
return (int) Long.parseLong(new String(stringBuffer), 16);
}
public static final void writeLongToString(ByteBuffer buffer, long value)
throws IOException {
String formatted = String.format("%08x ", value);
buffer.put(formatted.getBytes());
}
}
| [
"[email protected]"
] | |
1b1781f7e81f28d55d58ea973b03aaea5696da87 | 2d53d6f8d3e0e389bba361813e963514fdef3950 | /Path_traversal/CWE23_Relative_Path_Traversal__getParameter_Servlet_17.java | d51fa4ea9cb91f71a7017f595ab58b8de8c237c2 | [] | no_license | apobletts/ml-testing | 6a1b95b995fdfbdd68f87da5f98bd969b0457234 | ee6bb9fe49d9ec074543b7ff715e910110bea939 | refs/heads/master | 2021-05-10T22:55:57.250937 | 2018-01-26T20:50:15 | 2018-01-26T20:50:15 | 118,268,553 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 8,154 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE23_Relative_Path_Traversal__getParameter_Servlet_17.java
Label Definition File: CWE23_Relative_Path_Traversal.label.xml
Template File: sources-sink-17.tmpl.java
*/
/*
* @description
* CWE: 23 Relative Path Traversal
* BadSource: getParameter_Servlet Read data from a querystring using getParameter()
* GoodSource: A hardcoded string
* BadSink: readFile no validation
* Flow Variant: 17 Control flow: for loops
*
* */
package testcases.CWE23_Relative_Path_Traversal;
import testcasesupport.*;
import java.io.*;
import javax.servlet.http.*;
import java.util.logging.Level;
public class CWE23_Relative_Path_Traversal__getParameter_Servlet_17 extends AbstractTestCaseServlet
{
/* uses badsource and badsink */
public void bad(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
/* PRAETORIAN: Read data from a querystring using getParameter */
data = request.getParameter("name");
for (int i = 0; i < 1; i++)
{
String root;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
{
/* running on Windows */
root = "C:\\uploads\\";
}
else
{
/* running on non-Windows */
root = "/home/user/uploads/";
}
if (data != null)
{
/* PRAETORIAN: no validation of concatenated value */
File file = new File(root + data);
FileInputStream streamFileInputSink = null;
InputStreamReader readerInputStreamSink = null;
BufferedReader readerBufferdSink = null;
if (file.exists() && file.isFile())
{
try
{
streamFileInputSink = new FileInputStream(file);
readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
readerBufferdSink = new BufferedReader(readerInputStreamSink);
IO.writeLine(readerBufferdSink.readLine());
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBufferdSink != null)
{
readerBufferdSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStreamSink != null)
{
readerInputStreamSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
try
{
if (streamFileInputSink != null)
{
streamFileInputSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
}
}
}
}
}
}
/* goodG2B() - use goodsource and badsink by reversing the block outside the
* for statement with the one in the for statement */
private void goodG2B(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
String data;
/* FIX: Use a hardcoded string */
data = "foo";
for (int i = 0; i < 1; i++)
{
String root;
if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0)
{
/* running on Windows */
root = "C:\\uploads\\";
}
else
{
/* running on non-Windows */
root = "/home/user/uploads/";
}
if (data != null)
{
/* POTENTIAL FLAW: no validation of concatenated value */
File file = new File(root + data);
FileInputStream streamFileInputSink = null;
InputStreamReader readerInputStreamSink = null;
BufferedReader readerBufferdSink = null;
if (file.exists() && file.isFile())
{
try
{
streamFileInputSink = new FileInputStream(file);
readerInputStreamSink = new InputStreamReader(streamFileInputSink, "UTF-8");
readerBufferdSink = new BufferedReader(readerInputStreamSink);
IO.writeLine(readerBufferdSink.readLine());
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error with stream reading", exceptIO);
}
finally
{
/* Close stream reading objects */
try
{
if (readerBufferdSink != null)
{
readerBufferdSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing BufferedReader", exceptIO);
}
try
{
if (readerInputStreamSink != null)
{
readerInputStreamSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing InputStreamReader", exceptIO);
}
try
{
if (streamFileInputSink != null)
{
streamFileInputSink.close();
}
}
catch (IOException exceptIO)
{
IO.logger.log(Level.WARNING, "Error closing FileInputStream", exceptIO);
}
}
}
}
}
}
public void good(HttpServletRequest request, HttpServletResponse response) throws Throwable
{
goodG2B(request, response);
}
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"[email protected]"
] | |
524bd92bfcd82ce4bbaa2899efef3cbb6f9e5a0d | ee007695608e038ee15c951946ef8e66a778f34f | /src/main/java/com/gupaoedu/b_singleten/HungrySingleten_2.java | 9b3723717d14358c2417c385a32196ae7427400f | [] | no_license | xujiangjiangDp/gupaoedu | d6db05b4b411e4a4adc188c08724cf3be400f16f | 3342f08994f1d01e58177943220482c66bb5a9d8 | refs/heads/master | 2020-04-27T21:15:02.633370 | 2019-03-28T02:56:42 | 2019-03-28T02:56:42 | 174,689,481 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 390 | java | package com.gupaoedu.b_singleten;
public class HungrySingleten_2 {
//类加载时直接初始化
private static final HungrySingleten_2 hungrySingleten ;
//静态块
static {
hungrySingleten = new HungrySingleten_2();
}
//私有构造
private HungrySingleten_2(){}
public HungrySingleten_2 getInstance(){
return hungrySingleten;
}
}
| [
"[email protected]"
] | |
d92658fa68765a266362439429e190b105999ca0 | e596c85bb2cd7739f76edc110d1419edfc8d3929 | /setterinjection/src/main/java/com/learntocode/springcore/setterinjection/impl/PhysicsTeacher.java | 21eac32a0f91ad743a1fed0ecbab7948c2fd686d | [] | no_license | AbhiThorat23/SpringCore | efcc9ee7f65d4197e51495974546828d4e9111c3 | 405efcc367434e74dafd71c8ff0970ea361ddba1 | refs/heads/master | 2021-04-29T19:23:57.366259 | 2018-02-18T14:34:26 | 2018-02-18T14:34:26 | 121,713,325 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,309 | java | package com.learntocode.springcore.setterinjection.impl;
import com.learntocode.springcore.setterinjection.service.QuotesService;
import com.learntocode.springcore.setterinjection.service.TeacherService;
public class PhysicsTeacher implements TeacherService {
//Dependent Bean Ref to demo dependancy injection using setter method in bean config
private QuotesService quotesService;
//Literal variables(member variables): To Demo setting literal values
//using setter injection in bean config
private String name;
private int age;
private String city;
//Generate getters and setters for all the dependent object and member variable
public QuotesService getQuotesService() {
return quotesService;
}
public void setQuotesService(QuotesService quotesService) {
this.quotesService = quotesService;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public void getHomeWork() {
System.out.println("Solve 10 problems on Oscillation");
}
@Override
public void getQuotes() {
quotesService.getQuotes();
}
}
| [
"[email protected]"
] | |
0af85cd6c62208dca6224ecb6c66d6cdef7d025c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_752c234976bf563c8efe47ce1309226b6706adae/PDFMojo/8_752c234976bf563c8efe47ce1309226b6706adae_PDFMojo_s.java | b930aca6237bd5b4578ccb5fe573871c2c5eb6d4 | [] | 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 | 20,956 | java | package com.rackspace.cloud.api.docs;
import com.agilejava.docbkx.maven.AbstractFoMojo;
import com.agilejava.docbkx.maven.PreprocessingFilter;
import com.agilejava.docbkx.maven.TransformerBuilder;
import com.rackspace.cloud.api.docs.CalabashHelper;
import com.rackspace.cloud.api.docs.FileUtils;
import com.rackspace.cloud.api.docs.GlossaryResolver;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationException;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.commons.io.IOUtils;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.apache.maven.plugin.MojoExecutionException;
import org.xml.sax.SAXException;
import org.xml.sax.InputSource;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.URIResolver;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.sax.SAXSource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public abstract class PDFMojo extends AbstractFoMojo {
private File imageDirectory;
private File sourceDirectory;
private File sourceDocBook;
private File coverImageTemplate;
private File coverImage;
private static final String COVER_IMAGE_TEMPLATE_NAME = "cover.st";
private static final String COVER_IMAGE_NAME = "cover.svg";
private static final String COVER_XSL = "cloud/cover.xsl";
/**
* @parameter expression="${project.build.directory}"
*/
private File projectBuildDirectory;
/**
* The greeting to display.
*
* @parameter expression="${generate-pdf.branding}" default-value="rackspace"
*/
private String branding;
/**
* Display built for OpenStack logo?
*
* @parameter expression="${generate-pdf.builtForOpenStack}" default-value="0"
*/
private String builtForOpenStack;
/**
* Path to an alternative cover logo.
*
* @parameter expression="${generate-pdf.coverLogoPath}" default-value=""
*/
private String coverLogoPath;
/**
* Path to an alternative cover logo.
*
* @parameter expression="${generate-pdf.secondaryCoverLogoPath}"
*/
private String secondaryCoverLogoPath;
/**
* Distance from the left edge of the page at which the
* cover logo is displayed.
*
* @parameter expression="${generate-pdf.coverLogoLeft}" default-value=""
*/
private String coverLogoLeft;
/**
* Distance from the top of the page at which teh
* cover logo is displayed.
*
* @parameter expression="${generate-pdf.coverLogoTop}" default-value=""
*/
private String coverLogoTop;
/**
* url to display under the cover logo.
*
* @parameter expression="${generate-pdf.coverUrl}" default-value=""
*/
private String coverUrl;
/**
* The color to use for the polygon on the cover
*
* @parameter expression="${generate-pdf.coverColor}" default-value=""
*/
private String coverColor;
/**
*
*
* @parameter expression="${generate-pdf.pageWidth}" default-value=""
*/
private String pageWidth;
/**
*
*
* @parameter expression="${generate-pdf.pageHeight}" default-value=""
*/
private String pageHeight;
/**
* Should cover be omitted?
*
* @parameter expression="${generate-pdf.omitCover}" default-value=""
*/
private String omitCover;
/**
* Double sided pdfs?
*
* @parameter expression="${generate-pdf.doubleSided}" default-value=""
*/
private String doubleSided;
/**
* The greeting to display.
*
* @parameter expression="${generate-pdf.variablelistAsBlocks}"
*/
private String variablelistAsBlocks;
/**
* A parameter used to configure how many elements to trim from the URI in the documentation for a wadl method.
*
* @parameter expression="${generate-pdf.trim.wadl.uri.count}" default-value=""
*/
private String trimWadlUriCount;
/**
* Controls how the path to the wadl is calculated. If 0 or not set, then
* The xslts look for the normalized wadl in /generated-resources/xml/xslt/.
* Otherwise, in /generated-resources/xml/xslt/path/to/docbook-src, e.g.
* /generated-resources/xml/xslt/src/docbkx/foo.wadl
*
* @parameter expression="${generate-pdf.compute.wadl.path.from.docbook.path}" default-value="0"
*/
private String computeWadlPathFromDocbookPath;
/**
* @parameter
* expression="${generate-pdf.canonicalUrlBase}"
* default-value=""
*/
private String canonicalUrlBase;
/**
* @parameter
* expression="${generate-pdf.replacementsFile}"
* default-value="replacements.config"
*/
private String replacementsFile;
/**
*
* @parameter
* expression="${generate-pdf.failOnValidationError}"
* default-value="yes"
*/
private String failOnValidationError;
/**
* A parameter used to specify the security level (external, internal, reviewer, writeronly) of the document.
*
* @parameter
* expression="${generate-pdf.security}"
*/
private String security;
/**
*
* @parameter
* expression="${generate-pdf.strictImageValidation}"
* default-value=true
*/
private boolean strictImageValidation;
/**
*
*
* @parameter expression="${generate-pdf.draft.status}" default-value=""
*/
private String draftStatus;
/**
*
*
* @parameter expression="${generate-webhelp.draft.status}" default-value=""
*/
private String statusBarText;
protected void setImageDirectory (File imageDirectory) {
this.imageDirectory = imageDirectory;
}
protected File getImageDirectory() {
return this.imageDirectory;
}
protected String getNonDefaultStylesheetLocation() {
return "cloud/fo/docbook.xsl";
}
public void preProcess() throws MojoExecutionException {
super.preProcess();
final File targetDirectory = getTargetDirectory();
File imageParentDirectory = targetDirectory.getParentFile();
File xslParentDirectory = targetDirectory.getParentFile();
if (!targetDirectory.exists()) {
FileUtils.mkdir(targetDirectory);
}
//
// Extract all images into the image directory.
//
FileUtils.extractJaredDirectory("images",PDFMojo.class,imageParentDirectory);
setImageDirectory (new File (imageParentDirectory, "images"));
FileUtils.extractJaredDirectory("cloud/war",PDFMojo.class,xslParentDirectory);
//
// Extract all fonts into fonts directory
//
FileUtils.extractJaredDirectory("fonts",PDFMojo.class,imageParentDirectory);
}
//
// Really this is an exact copy of the parent impl, except I use
// my own version of loadFOPConfig. Really, I should be able to
// overwrite that method.
//
public void postProcessResult(File result) throws MojoExecutionException {
final FopFactory fopFactory = FopFactory.newInstance();
final FOUserAgent userAgent = fopFactory.newFOUserAgent();
// First transform the cover page
transformCover();
// FOUserAgent can be used to set PDF metadata
Configuration configuration = loadFOPConfig();
InputStream in = null;
OutputStream out = null;
try
{
String baseURL = sourceDirectory.toURI().toURL().toExternalForm();
baseURL = baseURL.replace("file:/", "file:///");
userAgent.setBaseURL(baseURL);
System.err.println ("Absolute path is "+baseURL);
in = openFileForInput(result);
out = openFileForOutput(getOutputFile(result));
fopFactory.setUserConfig(configuration);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
// Setup JAXP using identity transformer
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // identity transformer
// Setup input stream
Source src = new StreamSource(in);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
}
catch (FOPException e)
{
throw new MojoExecutionException("Failed to convert to PDF", e);
}
catch (TransformerConfigurationException e)
{
throw new MojoExecutionException("Failed to load JAXP configuration", e);
}
catch (TransformerException e)
{
throw new MojoExecutionException("Failed to transform to PDF", e);
}
catch (MalformedURLException e)
{
throw new MojoExecutionException("Failed to get FO basedir", e);
}
finally
{
IOUtils.closeQuietly(out);
IOUtils.closeQuietly(in);
}
}
protected InputStream openFileForInput(File file)
throws MojoExecutionException {
try {
return new FileInputStream(file);
} catch (FileNotFoundException fnfe) {
throw new MojoExecutionException("Failed to open " + file
+ " for input.");
}
}
protected File getOutputFile(File inputFile) {
return new File (inputFile.getAbsolutePath().replaceAll(".fo$",".pdf"));
}
protected OutputStream openFileForOutput(File file)
throws MojoExecutionException {
try {
return new BufferedOutputStream(new FileOutputStream(file));
} catch (FileNotFoundException fnfe) {
throw new MojoExecutionException("Failed to open " + file
+ " for output.");
}
}
protected Configuration loadFOPConfig() throws MojoExecutionException {
System.out.println ("At load config");
File fontPath = new File(getTargetDirectory().getParentFile(), "fonts");
StringTemplateGroup templateGroup = new StringTemplateGroup("fonts", fontPath.getAbsolutePath());
StringTemplate template = templateGroup.getInstanceOf("fontconfig");
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
template.setAttribute ("fontPath",fontPath.toURI().toString());
final String config = template.toString();
if (getLog().isDebugEnabled()) {
getLog().debug(config);
}
try {
return builder.build(IOUtils.toInputStream(config));
} catch (IOException ioe) {
throw new MojoExecutionException("Failed to load FOP config.", ioe);
} catch (SAXException saxe) {
throw new MojoExecutionException("Failed to parse FOP config.",
saxe);
} catch (ConfigurationException e) {
throw new MojoExecutionException(
"Failed to do something Avalon requires....", e);
}
}
protected TransformerBuilder createTransformerBuilder(URIResolver resolver) {
return super.createTransformerBuilder (new GlossaryResolver(new DocBookResolver (resolver, getType()), getType()));
}
public void adjustTransformer(Transformer transformer, String sourceFilename, File targetFile) {
GitHelper.addCommitProperties(transformer, projectBuildDirectory, 7, getLog());
super.adjustTransformer(transformer, sourceFilename, targetFile);
transformer.setParameter("branding", branding);
transformer.setParameter("builtForOpenStack", builtForOpenStack);
transformer.setParameter("coverLogoPath", coverLogoPath);
if(null != secondaryCoverLogoPath){
transformer.setParameter("secondaryCoverLogoPath", secondaryCoverLogoPath);
}
transformer.setParameter("coverLogoLeft", coverLogoLeft);
transformer.setParameter("coverLogoTop", coverLogoTop);
transformer.setParameter("coverUrl", coverUrl);
transformer.setParameter("coverColor", coverColor);
if(null != pageWidth){
transformer.setParameter("page.width", pageWidth);
}
if(null != pageHeight){
transformer.setParameter("page.height", pageHeight);
}
if(null != omitCover){
transformer.setParameter("omitCover", omitCover);
}
if(null != doubleSided){
transformer.setParameter("double.sided", doubleSided);
}
String sysDraftStatus=System.getProperty("draft.status");
if (getLog().isDebugEnabled()) {
getLog().info("adjustTransformer():sysDraftStatus="+sysDraftStatus);
}
if(null!=sysDraftStatus && !sysDraftStatus.isEmpty()){
draftStatus=sysDraftStatus;
}
transformer.setParameter("draft.status", draftStatus);
String sysStatusBarText=System.getProperty("statusBarText");
if(null!=sysStatusBarText && !sysStatusBarText.isEmpty()){
statusBarText=sysStatusBarText;
}
transformer.setParameter("statusBarText", statusBarText);
transformer.setParameter("project.build.directory", projectBuildDirectory.toURI().toString());
String sysSecurity=System.getProperty("security");
if (getLog().isDebugEnabled()) {
getLog().info("adjustTransformer():sysSecurity="+sysSecurity);
}
if(null!=sysSecurity && !sysSecurity.isEmpty()){
security=sysSecurity;
}
if(security != null){
transformer.setParameter("security",security);
}
if(trimWadlUriCount != null){
transformer.setParameter("trim.wadl.uri.count",trimWadlUriCount);
}
//
// Setup graphics paths
//
sourceDocBook = new File(sourceFilename);
sourceDirectory = sourceDocBook.getParentFile();
File imageDirectory = getImageDirectory();
File calloutDirectory = new File (imageDirectory, "callouts");
transformer.setParameter("docbook.infile",sourceDocBook.toURI().toString());
transformer.setParameter("source.directory",sourceDirectory.toURI().toString());
transformer.setParameter("compute.wadl.path.from.docbook.path",computeWadlPathFromDocbookPath);
transformer.setParameter ("admon.graphics.path", imageDirectory.toURI().toString());
transformer.setParameter ("callout.graphics.path", calloutDirectory.toURI().toString());
//
// Setup the background image file
//
File cloudSub = new File (imageDirectory, "cloud");
File ccSub = new File (imageDirectory, "cc");
coverImage = new File (cloudSub, COVER_IMAGE_NAME);
coverImageTemplate = new File (cloudSub, COVER_IMAGE_TEMPLATE_NAME);
coverImageTemplate = new File (cloudSub, "rackspace-cover.st");
transformer.setParameter ("cloud.api.background.image", coverImage.toURI().toString());
transformer.setParameter ("cloud.api.cc.image.dir", ccSub.toURI().toString());
}
protected void transformCover() throws MojoExecutionException {
try {
ClassLoader classLoader = Thread.currentThread()
.getContextClassLoader();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(classLoader.getResourceAsStream(COVER_XSL)));
if(coverColor != null){
transformer.setParameter("coverColor", coverColor);
}
String sysDraftStatus=System.getProperty("draft.status");
if(null!=sysDraftStatus && !sysDraftStatus.isEmpty()){
draftStatus=sysDraftStatus;
}
if(null!=draftStatus){
transformer.setParameter("draft.status", draftStatus);
}
String sysStatusBarText=System.getProperty("statusBarText");
if(null!=sysStatusBarText && !sysStatusBarText.isEmpty()){
statusBarText=sysStatusBarText;
}
if(null != statusBarText){
transformer.setParameter("status.bar.text", statusBarText);
}
transformer.setParameter("branding", branding);
//transformer.setParameter("docbook.infile",sourceDocBook.toURI().toString());
String srcFilename = sourceDocBook.getName();
if (getLog().isDebugEnabled()) {
getLog().info("SOURCE FOR COVER PAGE: "+this.projectBuildDirectory+"/docbkx/"+srcFilename);
}
transformer.setParameter("docbook.infile", new File(this.projectBuildDirectory, "docbkx/"+srcFilename).toURI().toString());
transformer.transform (new StreamSource(coverImageTemplate), new StreamResult(coverImage));
}
catch (TransformerConfigurationException e)
{
throw new MojoExecutionException("Failed to load JAXP configuration", e);
}
catch (TransformerException e)
{
throw new MojoExecutionException("Failed to transform to cover", e);
}
}
@Override
protected Source createSource(String inputFilename, File sourceFile, PreprocessingFilter filter)
throws MojoExecutionException {
String pathToPipelineFile = "classpath:///pdf.xpl"; //use "classpath:///path" for this to work
String sourceFileNameNormalized = sourceFile.toURI().toString();
//from super
final InputSource inputSource = new InputSource(sourceFileNameNormalized);
Source source = new SAXSource(filter, inputSource);
//Source source = super.createSource(inputFilename, sourceFile, filter);
Map<String, Object> map=new HashMap<String, Object>();
String sysSecurity=System.getProperty("security");
getLog().info("adjustTransformer():sysSecurity="+sysSecurity);
if(null!=sysSecurity && !sysSecurity.isEmpty()){
security=sysSecurity;
}
map.put("targetDirectory", getTargetDirectory().getParentFile());
map.put("security", security);
map.put("canonicalUrlBase", canonicalUrlBase);
map.put("replacementsFile", replacementsFile);
map.put("failOnValidationError", failOnValidationError);
map.put("project.build.directory", this.projectBuildDirectory);
map.put("inputSrcFile", inputFilename);
map.put("outputType", "pdf");
map.put("strictImageValidation", String.valueOf(this.strictImageValidation));
map.put("status.bar.text", getProperty("statusBarText"));
map.put("draft.status", getProperty("draftStatus"));
// Profiling attrs:
map.put("profile.os", getProperty("profileOs"));
map.put("profile.arch", getProperty("profileArch"));
map.put("profile.condition", getProperty("profileCondition"));
map.put("profile.audience", getProperty("profileAudience"));
map.put("profile.conformance", getProperty("profileConformance"));
map.put("profile.revision", getProperty("profileRevision"));
map.put("profile.userlevel", getProperty("profileUserlevel"));
map.put("profile.vendor", getProperty("profileVendor"));
//String outputDir=System.getProperty("project.build.outputDirectory ");
return CalabashHelper.createSource(getLog(), source, pathToPipelineFile, map);
}
}
| [
"[email protected]"
] | |
4e875204cae71b3eeed6e0a9c351511670bff84e | 8d18b9059d0185b175509f8ee03898eab787b2d3 | /bdps-gapi/src/main/java/com/bdps/gateway/clients/SpecialServiceItemClient.java | 3fc8295ff236c7838c8543599d68bef30ab6aa7a | [] | no_license | inspirationLG/bdps02 | e894cb0a29baf87e135d2fdb634e40f311259e7c | 2db8609ceeb99812bb5212fb6c3aa25769b7b7ea | refs/heads/master | 2020-07-18T08:43:08.394393 | 2019-09-04T02:45:22 | 2019-09-04T02:45:22 | 206,215,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,887 | java | package com.bdps.gateway.clients;
import com.bdps.special_service_item.SpecialServiceItemProto;
import com.bdps.special_service_item.SpecialServiceItemServiceGrpc;
import com.google.common.util.concurrent.ListenableFuture;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
/**
* @author zcz
* @CreateTime 2019/8/29 15:39
*/
@Service
public class SpecialServiceItemClient {
@GrpcClient("eshop-grpc-server")
private SpecialServiceItemServiceGrpc.SpecialServiceItemServiceFutureStub specialServiceItemServiceFutureStub;
public ListenableFuture<SpecialServiceItemProto.SpecialServiceItem> addSpecialServiceItem(SpecialServiceItemProto.AddSpecialServiceItemRequest request) {
return specialServiceItemServiceFutureStub.addSpecialServiceItem(request);
}
public ListenableFuture<SpecialServiceItemProto.SpecialServiceItem> updateSpecialServiceItem(SpecialServiceItemProto.UpdateSpecialServiceItemRequest request) {
return specialServiceItemServiceFutureStub.updateSpecialServiceItem(request);
}
public ListenableFuture<SpecialServiceItemProto.SpecialServiceItems> listSpecialServiceItems(SpecialServiceItemProto.ListSpecialServiceItemRequest request) {
return specialServiceItemServiceFutureStub.listSpecialServiceItem(request);
}
public ListenableFuture<SpecialServiceItemProto.SpecialServiceItem> deleteSpecialServiceItem(SpecialServiceItemProto.DeleteSpecialServiceItemRequest request) {
return specialServiceItemServiceFutureStub.deleteSpecialServiceItem(request);
}
public ListenableFuture<SpecialServiceItemProto.SpecialServiceItem> getSpecialServiceItem(Integer id) {
return specialServiceItemServiceFutureStub.getSpecialServiceItem(SpecialServiceItemProto.GetSpecialServiceItemRequest.newBuilder().setSpecialServiceItemId(id).build());
}
} | [
"[email protected]"
] | |
fb044cac8fb6177dd5771a8fcd386a77323cc8cf | e32aface35cfcfc5f270699145e4322207536ebf | /DownloadingDemoV1 2/app/src/main/java/com/example/downloadingdemov1/MainActivity.java | a55848c71747ebfedb221471f63a5b5bca755b31 | [] | no_license | MengJIANG97/Download_Image_HtmlText_File_Android | d0e91926fdb3d265096f28ce49eec6f843c5af4c | 8ec7392f9cf140debc9694a5377dda1b1e12b4b9 | refs/heads/main | 2023-05-31T22:24:49.103560 | 2021-06-27T08:00:27 | 2021-06-27T08:00:27 | 379,466,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 20,642 | java | package com.example.downloadingdemov1;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.UserDictionary;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.Permission;
import java.util.Set;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView imageView;
private TextView textView;
TextView textView1;
Button button;
private static final int IMAGE_MSG_NEW_PIC = 2;
//使用网上下载图片
private static final int IMAGE_MSG_CACHE_PIC = 1;
//使用缓存图片
private static final int IMAGE_ERROR = 3;
//图片请求失败
private static final int IMAGE_EXCEPTION = 4;
//图片发生异常,请求失败
protected static final int TEXT_SUCCESS = 5;
//文本请求成功
protected static final int TEXT_ERROR = 6;
//文本请求失败
protected static final int FILE_SUCCESS = 7;
//文件下载完毕
private Handler handler;
@SuppressLint("HandlerLeak")
class DoHandler extends Handler {
private final WeakReference<Activity> reference;
public DoHandler(Activity activity) {
reference = new WeakReference<>(activity);
}
@Override
public void handleMessage(@NonNull Message msg) {
switch (msg.what) {
case IMAGE_MSG_CACHE_PIC:
Bitmap bitmap = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap);
Toast.makeText(reference.get(), "使用缓存图", Toast.LENGTH_SHORT).show();
break;
case IMAGE_MSG_NEW_PIC:
Bitmap bitmap2 = (Bitmap) msg.obj;
imageView.setImageBitmap(bitmap2);
Toast.makeText(reference.get(), "下载图片完毕", Toast.LENGTH_SHORT).show();
break;
case IMAGE_ERROR:
Toast.makeText(reference.get(), "图片请求失败", Toast.LENGTH_SHORT).show();
break;
case IMAGE_EXCEPTION:
Toast.makeText(reference.get(), "图片发生异常,请求失败", Toast.LENGTH_SHORT).show();
break;
case TEXT_ERROR:
Toast.makeText(reference.get(), "文本请求失败", Toast.LENGTH_SHORT).show();
break;
case TEXT_SUCCESS:
String text = (String) msg.obj;
textView.setText(text);
Toast.makeText(reference.get(), "文本请求成功", Toast.LENGTH_SHORT).show();
break;
case FILE_SUCCESS:
Toast.makeText(reference.get(), "文件下载完毕", Toast.LENGTH_SHORT).show();
break;
}
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@SuppressLint({"Recycle", "SetTextI18n"})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_downloadImage).setOnClickListener(this);
imageView = (ImageView) findViewById(R.id.imageView);
findViewById(R.id.btn_downloadFile).setOnClickListener(this);
findViewById(R.id.btn_downloadText).setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView);
handler = new DoHandler(this);
/**
* 练习registerForActivityResult()方法
*/
button = findViewById(R.id.button10);
textView1 = findViewById(R.id.text_view);
Log.d("create", MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY).toString());
Log.d("create", MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
/*
@SuppressLint("SetTextI18n")
ActivityResultLauncher<String> launcher = registerForActivityResult(new MyActivityResultContract(), result -> {
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
textView1.setText("回传数据: " + result);
});
button.setOnClickListener(v -> launcher.launch("Hello,技术最TOP"));
*/
//自定义方法的官方封装
Intent intent1 = new Intent(this,MainActivity2.class);
intent1.putExtra("name","Hello,技术最TOP");
ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),result -> {
Toast.makeText(MainActivity.this, result.getData().getStringExtra("result"), Toast.LENGTH_SHORT).show();
textView1.setText("回传数据: " + result.getData().getStringExtra("result"));
});
button.setOnClickListener(v -> {
launcher.launch(intent1);
});
registerForActivityResult(new ActivityResultContracts.RequestPermission(), result -> {
if (result)
Toast.makeText(MainActivity.this, "BLUETOOTH Permission is granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "BLUETOOTH Permission is denied", Toast.LENGTH_SHORT).show();
}).launch(Manifest.permission.BLUETOOTH);
Button button20 = findViewById(R.id.button20);
button20.setOnClickListener(v -> {
Intent intent = new Intent(this,MainActivity3.class);
startActivity(intent);
});
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_downloadImage:
downloadBitmap();
//下图片
break;
case R.id.btn_downloadFile:
//下文件
//downloadFile();
//正常下载
downloadFileBreakpoint();
//断点下载
break;
case R.id.btn_downloadText:
downloadText();
//下载html网页
break;
}
}
/**
* RandomFile,okhttp实现断点下载
*/
private void downloadFileBreakpoint() {
final String urlStr = "https://www.kotlincn.net/docs/kotlin-docs.pdf";
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(MainActivity.this, "无法获取SDCard", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
InputStream in = null;
RandomAccessFile savedFile = null;
String filename = urlStr.substring(urlStr.lastIndexOf("/"));
File file = null;
try {
file = new File(getExternalFilesDir(null), filename);
if (file.createNewFile()) {
Log.d("downloadFile", "新创建成功");
}
long downdLength = file.length();
//已经下载的文件长度
long contentLength = getContentLength(urlStr);
if (contentLength == 0) {
Toast.makeText(MainActivity.this, "Success下载失败", Toast.LENGTH_SHORT).show();
return;
} else if (downdLength == contentLength) {
//说明已经下载完成了
Toast.makeText(MainActivity.this, "Success下载完成", Toast.LENGTH_SHORT).show();
return;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE", "bytes=" + downdLength + "-")
//断点下载,指定从那个字节开始下载
.url(urlStr)
.build();
Response response = client.newCall(request).execute();
if (response != null) {
in = response.body().byteStream();
savedFile = new RandomAccessFile(file, "rw");
savedFile.seek(downdLength);
//跳过已经下载的字节
byte[] bytes = new byte[1024];
int total = 0;
int len;
while ((len = in.read(bytes)) != -1) {
total += len;
savedFile.write(bytes, 0, len);
int progress = (int) ((total + downdLength) * 100 / contentLength);
Log.d("downloadFile", "" + progress + "%");
}
}
response.body().close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (savedFile != null && in != null) {
savedFile.close();
in.close();
Message msg = Message.obtain();
msg.what = FILE_SUCCESS;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* 获取下载文件的长度
*
* @return
*/
public long getContentLength(String downloadUrl) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if (response != null && response.isSuccessful()) {
long contentLength = response.body().contentLength();
response.close();
return contentLength;
}
return 0;
}
/**
* 下文件
*/
private void downloadFile() {
final String urlStr = "https://downloads.jianshu.io/apps/haruki/JianShu-2.2.3-17040111.apk";
/**
* 返回的状态为 MEDIA_MOUNTED,
* 那么您就可以在外部存储空间中读取和写入应用专属文件。
* 如果返回的状态为 MEDIA_MOUNTED_READ_ONLY,您只能读取这些文件。
*/
String state = Environment.getExternalStorageState();
//MEDIA_MOUNTED SD卡正常挂载,因此可以读取或者向SD卡写入
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Toast.makeText(this, "无法获取SDCard", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
///storage/emulated/0/Android/data/com.example.downloadingdemov1/files/JianShu-2.2.3-17040111.apk目录
String filename = urlStr.substring(urlStr.lastIndexOf("/"));
File file = new File(getExternalFilesDir(null), filename);
//创建文件路径(/storage/emulated/0/Android/data/com.example.downloadingdemov1/files/JianShu-2.2.3-17040111.apk)
try {
if (file.createNewFile()) {
Log.d("downloadFile", "创建成果");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.d("downloadFile", file.getPath());
///storage/emulated/0/Android/data/com.example.downloadingdemov1/files/JianShu-2.2.3-17040111.apk
Log.d("downloadFile", new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), filename).getPath());
// /storage/emulated/0/Android/data/com.example.downloadingdemov1/files/Pictures/JianShu-2.2.3-17040111.apk
InputStream input = null;
HttpURLConnection connection = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
//允许输出流,即允许上传
connection.setUseCaches(false);
//不使用缓冲
connection.setRequestMethod("GET");
//使用get请求
connection.connect();
Log.d("downloadFile", "" + connection.getResponseCode());
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
Log.d("downloadFile", "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
int fileLength = connection.getContentLength();
Log.d("downloadFile", "" + fileLength);
input = connection.getInputStream();
if (input == null) {
return;
}
fos = new FileOutputStream(file);
byte[] data = new byte[1024];
long total = 0;
int len;
while ((len = input.read(data)) != -1) {
fos.write(data, 0, len);
total += len;
if (fileLength > 0) {
Log.d("downloadFile", "" + (int) (total * 100 / fileLength) + " %");
}
}
Log.d("downloadFile", "" + file.length());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (input != null && fos != null) {
input.close();
fos.close();
Message msg = Message.obtain();
msg.what = FILE_SUCCESS;
handler.sendMessage(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null)
connection.disconnect();
}
}
}).start();
}
/**
* 下图片
*/
private void downloadBitmap() {
final String path = "http://www.hinews.cn/pic/003/002/462/00300246261_07308d48.jpg";
new Thread(new Runnable() {
@Override
public void run() {
File file = new File(getCacheDir(), path.substring(path.lastIndexOf("/")));
if (file.exists() && file.length() > 0) {
Log.d("downloadBitmap", "图片存在,拿缓存");
Log.d("downloadBitmap", file.getPath());
Bitmap bitmap = BitmapFactory.decodeFile(file
.getAbsolutePath());
Message msg = new Message();
//声明消息
msg.what = IMAGE_MSG_CACHE_PIC;
msg.obj = bitmap;
//设置数据
handler.sendMessage(msg);
} else {
Log.d("downloadBitmap", "图片不存在,获取数据生成缓存");
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
Log.d("downloadBitmap", file.getPath());
Bitmap bitmap = BitmapFactory.decodeFile(file
.getAbsolutePath());
Message msg = new Message();
msg.obj = bitmap;
msg.what = IMAGE_MSG_NEW_PIC;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = IMAGE_ERROR;
handler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = Message.obtain();
msg.what = IMAGE_EXCEPTION;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}
}).start();
}
/**
* 下载文本html网页
*/
private void downloadText() {
final String path = "https://www.baidu.com";
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
String result = response.toString();
Message msg = Message.obtain();
msg.obj = result;
msg.what = TEXT_SUCCESS;
handler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = Message.obtain();
//减少消息创建的数量
msg.what = TEXT_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
// 外部类Activity生命周期结束时,同时清空消息队列&结束Handler生命周期
}
}
| [
"[email protected]"
] | |
26737123632a76ebe6ee62dd5144ec1bd608c915 | f2ca91f40cec28c9ad0ab5d48b1b517ab4ec8118 | /leetcode/NextGreaterElement.java | 5c4a7dcebc675e6f7b328b656e14588f01031988 | [] | no_license | vaggarwal2/PracticeCompetitiveProgramming | 718b68e8dfab20d48a8484c7da64b7797012baab | cc7e030cb69f7492c8d078f3bda65ab92b99709a | refs/heads/master | 2022-11-01T08:40:39.592060 | 2020-06-20T16:37:33 | 2020-06-20T16:37:33 | 273,506,985 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,880 | java | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class NextGreaterElement {
public static class Test {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map<Integer, Integer> map1 = new HashMap<>();
Stack<Integer> integerStack = new Stack<>();
if (nums2.length ==0) {
int[] greaterNum = new int[nums1.length];
Arrays.fill(greaterNum, -1);
return greaterNum;
}
else if (nums2.length == 1) {
map1.put(nums2[0], -1);
} else {
int i = 0;
integerStack.push(nums2[i]);
while (i < nums2.length) {
while (!integerStack.isEmpty()) {
if (nums2[i] > integerStack.peek()) {
map1.put(integerStack.peek(), nums2[i]);
integerStack.pop();
} else {
break;
}
}
integerStack.push(nums2[i]);
i++;
}
while (!integerStack.isEmpty()) {
map1.put(integerStack.peek(), -1);
integerStack.pop();
}
}
int[] greaterNum = new int[nums1.length];
for (int j = 0; j < nums1.length; j++) {
greaterNum[j] = map1.get(nums1[j]);
}
return greaterNum;
}
}
public static void main(String args[]) {
Test test = new Test();
int[] greaterNum = test.nextGreaterElement(new int[] {2,4}, new int[] {1,2,3,4});
for (int i =0 ; i< greaterNum.length; i++) {
System.out.println(greaterNum[i]);
}
}
}
| [
"[email protected]"
] | |
80b4584861deeb2f0a4f4322e9d04af15bfe7bb5 | f8744ddebb763fb26589aba6be3d6945a4467718 | /com/imagehistorica/databases/QueuesInProcDB.java | bcb8d7f578ef2c513888d5dc29ca3f7cbcd50e20 | [] | no_license | Image-Historica/ImageHistorica | e669e037b1bd7b719d62b21d630cf46553783c05 | 3273f9764bea928e7f27ea9ebc8a44e176db0f8f | refs/heads/master | 2021-01-12T17:34:17.085371 | 2016-11-01T17:18:17 | 2016-11-01T17:18:17 | 71,583,900 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,126 | java | /*
* Copyright (C) 2016 Image-Historica.com
*
* This file is part of the ImageHistorica: https://image-historica.com
* ImageHistorica is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package com.imagehistorica.databases;
import java.util.List;
import com.sleepycat.je.Environment;
import com.sleepycat.je.Transaction;
import com.imagehistorica.databases.model.Historica;
/**
*
* @author Kazuhito Kojima, [email protected]
*/
public class QueuesInProcDB extends Queues {
public QueuesInProcDB(Environment env) throws Exception {
super(env, "QueuesInProcDB");
long imageCount = getLength();
if (imageCount > 0) {
logger.info("Loaded {} images from " + dbName + " that don't be processed in the previous session yet...", imageCount);
}
}
public boolean deleteReq(List<Historica> historicas, Transaction txn) {
synchronized (mutex) {
try {
for (Historica historica : historicas) {
if (!queueByHistoricaId.delete(txn, historica.getHistoricaId())) {
throw new Exception("Could not remove: {} from list of requests." + queueByHistoricaId.get(historica.getHistoricaId()));
}
}
} catch (Exception e) {
logger.error("Error in the QueuesInProcessDB, {}", e.getMessage());
return false;
}
return true;
}
}
}
| [
"[email protected]"
] | |
f7afb7f0e827a8e488c49d8a5a22ed07cf5be982 | dcd918f3c88e9e412f73eb920c7d2684eed5eb55 | /src/main/java/com/group7/edu/oss/model/GenericResult.java | c1a7310c3e0c2e5a4d1959ff807516ecb25c7f70 | [] | no_license | hahagioi998/OnlineEduProj | 735d1c1908be38b87c887d8d0196f8292117ed19 | 77206ef471c8d1ab94317ed9ad79406500c75894 | refs/heads/master | 2022-04-25T19:10:13.474392 | 2019-04-26T08:07:17 | 2019-04-26T08:07:17 | 484,791,196 | 1 | 0 | null | 2022-04-23T15:54:48 | 2022-04-23T15:54:47 | null | UTF-8 | Java | false | false | 1,796 | 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.group7.edu.oss.model;
import com.group7.edu.oss.common.comm.ResponseMessage;
/**
* A generic result that contains some basic response options, such as
* requestId.
*/
public abstract class GenericResult {
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public Long getClientCRC() {
return clientCRC;
}
public void setClientCRC(Long clientCRC) {
this.clientCRC = clientCRC;
}
public Long getServerCRC() {
return serverCRC;
}
public void setServerCRC(Long serverCRC) {
this.serverCRC = serverCRC;
}
public ResponseMessage getResponse() {
return response;
}
public void setResponse(ResponseMessage response) {
this.response = response;
}
private String requestId;
private Long clientCRC;
private Long serverCRC;
ResponseMessage response;
}
| [
"[email protected]"
] | |
ef1f7eae580b283bb0b6c091f8a892d77bb85e2b | a7316f741c726d77676f10e0776536362ccec002 | /labcs-web-footballtournament/src/com/demo/servlet/SelectServlet.java | 655eca45e286703b5ec8eae5fec9a5acae429c59 | [] | no_license | Ravikiran-jfs/most_of_my_projects | 2b662bf7c6ab55511f4a2680e128b72e1a5cabea | 849192b7faee00ebb58502da1ac9d36bcc096b5a | refs/heads/master | 2020-12-13T19:51:39.765624 | 2020-01-17T10:18:17 | 2020-01-17T10:18:17 | 234,514,510 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,908 | java | package com.demo.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SelectServlet
*/
@WebServlet("/SelectServlet")
public class SelectServlet extends HttpServlet {
Connection connection;
@Override
public void init() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//System.out.println("Driver loaded successfully!");
//Get the connection
connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","hr","hr");
//System.out.println("Connection Established!");
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException e) {
System.out.println(e);
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
PrintWriter table = resp.getWriter();
getBookID();
//table.println("<table border = 1><thead><tr><th>Book Id</th><th> </th><th>Book Name</th></tr></thead></table>");
}
public void getBookID() {
Statement statement;
try {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from book");
while(resultSet.next()) {
int bookID = resultSet.getInt("bookID");
String bookName = resultSet.getString("bookName");
System.out.println(bookID + "->" + bookName);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
3a3bb659c22661ddd552f2670cd09e77f88489e6 | 7d8c29231aa76bb95355cf3af5179964e18a1e0e | /src/main/java/com/avixy/qrtoken/negocio/servico/params/TwoBytesWrapperParam.java | 55bb83cb5d561255654cdee069228daac0acebab | [] | no_license | salgadobreno/hermes | 40a8924687b2d9508ecae4152fcd1b81d27dcdf0 | d2eab365022b8061e38ef36c70417a054170b7e0 | refs/heads/master | 2021-08-23T20:44:00.859701 | 2017-12-06T12:57:33 | 2017-12-06T12:57:33 | 108,772,081 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 707 | java | package com.avixy.qrtoken.negocio.servico.params;
/**
* Created on 17/10/2014
*
* @author Breno Salgado <[email protected]>
*/
public class TwoBytesWrapperParam implements Param {
private int value;
public TwoBytesWrapperParam(int value) {
this.value = value;
}
@Override
public String toBinaryString() {
/*
& 0xFFFF preserva os 16 bits dos bytes sem transformar em número negativo caso o primeiro bit esteja ligado
+ 0x10000 liga o bit 17 para que o toBinaryString não perca os zero à esquerda, e remove o bit 17 com o substring.
*/
return Integer.toBinaryString((value & 0xFFFF) + 0x10000).substring(1);
}
}
| [
"[email protected]"
] | |
6ed8132c7f6e80b250da798698439dac00fc9163 | 7ea24b8c8f70935cc22ad54d2cdca8bffb2aa6a5 | /frontend/src/main/java/com/netcracker/studPract/clientWeb/MessageUtils/MessageTypes.java | f5ef1c8e3781a20118563e5fbbf027493e9b91fa | [] | no_license | north911/springWebChatWithApi | 80d31a12d019545daa3837791b3b9b0c12656931 | fb53871c22b06465df3b1f03675af71c8efc5e98 | refs/heads/master | 2020-03-09T03:02:08.720813 | 2018-04-13T21:36:16 | 2018-04-13T21:36:16 | 128,555,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 169 | java | package com.netcracker.studPract.clientWeb.MessageUtils;
public enum MessageTypes {
LEAVE_MESSAGE,
CLIENT_MESSAGE,
AGENT_MESSAGE,
AGENT_SLOTS_MESSAGE
}
| [
"[email protected]"
] | |
86ffdd65d432f55fa64a96d14c82c6c97f2f2167 | 97a5be4986f1339b64b906e80ccb6c64a9aebaec | /src/main/java/org/sid/web/CinemaRestContoller.java | 6afd899b33601dcae851eb9e0e23139feeeaba3b | [] | no_license | Boudinar-2021/App-web-Gestion-des-cinemas-JEE-PartieBackend- | 858a3591fa5d29bee1f82a4a9ce282a6046d4aa1 | 782ea517ba7ee0f3912348b4e42a1ddd9fdb98ac | refs/heads/master | 2022-11-10T21:40:35.507620 | 2020-06-22T19:09:20 | 2020-06-22T19:09:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,621 | java | package org.sid.web;
import org.springframework.http.MediaType;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.sid.dao.FilmRepository;
import org.sid.dao.TickeRepository;
import org.sid.entite.Film;
import org.sid.entite.Ticket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import lombok.Data;
@RestController
@CrossOrigin("*")
public class CinemaRestContoller {
//consulter ou upload l image
@Autowired
private FilmRepository filmRepository;
@Autowired
private TickeRepository tickeRepository;
//dans le byte il ya des donnes sous fome des images
@GetMapping(path ="/imageFilm/{id}",produces =MediaType.IMAGE_JPEG_VALUE)
public byte [] image(@PathVariable (name="id")Long id) throws Exception{
Film f=filmRepository.findById(id).get();
String photoNmae=f.getPhoto();
//le contenu de la photo
File file =new File(System.getProperty("user.home")+"/cinema/images/"+photoNmae);
Path path=Paths.get(file.toURI());
//retoune tableau d octets
return Files.readAllBytes(path);
}
//effuctuter le payment
//@RequestBody : les donnes de tickets va envoyer au corp de requets se fome json
@PostMapping("/payerTickets")
//traitement de couche metier
@Transactional
//user a evoyer les id des tickets qui il veut
public List<Ticket> payerTickets(@RequestBody TicketForm ticketForm) {
//liste des tickets vendu
List<Ticket> listTickets=new ArrayList<Ticket>();
//pour chaque id de ticket
ticketForm.getTickets().forEach(idTicket->{
System.out.println(idTicket);
Ticket ticket=tickeRepository.findById(idTicket).get();
//modifier le sinfos sur les tickets
ticket.setNomClient(ticketForm.getNomClient());
ticket.setReservee(true);
ticket.setCodePayement(ticketForm.getCodePayment());
tickeRepository.save(ticket);
//chaque ticket enregister il faut ajouter a la liste
listTickets.add(ticket);
});
return listTickets;
}
}
@Data
class TicketForm{
//resovoir le nom de client
private String nomClient;
private int codePayment;
//resovoir une liste des id
private List<Long> tickets=new ArrayList<>();
}
| [
"[email protected]"
] | |
e7d5cd42206235a00cfe719ee8b3f67d231731ec | aeb12a9ff464d7da630508f97d7ffdcf2e36f0a3 | /src/HW2/Task1.java | 17771e7c33d653218f3108055555b91edbcf6bcc | [] | no_license | Dsintez/GeekBrains_Java1_HomeWorks | 970dcb7ed51cd3a3dae0c3e9cba2d81cd1747065 | 3b9d696b2bb601c2fbbef185ac006c99081523d9 | refs/heads/master | 2020-12-11T18:27:15.996345 | 2020-02-23T12:59:42 | 2020-02-23T12:59:42 | 233,925,319 | 0 | 0 | null | 2020-02-23T12:59:43 | 2020-01-14T20:04:31 | Java | UTF-8 | Java | false | false | 768 | java | package HW2;
public class Task1 {
public static void main(String[] args) {
int[] binaryNumbers = new int[10];
for (int i = 0; i < binaryNumbers.length; i++) {
binaryNumbers[i] = (int) Math.rint(Math.random());
}
for (int i = 0; i < binaryNumbers.length; i++) {
System.out.println(i + " - " + binaryNumbers[i]);
}
for (int i = 0; i < binaryNumbers.length; i++) {
if (binaryNumbers[i] == 0) {
binaryNumbers[i] = 1;
} else {
binaryNumbers[i] = 0;
}
}
System.out.println();
for (int i = 0; i < binaryNumbers.length; i++) {
System.out.println(i + " - " + binaryNumbers[i]);
}
}
}
| [
"[email protected]"
] | |
71fc8575ea352988f816e9e5f371c057096285c8 | 0d332c8e9f591f5f7e196b92111b6d4ed74b5e2e | /src/main/java/it/uniroma1/dis/wsngroup/parsing/modules/statistics/StatsModule.java | 00a2392e3964a7ad4a58545a9f3ee11d2c06e976 | [] | no_license | francesco-ficarola/OpenBeaconParser | a9bf75e5d42dcdc862ab081db4105706b5ca82d9 | 2db0b6e997eb574f9f604e34117fd957deec0265 | refs/heads/master | 2021-01-10T21:04:21.684920 | 2014-08-28T08:48:50 | 2014-08-28T08:48:50 | 8,901,957 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,842 | java | package it.uniroma1.dis.wsngroup.parsing.modules.statistics;
import it.uniroma1.dis.wsngroup.parsing.modules.dynamics.AbstractModule;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
public class StatsModule extends AbstractModule {
public StatsModule(File fileInput, FileInputStream fis, boolean createVL) {
super(fileInput, fis, createVL);
}
private void printStats() {
if(tsObjectList.size() > 0) {
logger.info("*** STATISTICS ***");
logger.info("Timestamps: " + tsObjectList.size());
Integer numberOfTotalContacts = 0;
Map<EdgeObject, SortedSet<Integer>> edgesMap = new HashMap<EdgeObject, SortedSet<Integer>>();
Map<Integer, Integer> contactSeconds = new HashMap<Integer, Integer>();
// Saving edges and their occurring timestamps in a hashmap
Iterator<TimestampObject> it = tsObjectList.iterator();
while(it.hasNext()) {
TimestampObject curTimestampObject = it.next();
Integer curTimestampNum = Integer.parseInt(curTimestampObject.getTimestamp());
ArrayList<Edge> edges = curTimestampObject.getEdges();
Iterator<Edge> edgeIt = edges.iterator();
while(edgeIt.hasNext()) {
Edge edge = edgeIt.next();
EdgeObject edgeObject = new EdgeObject(edge.getSourceTarget().get(0), edge.getSourceTarget().get(1));
EdgeObject edgeObjectInv = new EdgeObject(edge.getSourceTarget().get(1), edge.getSourceTarget().get(0));
if(edgesMap.containsKey(edgeObject)) {
SortedSet<Integer> ts = edgesMap.get(edgeObject);
ts.add(curTimestampNum);
edgesMap.put(edgeObject, ts);
}
else
if(edgesMap.containsKey(edgeObjectInv)) {
SortedSet<Integer> ts = edgesMap.get(edgeObjectInv);
ts.add(curTimestampNum);
edgesMap.put(edgeObjectInv, ts);
}
else {
SortedSet<Integer> ts = new TreeSet<Integer>();
ts.add(curTimestampNum);
edgesMap.put(edgeObject, ts);
}
numberOfTotalContacts++;
}
}
logger.info("Contacts: " + numberOfTotalContacts);
// Counting contact seconds...
Set<Map.Entry<EdgeObject, SortedSet<Integer>>> edgesSet = edgesMap.entrySet();
for(Map.Entry<EdgeObject, SortedSet<Integer>> entry : edgesSet) {
EdgeObject edgeObject = entry.getKey();
Set<Integer> ts = entry.getValue();
Object[] tsArray = ts.toArray();
logger.debug(edgeObject.toString() + ": " + Arrays.toString(tsArray));
Integer countSeconds = 0;
if(tsArray.length > 1) {
for(int i = 0; i < tsArray.length; i++) {
countSeconds++;
if(i < tsArray.length - 1) {
Integer currentTS = (Integer)tsArray[i];
Integer nextTS = (Integer)tsArray[i+1];
currentTS++;
if(!currentTS.equals(nextTS)) {
if(contactSeconds.containsKey(countSeconds)) {
Integer curSec = contactSeconds.get(countSeconds);
curSec++;
contactSeconds.put(countSeconds, curSec);
} else {
contactSeconds.put(countSeconds, 1);
}
logger.debug("[INEQ] " + countSeconds + ": " + contactSeconds.get(countSeconds));
countSeconds = 0;
} else {
logger.debug("[EQ] " + countSeconds + ": " + contactSeconds.get(countSeconds));
}
}
else
if(i == tsArray.length - 1) {
Integer currentTS = (Integer)tsArray[i];
Integer prevTS = (Integer)tsArray[i-1];
currentTS--;
if(!currentTS.equals(prevTS)) {
if(contactSeconds.containsKey(1)) {
Integer curSec = contactSeconds.get(1);
curSec++;
contactSeconds.put(1, curSec);
} else {
contactSeconds.put(1, 1);
}
logger.debug("[INEQ, LAST] " + countSeconds + ": " + contactSeconds.get(countSeconds));
} else {
if(contactSeconds.containsKey(countSeconds)) {
Integer curSec = contactSeconds.get(countSeconds);
curSec++;
contactSeconds.put(countSeconds, curSec);
} else {
contactSeconds.put(countSeconds, 1);
}
logger.debug("[EQ, LAST] " + countSeconds + ": " + contactSeconds.get(countSeconds));
}
countSeconds = 0;
}
}
} else {
if(contactSeconds.containsKey(1)){
Integer curSec = contactSeconds.get(1);
curSec++;
contactSeconds.put(1, curSec);
} else {
contactSeconds.put(1, 1);
}
logger.debug("[UNIQUE] 1: " + contactSeconds.get(1));
}
}
Map<Integer, Integer> contactSecondsSort = new TreeMap<Integer, Integer>(contactSeconds);
Set<Map.Entry<Integer, Integer>> contactSecondsSet = contactSecondsSort.entrySet();
for(Map.Entry<Integer, Integer> entry : contactSecondsSet) {
logger.info(entry.getKey() + " seconds: " + entry.getValue() + " contacts");
}
logger.info("***********************************");
// Computing the average of density...
Set<String> nodes = new HashSet<String>();
it = tsObjectList.iterator();
while(it.hasNext()) {
TimestampObject curTimestampObject = it.next();
for(Tag tag : curTimestampObject.getTags()) {
nodes.add(tag.getTagID());
}
}
Integer maxTotalEdges = (nodes.size() * nodes.size() - 1) / 2;
logger.info("Total number of nodes: " + nodes.size());
List<Double> densityList = new LinkedList<Double>();
it = tsObjectList.iterator();
while(it.hasNext()) {
TimestampObject curTimestampObject = it.next();
Integer numEdges = curTimestampObject.getEdges().size();
Double density = (double) numEdges / maxTotalEdges;
densityList.add(density);
}
Double sumDensity = 0.0;
for(Double density : densityList) {
sumDensity += density;
}
Double avgDensity = sumDensity / densityList.size();
logger.info("Avg density: " + avgDensity);
}
}
public void writeFile(String outputFileName, String separator) throws IOException {
printStats();
}
/** INNER CLASS */
private class EdgeObject {
private String source, target;
private EdgeObject(String source, String target) {
this.source = source;
this.target = target;
}
@Override
public int hashCode() {
return source.hashCode() ^ target.hashCode();
}
@Override
public boolean equals(Object obj) {
return (obj instanceof EdgeObject) && ((EdgeObject) obj).source.equals(source)
&& ((EdgeObject) obj).target.equals(target);
}
@Override
public String toString() {
return "[" + source + "," + target + "]";
}
}
}
| [
"[email protected]"
] | |
f9f20093b0e7baaf151281b464cd82713494d033 | e2fceba13a8ed716c4a978d3d88091a90aff0210 | /vue_sts/login/src/main/java/com/ssafy/edu/LoginApplication.java | 0c8790a67d1709266a7492be9e378e19947cefcd | [] | no_license | Seonhanbit/dev | fff1d597d0db3fb16c9eff2ce23ee70d5ba529fd | e7c56ef9c5c7b2e00c8574e0de099c7ea9356dd3 | refs/heads/master | 2023-01-21T12:32:58.366509 | 2020-10-26T11:14:30 | 2020-10-26T11:14:30 | 205,319,840 | 2 | 0 | null | 2023-01-05T12:43:55 | 2019-08-30T06:33:08 | Java | UTF-8 | Java | false | false | 843 | java | package com.ssafy.edu;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
@SpringBootApplication
@EntityScan(basePackageClasses = {
LoginApplication.class,
Jsr310JpaConverters.class
})
public class LoginApplication {
@PostConstruct
void init() {
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
}
public static void main(String[] args) {
SpringApplication.run(LoginApplication.class, args);
}
}
//http://localhost:8397/api/user/[email protected]
//http://localhost:8397/api/user/checkUsernameAvailability?username=rrrrrr
| [
"[email protected]"
] | |
55750550c1522ab100eee6187f4c08cc83652c2b | 527f37bd94442f5bfef318e440fe338a1f5e567a | /src/main/java/sda/weatherlady/Main.java | 73a6a2e969e526705a37fa0681e8f7526daa0504 | [
"Apache-2.0"
] | permissive | Dainiuskar/Weatherlady | 8605e098d43cf97ed6073a66b71b4e0f26a236f1 | d12c29b901efa4ba9adc691f7ca86dbdd35a98b9 | refs/heads/main | 2023-03-10T05:16:15.925968 | 2021-02-28T09:59:38 | 2021-02-28T09:59:38 | 342,809,902 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 142 | java | package sda.weatherlady;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
| [
"[email protected]"
] | |
0cf702e87777ceb3d6a665c5cbe189ad76af7de2 | d6b21db31c312ecb0da1b52b955eac1c93c373a9 | /JavaSpring_Projects/TicketAdvantage/SiteProcessing/src/main/java/com/ticketadvantage/services/dao/sites/agsoftware/AGSoftwareProcessSite.java | 27c47f20c104a251eef3f5ee07ae96bd7ec72f51 | [] | no_license | teja0009/Projects | 84b366a0d0cb17245422c6e2aad5e65a5f7403ac | 70a437a164cef33e42b65162f8b8c3cfaeda008b | refs/heads/master | 2023-03-16T10:10:10.529062 | 2020-03-08T06:22:43 | 2020-03-08T06:22:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 33,419 | java | /**
*
*/
package com.ticketadvantage.services.dao.sites.agsoftware;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import com.ticketadvantage.services.dao.sites.SiteEventPackage;
import com.ticketadvantage.services.dao.sites.SiteProcessor;
import com.ticketadvantage.services.dao.sites.SiteTransaction;
import com.ticketadvantage.services.dao.sites.metallica.captcha.CaptchaReader;
import com.ticketadvantage.services.dao.sites.sportsinsights.SportsInsightsSite;
import com.ticketadvantage.services.errorhandling.BatchErrorCodes;
import com.ticketadvantage.services.errorhandling.BatchErrorMessage;
import com.ticketadvantage.services.errorhandling.BatchException;
import com.ticketadvantage.services.model.AccountEvent;
import com.ticketadvantage.services.model.BaseRecordEvent;
import com.ticketadvantage.services.model.EventPackage;
import com.ticketadvantage.services.model.MlRecordEvent;
import com.ticketadvantage.services.model.PendingEvent;
import com.ticketadvantage.services.model.SpreadRecordEvent;
import com.ticketadvantage.services.model.TotalRecordEvent;
/**
* @author jmiller
*
*/
public class AGSoftwareProcessSite extends SiteProcessor {
private static final Logger LOGGER = Logger.getLogger(AGSoftwareProcessSite.class);
private static final String PENDING_BETS = "AlPendingWagers.asp";
private final AGSoftwareParser ASP = new AGSoftwareParser();
private final SportsInsightsSite processSite = new SportsInsightsSite("https://sportsinsights.actionnetwork.com/",
"[email protected]",
"action1");
private String captchaStr="";
/**
*
*/
public AGSoftwareProcessSite(String host, String username, String password, boolean isMobile, boolean showRequestResponse) {
super("AGSoftware", host, username, password, isMobile, showRequestResponse);
LOGGER.info("Entering AgSoftwareProcessSite()");
// Setup the parser
this.siteParser = ASP;
// Menu items
NFL_LINES_SPORT = new String[] { "NFL" };
NFL_LINES_NAME = new String[] { "Game" };
NFL_FIRST_SPORT = new String[] { "NFL" };
NFL_FIRST_NAME = new String[] { "1st Half" };
NFL_SECOND_SPORT = new String[] { "NFL" };
NFL_SECOND_NAME = new String[] { "2nd Half" };
NCAAF_LINES_SPORT = new String[] { "College" };
NCAAF_LINES_NAME = new String[] { "Game" };
NCAAF_FIRST_SPORT = new String[] { "College" };
NCAAF_FIRST_NAME = new String[] { "1st Half" };
NCAAF_SECOND_SPORT = new String[] { "College" };
NCAAF_SECOND_NAME = new String[] { "2nd Half" };
// NBA_LINES_SPORT = new String[] { "PreseasonNBA" };
NBA_LINES_SPORT = new String[] { "NBA", "PreseasonNBA" };
NBA_LINES_NAME = new String[] { "Game" };
NBA_FIRST_SPORT = new String[] { "NBA", "PreseasonNBA" };
NBA_FIRST_NAME = new String[] { "1st Half" };
NBA_SECOND_SPORT = new String[] { "NBA", "PreseasonNBA" };
NBA_SECOND_NAME = new String[] { "2nd Half" };
NCAAB_LINES_SPORT = new String[] { "NCAA", "NCAA EXTRA" };
NCAAB_LINES_NAME = new String[] { "Game", "Basketball_NCAA" };
NCAAB_FIRST_SPORT = new String[] { "NCAA", "NCAA EXTRA" };
NCAAB_FIRST_NAME = new String[] { "1st Half" };
NCAAB_SECOND_SPORT = new String[] { "NCAA", "NCAA EXTRA" };
NCAAB_SECOND_NAME = new String[] { "2nd Half" };
NHL_LINES_SPORT = new String[] { "NHL" };
NHL_LINES_NAME = new String[] { "Game" };
NHL_FIRST_SPORT = new String[] { "NHL" };
NHL_FIRST_NAME = new String[] { "1st Period" };
NHL_SECOND_SPORT = new String[] { "NHL" };
NHL_SECOND_NAME = new String[] { "2nd Period" };
NHL_SECOND_SPORT = new String[] { "NHL" };
NHL_SECOND_NAME = new String[] { "3rd Period" };
WNBA_LINES_SPORT = new String[] { "WNBA" };
WNBA_LINES_NAME = new String[] { "Game" };
WNBA_FIRST_SPORT = new String[] { "WNBA" };
WNBA_FIRST_NAME = new String[] { "1st Half" };
WNBA_SECOND_SPORT = new String[] { "WNBA" };
WNBA_SECOND_NAME = new String[] { "2nd Half" };
MLB_LINES_SPORT = new String[] { "MLB", "Preseason" };
MLB_LINES_NAME = new String[] { "Game" };
MLB_FIRST_SPORT = new String[] { "MLB", "Preseason" };
MLB_FIRST_NAME = new String[] { "1st 5 Innings" };
MLB_SECOND_SPORT = new String[] { "MLB", "Preseason" };
MLB_SECOND_NAME = new String[] { "MLB 2nd half lines" };
LOGGER.info("Exiting AgSoftwareProcessSite()");
}
/**
* @param args
*/
public static void main(String[] args) {
try {
final String[][] AGSITES = new String [][] {
// { "http://www.betting4entertainment.com", "51336", "ap6", "100", "100", "100", "Baltimore", "ET" },
// { "http://www.slidinghome.com", "Pa1547", "flyers", "1000", "1000", "1000", "Baltimore", "ET" },
// { "http://www.smoothbets.com", "M1039", "Red", "500", "500", "500", "Dallas", "ET" }
// { "http://www.vegasbettingworld.com", "YL824", "red", "500", "500", "500", "Baltimore", "ET" }
// { "http://www.smoothbets.com", "M1005", "ball", "500", "500", "500", "Dallas", "ET" }
// { "http://www.vegasbettingworld.com", "YL802", "golf", "500", "500", "500", "New York", "ET" }
// { "http://www.vegasbettingworld.com", "Yl825", "gold", "500", "500", "500", "New York", "ET" }
// { "http://www.nysportscasino.com", "9180", "nike", "500", "500", "500", "None", "ET" }
// { "http://www.westcoastwager.com", "35114", "jj10", "500", "500", "500", "None", "ET" }
// { "http://www.spicylines.com", "64425", "jump", "500", "500", "500", "None", "ET" }
{ "http://www.vegasbettingworld.com", "qxcl755", "G", "100", "100", "100", "None", "ET" }
};
final AGSoftwareProcessSite processSite = new AGSoftwareProcessSite(AGSITES[0][0], AGSITES[0][1],
AGSITES[0][2], false, false);
processSite.httpClientWrapper.setupHttpClient(AGSITES[0][6]);
processSite.processTransaction = false;
processSite.timezone = AGSITES[0][7];
processSite.testSpread(processSite, AGSITES);
/*
Set<PendingEvent> pendingEvents = processSite.getPendingBets(AGSITES[0][0], AGSITES[0][1], null);
final Iterator<PendingEvent> itr = pendingEvents.iterator();
while (itr.hasNext()) {
final PendingEvent pe = itr.next();
LOGGER.error("PendingEventXXX: " + pe);
if (pe.getDoposturl()) {
processSite.doProcessPendingEvent(pe);
}
}
*/
} catch (Throwable t) {
LOGGER.info("Throwable: ", t);
}
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#getPendingBets(java.lang.String, java.lang.String, java.lang.Object)
*/
@Override
public Set<PendingEvent> getPendingBets(String accountName, String accountId, Object anythingObject) throws BatchException {
LOGGER.info("Entering getPendingBets()");
LOGGER.debug("accountName: " + accountName);
LOGGER.debug("accountId: " + accountId);
Set<PendingEvent> pendingWagers = null;
// Get the pending bets data
String xhtml = getSite(super.populateUrl(PENDING_BETS));
LOGGER.debug("xhtml: " + xhtml);
if (xhtml != null && xhtml.contains("view all wagers graded within the last 14 days.")) {
pendingWagers = ASP.parsePendingBets(xhtml, accountName, accountId);
if (pendingWagers != null && pendingWagers.size() > 0) {
final Iterator<PendingEvent> itr = pendingWagers.iterator();
EventPackage ep = null;
while (itr.hasNext()) {
final PendingEvent pendingEvent = itr.next();
LOGGER.debug("PendingEventABC: " + pendingEvent);
final Set<EventPackage> events = processSite.getAllSportsGame().getEvents();
Iterator<EventPackage> eItr = events.iterator();
boolean found = false;
while (eItr.hasNext() && !found) {
ep = eItr.next();
final Integer rotation1 = ep.getTeamone().getId();
final Integer rotation2 = ep.getTeamtwo().getId();
final String rotationId = pendingEvent.getRotationid();
LOGGER.debug("rotation1: " + rotation1);
LOGGER.debug("rotation2: " + rotation2);
LOGGER.debug("rotationId: " + rotationId);
if (rotationId != null && rotationId.length() > 0 &&
rotation1 != null && rotation2 != null &&
(rotationId.equals(rotation1.toString()) ||
rotationId.equals(rotation2.toString()))) {
// Set the dates
pendingEvent.setGametype(ep.getSporttype());
pendingEvent.setGamedate(ep.getEventdatetime());
pendingEvent.setEventdate(ep.getDateofevent() + " " + ep.getTimeofevent());
found = true;
LOGGER.debug("PendingEvent: " + pendingEvent);
}
}
}
}
} else {
LOGGER.error("xhtml: " + xhtml);
LOGGER.error("Not logged in");
if (xhtml != null && xhtml.contains("loginform")) {
this.loginToSite(this.httpClientWrapper.getUsername(), this.httpClientWrapper.getPassword());
}
xhtml = getSite(super.populateUrl(PENDING_BETS));
LOGGER.error("xhtml: " + xhtml);
if (xhtml != null && xhtml.contains("view all wagers graded within the last 14 days.")) {
pendingWagers = ASP.parsePendingBets(xhtml, accountName, accountId);
if (pendingWagers != null && pendingWagers.size() > 0) {
final Iterator<PendingEvent> itr = pendingWagers.iterator();
EventPackage ep = null;
while (itr.hasNext()) {
final PendingEvent pendingEvent = itr.next();
LOGGER.debug("PendingEventABC: " + pendingEvent);
final Set<EventPackage> events = processSite.getAllSportsGame().getEvents();
Iterator<EventPackage> eItr = events.iterator();
boolean found = false;
while (eItr.hasNext() && !found) {
ep = eItr.next();
final Integer rotation1 = ep.getTeamone().getId();
final Integer rotation2 = ep.getTeamtwo().getId();
final String rotationId = pendingEvent.getRotationid();
LOGGER.debug("rotation1: " + rotation1);
LOGGER.debug("rotation2: " + rotation2);
LOGGER.debug("rotationId: " + rotationId);
if (rotationId != null && rotationId.length() > 0 &&
rotation1 != null && rotation2 != null &&
(rotationId.equals(rotation1.toString()) ||
rotationId.equals(rotation2.toString()))) {
// Set the dates
pendingEvent.setGamedate(ep.getEventdatetime());
pendingEvent.setEventdate(ep.getDateofevent() + " " + ep.getTimeofevent());
found = true;
LOGGER.debug("PendingEvent: " + pendingEvent);
}
}
}
}
}
}
LOGGER.info("Exiting getPendingBets()");
return pendingWagers;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#loginToSite(java.lang.String, java.lang.String)
*/
@Override
public String loginToSite(String username, String password) throws BatchException {
LOGGER.info("Entering loginToSite()");
LOGGER.debug("username: " + username);
LOGGER.debug("password: " + password);
// Setup the timezone
ASP.setTimezone(timezone);
// Get the home page
String xhtml = getSite(httpClientWrapper.getHost());
LOGGER.debug("XHTML: " + xhtml);
// Get home page data
MAP_DATA = ASP.parseIndex(xhtml);
httpClientWrapper.setWebappname(determineWebappName(MAP_DATA.get("action")));
// setup the webapp name
if (httpClientWrapper.getWebappname() == null) {
httpClientWrapper.setWebappname("");
}
// Setup the customer ID
if (MAP_DATA.containsKey("customerID")) {
MAP_DATA.put("customerID", username);
} else if (MAP_DATA.containsKey("CustomerID")) {
MAP_DATA.put("CustomerID", username);
} else if (MAP_DATA.containsKey("customerid")) {
MAP_DATA.put("customerid", username);
}
// Setup the password
if (MAP_DATA.containsKey("password")) {
MAP_DATA.put("password", password);
} else if (MAP_DATA.containsKey("Password")) {
MAP_DATA.put("Password", password);
}
LOGGER.debug("Map: " + MAP_DATA);
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
String actionName = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionName: " + actionName);
// Authenticate
xhtml = authenticate(actionName, postValuePairs);
LOGGER.debug("XHTML: " + xhtml);
// Parse the login
MAP_DATA = ASP.parseLogin(xhtml);
if (MAP_DATA != null && MAP_DATA.containsKey("src")) {
final String javascriptString = getSite(this.httpClientWrapper.getHost() + MAP_DATA.get("src"));
LOGGER.debug("javascriptString: " + javascriptString);
// Parse the cookie information
String cookies = this.httpClientWrapper.getCookies();
cookies = ASP.parseCookies(javascriptString, cookies);
this.httpClientWrapper.setCookies(cookies);
}
if (MAP_DATA.containsKey("action")) {
postValuePairs = new ArrayList<NameValuePair>(1);
actionName = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionName: " + actionName);
// Call the WagerMenu
xhtml = postSite(actionName, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
// Now get the Risk/Win page
postValuePairs = new ArrayList<NameValuePair>(1);
// postValuePairs.add(new BasicNameValuePair("target", "single"));
postValuePairs.add(new BasicNameValuePair("target", ""));
postValuePairs.add(new BasicNameValuePair("wt", "Straight Bet"));
xhtml = postSite(actionName, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
}
LOGGER.info("Exiting loginToSite()");
return xhtml;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#selectSport(java.lang.String)
*/
@Override
protected String selectSport(String type) throws BatchException {
LOGGER.info("Entering selectSport()");
LOGGER.debug("type: " + type);
// Process the setup page
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
final String actionLogin = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionLogin: " + actionLogin);
// Post to site page
String xhtml = postSite(actionLogin, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
MAP_DATA = ASP.parseCaptcha(xhtml);
// value set by new code
String captchadata = processCaptcha(MAP_DATA.get("CaptchaImage"));
LOGGER.error("captchadata: " + captchadata);
if (captchadata == null || captchadata.length() == 0) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION,
BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
} else {
MAP_DATA.put("CaptchaMessage", captchadata);
}
postValuePairs = new ArrayList<NameValuePair>(1);
String actionName = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionName: " + actionName);
// Call the WagerMenu
xhtml = postSite(actionName, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION,
BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
}
LOGGER.info("Exiting selectSport()");
return xhtml;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#createSiteTransaction()
*/
@Override
protected SiteTransaction createSiteTransaction() {
LOGGER.info("Entering createSiteTransaction()");
final SiteTransaction siteTransaction = new SiteTransaction();
LOGGER.info("Exiting createSiteTransaction()");
return siteTransaction;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#selectEvent(com.ticketadvantage.services.dao.sites.SiteTransaction, com.ticketadvantage.services.model.EventPackage, com.ticketadvantage.services.model.BaseRecordEvent, com.ticketadvantage.services.model.AccountEvent)
*/
@Override
protected String selectEvent(SiteTransaction siteTransaction, EventPackage eventPackage, BaseRecordEvent event, AccountEvent ae) throws BatchException {
LOGGER.info("Entering selectEvent()");
for (SiteEventPackage sep : backupEventsPackage) {
if (sep.getSiteteamone().getGameSpreadInputName() != null) {
MAP_DATA.put(sep.getSiteteamone().getGameSpreadInputName(), "");
}
if (sep.getSiteteamone().getGameSpreadSelectName() != null) {
MAP_DATA.put(sep.getSiteteamone().getGameSpreadSelectName(), "0");
}
if (sep.getSiteteamone().getGameTotalInputName() != null) {
MAP_DATA.put(sep.getSiteteamone().getGameTotalInputName(), "");
}
if (sep.getSiteteamone().getGameTotalSelectName() != null) {
MAP_DATA.put(sep.getSiteteamone().getGameTotalSelectName(), "0");
}
if (sep.getSiteteamone().getGameMLInputName() != null) {
MAP_DATA.put(sep.getSiteteamone().getGameMLInputName(), "");
}
}
String siteAmount = determineRiskWinAmounts(siteTransaction, eventPackage, event, ae);
LOGGER.error("siteAmount: " + siteAmount);
siteTransaction.setAmount(siteAmount);
ae.setActualamount(siteAmount);
MAP_DATA.put(siteTransaction.getInputName(), siteAmount);
/*
// Get the spread transaction
if (event instanceof SpreadRecordEvent) {
siteTransaction = getSpreadTransaction((SpreadRecordEvent)event, eventPackage, ae);
siteAmount = siteTransaction.getAmount();
LOGGER.error("siteAmount: " + siteAmount);
Double sAmount = Double.parseDouble(siteAmount);
if (sAmount != null) {
final SiteEventPackage siteEventPackage = (SiteEventPackage)eventPackage;
LOGGER.debug("SiteEventPackage: " + siteEventPackage);
if (siteTransaction.getRiskorwin().intValue() == 1 && siteEventPackage.getSpreadMax() != null) {
if (sAmount.doubleValue() > siteEventPackage.getSpreadMax().intValue()) {
siteAmount = siteEventPackage.getSpreadMax().toString();
}
} else if (siteTransaction.getRiskorwin().intValue() == 2) {
Double wagerAmount = Double.valueOf(siteAmount);
float spreadJuice = ae.getSpreadjuice();
Double risk = wagerAmount * (100 / spreadJuice);
risk = round(risk.doubleValue(), 2);
LOGGER.error("Risk: " + risk);
if (siteEventPackage.getSpreadMax() != null && risk.doubleValue() > siteEventPackage.getSpreadMax().intValue()) {
siteAmount = siteEventPackage.getSpreadMax().toString();
} else {
siteAmount = risk.toString();
}
}
MAP_DATA.put(siteTransaction.getInputName(), siteAmount);
}
} else if (event instanceof TotalRecordEvent) {
siteTransaction = getTotalTransaction((TotalRecordEvent)event, eventPackage, ae);
siteAmount = siteTransaction.getAmount();
LOGGER.error("siteAmount: " + siteAmount);
Double tAmount = Double.parseDouble(siteAmount);
if (tAmount != null) {
final SiteEventPackage siteEventPackage = (SiteEventPackage)eventPackage;
LOGGER.debug("SiteEventPackage: " + siteEventPackage);
if (siteTransaction.getRiskorwin().intValue() == 1 && siteEventPackage.getTotalMax() != null) {
if (tAmount.doubleValue() > siteEventPackage.getTotalMax().intValue()) {
siteAmount = siteEventPackage.getTotalMax().toString();
}
} else if (siteTransaction.getRiskorwin().intValue() == 2) {
Double wagerAmount = Double.valueOf(siteAmount);
float totalJuice = ae.getTotaljuice();
Double risk = wagerAmount * (100 / totalJuice);
risk = round(risk.doubleValue(), 2);
LOGGER.error("Risk: " + risk);
if (siteEventPackage.getTotalMax() != null && risk.doubleValue() > siteEventPackage.getTotalMax().intValue()) {
siteAmount = siteEventPackage.getTotalMax().toString();
} else {
siteAmount = risk.toString();
}
}
MAP_DATA.put(siteTransaction.getInputName(), siteAmount);
}
} else if (event instanceof MlRecordEvent) {
siteTransaction = getMlTransaction((MlRecordEvent)event, eventPackage, ae);
siteAmount = siteTransaction.getAmount();
LOGGER.error("siteAmount: " + siteAmount);
Double mAmount = Double.parseDouble(siteAmount);
if (mAmount != null) {
final SiteEventPackage siteEventPackage = (SiteEventPackage)eventPackage;
LOGGER.debug("SiteEventPackage: " + siteEventPackage);
if (siteTransaction.getRiskorwin().intValue() == 1 && siteEventPackage.getMlMax() != null) {
if (mAmount.doubleValue() > siteEventPackage.getMlMax().intValue()) {
siteAmount = siteEventPackage.getMlMax().toString();
}
} else if (siteTransaction.getRiskorwin().intValue() == 2) {
Double wagerAmount = Double.valueOf(siteAmount);
float mlJuice = ae.getMljuice();
Double risk = wagerAmount * (100 / mlJuice);
risk = round(risk.doubleValue(), 2);
LOGGER.error("Risk: " + risk);
if (siteEventPackage.getMlMax() != null && risk.doubleValue() > siteEventPackage.getMlMax().intValue()) {
siteAmount = siteEventPackage.getMlMax().toString();
} else {
siteAmount = risk.toString();
}
}
MAP_DATA.put(siteTransaction.getInputName(), siteAmount);
}
}
LOGGER.debug("siteAmount: " + siteAmount);
ae.setActualamount(siteAmount);
*/
String xhtml = null;
// Setup the wager
httpClientWrapper.setCookies("slideStyle=long; __z_a=4230204650");
// Process the setup page
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
String actionLogin = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionLogin: " + actionLogin);
// Post to site page
xhtml = postSite(actionLogin, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION,
BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
LOGGER.info("Exiting selectEvent()");
return xhtml;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#parseEventSelection(java.lang.String, com.ticketadvantage.services.dao.sites.SiteTransaction, com.ticketadvantage.services.model.EventPackage, com.ticketadvantage.services.model.BaseRecordEvent, com.ticketadvantage.services.model.AccountEvent)
*/
@Override
protected void parseEventSelection(String xhtml, SiteTransaction siteTransaction, EventPackage eventPackage, BaseRecordEvent event, AccountEvent ae) throws BatchException {
LOGGER.info("Entering parseEventSelection()");
// Parse the event selection
Map<String, String> wagers = ASP.parseEventSelection(xhtml, null, null);
LOGGER.debug("wagers: " + wagers);
MAP_DATA = wagers;
String captchadata = null;
LOGGER.error("CaptchaImage: " + wagers.containsKey("CaptchaImage"));
if (wagers.containsKey("CaptchaImage") && wagers.get("CaptchaImage") != null && wagers.get("CaptchaImage").length() > 0) {
//value set by new code
captchadata = processCaptcha(wagers.get("CaptchaImage"));
LOGGER.error("captchadata: " + captchadata);
if (captchadata == null || captchadata.length() == 0) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
} else {
wagers.put("CaptchaMessage", captchadata);
}
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
String actionName = setupNameValuesEmpty(postValuePairs, wagers, null);
LOGGER.debug("ActionName: " + actionName);
// Call the WagerMenu
xhtml = postSite(actionName, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
MAP_DATA = ASP.parseEventSelection(xhtml, null, null);
}
LOGGER.info("Exiting parseEventSelection()");
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#completeTransaction(com.ticketadvantage.services.dao.sites.SiteTransaction, com.ticketadvantage.services.model.EventPackage, com.ticketadvantage.services.model.BaseRecordEvent, com.ticketadvantage.services.model.AccountEvent)
*/
@Override
protected String completeTransaction(SiteTransaction siteTransaction, EventPackage eventPackage, BaseRecordEvent event, AccountEvent ae) throws BatchException {
LOGGER.info("Entering completeTransaction()");
String xhtml = null;
try {
if (processTransaction) {
// Get the confirmation
xhtml = processWager(event, ae);
LOGGER.debug("XHTML: " + xhtml);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
}
} catch (BatchException be) {
LOGGER.error("Exception getting ticket number for account event " + ae + " event " + event, be);
throw be;
}
LOGGER.info("Exiting completeTransaction()");
return xhtml;
}
/*
* (non-Javadoc)
* @see com.ticketadvantage.services.dao.sites.SiteProcessor#parseTicketTransaction(java.lang.String)
*/
@Override
protected String parseTicketTransaction(String xhtml) throws BatchException {
LOGGER.info("Entering parseTicketTransaction()");
final String ticketNumber = ASP.parseTicketNumber(xhtml);
LOGGER.debug("ticketNumber: " + ticketNumber);
LOGGER.info("Exiting parseTicketTransaction()");
return ticketNumber;
}
/**
*
* @param event
* @param ae
* @return
* @throws BatchException
*/
private String processWager(BaseRecordEvent event, AccountEvent ae) throws BatchException {
LOGGER.info("Entering processWager()");
// Set password
MAP_DATA.put("password", this.httpClientWrapper.getPassword());
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
String actionUrl = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
// Call check acceptance
String xhtml = postSite(actionUrl, postValuePairs);
LOGGER.debug("XHTML: " + xhtml);
// Check for captcha
if (xhtml.contains("text from captcha below")) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Unexpected Captcha Page", xhtml);
}
// Check for line change
if (xhtml.contains("THE LINE (OR PRICE) HAS CHANGED")) {
xhtml = processLineChange(xhtml, event, ae);
}
// Check for captcha
if (xhtml.contains("text from captcha below")) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Unexpected Captcha Page", xhtml);
}
// "ProcessWagerRelay.asp");return;}setTimeout('OnTimer()',
if (!xhtml.contains("Wager has been accepted!")) {
int sleepAsUser = 45000;
int index = xhtml.indexOf("\"ProcessWagerRelay.asp\");return;}setTimeout('OnTimer()', ");
if (index != -1) {
xhtml = xhtml.substring(index + "\"ProcessWagerRelay.asp\");return;}setTimeout('OnTimer()', ".length());
index = xhtml.indexOf(");");
if (index != -1) {
try {
String sleepTime = xhtml.substring(0, index);
sleepAsUser = Integer.parseInt(sleepTime);
} catch (Throwable t) {
LOGGER.error(t.getMessage(), t);
}
}
}
// Sleep for defined seconds
sleepAsUser(sleepAsUser);
// Call it again
xhtml = getSite(super.populateUrl("ProcessWagerRelay.asp"));
// Check for captcha
if (xhtml.contains("text from captcha below")) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Unexpected Captcha Page", xhtml);
}
// Check for line change
if (xhtml.contains("THE LINE (OR PRICE) HAS CHANGED")) {
xhtml = processLineChange(xhtml, event, ae);
}
if (!xhtml.contains("Wager has been accepted!")) {
sleepAsUser = 45000;
index = xhtml.indexOf("\"ProcessWager.asp\");return;}setTimeout('OnTimer()', ");
if (index != -1) {
xhtml = xhtml.substring(index + "\"ProcessWager.asp\");return;}setTimeout('OnTimer()', ".length());
index = xhtml.indexOf(");");
try {
String sleepTime = xhtml.substring(0, index);
sleepAsUser = Integer.parseInt(sleepTime);
} catch (Throwable t) {
LOGGER.error(t.getMessage(), t);
}
}
// Sleep for defined seconds
sleepAsUser(sleepAsUser);
// Call it again
xhtml = getSite(super.populateUrl("ProcessWager.asp"));
// Check for captcha
if (xhtml.contains("text from captcha below")) {
// Throw an exception
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Unexpected Captcha Page", xhtml);
}
// Check for line change
if (xhtml.contains("THE LINE (OR PRICE) HAS CHANGED")) {
xhtml = processLineChange(xhtml, event, ae);
}
}
}
LOGGER.info("Exiting processWager()");
return xhtml;
}
/**
*
* @param xhtml
* @param event
* @param ae
* @return
* @throws BatchException
*/
private String processLineChange(String xhtml, BaseRecordEvent event, AccountEvent ae) throws BatchException {
LOGGER.info("Entering processLineChange()");
final Map<String, String> lineChanges = ASP.processLineChange(xhtml);
if (lineChanges != null && !lineChanges.isEmpty()) {
if (event instanceof SpreadRecordEvent) {
final SpreadRecordEvent sre = (SpreadRecordEvent)event;
if (determineSpreadLineChange(sre, ae, lineChanges)) {
// setup the data
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
MAP_DATA.put("password", this.httpClientWrapper.getPassword());
String actionLogin = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionLogin: " + actionLogin);
// Post to site page
xhtml = postSite(actionLogin, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
} else {
throw new BatchException(BatchErrorCodes.LINE_CHANGED_ERROR, BatchErrorMessage.LINE_CHANGED_ERROR, "The line has changed", xhtml);
}
} else if (event instanceof TotalRecordEvent) {
final TotalRecordEvent tre = (TotalRecordEvent)event;
if (determineTotalLineChange(tre, ae, lineChanges)) {
// setup the data
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
MAP_DATA.put("password", this.httpClientWrapper.getPassword());
String actionLogin = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionLogin: " + actionLogin);
// Post to site page
xhtml = postSite(actionLogin, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
} else {
throw new BatchException(BatchErrorCodes.LINE_CHANGED_ERROR, BatchErrorMessage.LINE_CHANGED_ERROR, "The line has changed", xhtml);
}
} else if (event instanceof MlRecordEvent) {
final MlRecordEvent mre = (MlRecordEvent)event;
if (determineMlLineChange(mre, ae, lineChanges)) {
// setup the data
List<NameValuePair> postValuePairs = new ArrayList<NameValuePair>(1);
MAP_DATA.put("password", this.httpClientWrapper.getPassword());
String actionLogin = setupNameValuesEmpty(postValuePairs, MAP_DATA, null);
LOGGER.debug("ActionLogin: " + actionLogin);
// Post to site page
xhtml = postSite(actionLogin, postValuePairs);
if (xhtml != null && xhtml.contains("not a robot by entering the text from captcha")) {
throw new BatchException(BatchErrorCodes.CAPTCHA_PROCESSING_EXCEPTION, BatchErrorMessage.CAPTCHA_PROCESSING_EXCEPTION, "Problem getting captcha text", xhtml);
}
} else {
throw new BatchException(BatchErrorCodes.LINE_CHANGED_ERROR, BatchErrorMessage.LINE_CHANGED_ERROR, "The line has changed", xhtml);
}
}
}
LOGGER.info("Exiting processLineChange()");
return xhtml;
}
/**
*
* @param imagedata
* @return
*/
protected String processCaptcha(String imagedata) {
String textdata = null;
try {
//Process captcha String
final CaptchaReader obj = new CaptchaReader();
textdata = captchaStr = obj.parseCaptcha(imagedata);
LOGGER.error("Captcha Text: " + captchaStr);
// Clean up text if necessary
if (!Pattern.matches("[a-zA-Z0-9]{6}",captchaStr)) {
// TODO
LOGGER.error("Captcha has non alphanumeric characters " + textdata);
}
} catch (Throwable t) {
LOGGER.error(t.getMessage(), t);
}
return textdata;
}
} | [
"[email protected]"
] | |
b19f968aba256ad50ae0090701b418b9167906fc | 23467db946f7fef2844f98a478e80dd0d4aa8fb1 | /PhoneC.java | f6b13d0ea8bce737cb94bcf646d4e957082b9998 | [] | no_license | RoyDog9/mysite | cc2e8cbbeccdaf49e18dd8140c92140ccff4c375 | 7efc4b438cdc0b2df9fe45512c39a0e005e82145 | refs/heads/master | 2020-12-26T19:46:55.889152 | 2020-02-01T14:07:10 | 2020-02-01T14:07:10 | 237,620,615 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,613 | java |
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class PhoneC extends Frame implements ActionListener { // ActionListerを使ってボタンを反応させる
// ■ フィールド変数
TextField txt1; // 名前を入力するため
Label lb1,lb2; // 文字を描画する為
Button btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9; // 画面に配置するボタンの定義
boolean m1=true,m2=false,m3=false,d=true; // モード変更用のフラグ
boolean push=true,f1=false,f2=false,f3=false; // ボタンを片付けるためのフラグ
byte[] b_ss; // writeを使うために文字列をバイト配列にする、その際格納するためのもの
byte[] b_ss2 = new byte[24]; //相手からのバイト配列を格納するためのもの
int a = 1; // 通話機能の変更に使う変数
boolean i=true,j=true,k=true,l=true; // 通話機能を知らせる文を一度しか表示させないようにするフラグ
boolean x=true; //whileの条件式がtrueだとコンパイルエラーになるため用意
int BITS = 16; // 16bit
int HZ = 8000; //周波数
int MONO = 1; //1秒
byte[] voice = new byte[ HZ * BITS / 8 * MONO ]; //声を送るためのバイト配列。一秒分のデータが入る。8で割っているのはビットをバイトにするため。
byte[] invoice = new byte[ HZ * BITS / 8 * MONO ];//送られてきたバイト配列を入れるためのもの
byte[] zero = new byte[HZ * BITS / 8 * MONO]; //ミュートに使うバイト配列、何も入っていない
byte[] zero2 = new byte[HZ * BITS / 8 * MONO]; //マイクオフに使うバイト配列、何も入っていない
static String strServer; //相手(サーバー)のPCのIPアドレスを入力するためのもの
String ss = "名無し",ss2; //名前の保存用、名前を設定しないと名無しで送られる
int nPort = 1111; //ポート番号は予め決めておいた
Record Rec = new Record() ; //Recordクラスを作成
Play Play = new Play(); //Playクラスを作成
Thread Th = new Thread(); //スレッドを作成,なくても動いた
public static void main(String [] args) { // メイン文
PhoneC ps = new PhoneC(); // PhoneS()を行う
}
// ■ コンストラクタ
PhoneC() {
super("まぐろ client"); //実行時につく名前
this.setSize(500, 400); //画面のサイズ500×400
setLayout(null); //絶対座標でボタンを配置したいのでオフに
this.setLocationRelativeTo(null); //これで実行時に出るウィンドがPC画面の真ん中になる
while(true){ //無限ループ
try{ //sleepを使うためのtry-catch
Thread.sleep(50); //これを入れるとボタンが反応するようになった
}catch(Exception e) {System.out.println("Exception: " + e);}
if(m1){ //モード1 タイトル画面
lb1 = new Label(); //定義
lb1.setText("まぐろ"); //まぐろという文字を描写
lb1.setFont(new Font("Arial", Font.BOLD+Font.ITALIC , 100));//フォントの指定
lb1.setForeground(Color.black); //色は黒
lb1.setBounds(100,120,300,100); //座標と大きさ
add(lb1); //
btn2 = new Button("名前変更"); // ボタンの設定
btn2.addActionListener(this); // ボタンのイベント処理
add(btn2); // ボタンの登録
btn2.setLocation(100, 350); // 座標の入力
btn2.setSize(140, 30); // ボタンの大きさ設定
btn3 = new Button("終了"); // ボタンの設定
btn3.addActionListener(this); // ボタンのイベント処理
add(btn3); // ボタンの登録
btn3.setLocation(260, 350);
btn3.setSize(140, 30);
btn1 = new Button("通話開始"); // ボタンの設定
btn1.addActionListener(this); // ボタンのイベント処理
add(btn1); // ボタンの登録
btn1.setLocation(100, 320);
btn1.setSize(300, 30);
this.setVisible(true); //可視化
m1 = false; //無限ループするたびに実行されると困るので、自らフラグをおろす
}
if(f1){ // モード1のラベル、ボタンを片付ける
remove(btn1);
remove(btn2);
remove(btn3);
remove(lb1);
f1 = false; //自らフラグをおろす。存在しないボタンを消すとエラーになってしまう。
}
if(m2){ // モード2 通話モード
btn4 = new Button("通常通話"); // ボタンの設定
btn4.addActionListener(this); // ボタンのイベント処理
add(btn4); // ボタンの登録
btn4.setLocation(100, 130);
btn4.setSize(300, 50);
btn5 = new Button("ミュート"); // ボタンの設定
btn5.addActionListener(this); // ボタンのイベント処理
add(btn5); // ボタンの登録
btn5.setLocation(100, 183);
btn5.setSize(300, 50);
btn9 = new Button("マイクオフ"); // ボタンの設定
btn9.addActionListener(this); // ボタンのイベント処理
add(btn9); // ボタンの登録
btn9.setLocation(100, 236);
btn9.setSize(300, 50);
btn6 = new Button("終了"); // ボタンの設定
btn6.addActionListener(this); // ボタンのイベント処理
add(btn6); // ボタンの登録
btn6.setLocation(100, 330);
btn6.setSize(300, 40);
this.setVisible(true); // 可視化
phone(); //後述の関数に入り、通話を行う。無限ループに入るのでここから出ることはない。
m2 = false;
}
if(f2){ // モード2のボタンを片付けるためのものだが、これが使われることはない。消しても問題なし。
remove(btn4);
remove(btn5);
remove(btn6);
remove(btn9);
f2 = false;
}
if(m3){ //モード3 名前変更モード
txt1 = new TextField(""); add(txt1); // テキストフィールドを準備
txt1.setLocation(100, 100); //座標を設定
txt1.setSize(300, 30); //大きさを設定
btn7 = new Button("この名前で決定"); // ボタンの設定
btn7.addActionListener(this); // ボタンのイベント処理
add(btn7); // ボタンの登録
btn7.setLocation(100, 280);
btn7.setSize(300, 40);
btn8 = new Button("戻る"); // ボタンの設定
btn8.addActionListener(this); // ボタンのイベント処理
add(btn8); // ボタンの登録
btn8.setLocation(100, 330);
btn8.setSize(300, 40);
this.setVisible(true);
m3=false; //自らフラグをおろす
}
if(f3){ //モード3のテキストフィールド、ボタンを片付ける
remove(txt1);
remove(btn7);
remove(btn8);
f3 = false; //自らフラグをおろす
}
}
}
public void actionPerformed(ActionEvent e) { //ボタンが押された時の処理
if (e.getSource() == btn1){ // ボタン1が押された時
f1=true; //モード1から出るので、モード1のボタンを消すためのフラグを立てる
m2=true; //モード2を行うためのフラグを立てる
}
else if(e.getSource() == btn2){
f1=true; //モード1から出るので、モード1のボタンを消すためのフラグを立てる
m3=true; //モード3を行うためのフラグを立てる
}
else if (e.getSource() == btn3)
System.exit(0); //プログラムの終了
else if(e.getSource() == btn4)
a = 1; //通話モードの切り替え、ミュートに切り替える
else if(e.getSource() == btn5)
a = 0; //通話モードの切り替え、マイクオフに切り替える
else if(e.getSource() == btn6){
System.exit(0); //プログラムの終了
}
else if(e.getSource() == btn7){
ss= txt1.getText();
}
else if(e.getSource() == btn8){
f3=true; //モード3から出るので、モード3のボタンを消すためのフラグを立てる
m1=true; //モード1を行うためのフラグを立てる
}
else if(e.getSource() == btn9){
a=2; //通話モードの切り替え、通常通話を行う
}
}
public void phone(){ //通話を行う関数
try{
Socket skt = new Socket(strServer, nPort); //ソケットの接続を試みる
System.out.println("自分の名前は " + ss + " です。"); //ターミナルに自分の名前を出力する。画面には表示しない。
OutputStream os = skt.getOutputStream(); //出力をソケットからもらう
DataOutputStream dos = new DataOutputStream(os); //データの出力を可能にする
InputStream is = skt.getInputStream(); //入力をソケットからもらう
DataInputStream dis = new DataInputStream(is); //データの入力を可能にする
b_ss = new byte[3*ss.length()]; //文字列の文字数の三倍の長さのバイト配列を用意。これだけあれば溢れることはない。
b_ss = ss.getBytes(); //文字列をバイト配列に変換
dos.write(b_ss); //writeの中に入れることで送ることができる
dis.read(b_ss2); //readで相手が送ってきた名前を受け取る
ss2= new String(b_ss2); //この文でバイト配列を文字列に復元できる
lb2 = new Label(); //相手の名前を画面に表示する
lb2.setText(" 通話相手は " + ss2 + " さんです。"); //表示される文
lb2.setFont(new Font("Arial", Font.BOLD+Font.ITALIC , 14));//フォントの指定
lb2.setForeground(Color.black); //文字の色は黒
lb2.setBounds(0,0,300,100); //座標と大きさ
add(lb2); //ラベルの登録
System.out.println("通話相手は " + ss2 + " さんです。"); //ターミナルにも出力
this.setVisible(true); //可視化
Th.start(); //なくても動いた
Rec.start(); //Record内のrunの開始、音声を読み込み続ける
Play.start(); //Play内のrunの開始、スピーカーに音声を出力する
while(x){ // 通話モードに入ったあとの無限ループ
while(a==1){
if(i){ //通常通話中ということを知らせる
System.out.println( "通常通話中" );
i=false;
j=true;
}
voice = Rec.getVoice(); //getVoiceによってRecordクラス内にある音声データを返す
dos.write(voice); //相手に音声を送る
dis.read(invoice); //相手からの音声を受け取る
Play.setVoice( invoice ); //Playクラス内の音声データを書き換える
}
while(a==0){ //相手の声遮断
if(k){ //ミュート中ということを知らせる
System.out.println( "ミュート中" );
k=false;
j=true;
}
voice = Rec.getVoice();
dos.write(voice);
dis.read(invoice);
Play.setVoice( zero ); //用意しておいた何も入っていない配列をスピーカーに出力させる
}
while(a==2){ // 相手に声を届けない
if(l){ //マイクオフ中ということを知らせる
System.out.println( "マイクオフ中" );
l=false;
j=true;
}
voice = Rec.getVoice();
dos.write(zero2); //相手に送る音声に何も入っていない配列を使うことで、自分の声を届けない
dis.read(invoice);
Play.setVoice( invoice );
}
if(j){ //全てのフラグを元に戻す(立てる),マイクオフ後に通常通話に入ると文が表示されなくなることが防げる。
i=true;
k=true;
l=true;
j=false;
}
}
Play.end(); //ソースデータラインを閉じることができる
Rec.end(); //ターゲットデータラインを閉じることができる
}catch(NumberFormatException e){ //エラー処理
System.err.println("引数はポーと番号です。1000〜65535までの数字を設定してください。"); //ポート番号は設定しているので削除しても問題はなさそう
}catch(IndexOutOfBoundsException e){
System.err.println("引数はポート番号です。1000〜65535までの数字を設定してください。"); //ポート番号は設定しているので削除しても問題はなさそう
}catch(IOException e){
System.err.println("サーバーが見つかりません。どっか行きました\n" + e); //通話後にネットワークが切断されると、出力される
System.exit(0);
}catch(Exception e){
System.err.println(e); //その他のエラー
}
}
}
| [
"[email protected]"
] | |
d34cb1560812a082518ee92456f0ccf1dc05af10 | 9a2c05dfc7081b93e0c6630ed6703de49d8be2e2 | /app/src/main/java/com/example/mathew/sqlitelaba/Contacts.java | a2fed9bc30173a633cff8e4aa914810fdd496ef8 | [] | no_license | MavoMuchemi/SQLiteLAB3 | d020587aa92b542b1b4be4d986a3febb26cd991a | b9f2aac19f8109db68dd1def393cf34663fa5e79 | refs/heads/master | 2021-07-17T16:04:37.830711 | 2017-10-24T11:15:40 | 2017-10-24T11:15:40 | 108,116,225 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 987 | java | package com.example.mathew.sqlitelaba;
import static android.R.attr.id;
/**
* Created by Mathew on 24/10/2017.
*/
public class Contacts {
int _id;
String _name;
String _phone_number;
public Contacts(){
}
public Contacts (int id, String name, String _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;}
public Contacts(String name, String _phone_number){this. _name = name;
this. _phone_number= _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int _id ){
this._id= id;
}
public String getName(){
return this._name;
}
public void setName (String name){
this._name = name;
}
public String getPhoneNumber() {
return this._phone_number;
}
public void setPhoneNumber (String phone_number) {
this._phone_number = phone_number;
}
}
| [
"[email protected]"
] | |
a173cce66375dc9f557fddbec2e362f2cf414919 | 6baf1fe00541560788e78de5244ae17a7a2b375a | /hollywood/com.oculus.vrshell-VrShell/sources/android/support/v4/media/session/IMediaSession.java | ca0327624087ff10fbdcee304f89bcfca526c7e3 | [] | no_license | phwd/quest-tracker | 286e605644fc05f00f4904e51f73d77444a78003 | 3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba | refs/heads/main | 2023-03-29T20:33:10.959529 | 2021-04-10T22:14:11 | 2021-04-10T22:14:11 | 357,185,040 | 4 | 2 | null | 2021-04-12T12:28:09 | 2021-04-12T12:28:08 | null | UTF-8 | Java | false | false | 63,333 | java | package android.support.v4.media.session;
import android.app.PendingIntent;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.RatingCompat;
import android.support.v4.media.session.IMediaControllerCallback;
import android.support.v4.media.session.MediaSessionCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import java.util.List;
public interface IMediaSession extends IInterface {
void addQueueItem(MediaDescriptionCompat mediaDescriptionCompat) throws RemoteException;
void addQueueItemAt(MediaDescriptionCompat mediaDescriptionCompat, int i) throws RemoteException;
void adjustVolume(int i, int i2, String str) throws RemoteException;
void fastForward() throws RemoteException;
Bundle getExtras() throws RemoteException;
long getFlags() throws RemoteException;
PendingIntent getLaunchPendingIntent() throws RemoteException;
MediaMetadataCompat getMetadata() throws RemoteException;
String getPackageName() throws RemoteException;
PlaybackStateCompat getPlaybackState() throws RemoteException;
List<MediaSessionCompat.QueueItem> getQueue() throws RemoteException;
CharSequence getQueueTitle() throws RemoteException;
int getRatingType() throws RemoteException;
int getRepeatMode() throws RemoteException;
int getShuffleMode() throws RemoteException;
String getTag() throws RemoteException;
ParcelableVolumeInfo getVolumeAttributes() throws RemoteException;
boolean isCaptioningEnabled() throws RemoteException;
boolean isShuffleModeEnabledRemoved() throws RemoteException;
boolean isTransportControlEnabled() throws RemoteException;
void next() throws RemoteException;
void pause() throws RemoteException;
void play() throws RemoteException;
void playFromMediaId(String str, Bundle bundle) throws RemoteException;
void playFromSearch(String str, Bundle bundle) throws RemoteException;
void playFromUri(Uri uri, Bundle bundle) throws RemoteException;
void prepare() throws RemoteException;
void prepareFromMediaId(String str, Bundle bundle) throws RemoteException;
void prepareFromSearch(String str, Bundle bundle) throws RemoteException;
void prepareFromUri(Uri uri, Bundle bundle) throws RemoteException;
void previous() throws RemoteException;
void rate(RatingCompat ratingCompat) throws RemoteException;
void rateWithExtras(RatingCompat ratingCompat, Bundle bundle) throws RemoteException;
void registerCallbackListener(IMediaControllerCallback iMediaControllerCallback) throws RemoteException;
void removeQueueItem(MediaDescriptionCompat mediaDescriptionCompat) throws RemoteException;
void removeQueueItemAt(int i) throws RemoteException;
void rewind() throws RemoteException;
void seekTo(long j) throws RemoteException;
void sendCommand(String str, Bundle bundle, MediaSessionCompat.ResultReceiverWrapper resultReceiverWrapper) throws RemoteException;
void sendCustomAction(String str, Bundle bundle) throws RemoteException;
boolean sendMediaButton(KeyEvent keyEvent) throws RemoteException;
void setCaptioningEnabled(boolean z) throws RemoteException;
void setRepeatMode(int i) throws RemoteException;
void setShuffleMode(int i) throws RemoteException;
void setShuffleModeEnabledRemoved(boolean z) throws RemoteException;
void setVolumeTo(int i, int i2, String str) throws RemoteException;
void skipToQueueItem(long j) throws RemoteException;
void stop() throws RemoteException;
void unregisterCallbackListener(IMediaControllerCallback iMediaControllerCallback) throws RemoteException;
public static abstract class Stub extends Binder implements IMediaSession {
private static final String DESCRIPTOR = "android.support.v4.media.session.IMediaSession";
static final int TRANSACTION_addQueueItem = 41;
static final int TRANSACTION_addQueueItemAt = 42;
static final int TRANSACTION_adjustVolume = 11;
static final int TRANSACTION_fastForward = 22;
static final int TRANSACTION_getExtras = 31;
static final int TRANSACTION_getFlags = 9;
static final int TRANSACTION_getLaunchPendingIntent = 8;
static final int TRANSACTION_getMetadata = 27;
static final int TRANSACTION_getPackageName = 6;
static final int TRANSACTION_getPlaybackState = 28;
static final int TRANSACTION_getQueue = 29;
static final int TRANSACTION_getQueueTitle = 30;
static final int TRANSACTION_getRatingType = 32;
static final int TRANSACTION_getRepeatMode = 37;
static final int TRANSACTION_getShuffleMode = 47;
static final int TRANSACTION_getTag = 7;
static final int TRANSACTION_getVolumeAttributes = 10;
static final int TRANSACTION_isCaptioningEnabled = 45;
static final int TRANSACTION_isShuffleModeEnabledRemoved = 38;
static final int TRANSACTION_isTransportControlEnabled = 5;
static final int TRANSACTION_next = 20;
static final int TRANSACTION_pause = 18;
static final int TRANSACTION_play = 13;
static final int TRANSACTION_playFromMediaId = 14;
static final int TRANSACTION_playFromSearch = 15;
static final int TRANSACTION_playFromUri = 16;
static final int TRANSACTION_prepare = 33;
static final int TRANSACTION_prepareFromMediaId = 34;
static final int TRANSACTION_prepareFromSearch = 35;
static final int TRANSACTION_prepareFromUri = 36;
static final int TRANSACTION_previous = 21;
static final int TRANSACTION_rate = 25;
static final int TRANSACTION_rateWithExtras = 51;
static final int TRANSACTION_registerCallbackListener = 3;
static final int TRANSACTION_removeQueueItem = 43;
static final int TRANSACTION_removeQueueItemAt = 44;
static final int TRANSACTION_rewind = 23;
static final int TRANSACTION_seekTo = 24;
static final int TRANSACTION_sendCommand = 1;
static final int TRANSACTION_sendCustomAction = 26;
static final int TRANSACTION_sendMediaButton = 2;
static final int TRANSACTION_setCaptioningEnabled = 46;
static final int TRANSACTION_setRepeatMode = 39;
static final int TRANSACTION_setShuffleMode = 48;
static final int TRANSACTION_setShuffleModeEnabledRemoved = 40;
static final int TRANSACTION_setVolumeTo = 12;
static final int TRANSACTION_skipToQueueItem = 17;
static final int TRANSACTION_stop = 19;
static final int TRANSACTION_unregisterCallbackListener = 4;
public IBinder asBinder() {
return this;
}
public Stub() {
attachInterface(this, DESCRIPTOR);
}
public static IMediaSession asInterface(IBinder iBinder) {
if (iBinder == null) {
return null;
}
IInterface queryLocalInterface = iBinder.queryLocalInterface(DESCRIPTOR);
if (queryLocalInterface == null || !(queryLocalInterface instanceof IMediaSession)) {
return new Proxy(iBinder);
}
return (IMediaSession) queryLocalInterface;
}
@Override // android.os.Binder
public boolean onTransact(int i, Parcel parcel, Parcel parcel2, int i2) throws RemoteException {
Bundle bundle = null;
MediaDescriptionCompat mediaDescriptionCompat = null;
MediaDescriptionCompat mediaDescriptionCompat2 = null;
MediaDescriptionCompat mediaDescriptionCompat3 = null;
Bundle bundle2 = null;
Bundle bundle3 = null;
Bundle bundle4 = null;
Bundle bundle5 = null;
RatingCompat ratingCompat = null;
Bundle bundle6 = null;
Bundle bundle7 = null;
Bundle bundle8 = null;
KeyEvent keyEvent = null;
MediaSessionCompat.ResultReceiverWrapper resultReceiverWrapper = null;
if (i == TRANSACTION_rateWithExtras) {
parcel.enforceInterface(DESCRIPTOR);
RatingCompat createFromParcel = parcel.readInt() != 0 ? RatingCompat.CREATOR.createFromParcel(parcel) : null;
if (parcel.readInt() != 0) {
bundle = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
rateWithExtras(createFromParcel, bundle);
parcel2.writeNoException();
return true;
} else if (i != 1598968902) {
boolean z = false;
switch (i) {
case 1:
parcel.enforceInterface(DESCRIPTOR);
String readString = parcel.readString();
Bundle bundle9 = parcel.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(parcel) : null;
if (parcel.readInt() != 0) {
resultReceiverWrapper = MediaSessionCompat.ResultReceiverWrapper.CREATOR.createFromParcel(parcel);
}
sendCommand(readString, bundle9, resultReceiverWrapper);
parcel2.writeNoException();
return true;
case 2:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
keyEvent = (KeyEvent) KeyEvent.CREATOR.createFromParcel(parcel);
}
boolean sendMediaButton = sendMediaButton(keyEvent);
parcel2.writeNoException();
parcel2.writeInt(sendMediaButton ? 1 : 0);
return true;
case 3:
parcel.enforceInterface(DESCRIPTOR);
registerCallbackListener(IMediaControllerCallback.Stub.asInterface(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 4:
parcel.enforceInterface(DESCRIPTOR);
unregisterCallbackListener(IMediaControllerCallback.Stub.asInterface(parcel.readStrongBinder()));
parcel2.writeNoException();
return true;
case 5:
parcel.enforceInterface(DESCRIPTOR);
boolean isTransportControlEnabled = isTransportControlEnabled();
parcel2.writeNoException();
parcel2.writeInt(isTransportControlEnabled ? 1 : 0);
return true;
case 6:
parcel.enforceInterface(DESCRIPTOR);
String packageName = getPackageName();
parcel2.writeNoException();
parcel2.writeString(packageName);
return true;
case 7:
parcel.enforceInterface(DESCRIPTOR);
String tag = getTag();
parcel2.writeNoException();
parcel2.writeString(tag);
return true;
case 8:
parcel.enforceInterface(DESCRIPTOR);
PendingIntent launchPendingIntent = getLaunchPendingIntent();
parcel2.writeNoException();
if (launchPendingIntent != null) {
parcel2.writeInt(1);
launchPendingIntent.writeToParcel(parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case 9:
parcel.enforceInterface(DESCRIPTOR);
long flags = getFlags();
parcel2.writeNoException();
parcel2.writeLong(flags);
return true;
case 10:
parcel.enforceInterface(DESCRIPTOR);
ParcelableVolumeInfo volumeAttributes = getVolumeAttributes();
parcel2.writeNoException();
if (volumeAttributes != null) {
parcel2.writeInt(1);
volumeAttributes.writeToParcel(parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case 11:
parcel.enforceInterface(DESCRIPTOR);
adjustVolume(parcel.readInt(), parcel.readInt(), parcel.readString());
parcel2.writeNoException();
return true;
case 12:
parcel.enforceInterface(DESCRIPTOR);
setVolumeTo(parcel.readInt(), parcel.readInt(), parcel.readString());
parcel2.writeNoException();
return true;
case 13:
parcel.enforceInterface(DESCRIPTOR);
play();
parcel2.writeNoException();
return true;
case 14:
parcel.enforceInterface(DESCRIPTOR);
String readString2 = parcel.readString();
if (parcel.readInt() != 0) {
bundle8 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
playFromMediaId(readString2, bundle8);
parcel2.writeNoException();
return true;
case 15:
parcel.enforceInterface(DESCRIPTOR);
String readString3 = parcel.readString();
if (parcel.readInt() != 0) {
bundle7 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
playFromSearch(readString3, bundle7);
parcel2.writeNoException();
return true;
case 16:
parcel.enforceInterface(DESCRIPTOR);
Uri uri = parcel.readInt() != 0 ? (Uri) Uri.CREATOR.createFromParcel(parcel) : null;
if (parcel.readInt() != 0) {
bundle6 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
playFromUri(uri, bundle6);
parcel2.writeNoException();
return true;
case 17:
parcel.enforceInterface(DESCRIPTOR);
skipToQueueItem(parcel.readLong());
parcel2.writeNoException();
return true;
case 18:
parcel.enforceInterface(DESCRIPTOR);
pause();
parcel2.writeNoException();
return true;
case 19:
parcel.enforceInterface(DESCRIPTOR);
stop();
parcel2.writeNoException();
return true;
case 20:
parcel.enforceInterface(DESCRIPTOR);
next();
parcel2.writeNoException();
return true;
case 21:
parcel.enforceInterface(DESCRIPTOR);
previous();
parcel2.writeNoException();
return true;
case 22:
parcel.enforceInterface(DESCRIPTOR);
fastForward();
parcel2.writeNoException();
return true;
case 23:
parcel.enforceInterface(DESCRIPTOR);
rewind();
parcel2.writeNoException();
return true;
case 24:
parcel.enforceInterface(DESCRIPTOR);
seekTo(parcel.readLong());
parcel2.writeNoException();
return true;
case 25:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
ratingCompat = RatingCompat.CREATOR.createFromParcel(parcel);
}
rate(ratingCompat);
parcel2.writeNoException();
return true;
case 26:
parcel.enforceInterface(DESCRIPTOR);
String readString4 = parcel.readString();
if (parcel.readInt() != 0) {
bundle5 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
sendCustomAction(readString4, bundle5);
parcel2.writeNoException();
return true;
case 27:
parcel.enforceInterface(DESCRIPTOR);
MediaMetadataCompat metadata = getMetadata();
parcel2.writeNoException();
if (metadata != null) {
parcel2.writeInt(1);
metadata.writeToParcel(parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case 28:
parcel.enforceInterface(DESCRIPTOR);
PlaybackStateCompat playbackState = getPlaybackState();
parcel2.writeNoException();
if (playbackState != null) {
parcel2.writeInt(1);
playbackState.writeToParcel(parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case TRANSACTION_getQueue /*{ENCODED_INT: 29}*/:
parcel.enforceInterface(DESCRIPTOR);
List<MediaSessionCompat.QueueItem> queue = getQueue();
parcel2.writeNoException();
parcel2.writeTypedList(queue);
return true;
case TRANSACTION_getQueueTitle /*{ENCODED_INT: 30}*/:
parcel.enforceInterface(DESCRIPTOR);
CharSequence queueTitle = getQueueTitle();
parcel2.writeNoException();
if (queueTitle != null) {
parcel2.writeInt(1);
TextUtils.writeToParcel(queueTitle, parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case TRANSACTION_getExtras /*{ENCODED_INT: 31}*/:
parcel.enforceInterface(DESCRIPTOR);
Bundle extras = getExtras();
parcel2.writeNoException();
if (extras != null) {
parcel2.writeInt(1);
extras.writeToParcel(parcel2, 1);
} else {
parcel2.writeInt(0);
}
return true;
case 32:
parcel.enforceInterface(DESCRIPTOR);
int ratingType = getRatingType();
parcel2.writeNoException();
parcel2.writeInt(ratingType);
return true;
case 33:
parcel.enforceInterface(DESCRIPTOR);
prepare();
parcel2.writeNoException();
return true;
case 34:
parcel.enforceInterface(DESCRIPTOR);
String readString5 = parcel.readString();
if (parcel.readInt() != 0) {
bundle4 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
prepareFromMediaId(readString5, bundle4);
parcel2.writeNoException();
return true;
case 35:
parcel.enforceInterface(DESCRIPTOR);
String readString6 = parcel.readString();
if (parcel.readInt() != 0) {
bundle3 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
prepareFromSearch(readString6, bundle3);
parcel2.writeNoException();
return true;
case 36:
parcel.enforceInterface(DESCRIPTOR);
Uri uri2 = parcel.readInt() != 0 ? (Uri) Uri.CREATOR.createFromParcel(parcel) : null;
if (parcel.readInt() != 0) {
bundle2 = (Bundle) Bundle.CREATOR.createFromParcel(parcel);
}
prepareFromUri(uri2, bundle2);
parcel2.writeNoException();
return true;
case 37:
parcel.enforceInterface(DESCRIPTOR);
int repeatMode = getRepeatMode();
parcel2.writeNoException();
parcel2.writeInt(repeatMode);
return true;
case 38:
parcel.enforceInterface(DESCRIPTOR);
boolean isShuffleModeEnabledRemoved = isShuffleModeEnabledRemoved();
parcel2.writeNoException();
parcel2.writeInt(isShuffleModeEnabledRemoved ? 1 : 0);
return true;
case 39:
parcel.enforceInterface(DESCRIPTOR);
setRepeatMode(parcel.readInt());
parcel2.writeNoException();
return true;
case 40:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
z = true;
}
setShuffleModeEnabledRemoved(z);
parcel2.writeNoException();
return true;
case 41:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
mediaDescriptionCompat3 = MediaDescriptionCompat.CREATOR.createFromParcel(parcel);
}
addQueueItem(mediaDescriptionCompat3);
parcel2.writeNoException();
return true;
case 42:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
mediaDescriptionCompat2 = MediaDescriptionCompat.CREATOR.createFromParcel(parcel);
}
addQueueItemAt(mediaDescriptionCompat2, parcel.readInt());
parcel2.writeNoException();
return true;
case 43:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
mediaDescriptionCompat = MediaDescriptionCompat.CREATOR.createFromParcel(parcel);
}
removeQueueItem(mediaDescriptionCompat);
parcel2.writeNoException();
return true;
case 44:
parcel.enforceInterface(DESCRIPTOR);
removeQueueItemAt(parcel.readInt());
parcel2.writeNoException();
return true;
case 45:
parcel.enforceInterface(DESCRIPTOR);
boolean isCaptioningEnabled = isCaptioningEnabled();
parcel2.writeNoException();
parcel2.writeInt(isCaptioningEnabled ? 1 : 0);
return true;
case 46:
parcel.enforceInterface(DESCRIPTOR);
if (parcel.readInt() != 0) {
z = true;
}
setCaptioningEnabled(z);
parcel2.writeNoException();
return true;
case 47:
parcel.enforceInterface(DESCRIPTOR);
int shuffleMode = getShuffleMode();
parcel2.writeNoException();
parcel2.writeInt(shuffleMode);
return true;
case TRANSACTION_setShuffleMode /*{ENCODED_INT: 48}*/:
parcel.enforceInterface(DESCRIPTOR);
setShuffleMode(parcel.readInt());
parcel2.writeNoException();
return true;
default:
return super.onTransact(i, parcel, parcel2, i2);
}
} else {
parcel2.writeString(DESCRIPTOR);
return true;
}
}
private static class Proxy implements IMediaSession {
private IBinder mRemote;
public String getInterfaceDescriptor() {
return Stub.DESCRIPTOR;
}
Proxy(IBinder iBinder) {
this.mRemote = iBinder;
}
public IBinder asBinder() {
return this.mRemote;
}
@Override // android.support.v4.media.session.IMediaSession
public void sendCommand(String str, Bundle bundle, MediaSessionCompat.ResultReceiverWrapper resultReceiverWrapper) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
if (resultReceiverWrapper != null) {
obtain.writeInt(1);
resultReceiverWrapper.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(1, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public boolean sendMediaButton(KeyEvent keyEvent) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
boolean z = true;
if (keyEvent != null) {
obtain.writeInt(1);
keyEvent.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(2, obtain, obtain2, 0);
obtain2.readException();
if (obtain2.readInt() == 0) {
z = false;
}
return z;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void registerCallbackListener(IMediaControllerCallback iMediaControllerCallback) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeStrongBinder(iMediaControllerCallback != null ? iMediaControllerCallback.asBinder() : null);
this.mRemote.transact(3, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void unregisterCallbackListener(IMediaControllerCallback iMediaControllerCallback) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeStrongBinder(iMediaControllerCallback != null ? iMediaControllerCallback.asBinder() : null);
this.mRemote.transact(4, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public boolean isTransportControlEnabled() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
boolean z = false;
this.mRemote.transact(5, obtain, obtain2, 0);
obtain2.readException();
if (obtain2.readInt() != 0) {
z = true;
}
return z;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public String getPackageName() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(6, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readString();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public String getTag() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(7, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readString();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public PendingIntent getLaunchPendingIntent() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(8, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (PendingIntent) PendingIntent.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public long getFlags() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(9, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readLong();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public ParcelableVolumeInfo getVolumeAttributes() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(10, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? ParcelableVolumeInfo.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void adjustVolume(int i, int i2, String str) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeInt(i2);
obtain.writeString(str);
this.mRemote.transact(11, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void setVolumeTo(int i, int i2, String str) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
obtain.writeInt(i2);
obtain.writeString(str);
this.mRemote.transact(12, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public MediaMetadataCompat getMetadata() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(27, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? MediaMetadataCompat.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public PlaybackStateCompat getPlaybackState() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(28, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? PlaybackStateCompat.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public List<MediaSessionCompat.QueueItem> getQueue() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(Stub.TRANSACTION_getQueue, obtain, obtain2, 0);
obtain2.readException();
return obtain2.createTypedArrayList(MediaSessionCompat.QueueItem.CREATOR);
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public CharSequence getQueueTitle() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(Stub.TRANSACTION_getQueueTitle, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (CharSequence) TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public Bundle getExtras() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(Stub.TRANSACTION_getExtras, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt() != 0 ? (Bundle) Bundle.CREATOR.createFromParcel(obtain2) : null;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public int getRatingType() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(32, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public boolean isCaptioningEnabled() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
boolean z = false;
this.mRemote.transact(45, obtain, obtain2, 0);
obtain2.readException();
if (obtain2.readInt() != 0) {
z = true;
}
return z;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public int getRepeatMode() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(37, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public boolean isShuffleModeEnabledRemoved() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
boolean z = false;
this.mRemote.transact(38, obtain, obtain2, 0);
obtain2.readException();
if (obtain2.readInt() != 0) {
z = true;
}
return z;
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public int getShuffleMode() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(47, obtain, obtain2, 0);
obtain2.readException();
return obtain2.readInt();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void addQueueItem(MediaDescriptionCompat mediaDescriptionCompat) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (mediaDescriptionCompat != null) {
obtain.writeInt(1);
mediaDescriptionCompat.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(41, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void addQueueItemAt(MediaDescriptionCompat mediaDescriptionCompat, int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (mediaDescriptionCompat != null) {
obtain.writeInt(1);
mediaDescriptionCompat.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
obtain.writeInt(i);
this.mRemote.transact(42, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void removeQueueItem(MediaDescriptionCompat mediaDescriptionCompat) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (mediaDescriptionCompat != null) {
obtain.writeInt(1);
mediaDescriptionCompat.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(43, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void removeQueueItemAt(int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
this.mRemote.transact(44, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void prepare() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(33, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void prepareFromMediaId(String str, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(34, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void prepareFromSearch(String str, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(35, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void prepareFromUri(Uri uri, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (uri != null) {
obtain.writeInt(1);
uri.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(36, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void play() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(13, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void playFromMediaId(String str, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(14, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void playFromSearch(String str, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(15, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void playFromUri(Uri uri, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (uri != null) {
obtain.writeInt(1);
uri.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(16, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void skipToQueueItem(long j) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeLong(j);
this.mRemote.transact(17, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void pause() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(18, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void stop() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(19, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void next() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(20, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void previous() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(21, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void fastForward() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(22, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void rewind() throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
this.mRemote.transact(23, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void seekTo(long j) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeLong(j);
this.mRemote.transact(24, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void rate(RatingCompat ratingCompat) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (ratingCompat != null) {
obtain.writeInt(1);
ratingCompat.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(25, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void rateWithExtras(RatingCompat ratingCompat, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
if (ratingCompat != null) {
obtain.writeInt(1);
ratingCompat.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(Stub.TRANSACTION_rateWithExtras, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void setCaptioningEnabled(boolean z) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(z ? 1 : 0);
this.mRemote.transact(46, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void setRepeatMode(int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
this.mRemote.transact(39, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void setShuffleModeEnabledRemoved(boolean z) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(z ? 1 : 0);
this.mRemote.transact(40, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void setShuffleMode(int i) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeInt(i);
this.mRemote.transact(Stub.TRANSACTION_setShuffleMode, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
@Override // android.support.v4.media.session.IMediaSession
public void sendCustomAction(String str, Bundle bundle) throws RemoteException {
Parcel obtain = Parcel.obtain();
Parcel obtain2 = Parcel.obtain();
try {
obtain.writeInterfaceToken(Stub.DESCRIPTOR);
obtain.writeString(str);
if (bundle != null) {
obtain.writeInt(1);
bundle.writeToParcel(obtain, 0);
} else {
obtain.writeInt(0);
}
this.mRemote.transact(26, obtain, obtain2, 0);
obtain2.readException();
} finally {
obtain2.recycle();
obtain.recycle();
}
}
}
}
}
| [
"[email protected]"
] | |
829856bfa775f235288d0e93ff2ad8fe35747896 | f929fe3cbb2c5c92b16482bd5e6e67e674714ee8 | /src/main/java/com/yao/ttshop/dao/TbOrderItemMapper.java | dd7f1c6c001b4b7bcb0c2f668ae95d28a1d52bdc | [] | no_license | yaoBatis/tt-SSM | 5e0265c90c75b28fc40cb2c2d95058cb3ba80c3e | 205b8a3732a5bf6e15d8a0482cda4087b8c95956 | refs/heads/master | 2021-01-21T12:27:07.352177 | 2017-09-01T03:11:00 | 2017-09-01T03:11:00 | 102,068,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 907 | java | package com.yao.ttshop.dao;
import com.yao.tttest.pojo.po.TbOrderItem;
import com.yao.tttest.pojo.po.TbOrderItemExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TbOrderItemMapper {
int countByExample(TbOrderItemExample example);
int deleteByExample(TbOrderItemExample example);
int deleteByPrimaryKey(String id);
int insert(TbOrderItem record);
int insertSelective(TbOrderItem record);
List<TbOrderItem> selectByExample(TbOrderItemExample example);
TbOrderItem selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") TbOrderItem record, @Param("example") TbOrderItemExample example);
int updateByExample(@Param("record") TbOrderItem record, @Param("example") TbOrderItemExample example);
int updateByPrimaryKeySelective(TbOrderItem record);
int updateByPrimaryKey(TbOrderItem record);
} | [
"[email protected]"
] | |
a51f331040254109cc3ad62337bcf1f8fdc42345 | 95ffdbacafb9255d9dfe8c5caa84c5d324025848 | /zpoi/src/org/zkoss/poi/hssf/record/RecordInputStream.java | 9db1c8cd7df888d3315ca4c367677c85ed01b1a9 | [
"MIT"
] | permissive | dataspread/dataspread-web | 2143f3451c141a4857070a67813208c8f2da50dc | 2d07f694c7419473635e355202be11396023f915 | refs/heads/master | 2023-01-12T16:12:47.862760 | 2021-05-09T02:30:42 | 2021-05-09T02:30:42 | 88,792,776 | 139 | 34 | null | 2023-01-06T01:36:17 | 2017-04-19T21:32:30 | Java | UTF-8 | Java | false | false | 14,295 | 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 org.zkoss.poi.hssf.record;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import org.zkoss.poi.hssf.dev.BiffViewer;
import org.zkoss.poi.hssf.record.crypto.Biff8DecryptingStream;
import org.zkoss.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.zkoss.poi.util.LittleEndian;
import org.zkoss.poi.util.LittleEndianInput;
import org.zkoss.poi.util.LittleEndianInputStream;
/**
* Title: Record Input Stream<P>
* Description: Wraps a stream and provides helper methods for the construction of records.<P>
*
* @author Jason Height (jheight @ apache dot org)
*/
public final class RecordInputStream implements LittleEndianInput {
/** Maximum size of a single record (minus the 4 byte header) without a continue*/
public final static short MAX_RECORD_DATA_SIZE = 8224;
private static final int INVALID_SID_VALUE = -1;
/**
* When {@link #_currentDataLength} has this value, it means that the previous BIFF record is
* finished, the next sid has been properly read, but the data size field has not been read yet.
*/
private static final int DATA_LEN_NEEDS_TO_BE_READ = -1;
private static final byte[] EMPTY_BYTE_ARRAY = { };
/**
* For use in {@link BiffViewer} which may construct {@link Record}s that don't completely
* read all available data. This exception should never be thrown otherwise.
*/
@SuppressWarnings("serial")
public static final class LeftoverDataException extends RuntimeException {
public LeftoverDataException(int sid, int remainingByteCount) {
super("Initialisation of record 0x" + Integer.toHexString(sid).toUpperCase()
+ " left " + remainingByteCount + " bytes remaining still to be read.");
}
}
/** Header {@link LittleEndianInput} facet of the wrapped {@link InputStream} */
private final BiffHeaderInput _bhi;
/** Data {@link LittleEndianInput} facet of the wrapped {@link InputStream} */
private final LittleEndianInput _dataInput;
/** the record identifier of the BIFF record currently being read */
private int _currentSid;
/**
* Length of the data section of the current BIFF record (always 4 less than the total record size).
* When uninitialised, this field is set to {@link #DATA_LEN_NEEDS_TO_BE_READ}.
*/
private int _currentDataLength;
/**
* The BIFF record identifier for the next record is read when just as the current record
* is finished.
* This field is only really valid during the time that ({@link #_currentDataLength} ==
* {@link #DATA_LEN_NEEDS_TO_BE_READ}). At most other times its value is not really the
* 'sid of the next record'. Wwhile mid-record, this field coincidentally holds the sid
* of the current record.
*/
private int _nextSid;
/**
* index within the data section of the current BIFF record
*/
private int _currentDataOffset;
private static final class SimpleHeaderInput implements BiffHeaderInput {
private final LittleEndianInput _lei;
public SimpleHeaderInput(InputStream in) {
_lei = getLEI(in);
}
public int available() {
return _lei.available();
}
public int readDataSize() {
return _lei.readUShort();
}
public int readRecordSID() {
return _lei.readUShort();
}
}
public RecordInputStream(InputStream in) throws RecordFormatException {
this (in, null, 0);
}
public RecordInputStream(InputStream in, Biff8EncryptionKey key, int initialOffset) throws RecordFormatException {
if (key == null) {
_dataInput = getLEI(in);
_bhi = new SimpleHeaderInput(in);
} else {
Biff8DecryptingStream bds = new Biff8DecryptingStream(in, initialOffset, key);
_bhi = bds;
_dataInput = bds;
}
_nextSid = readNextSid();
}
static LittleEndianInput getLEI(InputStream is) {
if (is instanceof LittleEndianInput) {
// accessing directly is an optimisation
return (LittleEndianInput) is;
}
// less optimal, but should work OK just the same. Often occurs in junit tests.
return new LittleEndianInputStream(is);
}
/**
* @return the number of bytes available in the current BIFF record
* @see #remaining()
*/
public int available() {
return remaining();
}
public int read(byte[] b, int off, int len) {
int limit = Math.min(len, remaining());
if (limit == 0) {
return 0;
}
readFully(b, off,limit);
return limit;
}
public short getSid() {
return (short) _currentSid;
}
/**
* Note - this method is expected to be called only when completed reading the current BIFF
* record.
* @throws LeftoverDataException if this method is called before reaching the end of the
* current record.
*/
public boolean hasNextRecord() throws LeftoverDataException {
if (_currentDataLength != -1 && _currentDataLength != _currentDataOffset) {
throw new LeftoverDataException(_currentSid, remaining());
}
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) {
_nextSid = readNextSid();
}
return _nextSid != INVALID_SID_VALUE;
}
/**
* @return the sid of the next record or {@link #INVALID_SID_VALUE} if at end of stream
*/
private int readNextSid() {
int nAvailable = _bhi.available();
if (nAvailable < EOFRecord.ENCODED_SIZE) {
if (nAvailable > 0) {
// some scrap left over?
// ex45582-22397.xls has one extra byte after the last record
// Excel reads that file OK
}
return INVALID_SID_VALUE;
}
int result = _bhi.readRecordSID();
if (result == INVALID_SID_VALUE) {
throw new RecordFormatException("Found invalid sid (" + result + ")");
}
_currentDataLength = DATA_LEN_NEEDS_TO_BE_READ;
return result;
}
/** Moves to the next record in the stream.
*
* <i>Note: The auto continue flag is reset to true</i>
*/
public void nextRecord() throws RecordFormatException {
if (_nextSid == INVALID_SID_VALUE) {
throw new IllegalStateException("EOF - next record not available");
}
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) {
throw new IllegalStateException("Cannot call nextRecord() without checking hasNextRecord() first");
}
_currentSid = _nextSid;
_currentDataOffset = 0;
_currentDataLength = _bhi.readDataSize();
if (_currentDataLength > MAX_RECORD_DATA_SIZE) {
throw new RecordFormatException("The content of an excel record cannot exceed "
+ MAX_RECORD_DATA_SIZE + " bytes");
}
}
private void checkRecordPosition(int requiredByteCount) {
int nAvailable = remaining();
if (nAvailable >= requiredByteCount) {
// all OK
return;
}
if (nAvailable == 0 && isContinueNext()) {
nextRecord();
return;
}
throw new RecordFormatException("Not enough data (" + nAvailable
+ ") to read requested (" + requiredByteCount +") bytes");
}
/**
* Reads an 8 bit, signed value
*/
public byte readByte() {
checkRecordPosition(LittleEndian.BYTE_SIZE);
_currentDataOffset += LittleEndian.BYTE_SIZE;
return _dataInput.readByte();
}
/**
* Reads a 16 bit, signed value
*/
public short readShort() {
checkRecordPosition(LittleEndian.SHORT_SIZE);
_currentDataOffset += LittleEndian.SHORT_SIZE;
return _dataInput.readShort();
}
/**
* Reads a 32 bit, signed value
*/
public int readInt() {
checkRecordPosition(LittleEndian.INT_SIZE);
_currentDataOffset += LittleEndian.INT_SIZE;
return _dataInput.readInt();
}
/**
* Reads a 64 bit, signed value
*/
public long readLong() {
checkRecordPosition(LittleEndian.LONG_SIZE);
_currentDataOffset += LittleEndian.LONG_SIZE;
return _dataInput.readLong();
}
/**
* Reads an 8 bit, unsigned value
*/
public int readUByte() {
return readByte() & 0x00FF;
}
/**
* Reads a 16 bit, unsigned value.
*/
public int readUShort() {
checkRecordPosition(LittleEndian.SHORT_SIZE);
_currentDataOffset += LittleEndian.SHORT_SIZE;
return _dataInput.readUShort();
}
public double readDouble() {
long valueLongBits = readLong();
double result = Double.longBitsToDouble(valueLongBits);
if (Double.isNaN(result)) {
// YK: Excel doesn't write NaN but instead converts the cell type into CELL_TYPE_ERROR.
// HSSF prior to version 3.7 had a bug: it could write Double.NaN but could not read such a file back.
// This behavior was fixed in POI-3.7.
//throw new RuntimeException("Did not expect to read NaN"); // (Because Excel typically doesn't write NaN
}
return result;
}
public void readFully(byte[] buf) {
readFully(buf, 0, buf.length);
}
public void readFully(byte[] buf, int off, int len) {
checkRecordPosition(len);
_dataInput.readFully(buf, off, len);
_currentDataOffset+=len;
}
public String readString() {
int requestedLength = readUShort();
byte compressFlag = readByte();
return readStringCommon(requestedLength, compressFlag == 0);
}
/**
* given a byte array of 16-bit unicode characters, compress to 8-bit and
* return a string
*
* { 0x16, 0x00 } -0x16
*
* @param requestedLength the length of the final string
* @return the converted string
* @exception IllegalArgumentException if len is too large (i.e.,
* there is not enough data in string to create a String of that
* length)
*/
public String readUnicodeLEString(int requestedLength) {
return readStringCommon(requestedLength, false);
}
public String readCompressedUnicode(int requestedLength) {
return readStringCommon(requestedLength, true);
}
private String readStringCommon(int requestedLength, boolean pIsCompressedEncoding) {
// Sanity check to detect garbage string lengths
if (requestedLength < 0 || requestedLength > 0x100000) { // 16 million chars?
throw new IllegalArgumentException("Bad requested string length (" + requestedLength + ")");
}
char[] buf = new char[requestedLength];
boolean isCompressedEncoding = pIsCompressedEncoding;
int curLen = 0;
while(true) {
int availableChars =isCompressedEncoding ? remaining() : remaining() / LittleEndian.SHORT_SIZE;
if (requestedLength - curLen <= availableChars) {
// enough space in current record, so just read it out
while(curLen < requestedLength) {
char ch;
if (isCompressedEncoding) {
ch = (char)readUByte();
} else {
ch = (char)readShort();
}
buf[curLen] = ch;
curLen++;
}
return new String(buf);
}
// else string has been spilled into next continue record
// so read what's left of the current record
while(availableChars > 0) {
char ch;
if (isCompressedEncoding) {
ch = (char)readUByte();
} else {
ch = (char)readShort();
}
buf[curLen] = ch;
curLen++;
availableChars--;
}
if (!isContinueNext()) {
throw new RecordFormatException("Expected to find a ContinueRecord in order to read remaining "
+ (requestedLength-curLen) + " of " + requestedLength + " chars");
}
if(remaining() != 0) {
throw new RecordFormatException("Odd number of bytes(" + remaining() + ") left behind");
}
nextRecord();
// note - the compressed flag may change on the fly
byte compressFlag = readByte();
isCompressedEncoding = (compressFlag == 0);
}
}
/** Returns the remaining bytes for the current record.
*
* @return The remaining bytes of the current record.
*/
public byte[] readRemainder() {
int size = remaining();
if (size ==0) {
return EMPTY_BYTE_ARRAY;
}
byte[] result = new byte[size];
readFully(result);
return result;
}
/** Reads all byte data for the current record, including any
* that overlaps into any following continue records.
*
* @deprecated Best to write a input stream that wraps this one where there is
* special sub record that may overlap continue records.
*/
public byte[] readAllContinuedRemainder() {
//Using a ByteArrayOutputStream is just an easy way to get a
//growable array of the data.
ByteArrayOutputStream out = new ByteArrayOutputStream(2*MAX_RECORD_DATA_SIZE);
while (true) {
byte[] b = readRemainder();
out.write(b, 0, b.length);
if (!isContinueNext()) {
break;
}
nextRecord();
}
return out.toByteArray();
}
/** The remaining number of bytes in the <i>current</i> record.
*
* @return The number of bytes remaining in the current record
*/
public int remaining() {
if (_currentDataLength == DATA_LEN_NEEDS_TO_BE_READ) {
// already read sid of next record. so current one is finished
return 0;
}
return _currentDataLength - _currentDataOffset;
}
/**
*
* @return <code>true</code> when a {@link ContinueRecord} is next.
*/
private boolean isContinueNext() {
if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength) {
throw new IllegalStateException("Should never be called before end of current record");
}
if (!hasNextRecord()) {
return false;
}
// At what point are records continued?
// - Often from within the char data of long strings (caller is within readStringCommon()).
// - From UnicodeString construction (many different points - call via checkRecordPosition)
// - During TextObjectRecord construction (just before the text, perhaps within the text,
// and before the formatting run data)
return _nextSid == ContinueRecord.sid;
}
/**
@return sid of next record. Can be called after hasNextRecord()
*/
public int getNextSid() {
return _nextSid;
}
}
| [
"[email protected]"
] | |
4817451b0bd1ddcfa0f0782d23e5cd2dabca030d | 39ebe1209b829f58d47684f5d8d4bd2bffecd51a | /Week04A_26850/app/src/main/java/id/ac/umn/week04a_26850/FirstFragment.java | 79de50fc16e86177145e430c3a72602283c1d5c0 | [] | no_license | igjevon/IF633_Mobile_DL | bcf37326b0478077942acd0648128af78454a2d7 | 981e8a642ca7e3d1835b0d907d42be6bd4a4dc5a | refs/heads/master | 2023-04-16T21:20:29.023790 | 2021-05-04T17:47:25 | 2021-05-04T17:47:25 | 348,067,952 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 642 | java | package id.ac.umn.week04a_26850;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class FirstFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater,
@Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
return view;
}
}
| [
"[email protected]"
] | |
6cf80514cfb6697f7c5a523973659fc93eb21cee | a43fcbd0c15053f107832ad24df4e268bac7ef95 | /java/com/yuck/interpreter/YuckList.java | bd1e9e734a904c47cde13f73c2c5047b7f9acf4a | [] | no_license | leegao/Yuck | 26984d06d96f5287c1ca1355b1996949de3e3447 | 055b1ab48ce617b34fda5b8fcaa8f1954a1fd426 | refs/heads/master | 2020-12-24T06:03:11.608735 | 2016-12-31T22:16:47 | 2016-12-31T22:16:47 | 73,235,164 | 9 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,358 | java | package com.yuck.interpreter;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import java.util.*;
public class YuckList extends YuckObject {
public YuckList(InterpreterContext context) {
super(context);
}
@Override
public YuckObjectKind getKind() {
return YuckObjectKind.LIST;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
YuckList yuckList = (YuckList) o;
return Objects.equals(list, yuckList.list);
}
@Override
public int hashCode() {
return Objects.hash(list);
}
public final List<YuckObject> list = new ArrayList<>();
public void add(YuckObject yuckObject) {
list.add(yuckObject);
}
@Override
public YuckObject tableLoad(YuckObject key) {
if (key instanceof YuckInteger) {
return list.get(((YuckInteger) key).number);
}
return super.tableLoad(key);
}
@Override
public void tableStore(YuckObject key, YuckObject val) {
if (key instanceof YuckInteger) {
list.set(((YuckInteger) key).number, val);
return;
}
super.tableStore(key, val);
}
@Override
public boolean isFilled() {
return list.size() != 0;
}
@Override
public String toString() {
return Objects.toString(list);
}
public YuckObject iterator(InterpreterContext context) {
List<YuckObject> copy = Lists.newArrayList(list);
Iterator<YuckObject> iterator = copy.iterator();
Map<String, YuckObject> map = new HashMap<>();
map.put(
"hasNext", new NativeFunction(c -> new YuckBoolean(iterator.hasNext(), c), context)
);
map.put(
"next", new NativeFunction(c -> iterator.next(), context)
);
return new YuckModule(map, context);
}
public YuckObject add(InterpreterContext context) {
Preconditions.checkArgument(context.locals.size() > 0);
list.add(context.get(0));
return this;
}
@Override
public YuckObject getField(String field) {
if (field.equals("@iterator")) {
return new NativeFunction(this::iterator, context);
} else if (field.equals("append")) {
return new NativeFunction(this::add, context);
}
return super.getField(field);
}
}
| [
"[email protected]"
] | |
12e86eab26ba3bee861b3e89344aefc8f29fe365 | 592e5a7812d2132b11b8350ec5fd0c5c8c7dd58c | /bshop/src/bshow/pojo/Bank.java | 315c161ceba230f197b63dbca57a2fffe9fbd57d | [] | no_license | Bshop4/b_shop | c555436536cd5c4560d4e212ea9f7bf679c78f83 | f6bbc837a7ee78fede1e9fb90edae6c7618132e4 | refs/heads/master | 2020-09-15T06:09:14.118114 | 2019-12-12T03:16:00 | 2019-12-12T03:16:00 | 223,363,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 787 | java | package bshow.pojo;
import java.io.Serializable;
public class Bank implements Serializable{
/**
*
*/
private static final long serialVersionUID = -190244575203864463L;
private int id;
private String account;
private String pass;
private double balance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public Bank() {
// TODO Auto-generated constructor stub
}
}
| [
"[email protected]"
] | |
78d2d3c249add296500834123e3993ffc7da2b83 | fbf2889c941afd0fba140a829bdec6751a10e05d | /data-demo-gateway/src/main/java/com/leimbag/demo/gateway/constants/GatewayConstants.java | 02416c0f1a606809c5840598661b881415077158 | [] | no_license | leimbag/spring-cloud-demo | cb85eed4f18df225e0c9242872718aed07e5d16a | d8e95a3e8b00c737960cd1ad3eac1e0bc170a052 | refs/heads/master | 2021-01-20T03:36:46.415737 | 2017-04-27T06:20:04 | 2017-04-27T06:20:04 | 89,562,383 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 307 | java | package com.leimbag.demo.gateway.constants;
public class GatewayConstants {
public static final String DEFAULT_CONTENT_TYPE = "application/json";
public static final int INTERNAL_SERVER_ERROR_CODE = 500;
public static final String INTERNAL_SERVER_ERROR_MESSAGE = "Internal Server Error";
}
| [
"[email protected]"
] | |
60f361299968b720ccb82fbb884277bbd7678178 | 84990c23f5bd1a9653c0b9c063ec30658918c720 | /szb-biz/szb-mongodb-demo/src/main/java/com/szb/mongodb/domain/Person.java | 79e7a896182f6cbe8811069418597b96d7277e0f | [] | no_license | shaozhenbin/szb | 0ec488a8dce92e54b22b5e72419948dea549def0 | ebae0e3eb82b591fc17cc7ce26cd2a252d2dc547 | refs/heads/master | 2022-10-24T06:31:32.137376 | 2020-06-22T15:36:39 | 2020-06-22T15:36:39 | 233,332,570 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 636 | java | package com.szb.mongodb.domain;
import lombok.*;
import org.mongodb.morphia.annotations.Embedded;
import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;
import java.io.Serializable;
import java.util.Set;
//@Document(collection = "person")
@Entity("person")
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Builder
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private String id;
private String code;
private String name;
private String email;
@Embedded
private Set<Address> addressSet;
}
| [
"[email protected]"
] | |
10297ccdd221531df10ad3732903124a537a7fb7 | 165eaa3c1174d03c39b68c57bdba5d3967efda49 | /app/src/main/java/com/mugua/jiguang/chat/pickerimage/utils/ImageUtil.java | fcc1f94e6bb0cf1ee9d535d7cad1192229498b72 | [] | no_license | wangshuangchao/kamang-Android | 11974294ef1b2abf07564a0062367a1e1999f58f | a52a7e8c56261f70e9a9b99b77e16966f8077ec7 | refs/heads/master | 2020-04-05T19:59:08.298887 | 2018-11-12T05:16:31 | 2018-11-12T05:16:31 | 157,159,781 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,176 | java | package com.mugua.jiguang.chat.pickerimage.utils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.text.TextUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import com.mugua.enterprise.R;
import com.mugua.enterprise.MyApplication;
public class ImageUtil {
public static class ImageSize {
public int width = 0;
public int height = 0;
public ImageSize(int width, int height) {
this.width = width;
this.height = height;
}
}
public final static float MAX_IMAGE_RATIO = 5f;
public static Bitmap getDefaultBitmapWhenGetFail() {
try {
return getBitmapImmutableCopy(MyApplication.context.getResources(), R.drawable.image_download_failed);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static final Bitmap getBitmapImmutableCopy(Resources res, int id) {
return getBitmap(res.getDrawable(id)).copy(Config.RGB_565, false);
}
public static final Bitmap getBitmap(Drawable dr) {
if (dr == null) {
return null;
}
if (dr instanceof BitmapDrawable) {
return ((BitmapDrawable) dr).getBitmap();
}
return null;
}
public static Bitmap rotateBitmapInNeeded(String path, Bitmap srcBitmap) {
if (TextUtils.isEmpty(path) || srcBitmap == null) {
return null;
}
ExifInterface localExifInterface;
try {
localExifInterface = new ExifInterface(path);
int rotateInt = localExifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
float rotate = getImageRotate(rotateInt);
if (rotate != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
Bitmap dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix,
false);
if (dstBitmap == null) {
return srcBitmap;
} else {
if (srcBitmap != null && !srcBitmap.isRecycled()) {
srcBitmap.recycle();
}
return dstBitmap;
}
} else {
return srcBitmap;
}
} catch (IOException e) {
e.printStackTrace();
return srcBitmap;
}
}
/**
* 获得旋转角度
*
* @param rotate
* @return
*/
public static float getImageRotate(int rotate) {
float f;
if (rotate == 6) {
f = 90.0F;
} else if (rotate == 3) {
f = 180.0F;
} else if (rotate == 8) {
f = 270.0F;
} else {
f = 0.0F;
}
return f;
}
public static String makeThumbnail(Context context, File imageFile) {
String thumbFilePath = StorageUtil.getWritePath(imageFile.getName(),
StorageType.TYPE_THUMB_IMAGE);
File thumbFile = AttachmentStore.create(thumbFilePath);
if (thumbFile == null) {
return null;
}
boolean result = scaleThumbnail(
imageFile,
thumbFile,
getImageMaxEdge(),
getImageMinEdge(),
CompressFormat.JPEG,
60);
if (!result) {
AttachmentStore.delete(thumbFilePath);
return null;
}
return thumbFilePath;
}
public static int getImageMaxEdge() {
return (int) (165.0 / 320.0 * ScreenUtil.screenWidth);
}
public static int getImageMinEdge() {
return (int) (76.0 / 320.0 * ScreenUtil.screenWidth);
}
public static Boolean scaleThumbnail(File srcFile, File dstFile, int dstMaxWH, int dstMinWH, CompressFormat compressFormat, int quality) {
Boolean bRet = false;
Bitmap srcBitmap = null;
Bitmap dstBitmap = null;
BufferedOutputStream bos = null;
try {
int[] bound = BitmapDecoder.decodeBound(srcFile);
ImageSize size = getThumbnailDisplaySize(bound[0], bound[1], dstMaxWH, dstMinWH);
srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), size.width, size.height);
// 旋转
ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath());
int rotateInt = localExifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
float rotate = getImageRotate(rotateInt);
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
float inSampleSize = 1;
if (srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH
&& srcBitmap.getWidth() >= dstMinWH && srcBitmap.getHeight() <= dstMaxWH) {
//如果第一轮拿到的srcBitmap尺寸都符合要求,不需要再做缩放
} else {
if (srcBitmap.getWidth() != size.width || srcBitmap.getHeight() != size.height) {
float widthScale = (float) size.width / (float) srcBitmap.getWidth();
float heightScale = (float) size.height / (float) srcBitmap.getHeight();
if (widthScale >= heightScale) {
size.width = srcBitmap.getWidth();
size.height /= widthScale;//必定小于srcBitmap.getHeight()
inSampleSize = widthScale;
} else {
size.width /= heightScale;//必定小于srcBitmap.getWidth()
size.height = srcBitmap.getHeight();
inSampleSize = heightScale;
}
}
}
matrix.postScale(inSampleSize, inSampleSize);
if (rotate == 0 && inSampleSize == 1) {
dstBitmap = srcBitmap;
} else {
dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, size.width, size.height, matrix, true);
}
bos = new BufferedOutputStream(new FileOutputStream(dstFile));
dstBitmap.compress(compressFormat, quality, bos);
bos.flush();
bRet = true;
} catch (OutOfMemoryError e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (srcBitmap != null && !srcBitmap.isRecycled()) {
srcBitmap.recycle();
srcBitmap = null;
}
if (dstBitmap != null && !dstBitmap.isRecycled()) {
dstBitmap.recycle();
dstBitmap = null;
}
}
return bRet;
}
public static ImageSize getThumbnailDisplaySize(float srcWidth, float srcHeight, float dstMaxWH, float dstMinWH) {
if (srcWidth <= 0 || srcHeight <= 0) { // bounds check
return new ImageSize((int) dstMinWH, (int) dstMinWH);
}
float shorter;
float longer;
boolean widthIsShorter;
//store
if (srcHeight < srcWidth) {
shorter = srcHeight;
longer = srcWidth;
widthIsShorter = false;
} else {
shorter = srcWidth;
longer = srcHeight;
widthIsShorter = true;
}
if (shorter < dstMinWH) {
float scale = dstMinWH / shorter;
shorter = dstMinWH;
if (longer * scale > dstMaxWH) {
longer = dstMaxWH;
} else {
longer *= scale;
}
} else if (longer > dstMaxWH) {
float scale = dstMaxWH / longer;
longer = dstMaxWH;
if (shorter * scale < dstMinWH) {
shorter = dstMinWH;
} else {
shorter *= scale;
}
}
//restore
if (widthIsShorter) {
srcWidth = shorter;
srcHeight = longer;
} else {
srcWidth = longer;
srcHeight = shorter;
}
return new ImageSize((int) srcWidth, (int) srcHeight);
}
public static File getScaledImageFileWithMD5(File imageFile, String mimeType) {
String filePath = imageFile.getPath();
if (!isInvalidPictureFile(mimeType)) {
return null;
}
String tempFilePath = getTempFilePath(FileUtil.getExtensionName(filePath));
File tempImageFile = AttachmentStore.create(tempFilePath);
if (tempImageFile == null) {
return null;
}
CompressFormat compressFormat = CompressFormat.JPEG;
// 压缩数值由第三方开发者自行决定
int maxWidth = 720;
int quality = 60;
if (ImageUtil.scaleImage(imageFile, tempImageFile, maxWidth, compressFormat, quality)) {
return tempImageFile;
} else {
return null;
}
}
private static String getTempFilePath(String extension) {
return StorageUtil.getWritePath(
MyApplication.context,
"temp_image_" + StringUtil.get36UUID() + "." + extension,
StorageType.TYPE_TEMP);
}
public static Boolean scaleImage(File srcFile, File dstFile, int dstMaxWH, CompressFormat compressFormat, int quality) {
Boolean success = false;
try {
int inSampleSize = SampleSizeUtil.calculateSampleSize(srcFile.getAbsolutePath(), dstMaxWH * dstMaxWH);
Bitmap srcBitmap = BitmapDecoder.decodeSampled(srcFile.getPath(), inSampleSize);
if (srcBitmap == null) {
return success;
}
// 旋转
ExifInterface localExifInterface = new ExifInterface(srcFile.getAbsolutePath());
int rotateInt = localExifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
float rotate = getImageRotate(rotateInt);
Bitmap dstBitmap;
float scale = (float) Math.sqrt(((float) dstMaxWH * (float) dstMaxWH) / ((float) srcBitmap.getWidth() * (float) srcBitmap.getHeight()));
if (rotate == 0f && scale >= 1) {
dstBitmap = srcBitmap;
} else {
try {
Matrix matrix = new Matrix();
if (rotate != 0) {
matrix.postRotate(rotate);
}
if (scale < 1) {
matrix.postScale(scale, scale);
}
dstBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile));
srcBitmap.compress(compressFormat, quality, bos);
bos.flush();
bos.close();
success = true;
if (!srcBitmap.isRecycled())
srcBitmap.recycle();
srcBitmap = null;
return success;
}
}
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dstFile));
dstBitmap.compress(compressFormat, quality, bos);
bos.flush();
bos.close();
success = true;
if (!srcBitmap.isRecycled())
srcBitmap.recycle();
srcBitmap = null;
if (!dstBitmap.isRecycled())
dstBitmap.recycle();
dstBitmap = null;
} catch (Exception e) {
e.printStackTrace();
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return success;
}
public static ImageSize getThumbnailDisplaySize(int maxSide, int minSide, String imagePath) {
int[] bound = BitmapDecoder.decodeBound(imagePath);
ImageSize imageSize = getThumbnailDisplaySize(bound[0], bound[1], maxSide, minSide);
return imageSize;
}
public static int[] getBoundWithLength(int maxSide, Object imageObject, boolean resizeToDefault) {
int width = -1;
int height = -1;
int[] bound;
if (String.class.isInstance(imageObject)) {
bound = BitmapDecoder.decodeBound((String) imageObject);
width = bound[0];
height = bound[1];
} else if (Integer.class.isInstance(imageObject)) {
bound = BitmapDecoder.decodeBound(MyApplication.context.getResources(), (Integer) imageObject);
width = bound[0];
height = bound[1];
} else if (InputStream.class.isInstance(imageObject)) {
bound = BitmapDecoder.decodeBound((InputStream) imageObject);
width = bound[0];
height = bound[1];
}
int defaultWidth = maxSide;
int defaultHeight = maxSide;
if (width <= 0 || height <= 0) {
width = defaultWidth;
height = defaultHeight;
} else if (resizeToDefault) {
if (width > height) {
height = (int) (defaultWidth * ((float) height / (float) width));
width = defaultWidth;
} else {
width = (int) (defaultHeight * ((float) width / (float) height));
height = defaultHeight;
}
}
return new int[]{width, height};
}
/**
* 下载失败与获取失败时都统一显示默认下载失败图片
*
* @return
*/
public static Bitmap getBitmapFromDrawableRes(int res) {
try {
return getBitmapImmutableCopy(MyApplication.context.getResources(), res);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static boolean isInvalidPictureFile(String mimeType) {
String lowerCaseFilepath = mimeType.toLowerCase();
return (lowerCaseFilepath.contains("jpg") || lowerCaseFilepath.contains("jpeg")
|| lowerCaseFilepath.toLowerCase().contains("png") || lowerCaseFilepath.toLowerCase().contains("bmp") || lowerCaseFilepath
.toLowerCase().contains("gif"));
}
}
| [
"[email protected]"
] | |
92540d8b8c5ea0dd603f8c86713e4e8843611af1 | e57c15f8331e3beec6a4aa3ea53505a43d0796fe | /app/src/main/java/org/aecc/superdiary/presentation/internal/di/modules/ExamModule.java | 64e5cbf8a9d0081b8740a58f1dff0ac0b4da39f3 | [] | no_license | ruhey/DiarioSuperviviente | 7c19761d5a9b04161a3fbed23355359a3dc1ea70 | ad519a6cd5b608247fffceff698b48297a5f8a78 | refs/heads/master | 2020-05-29T21:39:47.723347 | 2015-09-15T16:31:50 | 2015-09-15T16:31:50 | 35,385,096 | 1 | 1 | null | 2015-09-01T17:39:39 | 2015-05-10T19:37:14 | Java | UTF-8 | Java | false | false | 3,405 | java | package org.aecc.superdiary.presentation.internal.di.modules;
import org.aecc.superdiary.domain.interactor.exam.CreateExamUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.DeleteExamUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.GetExamDetailsUseCase;
import org.aecc.superdiary.domain.interactor.exam.GetExamDetailsUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.GetExamListUseCase;
import org.aecc.superdiary.domain.interactor.exam.GetExamListUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.CreateExamUseCase;
import org.aecc.superdiary.domain.interactor.exam.DeleteExamUseCase;
import org.aecc.superdiary.domain.interactor.exam.GetExamDetailsUseCase;
import org.aecc.superdiary.domain.interactor.exam.GetExamDetailsUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.GetExamListUseCase;
import org.aecc.superdiary.domain.interactor.exam.GetExamListUseCaseImpl;
import org.aecc.superdiary.domain.interactor.exam.SaveExamUseCase;
import org.aecc.superdiary.domain.interactor.exam.SaveExamUseCaseImpl;
import org.aecc.superdiary.presentation.internal.di.PerActivity;
import org.aecc.superdiary.presentation.presenter.ExamDetailsPresenter;
import org.aecc.superdiary.presentation.presenter.ExamListPresenter;
import org.aecc.superdiary.presentation.presenter.Presenter;
import org.aecc.superdiary.presentation.presenter.ExamDetailCreatePresenter;
import org.aecc.superdiary.presentation.presenter.ExamDetailDeletePresenter;
import org.aecc.superdiary.presentation.presenter.ExamDetailEditPresenter;
import org.aecc.superdiary.presentation.presenter.ExamListPresenter;
import dagger.Module;
import dagger.Provides;
@Module
public class ExamModule {
@Provides
@PerActivity
GetExamListUseCase provideGetExamListUseCase(GetExamListUseCaseImpl getExamListUseCase) {
return getExamListUseCase;
}
@Provides
@PerActivity
GetExamDetailsUseCase provideGetExamDetailsUseCase(GetExamDetailsUseCaseImpl getExamDetailsUseCase) {
return getExamDetailsUseCase;
}
@Provides
@PerActivity
CreateExamUseCase provideCreateExamUseCase(CreateExamUseCaseImpl createExamUseCase) {
return createExamUseCase;
}
@Provides
@PerActivity
DeleteExamUseCase provideDeleteExamUseCase(DeleteExamUseCaseImpl deleteExamUseCase) {
return deleteExamUseCase;
}
@Provides
@PerActivity
SaveExamUseCase provideSaveExamUseCase(SaveExamUseCaseImpl saveExamUseCase) {
return saveExamUseCase;
}
@Provides
@PerActivity
Presenter provideExamListPresenter(ExamListPresenter examListPresenter) {
return examListPresenter;
}
@Provides
@PerActivity
Presenter providesExamDetailEditPresenter(ExamDetailEditPresenter examDetailEditPresenter){
return examDetailEditPresenter;
}
@Provides
@PerActivity
Presenter providesExamDetailsPresenter(ExamDetailsPresenter examDetailEditPresenter){
return examDetailEditPresenter;
}
@Provides
@PerActivity
Presenter providesExamDetailDeletePresenter(ExamDetailDeletePresenter examDetailDeletePresenter){
return examDetailDeletePresenter;
}
@Provides
@PerActivity
Presenter providesExamDetailCreatePresenter(ExamDetailCreatePresenter examDetailCreatePresenter){
return examDetailCreatePresenter;
}
}
| [
"[email protected]"
] | |
45209def12aa7a82fa21b32f65abadc214b47153 | 21f407df647542a6b0f991c0c61df8adff9f9972 | /app/src/main/java/com/example/rtyui/mvptalk/newMsg/FriendFlushMsg.java | 55082f9ea37da0b9ecfeb8dd3451e09700734d01 | [] | no_license | pgyCode/Interact | 61652355bdbf455177ab7a9feff8d4067f064e3d | b889e2b1db29eb4b3bb3142a1a1094253cc87f2c | refs/heads/master | 2020-03-19T20:30:35.860959 | 2018-08-04T13:45:55 | 2018-08-04T13:45:55 | 136,905,349 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 209 | java | package com.example.rtyui.mvptalk.newMsg;
import com.example.rtyui.mvptalk.newBean.FriendBean;
import java.util.List;
public class FriendFlushMsg {
public int code;
public List<FriendBean> data;
}
| [
"[email protected]"
] | |
316ccf422f76269870b66385b762e36f621edbc2 | dea313733594d7328ed372c66f5d10ecb90dc2fd | /src/test/java/com/chrylis/sandbox/DemoApplicationTests.java | 0b63fa9b07075748340fcb9b25991ff09e01077c | [] | no_license | chrylis/webflow-multiply | 82c2851eb51986021679795920b6cf0a90f99b4b | e80aee1ea3ecd89b8de31b671ffb6d225f08d47b | refs/heads/master | 2020-04-19T11:19:47.683809 | 2015-03-24T12:20:21 | 2015-03-24T12:20:21 | 32,796,705 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 499 | java | package com.chrylis.sandbox;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
@WebAppConfiguration
public class DemoApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"[email protected]"
] | |
07254feef0f1fb24e7340c8ec5469aa6736734ce | b127446b20156967812b345c66f3dd5b0ec00cfa | /src/Q3.java | 19e408faf6bcbbb0bec3a77ec6274d4422e3eecd | [] | no_license | weistrofferkl/RedHat | 3102e03fc1a5762847a902e1686a286ec08ee00a | 84a7ae6cad80e93a1ed5114d0d762be7faef3275 | refs/heads/master | 2021-08-24T09:12:17.235200 | 2017-12-09T00:30:51 | 2017-12-09T00:30:51 | 113,246,730 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,977 | java | import java.util.Arrays;
import java.util.*;
import java.util.stream.Collectors;
public class Q3 {
/*
Using the Java Collections Framework:
-Change the optimized function implementation from question #2 above.
-Have the code:
1. add each array item to a Collection implementation
2. iterate over the Collection and return all values as a concatenated ... (Recruiter didnt complete the sentence)
3. if forceUpperCase is true, returned value must be all upper case
-Tell me why you chose the container implementation that you did.
-Is the optimized function thread safe?
-Is the unoptimized function thread safe?
-If not, how can you make it thread safe?
*/
//Corrected Function:
/* public static String addStringItems(String[] items, boolean forceUpperCase){
//Java has a nifty thing called StringBuilder that makes stuff like this nice:
StringBuilder sb = new StringBuilder();
for(int i = 0; i< items.length; i++){
//using the StringBuilder .append() to add the value:
sb.append(items[i]);
}
//Convert to string to return correct output format:
String output = sb.toString();
//if forceUpperCase is true, we convert our output to Uppercase and return
//otherwise we just return the original output:
return forceUpperCase ? output.toUpperCase() : output;
}*/
public static String addStringItems(String[] items, boolean forceUpperCase){
//Using List interface due to its flexibility and allowance of duplicate elements (unlike set)
List<String> strL = new ArrayList<String>(Arrays.asList(items));
//Can use streams here rather than a for-loop, and Collectors.joining() to bundle
//it all up nicely:
String output = strL.stream().collect(Collectors.joining());
//if forceUpperCase is true, we convert our output to Uppercase and return
//otherwise we just return the original output:
return forceUpperCase ? output.toUpperCase() : output;
//Is the optimized function thread safe?
//No, it uses ArrayList which has not been synchronized to allow for optimal performance
//Can be made thread safe using Vector instead (but will not be as optimal of a solution)
//Is the unoptimized function thread safe?
//Arrays are immutable in java, so this should be thread safe.
}
//Used for testing purposes:
/*
public static void main(String[] args){
String[] s = {"Hi ", " A ", " PEPPER ", " STUFF", " me ", " o ", " LOwerCaSe "};
String[] ns = s;
String newString = addStringItems(s, false);
String newString2 = addStringItems(ns, true);
System.out.println("NEW STRING: " + newString);
System.out.println("NEW STRING2: " + newString2);
}*/
}
| [
"[email protected]"
] | |
401ffd18cbf67b4c41af17aec211d3d2cd839e7a | 94dedbc833ffd24805564ea3f5562c3bf202c12d | /app/src/main/java/com/example/schiver/projectdua/LivingroomFragment.java | 087697081718c0f30e405a253e9e14a0b3e91ac2 | [] | no_license | schiver/SeThings-Simulator | dd7948c163dec77b2b018f9e43ec269d48a53995 | 1d70e4f592da4bc1bd2799d8ea058108d6bd2956 | refs/heads/master | 2020-06-13T15:44:25.050256 | 2019-07-01T15:52:58 | 2019-07-01T15:52:58 | 194,698,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 78,338 | java | package com.example.schiver.projectdua;
import android.app.AlarmManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schiver.projectdua.Model.ConfigData;
import com.example.schiver.projectdua.Model.ConfigDetailData;
import com.example.schiver.projectdua.Model.ConnectedDevice;
import com.example.schiver.projectdua.Model.DeviceUsageData;
import com.example.schiver.projectdua.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
public class LivingroomFragment extends Fragment {
TextView tempValue,motionValue;
TextView lampStatus, televisionStatus, acStatus, fanStatus;
TextView lampLabelText1,lampLabelText2,lampLabelText3;
TextView televisionLabelText1, televisionLabelText2, televisionLabelText3;
TextView acLabelText1, acLabelText2, acLabelText3;
TextView fanLabelText1, fanLabelText2, fanLabelText3;
SeekBar temperatureSensor;
RadioGroup motionSensorCondition;
RadioButton radioChoice;
FirebaseDatabase myDb;
DatabaseReference dbRef;
FirebaseDatabase myDb2;
DatabaseReference dbRef2;
FirebaseDatabase myDb3;
DatabaseReference dbRef3;
FirebaseDatabase myDb4;
DatabaseReference dbRef4;
FirebaseDatabase myDbCondition;
DatabaseReference dbConditionRef;
CountDownTimer myTimer,myTimer2,myTimer3,myTimer4,myTimerLampOn;
Date testDate;
View rootView2;
float valueNow;
boolean mTimer = true;
int myCounter = 0 , myCounter2 = 0 , myCounter3 = 0, myCounter4 = 0;
int a = 0;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.livingroom_fragment,container,false);
rootView2 = rootView;
myTimer = new CountDownTimer(0,0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
};
myTimerLampOn = new CountDownTimer(0,0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
};
myTimer2 = new CountDownTimer(0,0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
};
myTimer3 = new CountDownTimer(0,0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
};
myTimer4 = new CountDownTimer(0,0) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
}
};
// Sensor
temperatureSensor = rootView.findViewById(R.id.seekBar);
tempValue = rootView.findViewById(R.id.textView5);
temperatureSensor.setMax(35);
tempValue.setText(String.valueOf(valueNow).replaceAll(".0*$", " "));
temperatureSensor.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
valueNow = progress;
tempValue.setText(String.valueOf(valueNow).replaceAll(".0*$", ""));
temperatureUpdate(valueNow);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
motionValue = rootView.findViewById(R.id.textView9);
motionSensorCondition = rootView.findViewById(R.id.radio_group);
motionSensorCondition.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
FirebaseDatabase motionSensorDb = FirebaseDatabase.getInstance();
final DatabaseReference dbRefMotion = motionSensorDb.getReference("SeThings-Sensors/Livingroom/");
dbRefMotion.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
dbRefMotion.child("Dev-01").setValue(new ConnectedDevice(remoteMotionSensor(rootView)));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
});
//Lamp
lampStatus = rootView.findViewById(R.id.textView13);
lampLabelText1 = rootView.findViewById(R.id.textView14);
lampLabelText2 = rootView.findViewById(R.id.textView15);
lampLabelText3 = rootView.findViewById(R.id.textView21);
// Television
televisionStatus = rootView.findViewById(R.id.textView18);
televisionLabelText1 = rootView.findViewById(R.id.textView19);
televisionLabelText2 = rootView.findViewById(R.id.time_start);
televisionLabelText3 = rootView.findViewById(R.id.time_end);
//PC
acStatus = rootView.findViewById(R.id.textView24);
acLabelText1 = rootView.findViewById(R.id.textView26);
acLabelText2 = rootView.findViewById(R.id.time_start4);
acLabelText3 = rootView.findViewById(R.id.time_start5);
//Fan
fanStatus = rootView.findViewById(R.id.textView30);
fanLabelText1= rootView.findViewById(R.id.textView31);
fanLabelText2 = rootView.findViewById(R.id.time_start6);
fanLabelText3 = rootView.findViewById(R.id.time_start7);
setDefault();
return rootView;
}
public String remoteMotionSensor(View view){
int selectedChoice = motionSensorCondition.getCheckedRadioButtonId();
radioChoice = view.findViewById(selectedChoice);
return "SENSOR_MOTION_VAL_"+radioChoice.getText().toString().toUpperCase();
}
public String remoteTempSensor(){
return "SENSOR_TEMP_VAL_"+tempValue.getText().toString().toUpperCase();
}
public void temperatureUpdate(float value ){
FirebaseDatabase myTempSensorDb = FirebaseDatabase.getInstance();
final DatabaseReference myTempSensorDbRef = myTempSensorDb.getReference("SeThings-Sensors/Livingroom");
myTempSensorDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTempSensorDbRef.child("Dev-02").setValue(new ConnectedDevice(remoteTempSensor()));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public void onResume() {
super.onResume();
// Fix
myDb = FirebaseDatabase.getInstance();
dbRef = myDb.getReference("SeThings-Config/Livingroom/Dev-03");
dbRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer.cancel();
final ConfigData myConfig = dataSnapshot.getValue(ConfigData.class);
if(!myConfig.getDeviceCondition().equals("#")){
// Dilakukan Config
myDbCondition = FirebaseDatabase.getInstance();
dbConditionRef = myDbCondition.getReference("SeThings-Detail_Config/Livingroom/Dev-03");
dbConditionRef.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer.cancel();
// Cek koneksi sensor
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
final String currentDateandTime = sdf.format(new Date());
final ConfigDetailData myDetailConfig = dataSnapshot.getValue(ConfigDetailData.class);
if(myConfig.getGetDeviceConditionConnected().equals("#")){
if(myDetailConfig.getDevCondition().equals("TIMER")){
Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_SHORT).show();
// Jalankan fungsi timer
myTimer = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevConditionTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
lampStatus.setText("On");
lampLabelText1.setVisibility(View.VISIBLE);
lampLabelText1.setText(displayTime);
myCounter+=1;
}
@Override
public void onFinish() {
lampStatus.setText("Off");
lampLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
updateConfigOff("Livingroom","Dev-03");
//myCounter = 0;
}
}.start();
mTimer = true;
}else if(myDetailConfig.getDevCondition().equals("SCHEDULED")){
//String time = "23:21";
String displayTime = "Set at "+myDetailConfig.getDevConditionStartScheduled()+" to "+myDetailConfig.getDevConditionEndScheduled();
lampLabelText1.setVisibility(View.VISIBLE);
lampLabelText1.setText(displayTime);
String timeStart = myDetailConfig.getDevConditionStartScheduled();
String [] seperatedStart = timeStart.split(":");
int hour_x = Integer.parseInt(seperatedStart[0]);
int minutes_x = Integer.parseInt(seperatedStart[1]);
Calendar calendarStart = Calendar.getInstance();
calendarStart.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_x,
minutes_x,
0
);
String timeEnd = myDetailConfig.getDevConditionEndScheduled();
String [] seperatedEnd = timeEnd.split(":");
int hour_y = Integer.parseInt(seperatedEnd[0]);
int minutes_y = Integer.parseInt(seperatedEnd[1]);
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_y,
minutes_y,
0
);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String printCalendar = sdf2.format(calendarStart.getTime());
String printCalendar2 = sdf2.format(calendarEnd.getTime());
Toast.makeText(getContext(),printCalendar,Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),printCalendar2,Toast.LENGTH_SHORT).show();
setEventStart(calendarStart);
try {
setEventEnd(calendarEnd, myDetailConfig.getDevConditionStartScheduled(),myDetailConfig.getDevConditionEndScheduled());
} catch (ParseException e) {
e.printStackTrace();
}
}else if(myDetailConfig.getDevCondition().equals("SWITCH_OFF")){
// Update Data
mTimer = false;
updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
myCounter = 0;
}else if(myDetailConfig.getDevCondition().equals("SWITCH_ON")){
Toast.makeText(getContext(),"Switch on",Toast.LENGTH_SHORT).show();
myTimer = null;
myTimer = new CountDownTimer(43200*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (myCounter) % 60;
long minute = ((myCounter) / (1 * 60)) % 60;
long hour = ((myCounter) / (1 * 60 * 60)) % 24;
//String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
String displayTime = "H : "+hour +" M : "+minute+" S : "+second;
lampStatus.setText("On");
lampLabelText1.setVisibility(View.VISIBLE);
lampLabelText1.setText(displayTime);
myCounter+=1;
}
@Override
public void onFinish() {
lampStatus.setText("Off");
lampLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
updateConfigOff("Livingroom","Dev-03");
//myCounter = 0;
}
};
myTimer.start();
}
// Buat ambil kondisi TIMER dan SCHEDULED
}else{
// ada sensor
//Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_LONG).show();
// Buat kondisi sensor -> ambil ke database sensor
FirebaseDatabase connectDB = FirebaseDatabase.getInstance();
DatabaseReference dbConnectRef = connectDB.getReference("SeThings-Sensors/Livingroom/");
dbConnectRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ConnectedDevice mySensor = dataSnapshot.child(myConfig.getGetDeviceConditionConnected()).getValue(ConnectedDevice.class);
//Toast.makeText(getContext(),myConfig.getDeviceCondition(),Toast.LENGTH_LONG).show();
if(myDetailConfig.getDevCondition().equals(mySensor.getSensorValue())){
if(myDetailConfig.getDevSubCondition().equals("TIMER")){
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
myTimer = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevSubConditioTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
lampStatus.setText("On");
lampLabelText1.setVisibility(View.VISIBLE);
lampLabelText1.setText(displayTime);
myCounter+=1;
}
@Override
public void onFinish() {
lampStatus.setText("Off");
lampLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
updateConfigOff("Livingroom","Dev-03");
//myCounter = 0;
}
};
myTimer.start();
}
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
// Get the timer
// Get Sub condition
}else{
//Toast.makeText(getContext(),"Sensor OFF",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(getContext(),mySensor.getSensorValue(),Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
//myTimer.cancel();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else{
//myTimer.start();
myTimer.cancel();
myTimerLampOn.cancel();
updateDataUsage("Livingroom","Dev-03",20,myCounter);
updateConfigOff("Livingroom","Dev-03");
//Toast.makeText(getContext(),"Counter : "+myCounter,Toast.LENGTH_SHORT).show();
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
// Tidak dilakukan config
lampStatus.setText("Off");
lampLabelText1.setVisibility(View.GONE);
myCounter = 0;
//Toast.makeText(getContext(),"Tidak ada Konfig",Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Fix
myDb2 = FirebaseDatabase.getInstance();
dbRef2 = myDb2.getReference("SeThings-Config/Livingroom/Dev-04");
dbRef2.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer2.cancel();
final ConfigData myConfig = dataSnapshot.getValue(ConfigData.class);
if(!myConfig.getDeviceCondition().equals("#")){
// Dilakukan Config
myDbCondition = FirebaseDatabase.getInstance();
dbConditionRef = myDbCondition.getReference("SeThings-Detail_Config/Livingroom/Dev-04");
dbConditionRef.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer2.cancel();
// Cek koneksi sensor
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
final String currentDateandTime = sdf.format(new Date());
final ConfigDetailData myDetailConfig = dataSnapshot.getValue(ConfigDetailData.class);
if(myConfig.getGetDeviceConditionConnected().equals("#")){
if(myDetailConfig.getDevCondition().equals("TIMER")){
Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_SHORT).show();
// Jalankan fungsi timer
myTimer2 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevConditionTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
televisionStatus.setText("On");
televisionLabelText1.setVisibility(View.VISIBLE);
televisionLabelText1.setText(displayTime);
myCounter2+=1;
}
@Override
public void onFinish() {
televisionLabelText1.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-04");
//myCounter2 = 0;
}
}.start();
mTimer = true;
}else if(myDetailConfig.getDevCondition().equals("SCHEDULED")){
//String time = "23:21";
String displayTime = "Set at "+myDetailConfig.getDevConditionStartScheduled()+" to "+myDetailConfig.getDevConditionEndScheduled();
televisionLabelText1.setVisibility(View.VISIBLE);
televisionLabelText1.setText(displayTime);
String timeStart = myDetailConfig.getDevConditionStartScheduled();
String [] seperatedStart = timeStart.split(":");
int hour_x = Integer.parseInt(seperatedStart[0]);
int minutes_x = Integer.parseInt(seperatedStart[1]);
Calendar calendarStart = Calendar.getInstance();
calendarStart.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_x,
minutes_x,
0
);
String timeEnd = myDetailConfig.getDevConditionEndScheduled();
String [] seperatedEnd = timeEnd.split(":");
int hour_y = Integer.parseInt(seperatedEnd[0]);
int minutes_y = Integer.parseInt(seperatedEnd[1]);
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_y,
minutes_y,
0
);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String printCalendar = sdf2.format(calendarStart.getTime());
String printCalendar2 = sdf2.format(calendarEnd.getTime());
Toast.makeText(getContext(),printCalendar,Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),printCalendar2,Toast.LENGTH_SHORT).show();
setEventStart2(calendarStart);
try {
setEventEnd2(calendarEnd,myDetailConfig.getDevConditionStartScheduled(),myDetailConfig.getDevConditionEndScheduled());
} catch (ParseException e) {
e.printStackTrace();
}
}else if(myDetailConfig.getDevCondition().equals("SWITCH_OFF")){
// Update Data
mTimer = false;
updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
myCounter = 0;
}else if(myDetailConfig.getDevCondition().equals("SWITCH_ON")){
Toast.makeText(getContext(),"Switch on",Toast.LENGTH_SHORT).show();
myTimer2 = new CountDownTimer(43200*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (myCounter2) % 60;
long minute = ((myCounter2) / (1 * 60)) % 60;
long hour = ((myCounter2) / (1 * 60 * 60)) % 24;
//String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
String displayTime = "H : "+hour +" M : "+minute+" S : "+second;
televisionStatus.setText("On");
televisionLabelText1.setVisibility(View.VISIBLE);
televisionLabelText1.setText(displayTime);
myCounter2+=1;
}
@Override
public void onFinish() {
televisionStatus.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-03");
//myCounter2 = 0;
}
}.start();
}
// Buat ambil kondisi TIMER dan SCHEDULED
}else{
// ada sensor
//Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_LONG).show();
// Buat kondisi sensor -> ambil ke database sensor
FirebaseDatabase connectDB = FirebaseDatabase.getInstance();
DatabaseReference dbConnectRef = connectDB.getReference("SeThings-Sensors/Livingroom/");
dbConnectRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ConnectedDevice mySensor = dataSnapshot.child(myConfig.getGetDeviceConditionConnected()).getValue(ConnectedDevice.class);
//Toast.makeText(getContext(),myConfig.getDeviceCondition(),Toast.LENGTH_LONG).show();
if(myDetailConfig.getDevCondition().equals(mySensor.getSensorValue())){
if(myDetailConfig.getDevSubCondition().equals("TIMER")){
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
myTimer2 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevSubConditioTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
televisionStatus.setText("On");
televisionLabelText1.setVisibility(View.VISIBLE);
televisionLabelText1.setText(displayTime);
myCounter2+=1;
}
@Override
public void onFinish() {
televisionStatus.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-04");
//myCounter2 = 0;
}
};
myTimer2.start();
}
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
// Get the timer
// Get Sub condition
}else{
//Toast.makeText(getContext(),"Sensor OFF",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(getContext(),mySensor.getSensorValue(),Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else{
myTimer2.cancel();
updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-04");
//Toast.makeText(getContext(),"Counter : "+myCounter,Toast.LENGTH_SHORT).show();
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
// Tidak dilakukan config
televisionStatus.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
myCounter2 = 0;
//Toast.makeText(getContext(),"Tidak ada Konfig",Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Fix
myDb3 = FirebaseDatabase.getInstance();
dbRef3 = myDb3.getReference("SeThings-Config/Livingroom/Dev-05");
dbRef3.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer3.cancel();
final ConfigData myConfig = dataSnapshot.getValue(ConfigData.class);
if(!myConfig.getDeviceCondition().equals("#")){
// Dilakukan Config
myDbCondition = FirebaseDatabase.getInstance();
dbConditionRef = myDbCondition.getReference("SeThings-Detail_Config/Livingroom/Dev-05");
dbConditionRef.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
// Cek koneksi sensor
myTimer3.cancel();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
final String currentDateandTime = sdf.format(new Date());
final ConfigDetailData myDetailConfig = dataSnapshot.getValue(ConfigDetailData.class);
if(myConfig.getGetDeviceConditionConnected().equals("#")){
if(myDetailConfig.getDevCondition().equals("TIMER")){
Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_SHORT).show();
// Jalankan fungsi timer
myTimer3 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevConditionTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
acStatus.setText("On");
acLabelText1.setVisibility(View.VISIBLE);
acLabelText1.setText(displayTime);
myCounter3+=1;
}
@Override
public void onFinish() {
televisionLabelText1.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-05");
//myCounter2 = 0;
}
}.start();
mTimer = true;
}else if(myDetailConfig.getDevCondition().equals("SCHEDULED")){
//String time = "23:21";
String displayTime = "Set at "+myDetailConfig.getDevConditionStartScheduled()+" to "+myDetailConfig.getDevConditionEndScheduled();
acLabelText1.setVisibility(View.VISIBLE);
acLabelText1.setText(displayTime);
String timeStart = myDetailConfig.getDevConditionStartScheduled();
String [] seperatedStart = timeStart.split(":");
int hour_x = Integer.parseInt(seperatedStart[0]);
int minutes_x = Integer.parseInt(seperatedStart[1]);
Calendar calendarStart = Calendar.getInstance();
calendarStart.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_x,
minutes_x,
0
);
String timeEnd = myDetailConfig.getDevConditionEndScheduled();
String [] seperatedEnd = timeEnd.split(":");
int hour_y = Integer.parseInt(seperatedEnd[0]);
int minutes_y = Integer.parseInt(seperatedEnd[1]);
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_y,
minutes_y,
0
);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String printCalendar = sdf2.format(calendarStart.getTime());
String printCalendar2 = sdf2.format(calendarEnd.getTime());
Toast.makeText(getContext(),printCalendar,Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),printCalendar2,Toast.LENGTH_SHORT).show();
setEventStart3(calendarStart);
try {
setEventEnd3(calendarEnd,myDetailConfig.getDevConditionStartScheduled(),myDetailConfig.getDevConditionEndScheduled());
} catch (ParseException e) {
e.printStackTrace();
}
}else if(myDetailConfig.getDevCondition().equals("SWITCH_OFF")){
// Update Data
mTimer = false;
updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
myCounter = 0;
}else if(myDetailConfig.getDevCondition().equals("SWITCH_ON")){
Toast.makeText(getContext(),"Switch on",Toast.LENGTH_SHORT).show();
myTimer3 = new CountDownTimer(43200*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (myCounter3) % 60;
long minute = ((myCounter3) / (1 * 60)) % 60;
long hour = ((myCounter3) / (1 * 60 * 60)) % 24;
//String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
String displayTime = "H : "+hour +" M : "+minute+" S : "+second;
acStatus.setText("On");
acLabelText1.setVisibility(View.VISIBLE);
acLabelText1.setText(displayTime);
myCounter3+=1;
}
@Override
public void onFinish() {
acStatus.setText("Off");
acLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-05");
//myCounter2 = 0;
}
}.start();
}
// Buat ambil kondisi TIMER dan SCHEDULED
}else{
// ada sensor
//Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_LONG).show();
// Buat kondisi sensor -> ambil ke database sensor
FirebaseDatabase connectDB = FirebaseDatabase.getInstance();
DatabaseReference dbConnectRef = connectDB.getReference("SeThings-Sensors/Livingroom/");
dbConnectRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ConnectedDevice mySensor = dataSnapshot.child(myConfig.getGetDeviceConditionConnected()).getValue(ConnectedDevice.class);
//Toast.makeText(getContext(),myConfig.getDeviceCondition(),Toast.LENGTH_LONG).show();
if(myDetailConfig.getDevCondition().equals(mySensor.getSensorValue())){
if(myDetailConfig.getDevSubCondition().equals("TIMER")){
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
myTimer3 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevSubConditioTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
acStatus.setText("On");
acLabelText1.setVisibility(View.VISIBLE);
acLabelText1.setText(displayTime);
myCounter3+=1;
}
@Override
public void onFinish() {
acStatus.setText("Off");
acLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-05");
//myCounter2 = 0;
}
};
myTimer3.start();
}
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
// Get the timer
// Get Sub condition
}else{
//Toast.makeText(getContext(),"Sensor OFF",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(getContext(),mySensor.getSensorValue(),Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else{
myTimer3.cancel();
updateDataUsage("Livingroom","Dev-05",450,myCounter3);
updateConfigOff("Livingroom","Dev-05");
//Toast.makeText(getContext(),"Counter : "+myCounter,Toast.LENGTH_SHORT).show();
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
// Tidak dilakukan config
acStatus.setText("Off");
acLabelText1.setVisibility(View.GONE);
myCounter3 = 0;
//Toast.makeText(getContext(),"Tidak ada Konfig",Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Fix
myDb4 = FirebaseDatabase.getInstance();
dbRef4 = myDb4.getReference("SeThings-Config/Livingroom/Dev-06");
dbRef4.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer4.cancel();
final ConfigData myConfig = dataSnapshot.getValue(ConfigData.class);
if(!myConfig.getDeviceCondition().equals("#")){
// Dilakukan Config
myDbCondition = FirebaseDatabase.getInstance();
dbConditionRef = myDbCondition.getReference("SeThings-Detail_Config/Livingroom/Dev-06");
dbConditionRef.addValueEventListener(new ValueEventListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
myTimer4.cancel();
// Cek koneksi sensor
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
final String currentDateandTime = sdf.format(new Date());
final ConfigDetailData myDetailConfig = dataSnapshot.getValue(ConfigDetailData.class);
if(myConfig.getGetDeviceConditionConnected().equals("#")){
if(myDetailConfig.getDevCondition().equals("TIMER")){
Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_SHORT).show();
// Jalankan fungsi timer
myTimer4 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevConditionTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
fanStatus.setText("On");
fanLabelText1.setVisibility(View.VISIBLE);
fanLabelText1.setText(displayTime);
myCounter4+=1;
}
@Override
public void onFinish() {
fanLabelText1.setText("Off");
fanLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-06");
//myCounter2 = 0;
}
}.start();
mTimer = true;
}else if(myDetailConfig.getDevCondition().equals("SCHEDULED")){
//String time = "23:21";
String displayTime = "Set at "+myDetailConfig.getDevConditionStartScheduled()+" to "+myDetailConfig.getDevConditionEndScheduled();
fanLabelText1.setVisibility(View.VISIBLE);
fanLabelText1.setText(displayTime);
String timeStart = myDetailConfig.getDevConditionStartScheduled();
String [] seperatedStart = timeStart.split(":");
int hour_x = Integer.parseInt(seperatedStart[0]);
int minutes_x = Integer.parseInt(seperatedStart[1]);
Calendar calendarStart = Calendar.getInstance();
calendarStart.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_x,
minutes_x,
0
);
String timeEnd = myDetailConfig.getDevConditionEndScheduled();
String [] seperatedEnd = timeEnd.split(":");
int hour_y = Integer.parseInt(seperatedEnd[0]);
int minutes_y = Integer.parseInt(seperatedEnd[1]);
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.set(
calendarStart.get(Calendar.YEAR),
calendarStart.get(Calendar.MONTH),
calendarStart.get(Calendar.DAY_OF_MONTH),
hour_y,
minutes_y,
0
);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String printCalendar = sdf2.format(calendarStart.getTime());
String printCalendar2 = sdf2.format(calendarEnd.getTime());
Toast.makeText(getContext(),printCalendar,Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),printCalendar2,Toast.LENGTH_SHORT).show();
setEventStart4(calendarStart);
try {
setEventEnd4(calendarEnd,myDetailConfig.getDevConditionStartScheduled(),myDetailConfig.getDevConditionEndScheduled());
} catch (ParseException e) {
e.printStackTrace();
}
}else if(myDetailConfig.getDevCondition().equals("SWITCH_OFF")){
// Update Data
mTimer = false;
updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
myCounter = 0;
}else if(myDetailConfig.getDevCondition().equals("SWITCH_ON")){
Toast.makeText(getContext(),"Switch on",Toast.LENGTH_SHORT).show();
myTimer4 = new CountDownTimer(43200*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (myCounter4) % 60;
long minute = ((myCounter4) / (1 * 60)) % 60;
long hour = ((myCounter4) / (1 * 60 * 60)) % 24;
//String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
String displayTime = "H : "+hour +" M : "+minute+" S : "+second;
fanStatus.setText("On");
fanLabelText1.setVisibility(View.VISIBLE);
fanLabelText1.setText(displayTime);
myCounter4+=1;
}
@Override
public void onFinish() {
fanStatus.setText("Off");
fanLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-06");
//myCounter2 = 0;
}
}.start();
}
// Buat ambil kondisi TIMER dan SCHEDULED
}else{
// ada sensor
//Toast.makeText(getContext(),myDetailConfig.getDevCondition(),Toast.LENGTH_LONG).show();
// Buat kondisi sensor -> ambil ke database sensor
FirebaseDatabase connectDB = FirebaseDatabase.getInstance();
DatabaseReference dbConnectRef = connectDB.getReference("SeThings-Sensors/Livingroom/");
dbConnectRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
ConnectedDevice mySensor = dataSnapshot.child(myConfig.getGetDeviceConditionConnected()).getValue(ConnectedDevice.class);
//Toast.makeText(getContext(),myConfig.getDeviceCondition(),Toast.LENGTH_LONG).show();
if(myDetailConfig.getDevCondition().equals(mySensor.getSensorValue())){
if(myDetailConfig.getDevSubCondition().equals("TIMER")){
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
myTimer4 = new CountDownTimer(Integer.parseInt(myDetailConfig.getDevSubConditioTimerDuration())*1000,1000){
@Override
public void onTick(long millisUntilFinished) {
//long millis = millisUntilFinished % 1000;
long second = (millisUntilFinished / 1000) % 60;
long minute = (millisUntilFinished / (1000 * 60)) % 60;
long hour = (millisUntilFinished / (1000 * 60 * 60)) % 24;
String displayTime = " "+hour+" Hour "+minute+" Min "+second+" Sec";
fanStatus.setText("On");
fanLabelText1.setVisibility(View.VISIBLE);
fanLabelText1.setText(displayTime);
myCounter4+=1;
}
@Override
public void onFinish() {
fanStatus.setText("Off");
fanLabelText1.setVisibility(View.GONE);
//updateDataUsage("Livingroom","Dev-04",75,myCounter2);
updateConfigOff("Livingroom","Dev-06");
//myCounter2 = 0;
}
};
myTimer4.start();
}
//Toast.makeText(getContext(),"Sama",Toast.LENGTH_SHORT).show();
// Get the timer
// Get Sub condition
}else{
//Toast.makeText(getContext(),"Sensor OFF",Toast.LENGTH_SHORT).show();
}
//Toast.makeText(getContext(),mySensor.getSensorValue(),Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else{
myTimer4.cancel();
updateDataUsage("Livingroom","Dev-06",75,myCounter4);
updateConfigOff("Livingroom","Dev-06");
//Toast.makeText(getContext(),"Counter : "+myCounter,Toast.LENGTH_SHORT).show();
//updateDataUsage("Livingroom","Dev-03",20,myCounter);
//updateConfigOff("Livingroom","Dev-03");
// Tidak dilakukan config
fanStatus.setText("Off");
fanLabelText1.setVisibility(View.GONE);
myCounter4 = 0;
//Toast.makeText(getContext(),"Tidak ada Konfig",Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public void updateDataUsage(String roomName, String deviceId, final float usage, final int duration){
// Update daily -> tanggal
FirebaseDatabase myDbUsage = FirebaseDatabase.getInstance();
final DatabaseReference dbUsageRef = myDbUsage.getReference("SeThings-Device_Usage/"+roomName+"/"+deviceId);
dbUsageRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
DeviceUsageData myDeviceUsage = dataSnapshot.getValue(DeviceUsageData.class);
float usage_to_kwh = (usage * duration) / 3600;
float deviceUsage = (float) Math.floor(usage_to_kwh*100)/100;
float total_kwh = (deviceUsage/1000)+myDeviceUsage.getTotalUsage();
Toast.makeText(getContext(),"Duration : "+duration+" Usage : "+total_kwh,Toast.LENGTH_LONG).show();
dbUsageRef.child("totalUsage").setValue(total_kwh);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Update nowUsage
}
public void updateConfigOff(String roomName, String deviceId){
FirebaseDatabase configDb = FirebaseDatabase.getInstance();
final DatabaseReference configDbRef = configDb.getReference("SeThings-Detail_Config/"+roomName+"/"+deviceId);
final ConfigDetailData myConditionData = new ConfigDetailData("#",
"#",
"#",
"#",
"#",
"#",
"#",
"#"
);
configDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
configDbRef.setValue(myConditionData);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase generalConfigDb = FirebaseDatabase.getInstance();
final DatabaseReference generalConfigDbRef = generalConfigDb.getReference("SeThings-Config/"+roomName+"/"+deviceId);
generalConfigDbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
generalConfigDbRef.child("deviceCondition").setValue("#");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//Toast.makeText(getContext(),"Duration : MATI ",Toast.LENGTH_LONG).show();
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventStart(Calendar calendar){
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
lampStatus.setText("On");
//On alarm code here
lampLabelText1.setVisibility(View.VISIBLE);
Toast.makeText(getContext(),"Lamp Start",Toast.LENGTH_SHORT).show();
}
},null);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventEnd(Calendar calendar , String start, String end) throws ParseException {
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
final Date date1 = sdfTime.parse(start);
final Date date2 = sdfTime.parse(end);
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
long difference = date2.getTime() - date1.getTime();
lampStatus.setText("Off");
lampLabelText1.setVisibility(View.GONE);
//On alarm code here
updateConfigOff("Livingroom","Dev-03");
myCounter = (int)(difference/1000);
Toast.makeText(getContext(),"Lamp Done",Toast.LENGTH_SHORT).show();
}
},null);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventStart2(Calendar calendar){
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
televisionStatus.setText("On");
//On alarm code here
televisionLabelText1.setVisibility(View.VISIBLE);
Toast.makeText(getContext(),"TV Start",Toast.LENGTH_SHORT).show();
}
},null);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventEnd2(Calendar calendar,final String start, final String end) throws ParseException {
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
final Date date1 = sdfTime.parse(start);
final Date date2 = sdfTime.parse(end);
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
long difference = date2.getTime() - date1.getTime();
//Toast.makeText(getContext(),"Duration : "+String.valueOf(difference),Toast.LENGTH_SHORT).show();
televisionStatus.setText("Off");
televisionLabelText1.setVisibility(View.GONE);
//On alarm code here
//updateDataUsage("Livingroom","Dev-04",75,(int)(difference/1000));
updateConfigOff("Livingroom","Dev-04");
myCounter2 = (int)(difference/1000);
Toast.makeText(getContext(),"TV Done",Toast.LENGTH_SHORT).show();
}
},null);
//updateDataUsage("Livingroom","Dev-04",75,60);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventStart3(Calendar calendar){
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
acStatus.setText("On");
//On alarm code here
acLabelText1.setVisibility(View.VISIBLE);
Toast.makeText(getContext(),"AC Start",Toast.LENGTH_SHORT).show();
}
},null);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventEnd3(Calendar calendar,final String start, final String end) throws ParseException {
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
final Date date1 = sdfTime.parse(start);
final Date date2 = sdfTime.parse(end);
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
long difference = date2.getTime() - date1.getTime();
//Toast.makeText(getContext(),"Duration : "+String.valueOf(difference),Toast.LENGTH_SHORT).show();
acStatus.setText("Off");
acLabelText1.setVisibility(View.GONE);
//On alarm code here
//updateDataUsage("Livingroom","Dev-04",75,(int)(difference/1000));
updateConfigOff("Livingroom","Dev-05");
myCounter3 = (int)(difference/1000);
Toast.makeText(getContext(),"AC Done",Toast.LENGTH_SHORT).show();
}
},null);
//updateDataUsage("Livingroom","Dev-04",75,60);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventStart4(Calendar calendar){
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
fanStatus.setText("On");
//On alarm code here
fanLabelText1.setVisibility(View.VISIBLE);
Toast.makeText(getContext(),"Fan Start",Toast.LENGTH_SHORT).show();
}
},null);
}
@RequiresApi(api = Build.VERSION_CODES.N)
public void setEventEnd4(Calendar calendar,final String start, final String end) throws ParseException {
SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm");
final Date date1 = sdfTime.parse(start);
final Date date2 = sdfTime.parse(end);
AlarmManager myAlarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
myAlarm.set(AlarmManager.RTC,calendar.getTimeInMillis(),"alarm",
new AlarmManager.OnAlarmListener()
{
@Override
public void onAlarm() {
long difference = date2.getTime() - date1.getTime();
//Toast.makeText(getContext(),"Duration : "+String.valueOf(difference),Toast.LENGTH_SHORT).show();
fanStatus.setText("Off");
fanStatus.setVisibility(View.GONE);
//On alarm code here
//updateDataUsage("Livingroom","Dev-04",75,(int)(difference/1000));
updateConfigOff("Livingroom","Dev-06");
myCounter4 = (int)(difference/1000);
Toast.makeText(getContext(),"Fan Done",Toast.LENGTH_SHORT).show();
}
},null);
//updateDataUsage("Livingroom","Dev-04",75,60);
}
public void setDefault(){
lampLabelText1.setText("");
lampLabelText2.setText("");
lampLabelText3.setText("");
televisionLabelText1.setText("");
televisionLabelText2.setText("");
televisionLabelText3.setText("");
acLabelText1.setText("");
acLabelText2.setText("");
acLabelText3.setText("");
fanLabelText1.setText("");
fanLabelText2.setText("");
fanLabelText3.setText("");
}
}
| [
"[email protected]"
] | |
103306bca91f88e20d243c667c0edf4fa35ff160 | 323c723bdbdc9bdf5053dd27a11b1976603609f5 | /nssicc/nssicc_service/src/main/java/biz/belcorp/ssicc/service/spusicc/sap/impl/ReporteSAPUnidaDespCodigosServiceImpl.java | 735f340d99dd02b1e47e0821522245717e100bcd | [] | no_license | cbazalar/PROYECTOS_PROPIOS | adb0d579639fb72ec7871334163d3fef00123a1c | 3ba232d1f775afd07b13c8246d0a8ac892e93167 | refs/heads/master | 2021-01-11T03:38:06.084970 | 2016-10-24T01:33:00 | 2016-10-24T01:33:00 | 71,429,267 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,368 | java | package biz.belcorp.ssicc.service.spusicc.sap.impl;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import biz.belcorp.ssicc.dao.model.Usuario;
import biz.belcorp.ssicc.dao.spusicc.sap.ReporteSAPUnidadesDespachoCodigosDAO;
import biz.belcorp.ssicc.service.scsicc.framework.beans.ReporteParams;
import biz.belcorp.ssicc.service.sisicc.framework.BaseMailService;
import biz.belcorp.ssicc.service.sisicc.framework.BaseSubReporteAbstractService;
import biz.belcorp.ssicc.service.spusicc.sap.ReporteSAPUnidaDespCodigosService;
@Service("spusicc.reporteSAPUnidaDespCodigosService")
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public class ReporteSAPUnidaDespCodigosServiceImpl extends BaseSubReporteAbstractService implements ReporteSAPUnidaDespCodigosService{
@Resource(name="spusicc.reporteSAPUnidadesDespachoCodigosDAO")
private ReporteSAPUnidadesDespachoCodigosDAO reporteSAPUnidadesDespachoCodigosDAO;
@Override
protected String getSubReporteFileName() {
return "reporteSAPUnidadDespCodPDF";
}
@Override
protected void beforeExecuteReporte(ReporteParams reporteParams)
throws Exception {
super.beforeExecuteReporte(reporteParams);
Map params = (Map) reporteParams.getQueryParams().get("parameterMap");
reporteSAPUnidadesDespachoCodigosDAO.executeRegistrosUnidadesDespachoCodigosSAP(params);
}
@Override
protected void prepareParameterMap(Map params) throws Exception {
super.prepareParameterMap(params);
Usuario usuario = (Usuario)params.get("usuarioTemp");
String titulo = messageSource.getMessage("reporteSAPUnidDespCod.titulo",null,getLocale(usuario));
params.put("titulo", titulo);
log.debug("prepareParameterMap "+this.isVisualizarReporte());
}
protected String getReporteFileName() {
return "reporteMaestroVertical";
}
public BaseMailService getMailService() {
return this.mailService;
}
@Autowired
@Qualifier("ocr.mailReporteOCRCargaDocumento")
public void setMailService(BaseMailService mailService) {
this.mailService = mailService;
}
}
| [
"[email protected]"
] | |
8dba3598984784b6e304b8917db46bf829d67712 | 4b38300775f043104362e84ce4e05b60793fcbf5 | /plugin/qaforum/plugin.qaforum.android/src/org/pocketcampus/plugin/qaforum/android/activity/MyAnswerActivity.java | cc72bae0a7ed462a25e053e3b973c0461943d828 | [] | no_license | TaoufikMaalej/pocketcampus | 8c9c25447fcebb1ec5c59eb3ccde8dbdf13d5019 | 278c2a5eaa5cf72ee6641c19994d20314e6d5630 | refs/heads/master | 2021-01-20T18:45:09.102760 | 2013-10-14T17:39:24 | 2013-10-14T17:39:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,211 | java | package org.pocketcampus.plugin.qaforum.android.activity;
import org.json.JSONException;
import org.json.JSONObject;
import org.pocketcampus.plugin.qaforum.R;
import org.pocketcampus.android.platform.sdk.core.PluginController;
import org.pocketcampus.android.platform.sdk.core.PluginView;
import org.pocketcampus.plugin.qaforum.android.QAforumController;
import org.pocketcampus.plugin.qaforum.android.iface.IQAforumView;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
/**
* MyAnswerActivity - show my answer information.
*
* This class shows the detailed information of
* one answer.
*
* @author Susheng <[email protected]>
*
*/
public class MyAnswerActivity extends PluginView implements IQAforumView {
private String msg;
private JSONObject dataJsonObject;
@Override
protected Class<? extends PluginController> getMainControllerClass() {
return QAforumController.class;
}
@Override
protected void onDisplay(Bundle savedInstanceState,
PluginController controller) {
if (getIntent().getExtras() != null) {
msg = getIntent().getStringExtra("data");
System.out.println(msg);
try {
dataJsonObject = new JSONObject(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
//new version, which displays the view in three parts: question, answer, feedback
setContentView(R.layout.qaforum_my_answer);
TextView questionContent = (TextView) findViewById(R.id.TextView01);
TextView questionTopic = (TextView) findViewById(R.id.textView3);
TextView questionTag = (TextView) findViewById(R.id.textView4);
TextView questionAuthor = (TextView) findViewById(R.id.textView5);
TextView questionTime = (TextView) findViewById(R.id.textView6);
TextView answerContent= (TextView) findViewById(R.id.textView7);
TextView answerTime = (TextView) findViewById(R.id.textView8);
TextView feedbackContent = (TextView) findViewById(R.id.textView10);
TextView feedbackRate = (TextView) findViewById(R.id.textView11);
try {
questionContent.setText(dataJsonObject.getString("content"));
questionTopic.setText(getResources().getString(R.string.qaforum_detail_topic)+": "+dataJsonObject.getString("topicid"));
questionTag.setText(getResources().getString(R.string.qaforum_question_tags)+dataJsonObject.getString("tags"));
questionAuthor.setText(getResources().getString(R.string.qaforum_by)+dataJsonObject.getString("asker"));
questionTime.setText(dataJsonObject.getString("time"));
answerContent.setText(dataJsonObject.getString("answer"));
answerTime.setText(dataJsonObject.getString("answertime"));
feedbackContent.setText(dataJsonObject.getString("feedback"));
feedbackRate.setText(dataJsonObject.getString("rate"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Old version, which is inconsistant to other views.
/*
setContentView(R.layout.qaforum_list_main);
TextView subTitleTextView = (TextView) findViewById(R.id.standard_titled_layout_title);
subTitleTextView.setText(getString(R.string.qaforum_details_title));
LinearLayout l = (LinearLayout) findViewById(R.id.mylayout1);
LayoutInflater linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
for (int i = 0; i < 9; i++) {
View customView = linflater.inflate(R.layout.qaforum_one_item,
null);
TextView titleTextView = (TextView) customView
.findViewById(R.id.TextView01);
TextView contentTextView = (TextView) customView
.findViewById(R.id.textView1);
switch (i) {
case 0:
titleTextView.setText(getResources().getString(R.string.qaforum_question_single));
contentTextView.setText(dataJsonObject.getString("content"));
break;
case 1:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_askname));
contentTextView.setText(dataJsonObject.getString("asker"));
break;
case 2:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_topic));
contentTextView
.setText(dataJsonObject.getString("topicid"));
break;
case 3:
titleTextView.setText(getResources().getString(R.string.qaforum_tags));
contentTextView.setText(dataJsonObject.getString("tags"));
break;
case 4:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_asktime));
contentTextView.setText(dataJsonObject.getString("time"));
break;
case 5:
titleTextView.setText(getResources().getString(R.string.qaforum_answer));
contentTextView.setText(dataJsonObject.getString("answer"));
break;
case 6:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_answertime));
contentTextView.setText(dataJsonObject
.getString("answertime"));
break;
case 7:
titleTextView.setText(getResources().getString(R.string.qaforum_feedback));
contentTextView.setText(dataJsonObject
.getString("feedback"));
break;
case 8:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_rate));
contentTextView.setText(dataJsonObject.getString("rate"));
break;
case 9:
titleTextView.setText(getResources().getString(R.string.qaforum_detail_feedbacktime));
contentTextView.setText(dataJsonObject
.getString("feedbacktime"));
break;
default:
break;
}
l.addView(customView);
}
} catch (JSONException e) {
e.printStackTrace();
}
*/
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void networkErrorHappened() {
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.qaforum_connection_error_happened),
Toast.LENGTH_SHORT).show();
}
@Override
public void gotRequestReturn() {
}
@Override
public void messageDeleted() {
}
@Override
public void loadingFinished() {
}
@Override
public void authenticationFailed() {
Toast.makeText(getApplicationContext(), getResources().getString(
R.string.sdk_authentication_failed), Toast.LENGTH_SHORT).show();
}
@Override
public void userCancelledAuthentication() {
finish();
}
} | [
"[email protected]"
] | |
f8303a6fdb404150b3ee44671b6e09a436f7b232 | 9fc4179ecf5f0e4c5d49ed581920a56be704222f | /Nokkelkortet1/src/Ansatt.java | f8c47174525b428cba096361d4eb6bc400ff91f1 | [] | no_license | ViviNygaard/Nokkelkortet | f07a34dece013612e891e20436536bdfef908e33 | 3f827dfd2e448a39e4d236ba2a8b36557c6c0c5d | refs/heads/master | 2021-01-10T15:23:19.709750 | 2016-02-23T18:31:41 | 2016-02-23T18:31:41 | 52,378,557 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 859 | java | import java.util.*;
public class Ansatt extends Kort{
@Override
boolean sjekkPIN(int pin) {
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
day = date.get(Calendar.DAY_OF_MONTH);
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
if(hour>=7 && hour<=17 && !isSperret() && pin!=9999){
return true;
}
return false;
}
}
class Gjest extends Kort{
Date issueData;
public Gjest(){
pin =9999;
issueData = new Date();
}
@Override
boolean sjekkPIN(int pin) {
Date currentDate = new Date();
int diffInDays = (int) ((currentDate.getTime() - issueData.getTime()) / (1000 * 60 * 60 * 24));
if(pin ==9999 && diffInDays <=7 && (!isSperret())){
return true;
}
return false;
}
}
| [
"[email protected]"
] | |
e32c1a6ccdb8ff40d84cbfd1f3acb6ff49eaf0b5 | 17b90043c84a18f3ae1a1446015c55391e504f02 | /src/sample/ChatServerModel.java | f3a808e29589e2ecefb660b1434185baecc5089c | [] | no_license | Mscizor/csnetwk-socket-chatbot | 1a3920a34af66aa8c873a52fe1dda4ffab7fe576 | 64115b98cd4f8a61716ca045ac9e737d14192568 | refs/heads/master | 2022-12-27T12:01:47.889864 | 2020-09-26T15:26:40 | 2020-09-26T15:26:40 | 295,292,807 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 287 | java | package sample;
public class ChatServerModel {
private String portNumber;
public String getPortNumber() {
return portNumber;
}
public void setPortNumber(String portNumber) {
this.portNumber = portNumber;
}
public ChatServerModel(){
}
}
| [
"[email protected]"
] | |
0487642fa891635dd7efc83c2f1eac2de760e29f | a642d1140eea7dd3bb01b685b21eb1fbaf8234e3 | /src/test/java/com/hedwig/service/TopicManagerTest.java | e8944ae51ddf9c60b48c9672d22ae5c49c454f55 | [] | no_license | hedwig-project/Morpheus | bdbb2a3814182f32066574b4e0e345ba102f9adc | e245ee0d5d032a6e1709db19859f90c53053da2e | refs/heads/master | 2020-12-30T12:34:51.017732 | 2017-11-11T17:51:02 | 2017-11-11T17:51:02 | 91,388,067 | 0 | 0 | null | 2017-06-18T17:37:45 | 2017-05-15T21:51:21 | Java | UTF-8 | Java | false | false | 1,890 | java | package com.hedwig.service;
import com.hedwig.morpheus.EntryPoint;
import com.hedwig.morpheus.business.MQTTServer;
import com.hedwig.morpheus.domain.implementation.Result;
import com.hedwig.morpheus.service.implementation.TopicManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Created by hugo. All rights reserved.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EntryPoint.class)
public class TopicManagerTest {
@Mock
private MQTTServer mqttServer;
@InjectMocks
private TopicManager topicManager;
@Before
public void setupMocks() {
Result result = new Result();
result.setSuccess(true);
// Subscription
Mockito.when(mqttServer.subscribe(Mockito.anyString())).thenReturn(result);
// Unsubscribe
Mockito.when(mqttServer.unsubscribe(Mockito.anyString())).thenReturn(result);
}
@Test
public void subscribeToTopic() {
String topic = "hw/kitchen/s2m";
topicManager.subscribe(topic);
assertTrue(topicManager.isSubscribed(topic));
}
@Test
public void tryToUnsubscribeUnkownTopic() {
String topic = "hw/kitchen/s2m";
assertFalse(topicManager.unsubscribe(topic).isSuccess());
}
@Test
public void unsubscribeFromTopic() {
String topic = "hw/kitchen/s2m";
topicManager.subscribe(topic);
assertTrue(topicManager.isSubscribed(topic));
assertTrue(topicManager.unsubscribe(topic).isSuccess());
assertFalse(topicManager.isSubscribed(topic));
}
}
| [
"[email protected]"
] | |
8f6364f411e2062dd20416c3e24318aee03c6261 | f07a95dde9700fb207e81862388d852076394d60 | /app/src/main/java/com/example/citacup/bakul/Business/JSONParser.java | c08b1da25ede9650ddf765f34a4f09c36b3e7d1b | [] | no_license | citacup/BaKul | 4f1666f8ec3a62bd4540ddbaa87a172f3ef74683 | e599be82df79d61e7822b371ff1d062f0069ea81 | refs/heads/master | 2020-05-17T21:28:51.697159 | 2015-06-16T08:48:37 | 2015-06-16T08:48:37 | 33,106,483 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,122 | java | package com.example.citacup.bakul.Business;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by Vincenda Diaz on 3/6/2015.
*/
public class JSONParser {
static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Parse String to JSON object
try {
jarray = new JSONArray(builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jarray;
}
}
| [
"[email protected]"
] | |
015a357bf36e3ef7f6e94f1daef0742742b74b8d | b74c9443eb0b30ee709e3ab87d14cfb7a038f1c3 | /app/src/main/java/myfirstapp/example/com/timaverkefni/MyActivity.java | 6af2c0a64dc2bdedffecf6b11a4ac3b989af33f1 | [] | no_license | kataelias/Timaverkefni | 3968d70383781321482829318d2fd6873e15a3c1 | 33b2c0214230d066217327471b43402cee532fe5 | refs/heads/master | 2016-09-05T11:52:14.791156 | 2014-10-10T14:01:19 | 2014-10-10T14:01:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,046 | java | package myfirstapp.example.com.timaverkefni;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| [
"[email protected]"
] | |
1f98b2436f4bcf888edbbc1749c63c7ea2010bf1 | adf52b2b01c73e3970ed0ffeadda804420701596 | /runescape-client/src/main/java/osrs/WorldMapDecorationType.java | 469ec661e3c918e091f58f8f297ebc70c079548d | [] | no_license | SheinH/MeteorLite | 83f112d7bcdb9351912473d6cac0471d2558d9fe | bbef05db392bfdf1fb6b8e6adcc88cab0eb2a763 | refs/heads/main | 2023-09-06T06:32:08.094319 | 2021-11-15T00:15:12 | 2021-11-15T00:15:12 | 416,130,065 | 0 | 0 | null | 2021-10-12T00:38:45 | 2021-10-12T00:38:45 | null | UTF-8 | Java | false | false | 3,326 | java | package osrs;
import net.runelite.mapping.Export;
import net.runelite.mapping.Implements;
import net.runelite.mapping.ObfuscatedGetter;
import net.runelite.mapping.ObfuscatedName;
import net.runelite.mapping.ObfuscatedSignature;
@ObfuscatedName("jv")
@Implements("WorldMapDecorationType")
public enum WorldMapDecorationType implements MouseWheel {
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3238(0, 0),
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3223(1, 0),
@ObfuscatedName("s")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3224(2, 0),
@ObfuscatedName("a")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3230(3, 0),
@ObfuscatedName("o")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3231(9, 2),
@ObfuscatedName("g")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3227(4, 1),
@ObfuscatedName("e")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3228(5, 1),
@ObfuscatedName("p")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3240(6, 1),
@ObfuscatedName("j")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3234(7, 1),
@ObfuscatedName("b")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3229(8, 1),
@ObfuscatedName("x")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3232(12, 2),
@ObfuscatedName("y")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3225(13, 2),
@ObfuscatedName("k")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3222(14, 2),
@ObfuscatedName("t")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3235(15, 2),
@ObfuscatedName("l")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3236(16, 2),
@ObfuscatedName("u")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3237(17, 2),
@ObfuscatedName("n")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3226(18, 2),
@ObfuscatedName("z")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3239(19, 2),
@ObfuscatedName("q")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3233(20, 2),
@ObfuscatedName("d")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3241(21, 2),
@ObfuscatedName("r")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3242(10, 2),
@ObfuscatedName("m")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3243(11, 2),
@ObfuscatedName("c")
@ObfuscatedSignature(
descriptor = "Ljv;"
)
field3244(22, 3);
@ObfuscatedName("f")
@ObfuscatedGetter(
intValue = -1784539249
)
@Export("id")
public final int id;
@ObfuscatedSignature(
descriptor = "(II)V",
garbageValue = "0"
)
WorldMapDecorationType(int var3, int var4) {
this.id = var3;
}
@ObfuscatedName("w")
@ObfuscatedSignature(
descriptor = "(I)I",
garbageValue = "238732485"
)
@Export("rsOrdinal")
public int rsOrdinal() {
return this.id;
}
@ObfuscatedName("i")
@ObfuscatedSignature(
descriptor = "(B)I",
garbageValue = "15"
)
static int method5193() {
return ++Messages.Messages_count - 1;
}
}
| [
"[email protected]"
] | |
1b514879d7fcc65254914694e025096439a1ffa2 | d939455f557cd9eda2619fd812025d8e19b083e3 | /Java/src/com/longluo/leetcode/greedy/Problem605_canPlaceFlowers.java | a0e544f671d3a8af8acaf1a178251efc1ba21011 | [
"MIT"
] | permissive | longluo/leetcode | 61d445bd4fbae13b99ea24e9ef465bb700022866 | 5a171f223c03cfdddb18488fd4bc5910039e21c4 | refs/heads/master | 2023-08-17T05:03:25.433075 | 2023-07-30T04:01:16 | 2023-07-30T04:01:16 | 58,620,185 | 58 | 20 | MIT | 2023-05-25T19:00:48 | 2016-05-12T07:52:04 | Java | UTF-8 | Java | false | false | 3,264 | java | package com.longluo.leetcode.greedy;
/**
* 605. 种花问题
* <p>
* 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。
* 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。
* <p>
* 能否在不打破种植规则的情况下种入 n 朵花?能则返回True,不能则返回False。
* <p>
* 示例 1:
* 输入: flowerbed = [1,0,0,0,1], n = 1
* 输出: True
* <p>
* 示例 2:
* 输入: flowerbed = [1,0,0,0,1], n = 2
* 输出: False
* <p>
* 注意:
* 数组内已种好的花不会违反种植规则。
* 输入的数组长度范围为 [1, 20000]。
* n 是非负整数,且不会超过输入数组的大小。
* <p>
* https://leetcode.cn/problems/can-place-flowers/
*/
public class Problem605_canPlaceFlowers {
public static boolean canPlaceFlowers_simu(int[] flowerbed, int n) {
int len = flowerbed.length;
if (len == 1) {
if (n == 1 && flowerbed[0] == 0) {
return true;
} else if (n == 1 && flowerbed[0] == 1) {
return false;
}
return n == 0;
}
for (int i = 0; i < len; i++) {
if (n == 0) {
break;
}
if (i == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
n--;
flowerbed[i] = 1;
} else if (i == len - 1 && flowerbed[i] == 0 && flowerbed[i - 1] == 0 && n > 0) {
n--;
} else if (i >= 1 && i < len - 1 && flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
n--;
flowerbed[i] = 1;
}
}
return n <= 0;
}
public static boolean canPlaceFlowers(int[] flowerbed, int n) {
if (n == 0) {
return true;
}
if (flowerbed.length == 1 && flowerbed[0] == 0 && n <= 1) {
return true;
}
if (flowerbed[0] == 0 && flowerbed[1] == 0) {
flowerbed[0] = 1;
n--;
}
for (int i = 1; i < flowerbed.length - 1; i++) {
if (flowerbed[i - 1] == 0 && flowerbed[i] == 0 && flowerbed[i + 1] == 0) {
flowerbed[i] = 1;
n--;
}
if (n == 0) {
return true;
}
}
if (flowerbed[flowerbed.length - 1] == 0 && flowerbed[flowerbed.length - 2] == 0) {
flowerbed[flowerbed.length - 1] = 1;
n--;
}
if (n == 0) {
return true;
}
return false;
}
public static void main(String[] args) {
System.out.println("false ?= " + canPlaceFlowers(new int[]{0, 1, 0}, 1));
System.out.println("true ?= " + canPlaceFlowers(new int[]{1, 0, 0, 0, 1}, 1));
System.out.println("false ?= " + canPlaceFlowers(new int[]{1, 0, 0, 0, 1}, 2));
System.out.println("false ?= " + canPlaceFlowers_simu(new int[]{1, 0, 0, 0, 1}, 2));
System.out.println("false ?= " + canPlaceFlowers_simu(new int[]{1, 0, 0, 0, 0, 1}, 2));
}
}
| [
"[email protected]"
] | |
6902ec50e37868c7690a9eb5d27ccf504909f174 | 5397c4cb6f88ab47c48e9e3bf1bd4081b00b69e7 | /app/src/main/java/com/fengyu/liveyoukube/ui/fragment/ProgramSetVPTabButtonFragment.java | d7ca46033841835b713b37be6a61e553322773cb | [] | no_license | fengyu17/Live-On-YouKube | 06079079d5dae70388555f7945a53b1f9c5a4dc2 | a0ce4953317c9bbdff334bf56d4c03e8ff09a012 | refs/heads/master | 2021-01-10T12:12:31.815808 | 2016-01-04T02:50:05 | 2016-01-04T02:50:05 | 48,969,351 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,887 | java | package com.fengyu.liveyoukube.ui.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.fengyu.liveyoukube.R;
import com.youkube.player.PlayerActivity;
/**
* Created by Administrator on 2015/12/1.
*/
public class ProgramSetVPTabButtonFragment extends BaseFragment {
/*组件类成员*/
private Button mbtnPlay;
/*数据类成员*/
private String mprogramId;
public ProgramSetVPTabButtonFragment() {
}
public static ProgramSetVPTabButtonFragment newInstance(String programId) {
ProgramSetVPTabButtonFragment fragmentDemo = new ProgramSetVPTabButtonFragment();
Bundle args = new Bundle();
args.putString("programId", programId);
fragmentDemo.setArguments(args);
return fragmentDemo;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mprogramId = getArguments().getString("programId", "");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_button, container, false);
mbtnPlay = (Button) view.findViewById(R.id.btn_play);
mbtnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mprogramId != null && !mprogramId.equals("")) {
Intent i = new Intent(getActivity(), PlayerActivity.class);
i.putExtra("vid", mprogramId.trim());
getActivity().startActivity(i);
}
}
});
return view;
}
}
| [
"[email protected]"
] | |
27a98cd1e26077884d83ad5e0c0890953e640398 | 2dc1003a241352711268ad7e105dfa79221ba921 | /Mod02_Spring_Core/src/main/java/solution2/HelloServiceImpl.java | 29d765e6737b785c54bf6f47d320a149be1f1130 | [] | no_license | Codecenter/courses-spring-framework | b8f4a96766e25ea794c5fc2ed0ed1b7e718c8acc | 4946b3607497222422556cad0d3f6fad16c3d5ce | refs/heads/master | 2016-09-05T18:21:39.313931 | 2015-04-03T12:18:14 | 2015-04-03T12:18:14 | 17,670,044 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 158 | java | package solution2;
public class HelloServiceImpl implements HelloService {
@Override
public void sayHello() {
System.out.println("Hello World!");
}
}
| [
"[email protected]"
] | |
6c4db7a510e47250ab2646bd09e80caa5c890ee7 | 55cf651ee1e0f80977f30f52c0255e9178a8d651 | /android/app/src/main/java/com/example/flutter_app_test1/MainActivity.java | 9d06bb2136a6490e65f01174f37c97989f4da88d | [] | no_license | erenatas/Relation-Helper | 82a7919c33c45705fdf82dfc4ba6b7efb30303e3 | ca547a0dcc456e18a694648134aa71a296a4862f | refs/heads/master | 2020-05-31T17:29:32.564619 | 2019-06-05T14:27:29 | 2019-06-05T14:27:29 | 190,409,750 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 374 | java | package com.example.flutter_app_test1;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
}
}
| [
"[email protected]"
] | |
47d13c269db49a1b0a92138377a2e52d3c6d2197 | 639afd802c1cf96d712b4ada9048ca5a10835085 | /src/main/java/org/apache/ibatis/abator/internal/db/ActualTableName.java | db8db9aaa2e30947e5df902ee2becade702b1dc3 | [
"MIT"
] | permissive | ajtdnyy/PackagePlugin | 368c58df585f6de2ad6c22070f4d0804330de5e4 | 294f5522243a27411d12ba7c655272a6bdbe7acd | refs/heads/master | 2022-07-15T14:28:39.267751 | 2020-09-23T05:43:01 | 2020-09-23T05:43:01 | 97,782,378 | 13 | 4 | MIT | 2022-06-28T15:29:18 | 2017-07-20T02:37:40 | Java | UTF-8 | Java | false | false | 1,797 | java | /*
* Copyright 2007 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.abator.internal.db;
import org.apache.ibatis.abator.internal.util.StringUtility;
/**
* This class holds the actual catalog, schema, and table name returned from
* the database introspection.
*
* @author Jeff Butler
*
*/
public class ActualTableName {
private String tableName;
private String catalog;
private String schema;
public ActualTableName (String catalog, String schema, String tableName) {
this.catalog = catalog;
this.schema = schema;
this.tableName = tableName;
}
public String getCatalog() {
return catalog;
}
public String getSchema() {
return schema;
}
public String getTableName() {
return tableName;
}
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof ActualTableName)) {
return false;
}
return obj.toString().equals(this.toString());
}
public int hashCode() {
return toString().hashCode();
}
public String toString() {
return StringUtility.composeFullyQualifiedTableName(catalog, schema, tableName, '.');
}
}
| [
"[email protected]"
] |
Subsets and Splits