blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f79dd78d04322938e06f982887265b938c0014ba | 5dd0d88c6fe65cb2a06c3d885a726b4a89b8a7b0 | /华为机试题/IP地址的合法性判断.java | cc59bbd0ab78a52ecd6e19ae72c82fe78064a169 | [] | no_license | xjtuselb/HUAWEI-machine-test | 3a2a7723a76a4568fb3e694fa728b745a4e92f93 | 7a9562347e2b5e340d0cf623c23fd7b53778e941 | refs/heads/master | 2020-09-19T16:17:35.685666 | 2016-09-10T14:15:53 | 2016-09-10T14:15:53 | 65,960,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 708 | java | package 华为机试题;
import java.util.Scanner;
public class IP地址的合法性判断 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String ip = sc.nextLine();
System.out.println(isRightIP(ip));
}
sc.close();
}
public static String isRightIP(String ip) {
for (int i = 0; i < ip.length(); i++) {
if (!"0123456789.".contains(ip.charAt(i) + ""))
return "NO";
}
if (ip.contains(" "))
return "NO";
String[] a = ip.split("\\.");
if (a.length != 4)
return "NO";
for (int i = 0; i < 4; i++) {
if (Integer.parseInt(a[i]) > 255 || Integer.parseInt(a[i]) < 0)
return "NO";
}
return "YES";
}
}
| [
"hest0001@outlook.com"
] | hest0001@outlook.com |
110a81692145353be8340398cadd9a4c2c6d7b08 | 9f335488a2e939dd0f1f63f2181d4f6ef9d25753 | /engine/src/main/java/org/camunda/bpm/engine/impl/externaltask/ExternalTaskLogger.java | a27ebd5229a01e04540f8a52c15330a308f71cb8 | [
"Apache-2.0"
] | permissive | LuisePufahl/camunda-bpm-platform_batchProcessing | 41448373f3dbcfc5fe36c28a92c51a3d55cf8081 | 59d29419f753fd7aa0be8b75326982fe6c735cbb | refs/heads/master | 2020-03-30T08:03:02.785718 | 2016-06-01T10:45:56 | 2016-06-01T10:45:56 | 55,690,196 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,567 | java | /*
* Copyright 2016 camunda services GmbH.
*
* 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.camunda.bpm.engine.impl.externaltask;
import org.camunda.bpm.engine.ProcessEngineException;
import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
/**
* Represents the logger for the external task.
*
* @author Christopher Zell <christopher.zell@camunda.org>
*/
public class ExternalTaskLogger extends ProcessEngineLogger {
/**
* Logs that the priority could not be determined in the given context.
*
* @param execution the context that is used for determining the priority
* @param value the default value
* @param e the exception which was catched
*/
public void couldNotDeterminePriority(ExecutionEntity execution, Object value, ProcessEngineException e) {
logWarn(
"001",
"Could not determine priority for external task created in context of execution {}. Using default priority {}",
execution, value, e);
}
}
| [
"zelldon91@gmail.com"
] | zelldon91@gmail.com |
0eea36ef525d4e3a75e7005f692fe61e04e8cc3d | 45987b82e85029d6d040f4208d57599e8ec02003 | /magicneptune/src/main/java/com/sillycat/magicneptune/controller/rest/FileRESTController.java | bdca4625ad7595e4eec0b47f9f52cab68ab66f5b | [] | no_license | luohuazju/magic | bd96da7c5f5b78af8093fbee11801af4f39bb14f | 324c74a706fbc1101aba2c1c097fa5c674ffe98a | refs/heads/master | 2022-12-23T04:37:09.269420 | 2021-05-05T18:19:03 | 2021-05-05T18:19:03 | 3,491,498 | 0 | 0 | null | 2022-12-16T01:28:49 | 2012-02-20T07:03:52 | JavaScript | UTF-8 | Java | false | false | 176 | java | package com.sillycat.magicneptune.controller.rest;
/**
*
* upload the files, graph, audio, video
* @author SILLYCAT
*
*/
public class FileRESTController {
}
| [
"luohuazju@gmail.com"
] | luohuazju@gmail.com |
ae60121387fc0b1023d970701feaa80142d47d31 | d707c711823f1d1cddb5a83a9637aef002faf496 | /src/main/java/com/example/company/security/SecurityService.java | cd9987a7585c129de6af50b225edbbeff7fb38de | [] | no_license | Aram955/company-employee-spring | 804b9fee82a781645ff302a4ca31e4d5b0e3be25 | 9a08705ddc947cf7424ccca5a1d8b87bb61a07a1 | refs/heads/main | 2023-07-17T05:49:31.139011 | 2021-09-01T10:11:42 | 2021-09-01T10:11:42 | 398,007,040 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 993 | java | package com.example.company.security;
import com.example.company.model.Employee;
import com.example.company.repository.EmployeeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
@RequiredArgsConstructor
public class SecurityService implements UserDetailsService {
private final EmployeeRepository employeeRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<Employee> byEmail = employeeRepository.findByEmail(s);
if (!byEmail.isPresent()){
throw new UsernameNotFoundException("User with"+ s+ "username does not exit");
}
return new CurrentUser(byEmail.get());
}
}
| [
"aram050385@gmail.com"
] | aram050385@gmail.com |
c2781d8798ba77af879e7a3cd98f8ab269ed9342 | a9727f50cc9e630e7cda9f5693353fcc8da64bda | /android/app/src/main/java/com/mysocialnetwork/MainActivity.java | fccb64679ec0f25e0d93522ad4988215dd9fdb37 | [] | no_license | PauloVieiraSousa/fiaprecycleapp | efc585a9546b1f56e20639c11fd7a3755eef72ba | f57db4370a84fb07e591228566e635c9657f44ba | refs/heads/main | 2023-07-30T06:18:55.339706 | 2021-09-22T04:01:16 | 2021-09-22T04:01:16 | 409,034,407 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 357 | java | package com.mysocialnetwork;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "MySocialNetwork";
}
}
| [
"paulogabrielvieira@gmail.com"
] | paulogabrielvieira@gmail.com |
82da53ab19e4b86b09df3d44f5f78c00aeb155ad | 691b1a76c781185d556e2549de00fc5acc52b710 | /src/main/java/com/george/kafka/ProducerWithCallback.java | be5c0a1f42614c12bbb596efb92d4cd91686503d | [] | no_license | nicholasjorge/kafka | b7bbb9559e9cdf27e6c0076761b2676732aa3808 | 6aba82d094c0b7401fb779becb17a93c2f198ce7 | refs/heads/master | 2020-07-22T17:52:48.228804 | 2019-09-09T10:09:30 | 2019-09-09T10:09:30 | 207,281,039 | 0 | 0 | null | 2023-09-05T22:01:55 | 2019-09-09T10:11:09 | Java | UTF-8 | Java | false | false | 1,750 | java | package com.george.kafka;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
public class ProducerWithCallback {
public static void main(String[] args) {
final String KAFKA_SERVER = "localhost:9092";
final Logger log = LoggerFactory.getLogger(ProducerWithCallback.class);
Properties properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_SERVER);
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
KafkaProducer<String,String> producer = new KafkaProducer<String,String>(properties);
for (int i = 0; i < 10; i++) {
ProducerRecord<String,String> record = new ProducerRecord<String,String>("first_topic", "hello-world" + Integer.toString(i));
producer.send(record, new Callback() {
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
if (e == null) {
log.info("Received new metadata. \n" + "Topic: " + recordMetadata.topic() + "\n" + "Partition: " + recordMetadata.partition() + "\n" + "Offset:"
+ recordMetadata.offset() + "\n" + "Timestamp: " + recordMetadata.timestamp());
} else {
log.error("Error while producing", e);
}
}
});
}
producer.flush();
producer.close();
}
}
| [
"george.nicolae@ericsson.com"
] | george.nicolae@ericsson.com |
ad9b79febca6b2edddcbed5c83bcb5b6ae2b2991 | 37f16c2005061831969de9cb3291e180fd25decf | /app/src/main/java/com/nopalyer/navigationdrawer/humanities/humanitiesvision.java | d1168fcbc8c03de7681a9f33a3c95a8388c2f224 | [] | no_license | anshika2002/NITH-App | 29a0d8c21fcfaecb240c2adda195896474ae341a | 969a8d9b3ee712e67c2528110926eac967c55df0 | refs/heads/master | 2023-03-18T11:07:43.618866 | 2020-08-22T13:04:16 | 2020-08-22T13:04:16 | 523,223,315 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 698 | java | package com.nopalyer.navigationdrawer.humanities;
import android.graphics.Color;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.nopalyer.navigationdrawer.R;
public class humanitiesvision extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.humanities_humanitiesvision);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Vision and Mission");
toolbar.setTitleTextColor(Color.WHITE);
}
}
| [
"shreyanshjain2674@gmail.com"
] | shreyanshjain2674@gmail.com |
9741563620b30989a2c20ca8e57cea0427d6abf6 | e65e1c39ce6c8bc80b06a1d51fc6f5395d390fcc | /src/Aula_06_Lista_Encadeada/testaNo.java | 2bcbb6be67ad2803977479262d3096aad8f062ae | [
"MIT"
] | permissive | roschel/senac-estrutura-de-dados | b2e8875869cf27338589520c2e39915900bff1b4 | 5fe9535dc7052c6ea15261d941e93c769ba7c152 | refs/heads/master | 2023-01-21T07:26:24.090975 | 2020-11-24T22:00:57 | 2020-11-24T22:00:57 | 291,530,610 | 0 | 5 | MIT | 2020-11-23T11:46:02 | 2020-08-30T18:41:59 | Java | UTF-8 | Java | false | false | 449 | 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 Aula_06_Lista_Encadeada;
/**
*
* @author joao
*/
public class testaNo {
public static void main(String[] args) {
No a = new No(5, null);
No b = new No(7, a);
No c = new No(3, b);
System.out.println(c);
}
}
| [
"joaomroschel@gmail.com"
] | joaomroschel@gmail.com |
81c77a7a7a4b57c6985afffbeb3e5a32ceadf056 | 1f189290f36a9445f2a50a98a9244ae23704addd | /recomendacionfc/src/test/java/com/isistan/lbsn/recomendacionfc/AppTest.java | 6bf93c18dc19cda0a67a9031fe69464991300320 | [] | no_license | carlosrios10/recomendacionjava | 3320c82814241a3d0a6dd64edce02e7c6f1103e8 | 81214ef05d93a601a72d883e5a74684847f32bfd | refs/heads/master | 2021-01-22T23:15:48.960520 | 2018-09-06T20:17:53 | 2018-09-06T20:17:53 | 31,434,723 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 660 | java | package com.isistan.lbsn.recomendacionfc;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"cm.rios.10@gmail.com"
] | cm.rios.10@gmail.com |
ca0f9d81517077016fa06ed15cbaf4939c659e22 | 8b44b29571d602747da5010ef89626045e29d1f7 | /SuperheroSquad/src/main/java/com/sg/superhero/controller/PowerController.java | ad2b672f876f98421e1ccab4899844e1227feba2 | [] | no_license | cwhart/RestTestingProject | d3486d9268b0b816df9b920ff53348f7d386a780 | 26bc2df1af1e8e5413b27c857194fc565ab1cc92 | refs/heads/master | 2022-12-23T19:22:44.915057 | 2019-10-09T13:18:03 | 2019-10-09T13:18:03 | 212,916,090 | 0 | 0 | null | 2022-12-16T11:08:11 | 2019-10-04T23:08:51 | Java | UTF-8 | Java | false | false | 4,140 | java | package com.sg.superhero.controller;
import com.sg.superhero.dto.Power;
import com.sg.superhero.viewmodels.power.create.CreatePowerCommandModel;
import com.sg.superhero.viewmodels.power.create.CreatePowerViewModel;
import com.sg.superhero.viewmodels.power.edit.EditPowerCommandModel;
import com.sg.superhero.viewmodels.power.edit.EditPowerViewModel;
import com.sg.superhero.viewmodels.power.list.ListPowerViewModel;
import com.sg.superhero.viewmodels.power.profile.ProfilePowerViewModel;
import com.sg.superhero.webservice.interfaces.PowerWebService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.inject.Inject;
import javax.validation.Valid;
@Controller
@RequestMapping(value = "/power")
public class PowerController {
private PowerWebService powerWebService;
@Inject
public PowerController(PowerWebService powerWebService) {
this.powerWebService = powerWebService;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public String list(@RequestParam(required = false) Integer offset, Model model) {
if (offset == null) {
offset = 0;
}
ListPowerViewModel viewModel = powerWebService.getPowerListViewModel(offset);
model.addAttribute("viewModel", viewModel);
return "power/list";
}
@RequestMapping(value = "/edit")
public String edit(@RequestParam Long id, Model model) {
EditPowerViewModel viewModel = powerWebService.getEditPowerViewModel(id);
model.addAttribute("viewModel", viewModel);
model.addAttribute("commandModel", viewModel.getCommandModel());
return "power/edit";
}
@RequestMapping(value = "/edit", method= RequestMethod.POST)
public String saveEdit(@Valid @ModelAttribute("commandModel") EditPowerCommandModel commandModel, BindingResult bindingResult, Model model) {
if(bindingResult.hasErrors()) {
EditPowerViewModel viewModel = powerWebService.getEditPowerViewModel(commandModel.getId());
model.addAttribute("viewModel", viewModel);
model.addAttribute("commandModel", commandModel);
return "power/edit";
}
powerWebService.saveEditPowerCommandModel(commandModel);
return "redirect:/power/profile?id=" + commandModel.getId();
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String create(Model model) {
CreatePowerViewModel viewModel = powerWebService.getCreatePowerViewModel();
model.addAttribute("viewModel", viewModel);
model.addAttribute("commandModel", viewModel.getCommandModel());
return "power/create";
}
@RequestMapping(value = "/create", method= RequestMethod.POST)
public String saveCreate(@Valid @ModelAttribute("commandModel") CreatePowerCommandModel commandModel, BindingResult bindingResult, Model model) {
if(bindingResult.hasErrors()) {
CreatePowerViewModel viewModel = powerWebService.getCreatePowerViewModel();
model.addAttribute("viewModel", viewModel);
model.addAttribute("commandModel", commandModel);
return "player/create";
}
Power power = powerWebService.saveCreatePowerCommandModel(commandModel);
return "redirect:/power/profile?id=" + power.getId();
}
@RequestMapping(value = "/profile")
public String profile(@RequestParam Long id, Model model) {
ProfilePowerViewModel viewModel = powerWebService.getPowerProfileViewModel(id);
model.addAttribute("viewModel", viewModel);
return "power/profile";
}
@RequestMapping(value = "/delete")
public String delete(@RequestParam Long id, Model model) {
powerWebService.deletePower(id);
return "redirect:/power/list";
}
} | [
"cynthia.hartnett@libertymutual.com"
] | cynthia.hartnett@libertymutual.com |
477b66cd8955085304f8312400fc53577a9d2fd6 | 064c564b68318e3d925b105a581d628b6830af52 | /UrnaEletronica/src/br/ifpb/edu/entidades/Voto.java | 6267826cfb28c0101800244726558242f8246812 | [] | no_license | AndreLuiz98/URNA-master | 9034b05e2abcb20512ad7e1ba7ed02448944f9cd | 8517c73f9027e2031de826392a984d41e424d331 | refs/heads/master | 2021-01-13T00:52:19.633416 | 2016-03-30T19:43:11 | 2016-03-30T19:43:11 | 54,942,350 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,758 | java | package br.ifpb.edu.entidades;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "tb_voto")
@NamedQuery(name = "Voto.getAll", query = "from Voto")
public class Voto {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_voto")
private Integer id;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_eleitor")
private Eleitor eleitor;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_candidato")
private Candidato candidato;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_urna")
private UrnaEletronica urnaEletronica;
@Column(name = "data")
private Date data;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Eleitor getEleitor() {
return eleitor;
}
public void setEleitor(Eleitor eleitor) {
this.eleitor = eleitor;
}
public Candidato getCandidato() {
return candidato;
}
public void setCandidato(Candidato candidato) {
this.candidato = candidato;
}
public UrnaEletronica getUrnaEletronica() {
return urnaEletronica;
}
public void setUrnaEletronica(UrnaEletronica urnaEletronica) {
this.urnaEletronica = urnaEletronica;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
}
| [
"matheus.costa.rodrigues98@gmail.com"
] | matheus.costa.rodrigues98@gmail.com |
bea2cbbf923b26c4a6f67eba8ca4461616c84d92 | 86aa5ffc239deb0c30c6518ba3e9f0337ca3546f | /app/src/main/java/com/progameming/internproject/CartListAdapter.java | f8fa496289a13605dd1e2467b56dd39579be9bef | [] | no_license | RyanYee1057/Kiosk | a5a06be70254ab26d38320930fa9a59a610b36d5 | 33e171ab93777418f35143e0660642f8d85eb7b9 | refs/heads/master | 2023-05-02T07:43:20.738429 | 2021-05-25T08:51:47 | 2021-05-25T08:51:47 | 327,861,404 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,346 | java | package com.progameming.internproject;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.zip.Inflater;
public class CartListAdapter extends BaseAdapter {
Context context;
private ArrayList<cartModel> c;
private LayoutInflater mInflater;
private boolean mShowCheckbox;
public CartListAdapter(Context context, ArrayList<cartModel> list, boolean showCheckbox) {
this.context = context;
this.c = list;
//mInflater = inflater;
mShowCheckbox = showCheckbox;
}
public CartListAdapter(ArrayList<cartModel> list, LayoutInflater Inflater, boolean showCheckbox) {
this.c = list;
mInflater = Inflater;
mShowCheckbox = showCheckbox;
}
@Override
public int getCount() {
return c.size();
}
@Override
public Object getItem(int position) {
return c.get(position);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
final ViewItem item;
if(view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_cart, null);
item = new ViewItem();
//JSONObject jsonObject;
item.product_id = view.findViewById(R.id.productID);
item.product_name = view.findViewById(R.id.productName);
item.selling_price = view.findViewById(R.id.productPrice);
item.product_pic = view.findViewById(R.id.p_pic);
item.quantity = view.findViewById(R.id.quantityNo);
item.checkBox = view.findViewById(R.id.checkBox);
item.num = view.findViewById(R.id.num);
item.plus = view.findViewById(R.id.button_plus);
item.minus = view.findViewById(R.id.button_minus);
view.setTag(item);
}else{
item = (ViewItem) view.getTag();
}
if(c != null) {
item.product_id.setText(c.get(position).getP_id());
item.selling_price.setText("RM " + c.get(position).getPrice());
item.product_name.setText(c.get(position).getP_name());
Glide.with(context).load(c.get(position).getP_pic()).override(160, 150).into(item.product_pic);
item.quantity.setText(c.get(position).getQuantity());
item.num.setText(c.get(position).getQuantity());
if(c.get(position).isSelected())
item.checkBox.setChecked(true);
else
item.checkBox.setChecked(false);
}
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
item.checkBox.setChecked(true);
c.get(position).setSelected(true);
}
else{
item.checkBox.setChecked(false);
c.get(position).setSelected(false);
}
}
});
item.plus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedNum = Integer.parseInt(item.num.getText().toString());
selectedNum++;
item.num.setText(String.valueOf(selectedNum));
item.quantity.setText(String.valueOf(selectedNum));
c.get(position).setQuantity(String.valueOf(selectedNum));
calculate();
}
});
item.minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int selectedNum = Integer.parseInt(item.num.getText().toString());
selectedNum--;
if (selectedNum <1)
selectedNum = 1;
item.num.setText(String.valueOf(selectedNum));
item.quantity.setText(String.valueOf(selectedNum));
c.get(position).setQuantity(String.valueOf(selectedNum));
calculate();
}
});
/*if(cartList != null) {
jsonObject = cartList.getJSONObject(position);
product_id.setText(jsonObject.getString("product_id"));
product_name.setText(jsonObject.getString("product_name"));
selling_price.setText(jsonObject.getString("selling_price"));
Glide.with(context).load(jsonObject.getString("img_url")).override(160, 150).into(product_pic);
}
*/
return view;
}
public void calculate(){
// LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//LayoutInflater.from(Cart);
//setContentView();
//View view = inflater.inflate(R.layout.activity_cart, null);
//TextView price = view.findViewById(R.id.showPrice);
double p = 0.00;
if(!c.isEmpty()) {
for (int i = 0; i < c.size(); i++) {
p += (Double.parseDouble(c.get(i).getPrice()) * Double.parseDouble(c.get(i).getQuantity()));
}
//price.setText("RM" + String.format("%.2f", p));
}else{
String pp = "RM 0";
p = 0.00;
//price.setText(pp);
}
Cart.getInstance().calculation(p);
//cart.calculation(p);
//Toast.makeText(context, "calculate: " + p, Toast.LENGTH_SHORT).show();
}
private class ViewItem {
TextView product_id;
TextView product_name;
TextView selling_price;
ImageView product_pic;
TextView quantity;
CheckBox checkBox;
ImageButton plus, minus;
TextView num;
}
}
| [
"yeezs-wm19@student.tarc.edu.my"
] | yeezs-wm19@student.tarc.edu.my |
f7b13976148558defd3f92d4fd3c49e5b2e526ac | 7c8252475222ffd75053a5b46acc203803002e46 | /33. Search in Rotated Sorted Array /Solutions.java | 0c5a95323fd2c46bfa54cfd7f6aa2e7a4fcfd013 | [] | no_license | KnowNothingg/Leetcode-Practice | d2a4c43aa5cbb9e9d83aaae451699c98c82d30c4 | 9eac99f84506d6bf3b8585300b5636e67c89dab7 | refs/heads/master | 2020-05-30T00:53:02.317684 | 2020-04-30T21:56:24 | 2020-04-30T21:56:24 | 189,466,856 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 464 | java | public class Solutions{
public static void main(String[] args) {
int[] arr1 = {4,5,6,7,0,1,2}; // target: 0 return 4
int[] arr2 = {4,5,6,7,0,1,2}; // target: 3 return -1
System.out.println(search(arr1, 0));
}
public static int search(int[] nums, int target) {
for(int i = 0; i < nums.length; i++){
if(nums[i] == target){
return i;
}
}
return -1;
}
} | [
"blackpeppersama@gmail.com"
] | blackpeppersama@gmail.com |
f5dc961acf50a162a3766afe0c81f740ad733f4d | 1d9850ef7433f889fa1b20ffdcc22924eba064e3 | /app/src/main/java/com/wisedu/scc/love/widget/html/Scanner.java | 6b50e4496eeae4541e89cd118d147f1f76872fa5 | [
"Apache-2.0"
] | permissive | suethan/love | 484809a39e33c2dcd487ac5deb98935fe8061061 | d951c9e6745cf2ead3548707e3e9d11f0053f86d | refs/heads/master | 2021-01-15T11:49:51.879653 | 2015-03-30T09:19:03 | 2015-03-30T09:19:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,369 | java | // This file is part of TagSoup and is Copyright 2002-2008 by John Cowan.
//
// TagSoup is licensed under the Apache License,
// Version 2.0. You may obtain a copy of this license at
// http://www.apache.org/licenses/LICENSE-2.0 . You may also have
// additional legal rights not granted by this license.
//
// TagSoup is distributed in the hope that it will be useful, but
// unless required by applicable law or agreed to in writing, TagSoup
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, either express or implied; not even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//
// Scanner
package com.wisedu.scc.love.widget.html;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.Reader;
/**
An interface allowing Parser to invoke scanners.
**/
public interface Scanner {
/**
Invoke a scanner.
@param r A source of characters to scan
@param h A ScanHandler to report events to
**/
public void scan(Reader r, ScanHandler h) throws IOException, SAXException;
/**
Reset the embedded locator.
@param publicid The publicid of the source
@param systemid The systemid of the source
**/
public void resetDocumentLocator(String publicid, String systemid);
/**
Signal to the scanner to start CDATA content mode.
**/
public void startCDATA();
}
| [
"ccliu@wisedu.com"
] | ccliu@wisedu.com |
c942d63dcd9c3891f7a9396f04881ee4454c7d0a | 9e09bdde4a67e3a8861f009d2dd08548eecced16 | /app/src/main/java/com/example/myappretrofitrxjava/TaskApi.java | a829010f9c3c733c3e9c8ea09c2268ae2d0e5199 | [] | no_license | Goncharov01/MyAppRetrofitRxjava | ec210b59329fd445126ffb14e574d5416a60ee16 | f7d8e2b0b0eeb7af0e4e4a8598cfaed31b8af493 | refs/heads/master | 2021-01-04T15:10:00.492092 | 2020-02-14T22:06:25 | 2020-02-14T22:06:25 | 240,606,564 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 232 | java | package com.example.myappretrofitrxjava;
import java.util.ArrayList;
import io.reactivex.Observable;
import retrofit2.http.GET;
public interface TaskApi {
@GET("api/task")
Observable<ArrayList<TaskModel>> getTask();
}
| [
"mr.sacha.goncharov.01@mail.ru"
] | mr.sacha.goncharov.01@mail.ru |
2c8253c5ceea3c237ef7599604e881e14a7063c0 | 2e39d5523e81cc7ec3f0d5b101e73e243e275888 | /kotlin/algorithms/GuideToCP/classic-cs-problems/src/main/kotlin/com/br/cp/problems/package-info.java | d9db4ee57194a24ddce269daeaee401d3ae30b09 | [] | no_license | chrislucas/competitive-programming | 9c85aaa54199c114cc455992c4722a228dcdc891 | 3ad9a2ceb69afdea151f66243ef86582361b57ff | refs/heads/master | 2023-07-29T19:02:56.353807 | 2023-07-17T13:57:00 | 2023-07-17T13:57:00 | 25,211,939 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 295 | java | package com.br.cp.problems;
/**
* Modulo para implementar os algoritmos ensinados no livro:
*
* Problemas classicos da da ciencia da computacao em pytohn de
* Davic Kopec
*
* Como no momento tenho interesse de estudar Kotlin, os algoritmos serao implementados
* nessa linguagem
*
* */ | [
"christoffer.luccas@gmail.com"
] | christoffer.luccas@gmail.com |
4eadbb17293ae5bd256444573605122399513afd | f9f69052124ec65ce2c9deb8893a3750e742dd13 | /GameMaster_Threads_5/src/database/GameMasterSQL.java | 5e279c979d2cba336d2fba03b9731e1a2b66c536 | [] | no_license | jasonmrimer/GameMaster | ad34f7514ed26ae15349a1ed519affb3e5aa43d5 | 15087116c06033c5583173b1dde73604475da498 | refs/heads/master | 2021-05-29T19:37:59.144320 | 2015-10-11T12:54:01 | 2015-10-11T12:54:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,508 | java | package database;
//This is the backend architecture for GameMaster.
//Created by: Dave Walters
//Date updated: 5/30/2014
import java.sql.*;
import java.util.*;
public class GameMasterSQL {
//constructor
public GameMasterSQL (){}
//Takes username and password input, runs it against the 'users' table in the
//database. If found, the query will return the userid. If not found, will return
//0. In the GUI, can make an if statement that displays a login failed message
//and call recursion.
public int login (Statement GameMasterQuery, String username, String password) throws SQLException {
ResultSet userCredentials;
int userid = 0;
userCredentials = GameMasterQuery.executeQuery ("SELECT *"
+ " FROM users"
+ " WHERE email = '" + username + "'"
+ " AND password = '" + password + "';");
if (userCredentials.next()){
userid = Integer.parseInt(userCredentials.getString("userid"));
} //end if
return userid;
} //end login()
//Takes userid int and queries the 'userchars' table to determine which charids
//are assigned to that userid. It will return an ArrayList with those numbers for
//further processing.
public ArrayList getUserCharArrayList (Statement GameMasterQuery, int userid, String gameString) throws SQLException {
ResultSet userCharResultSet;
ArrayList userCharArrayList = new ArrayList<Integer>();
userCharResultSet = GameMasterQuery.executeQuery ("SELECT userchars.charid"
+ " FROM characters INNER JOIN userchars"
+ " WHERE characters.game = '" + gameString + "'"
+ " AND userchars.charid = characters.charid"
+ " and userchars.userid = " + userid + ";");
while (userCharResultSet.next()){
userCharArrayList.add(Integer.parseInt(userCharResultSet.getString("charid")));
} //end while statement
return userCharArrayList;
} //end getUserCharArrayList()
public ArrayList getCharacterNames (Statement GameMasterQuery, ArrayList userCharArray) throws SQLException {
ResultSet charNamesResultSet;
ArrayList characterNames = new ArrayList<>();
for (int i = 0; i < userCharArray.size(); i++) {
charNamesResultSet = GameMasterQuery.executeQuery("SELECT name"
+ " FROM characters"
+ " WHERE charid = " + userCharArray.get(i));
while (charNamesResultSet.next()){
characterNames.add(charNamesResultSet.getString("name"));
}//end while statement
} //end for statement
return characterNames;
} //end getCharacterNames()
public HashMap getCharacterStats (Statement GameMasterQuery, int charid) throws SQLException {
ResultSet statResultSet;
HashMap characterStats = new HashMap<>();
statResultSet = GameMasterQuery.executeQuery("SELECT stats.str, stats.dex,"
+ " stats.con, stats.int, stats.wis, stats.cha, stats.level,"
+ " characters.race, characters.class"
+ " FROM stats INNER JOIN characters"
+ " WHERE stats.charid = " + charid
+ " AND characters.charid = " + charid
+ " AND stats.charid = characters.charid");
while (statResultSet.next()){
characterStats.put("STR", Integer.parseInt(statResultSet.getString("str")));
characterStats.put("DEX", Integer.parseInt(statResultSet.getString("dex")));
characterStats.put("CON", Integer.parseInt(statResultSet.getString("con")));
characterStats.put("INT", Integer.parseInt(statResultSet.getString("int")));
characterStats.put("WIS", Integer.parseInt(statResultSet.getString("wis")));
characterStats.put("CHA", Integer.parseInt(statResultSet.getString("cha")));
characterStats.put("LEVEL", Integer.parseInt(statResultSet.getString("level")));
characterStats.put("RACE", statResultSet.getString("race"));
characterStats.put("CLASS", statResultSet.getString("class"));
} //end while
return characterStats;
} //end getCharacterStats()
//Connects to the MySQL database
public Connection getConnection () throws SQLException {
loadDriver();
Connection GameMasterConnection = DriverManager.getConnection("jdbc:mysql://localhost:"
+ "3306/gamemaster?user=root&password=Aliens123");
return GameMasterConnection;
} //end getConnection()
//Loads the Classpath driver.
private void loadDriver () {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch (ClassNotFoundException e) {
System.out.println ("LoadDriver.java: ClassNotFoundException");
} catch (InstantiationException i) {
System.out.println ("LoadDriver.java: InstantiationException");
} catch (IllegalAccessException ie){
System.out.println ("LoadDriver.java: IllegalAccessException");
}
} //end loadDriver()
} //end GameMasterSQL class
| [
"lovenirds@gmail.com"
] | lovenirds@gmail.com |
5c55f33e770699fe48935474b6287375029e31e5 | 5f5c53fb983d8d976e966373858f1fd45b4a8c29 | /src/couponjo/facade/ClientFacade.java | d15a4b381d8cc12bd176f615611b787ff221d268 | [] | no_license | YanivBanjo/coupon_system | f7aefde8946fb0e52be6765a4cb9f9a430b25654 | be2dc63f01357d1c6ba3b885b9e9aca01ef4d61c | refs/heads/main | 2023-03-15T22:26:17.888330 | 2021-03-14T09:03:26 | 2021-03-14T09:03:26 | 336,510,194 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 555 | java | package couponjo.facade;
import couponjo.dao.CompanyDAO;
import couponjo.dao.CouponDAO;
import couponjo.dao.CustomerDAO;
import couponjo.dbdao.CompanyDBDAO;
import couponjo.dbdao.CouponDBDAO;
import couponjo.dbdao.CustomerDBDAO;
import java.sql.SQLException;
public abstract class ClientFacade {
protected CompanyDAO companyDAO = new CompanyDBDAO();
protected CustomerDAO customerDAO = new CustomerDBDAO();
protected CouponDAO couponDAO = new CouponDBDAO();
abstract boolean login(String email, String password) throws SQLException;
}
| [
"yb8749@att.com"
] | yb8749@att.com |
640506ab515e12c4b28bf481ba22ccc92b8183dc | 0c52abd314906b56b65a92fa7b8ed1823c455b78 | /src/discountstrategy/PercentOffDiscount.java | 8d5bce12e051e91e8f6738e8b927553a8e338797 | [] | no_license | mparish2/DiscountStrategy | 9cfc481cb3fa155ab6e90ad9a3d24c04a85f08a3 | 4f3b80cb6c02f60da01765fe672902edac4db9c1 | refs/heads/master | 2021-01-10T06:13:26.468974 | 2015-10-14T20:56:42 | 2015-10-14T20:56:42 | 43,410,717 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,529 | 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 discountstrategy;
/**
*
* @author mparish2
*/
public class PercentOffDiscount implements DiscountStrategy {
private double discountRate;
public PercentOffDiscount(double discountRate) {
this.discountRate = discountRate;
}
@Override
public double getDiscountProductTotal(double unitPrice, int quantity){
return (unitPrice * quantity) - getAmountSaved(unitPrice,quantity);
};
@Override
public double getAmountSaved(double unitPrice, int quantity){
return unitPrice * quantity * discountRate;
};
@Override
public double getDiscountRate() {
return discountRate;
}
@Override
public void setDiscountRate(double discountRate) {
if (discountRate == 0){
throw new ArithmeticException("need to put a rate in. can't be 0");
}
this.discountRate = discountRate;
}
public static void main(String[] args) {
DiscountStrategy discount = new QuantityDiscount(.10, 2);
double amount = discount.getAmountSaved(10.00, 2);
System.out.println("Discount Amount:" + amount);
double newTotal = discount.getDiscountProductTotal(10.00, 2);
System.out.println("Discounted Product Total:" + newTotal);
}
}
| [
"Matthew_2@Matthew.attlocal.net"
] | Matthew_2@Matthew.attlocal.net |
d6ee64e099d4401105e2985f54349176136e4135 | 4ca66f616ebd8c999f5917059cc21321e35ba851 | /src/minecraft/net/minecraft/entity/player/PlayerCapabilities.java | ea9420a51128c8412708985a135232e1a8e5a80e | [] | no_license | MobbyGFX96/Jupiter | 1c66c872b4944654c1554f6e3821a63332f5f2cb | c5ee2e16019fc57f5a7f3ecf4a78e9e64ab40221 | refs/heads/master | 2016-09-10T17:05:11.977792 | 2014-07-21T09:24:02 | 2014-07-21T09:24:02 | 22,002,806 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,075 | java | package net.minecraft.entity.player;
import net.minecraft.nbt.NBTTagCompound;
public class PlayerCapabilities {
private static final String __OBFID = "CL_00001708";
public boolean disableDamage;
public boolean isFlying;
public boolean allowFlying;
public boolean isCreativeMode;
public boolean allowEdit = true;
private float flySpeed = 0.05F;
private float walkSpeed = 0.1F;
public void writeCapabilitiesToNBT(NBTTagCompound p_75091_1_) {
NBTTagCompound var2 = new NBTTagCompound();
var2.setBoolean("invulnerable", this.disableDamage);
var2.setBoolean("flying", this.isFlying);
var2.setBoolean("mayfly", this.allowFlying);
var2.setBoolean("instabuild", this.isCreativeMode);
var2.setBoolean("mayBuild", this.allowEdit);
var2.setFloat("flySpeed", this.flySpeed);
var2.setFloat("walkSpeed", this.walkSpeed);
p_75091_1_.setTag("abilities", var2);
}
public void readCapabilitiesFromNBT(NBTTagCompound p_75095_1_) {
if (p_75095_1_.func_150297_b("abilities", 10)) {
NBTTagCompound var2 = p_75095_1_.getCompoundTag("abilities");
this.disableDamage = var2.getBoolean("invulnerable");
this.isFlying = var2.getBoolean("flying");
this.allowFlying = var2.getBoolean("mayfly");
this.isCreativeMode = var2.getBoolean("instabuild");
if (var2.func_150297_b("flySpeed", 99)) {
this.flySpeed = var2.getFloat("flySpeed");
this.walkSpeed = var2.getFloat("walkSpeed");
}
if (var2.func_150297_b("mayBuild", 1)) {
this.allowEdit = var2.getBoolean("mayBuild");
}
}
}
public float getFlySpeed() {
return this.flySpeed;
}
public void setFlySpeed(float p_75092_1_) {
this.flySpeed = p_75092_1_;
}
public float getWalkSpeed() {
return this.walkSpeed;
}
public void setPlayerWalkSpeed(float p_82877_1_) {
this.walkSpeed = p_82877_1_;
}
}
| [
"MObbyGFX96@hotmail.co.uk"
] | MObbyGFX96@hotmail.co.uk |
9de7662695b1ece7cd89db43577cb51722013ae7 | 227cfaf65cd33d32bb3bb179e2b6bc5d5bcdda2d | /app/src/main/java/com/oneice/onepanel/Fragments/FragmentWarning.java | 37c74afd0870f5699ee4d58c8bda8a8d8989bb9a | [] | no_license | ONEICE2018/ANDROID_ONEPANEL | 16f4b7697dc55eb4ca45ed9be14412ff572af6eb | d3350d6b4bd319175ae8e856cecfed238fbe9473 | refs/heads/master | 2023-03-04T18:19:27.116000 | 2021-01-11T03:13:23 | 2021-01-11T03:13:23 | 328,528,321 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 762 | java | package com.oneice.onepanel.Fragments;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import com.oneice.onepanel.R;
import com.oneice.onepanel.activity_communication.RefrashFregments;
public class FragmentWarning extends OneLifeFragment implements RefrashFregments {
public View onCreateView(LayoutInflater inflater , ViewGroup container, Bundle savedInstanceState){
View view=inflater .inflate(R.layout .fragment_warring ,container,false) ;
refrashinit(view);
return view;
}
@Override
public void refrashinterface(String refname) {
}
@Override
public void refrashinit(View view) {
}
}
| [
"kaijun.yang@wattsine.com"
] | kaijun.yang@wattsine.com |
1cb18f95c3bc98b6495bbe02f8dbfaf91ca80501 | 4427b2a327d1063419267f2b43b07c771254ac6a | /app/src/main/java/pujiwahono/app/advancepuji/view/main/MainView.java | 1d8a23ecf08dd3d568fa354efb1a2252598f18a5 | [] | no_license | puji26/AIK_Advance_Puji | d474ac401d63388cb79a8b6b2cf4a05e0ff79a85 | 0f86f34b2c1ef1a892fe5d46877e228bc680a1b9 | refs/heads/master | 2021-01-22T03:14:20.552107 | 2017-05-29T02:31:59 | 2017-05-29T02:31:59 | 92,363,776 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package pujiwahono.app.advancepuji.view.main;
import pujiwahono.app.advancepuji.models.main.MainModelImp;
/**
* Created by evpuji2017 on 5/25/17.
*/
public interface MainView {
void onSuccess(MainModelImp result);
void onError(Throwable err);
}
| [
"pwahono26@gmail.com"
] | pwahono26@gmail.com |
a72e9b81d170b55e1c8c302ad43a851eff17d6b5 | c145912ae0134318c2cc851b609103121bedd518 | /app/src/main/java/p2p/chimple/org/p2pconnector/sync/CommunicationCallBack.java | 260923c9342b8baf1d0ba1d532248548d8cde059 | [] | no_license | chimple/P2PConnector | d6998acc40797d0bf39c26731688898b606a9779 | d439b2a173ec27bac77ed94cdef5fb10b2c52f77 | refs/heads/master | 2020-03-11T08:04:42.345456 | 2018-06-04T04:55:56 | 2018-06-04T04:55:56 | 129,874,390 | 0 | 0 | null | 2018-04-30T10:55:27 | 2018-04-17T08:46:55 | Java | UTF-8 | Java | false | false | 301 | java | package p2p.chimple.org.p2pconnector.sync;
import java.net.Socket;
public interface CommunicationCallBack {
public void Connected(Socket socket);
public void GotConnection(Socket socket);
public void ConnectionFailed(String reason);
public void ListeningFailed(String reason);
}
| [
"Shyamal.Upadhyaya@openlane.com"
] | Shyamal.Upadhyaya@openlane.com |
d80f017c4519e4caa726c7fb3ec013cbd3f30056 | 872095f6ca1d7f252a1a3cb90ad73e84f01345a2 | /mediatek/proprietary/packages/apps/RCSe/RcsStack/src/com/orangelabs/rcs/service/api/FileTransferServiceImpl.java | 92f27043c87eaa5f9278e39c72043fe71599014f | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | colinovski/mt8163-vendor | 724c49a47e1fa64540efe210d26e72c883ee591d | 2006b5183be2fac6a82eff7d9ed09c2633acafcc | refs/heads/master | 2020-07-04T12:39:09.679221 | 2018-01-20T09:11:52 | 2018-01-20T09:11:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 61,545 | java | /*******************************************************************************
* Software Name : RCS IMS Stack
*
* Copyright (C) 2010 France Telecom S.A.
*
* 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.orangelabs.rcs.service.api;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.gsma.joyn.Build;
import org.gsma.joyn.IJoynServiceRegistrationListener;
import org.gsma.joyn.chat.ChatIntent;
import org.gsma.joyn.ft.FileTransfer;
import org.gsma.joyn.ft.FileTransferIntent;
import org.gsma.joyn.ft.FileTransferLog;
import org.gsma.joyn.ft.FileTransferServiceConfiguration;
import org.gsma.joyn.ft.IFileTransfer;
import org.gsma.joyn.ft.IFileTransferListener;
import org.gsma.joyn.ft.IFileTransferService;
import org.gsma.joyn.ft.INewFileTransferListener;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteCallbackList;
import com.orangelabs.rcs.core.Core;
import com.orangelabs.rcs.core.content.ContentManager;
import com.orangelabs.rcs.core.content.MmContent;
import com.orangelabs.rcs.core.ims.ImsModule;
import com.orangelabs.rcs.core.ims.network.sip.FeatureTags;
import com.orangelabs.rcs.core.ims.network.sip.SipUtils;
import com.orangelabs.rcs.core.ims.protocol.sdp.MediaAttribute;
import com.orangelabs.rcs.core.ims.protocol.sdp.MediaDescription;
import com.orangelabs.rcs.core.ims.protocol.sdp.SdpParser;
import com.orangelabs.rcs.core.ims.service.im.InstantMessagingService;
import com.orangelabs.rcs.core.ims.service.im.chat.ChatSession;
import com.orangelabs.rcs.core.ims.service.im.chat.ChatUtils;
import com.orangelabs.rcs.core.ims.service.im.chat.GroupChatSession;
import com.orangelabs.rcs.core.ims.service.im.chat.imdn.ImdnDocument;
import com.orangelabs.rcs.core.ims.service.im.filetransfer.FileSharingSession;
import com.orangelabs.rcs.core.ims.service.im.filetransfer.OriginatingExtendedFileSharingSession;
import com.orangelabs.rcs.core.ims.service.im.filetransfer.http.HttpFileTransferSession;
import com.orangelabs.rcs.platform.AndroidFactory;
import com.orangelabs.rcs.platform.file.FileDescription;
import com.orangelabs.rcs.platform.file.FileFactory;
import com.orangelabs.rcs.provider.messaging.FileTransferData;
import com.orangelabs.rcs.provider.messaging.RichMessagingHistory;
import com.orangelabs.rcs.provider.settings.RcsSettings;
import com.orangelabs.rcs.utils.DateUtils;
import com.orangelabs.rcs.utils.PhoneUtils;
import com.orangelabs.rcs.utils.logger.Logger;
import com.orangelabs.rcs.service.LauncherUtils;
import com.orangelabs.rcs.core.ims.service.im.filetransfer.TerminatingGroupFileSharingSession;
/**
* File transfer service implementation
*
* @author Jean-Marc AUFFRET
*/
public class FileTransferServiceImpl extends IFileTransferService.Stub {
/**
* List of service event listeners
*/
private RemoteCallbackList<IJoynServiceRegistrationListener> serviceListeners =
new RemoteCallbackList<IJoynServiceRegistrationListener>();
/**
* List of file transfer sessions
*/
private static Hashtable<String, IFileTransfer> ftSessions =
new Hashtable<String, IFileTransfer>();
/**
* List of file transfer invitation listeners
*/
private RemoteCallbackList<INewFileTransferListener> listeners =
new RemoteCallbackList<INewFileTransferListener>();
/**
* The logger
*/
private static Logger logger = Logger.getLogger(FileTransferServiceImpl.class.getName());
/**
* Lock used for synchronization
*/
private Object lock = new Object();
public static ArrayList<PauseResumeFileObject> mFileTransferPauseResumeData =
new ArrayList<PauseResumeFileObject>();
/**
* Constructor
*/
public FileTransferServiceImpl() {
if (logger.isActivated()) {
logger.info("File transfer service API is loaded");
}
}
/**
* Close API
*/
public void close() {
// Clear list of sessions
ftSessions.clear();
if (logger.isActivated()) {
logger.info("File transfer service API is closed");
}
}
/**
* Add a file transfer session in the list
*
* @param session File transfer session
*/
protected static void addFileTransferSession(FileTransferImpl session) {
if (logger.isActivated()) {
logger.debug("FTS Add a file transfer session in the list (size="
+ ftSessions.size() + ")" + " Id: " + session.getTransferId());
}
ftSessions.put(session.getTransferId(), session);
}
/**
* Remove a file transfer session from the list
*
* @param sessionId Session ID
*/
protected static void removeFileTransferSession(String sessionId) {
if (logger.isActivated()) {
logger.debug("FTS Remove a file transfer session from the list (size="
+ ftSessions.size() + ")" + " Id: " + sessionId);
}
ftSessions.remove(sessionId);
}
/**
* Returns true if the service is registered to the platform, else returns false
*
* @return Returns true if registered else returns false
*/
public boolean isServiceRegistered() {
return ServerApiUtils.isImsConnected();
}
/**
* Registers a listener on service registration events
*
* @param listener Service registration listener
*/
public void addServiceRegistrationListener(IJoynServiceRegistrationListener listener) {
synchronized (lock) {
if (logger.isActivated()) {
logger.info("FTS Add a service listener");
}
serviceListeners.register(listener);
}
}
/**
* Unregisters a listener on service registration events
*
* @param listener Service registration listener
*/
public void removeServiceRegistrationListener(IJoynServiceRegistrationListener listener) {
synchronized (lock) {
if (logger.isActivated()) {
logger.info("FTS Remove a service listener");
}
serviceListeners.unregister(listener);
}
}
/**
* Receive registration event
*
* @param state Registration state
*/
public void notifyRegistrationEvent(boolean state) {
if (logger.isActivated()) {
logger.info("FTS notifyRegistrationEvent State: " + state);
}
// Notify listeners
synchronized (lock) {
final int N = serviceListeners.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
if (state) {
serviceListeners.getBroadcastItem(i).onServiceRegistered();
} else {
serviceListeners.getBroadcastItem(i).onServiceUnregistered();
}
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Can't notify listener", e);
}
}
}
serviceListeners.finishBroadcast();
}
}
/**
* Receive a new file transfer invitation
*
* @param session File transfer session
* @param isGroup is group file transfer
*/
public void receiveHttpFileTransferInvitation(String remote, FileSharingSession session,
boolean isGroup) {
if (logger.isActivated()) {
logger.info("FTS Receive httpfile transfer invitation from " + remote + " isGroup "
+ isGroup);
}
String chatId = null;
int timeLen = session.getTimeLen();
if (session instanceof HttpFileTransferSession) {
chatId = ((HttpFileTransferSession) session).getContributionID();
if (logger.isActivated()) {
logger.info("FTS Receive HTTP file transfer invitation chatid: " + chatId);
}
} else if (isGroup) {
chatId = ((TerminatingGroupFileSharingSession) session).getGroupChatSession()
.getContributionID();
if (logger.isActivated()) {
logger.info("FTS Receive group MSRP file transfer invitation chatid: " + chatId);
}
}
// Extract number from contact
String number = remote;
if (isGroup) {
RichMessagingHistory.getInstance().addIncomingGroupFileTransfer(chatId, number,
session.getSessionID(), session.getContent());
} else {
// Update rich messaging history
RichMessagingHistory.getInstance().addFileTransfer(
number, session.getSessionID(),
FileTransfer.Direction.INCOMING, session.getContent());
}
RichMessagingHistory.getInstance().updateFileIcon(
session.getSessionID(), session.getThumbUrl());
if (RcsSettings.getInstance().isCPMSupported()) {
if (!(RichMessagingHistory.getInstance().getCoversationID(
session.getRemoteContact(), 1).equals(session.getConversationID()))) {
if (session.getConversationID() != null) {
if (logger.isActivated()) {
logger.info("FTS receiveHttpFileTransferInvitation OldId: "
+ RichMessagingHistory.getInstance().getCoversationID(
session.getRemoteContact(), 1) + " NewId: "
+ session.getConversationID());
}
RichMessagingHistory.getInstance().UpdateCoversationID(
session.getRemoteContact(), session.getConversationID(), 1);
} else {
if (logger.isActivated()) {
logger.info("FTS receiveHttpFileTransferInvitation"
+ " conversation id is null");
}
}
}
}
// Add session in the list
FileTransferImpl sessionApi = new FileTransferImpl(session);
FileTransferServiceImpl.addFileTransferSession(sessionApi);
// Broadcast intent related to the received invitation
Intent intent = new Intent(FileTransferIntent.ACTION_NEW_INVITATION);
intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
intent.putExtra(FileTransferIntent.EXTRA_CONTACT, number);
intent.putExtra(FileTransferIntent.EXTRA_DISPLAY_NAME, session.getRemoteDisplayName());
intent.putExtra(FileTransferIntent.EXTRA_TRANSFER_ID, session.getSessionID());
intent.putExtra(FileTransferIntent.EXTRA_FILENAME, session.getContent().getName());
intent.putExtra(FileTransferIntent.EXTRA_FILESIZE, session.getContent().getSize());
intent.putExtra(FileTransferIntent.EXTRA_FILETYPE, session.getContent().getEncoding());
intent.putExtra(FileTransferIntent.TIME_LEN, session.getTimeLen());
intent.putExtra(FileTransferIntent.GEOLOC_FILE, session.isGeoLocFile());
/** M: ftAutAccept @{ */
intent.putExtra("autoAccept", session.shouldAutoAccept());
/** @} */
String chatSessionId = null;
if (session instanceof HttpFileTransferSession) {
intent.putExtra("chatSessionId", ((HttpFileTransferSession)session).getChatSessionID());
if (isGroup) {
intent.putExtra("chatId", chatId);
}
intent.putExtra("isGroupTransfer", isGroup);
} else if (isGroup) {
chatSessionId = ((TerminatingGroupFileSharingSession) session).getGroupChatSession()
.getSessionID();
if (logger.isActivated()) {
logger.info("FTS Receive file transfer invitation: " + "Chatsessionid: "
+ chatSessionId);
}
intent.putExtra("chatSessionId", chatSessionId);
intent.putExtra("chatId", chatId);
intent.putExtra("isGroupTransfer", isGroup);
}
AndroidFactory.getApplicationContext().sendBroadcast(intent);
// Notify file transfer invitation listeners
synchronized (lock) {
final int N = listeners.beginBroadcast();
if (logger.isActivated()) {
logger.info("FTS Receive HTTP file transfer invitation N: " + N);
}
for (int i = 0; i < N; i++) {
try {
listeners.getBroadcastItem(i).onNewFileTransfer(session.getSessionID());
listeners.getBroadcastItem(i).onNewFileTransferReceived(
session.getSessionID(),
session.shouldAutoAccept(),
isGroup, chatSessionId, chatId, timeLen);
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Can't notify listener", e);
}
}
}
listeners.finishBroadcast();
}
}
/**
* Receive a new file transfer invitation
*
* @param session File transfer session
* @param isGroup is group file transfer
*/
public void receiveFileTransferInvitation(FileSharingSession session, boolean isGroup) {
if (logger.isActivated()) {
logger.info("Receive file transfer invitation from " + session.getRemoteContact()
+ " Timelen " + session.getTimeLen());
}
String chatId = null;
boolean isBurn = false;
isBurn = session.isBurnMessage();
boolean isPublicAccountFile = session.isPublicChatFile();
int timeLen = session.getTimeLen();
if (session instanceof HttpFileTransferSession) {
chatId = ((HttpFileTransferSession) session).getContributionID();
if (logger.isActivated()) {
logger.info("Receive HTTP file transfer invitation chatid: " + chatId);
}
} else if (isGroup) {
GroupChatSession parentSession =
((TerminatingGroupFileSharingSession) session).getGroupChatSession();
if (parentSession != null) {
chatId = parentSession.getContributionID();
} else {
String rejoinId = session.getDialogPath().getTarget();
chatId = RichMessagingHistory.getInstance().getChatIdbyRejoinId(rejoinId);
}
if (logger.isActivated()) {
logger.info("Receive group MSRP file transfer invitation chatid: " + chatId);
}
} else {
chatId = session.getRemoteContact();
if (logger.isActivated()) {
logger.info("Receive O2O MSRP file transfer invitation chatid: " + chatId);
}
}
String number;
int sessionType = FileTransferLog.Type.CHAT;
if (session.isPublicChatFile()) {
number = session.getRemoteContact();
sessionType = FileTransferLog.Type.PUBLIC;
} else {
if (isBurn)
sessionType = FileTransferLog.Type.BURN;
number = PhoneUtils.extractNumberFromUri(session.getRemoteContact());
}
RichMessagingHistory.getInstance().addExtendedFileTransfer(
chatId,
number,
session.getSessionID(),
FileTransfer.Direction.INCOMING,
sessionType,
session.getContent());
RichMessagingHistory.getInstance().updateFileTransferChatId(
session.getSessionID(), chatId, session.getMessageId());
if (session.getTimeLen() > 0) {
RichMessagingHistory.getInstance().updateFileTransferDuration(
session.getSessionID(), session.getTimeLen());
}
RichMessagingHistory.getInstance().updateFileIcon(
session.getSessionID(), session.getThumbUrl());
if (RcsSettings.getInstance().supportOP01()) {
String remoteSdp = session.getDialogPath().getInvite().getSdpContent();
SdpParser parser = new SdpParser(remoteSdp.getBytes());
Vector<MediaDescription> media = parser.getMediaDescriptions();
MediaDescription mediaDescription = media.elementAt(0);
MediaAttribute attrftid = mediaDescription.getMediaAttribute("file-transfer-id");
if (attrftid != null) {
RichMessagingHistory.getInstance().updateFileId(session.getSessionID(),
attrftid.getValue());
}
if (logger.isActivated()) {
logger.debug("file-transfer-id: " + attrftid.getValue());
}
}
try {
if (RcsSettings.getInstance().isCPMSupported() && isGroup) {
if (!(RichMessagingHistory.getInstance()
.getCoversationID(session.getRemoteContact(), 1).equals(session
.getConversationID()))) {
if (session.getConversationID() != null) {
if (logger.isActivated()) {
logger.info("FTS receiveFileTransferInvitation OldId: "
+ RichMessagingHistory.getInstance().getCoversationID(
session.getRemoteContact(), 1) + " NewId: "
+ session.getConversationID());
}
RichMessagingHistory.getInstance().UpdateCoversationID(
session.getRemoteContact(), session.getConversationID(), 1);
} else {
if (logger.isActivated()) {
logger.info("FTS receiveFileTransferInvitation Conversation Id is null");
}
}
}
}
} catch(Exception e){
e.printStackTrace();
}
// Add session in the list
FileTransferImpl sessionApi = new FileTransferImpl(session);
FileTransferServiceImpl.addFileTransferSession(sessionApi);
// addFileTransferPauseResumeData(
// session.getSessionID(),session.getContent().getUrl(),session.getContent().getSize(),0,
// session.getRemoteContact(),session.getHashselector());
// Broadcast intent related to the received invitation
Intent intent = new Intent(FileTransferIntent.ACTION_NEW_INVITATION);
intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
intent.putExtra(FileTransferIntent.EXTRA_CONTACT, number);
intent.putExtra(FileTransferIntent.EXTRA_DISPLAY_NAME, session.getRemoteDisplayName());
intent.putExtra(FileTransferIntent.EXTRA_TRANSFER_ID, session.getSessionID());
intent.putExtra(FileTransferIntent.EXTRA_FILENAME, session.getContent().getName());
intent.putExtra(FileTransferIntent.EXTRA_FILESIZE, session.getContent().getSize());
intent.putExtra(FileTransferIntent.EXTRA_FILETYPE, session.getContent().getEncoding());
intent.putExtra(FileTransferIntent.TIME_LEN, session.getTimeLen());
intent.putExtra(FileTransferIntent.GEOLOC_FILE, session.isGeoLocFile());
if (isBurn)
intent.putExtra(FileTransferIntent.EXTRA_TRANSFERTYPE, FileTransfer.Type.BURNED);
else
if (isPublicAccountFile)
intent.putExtra(FileTransferIntent.EXTRA_TRANSFERTYPE, FileTransfer.Type.PUBACCOUNT);
else
intent.putExtra(FileTransferIntent.EXTRA_TRANSFERTYPE, FileTransfer.Type.NORMAL);
String chatSessionId = null;
/** M: ftAutAccept @{ */
intent.putExtra("autoAccept", session.shouldAutoAccept());
/** @} */
if (session instanceof HttpFileTransferSession) {
chatSessionId = ((HttpFileTransferSession) session).getChatSessionID();
intent.putExtra("chatSessionId", chatSessionId);
if (isGroup) {
intent.putExtra("chatId", chatId);
}
intent.putExtra("isGroupTransfer", isGroup);
} else if (isGroup) {
//not happened now.
GroupChatSession parentSession =
((TerminatingGroupFileSharingSession) session).getGroupChatSession();
if (parentSession != null) {
chatSessionId = parentSession.getContributionID();
} else {
String rejoinId = session.getDialogPath().getTarget();
chatSessionId = RichMessagingHistory.getInstance().getChatIdbyRejoinId(rejoinId);
}
if (logger.isActivated()) {
logger.info("FTS Receive file transfer invitation: " + "Chatsessionid: "
+ chatSessionId);
}
intent.putExtra("chatSessionId", chatSessionId);
intent.putExtra("chatId", chatId);
intent.putExtra("isGroupTransfer", isGroup);
} else {
if (logger.isActivated()) {
logger.info("FTS Receive file transfer invitation: It is not group");
}
}
AndroidFactory.getApplicationContext().sendBroadcast(intent);
// Notify file transfer invitation listeners
synchronized (lock) {
final int N = listeners.beginBroadcast();
if (logger.isActivated()) {
logger.info("FTS receiveFileTransferInvitation N: " + N);
}
for (int i = 0; i < N; i++) {
try {
if (isPublicAccountFile) {
listeners.getBroadcastItem(i).onNewPublicAccountChatFile(
session.getSessionID(), session.shouldAutoAccept(), isGroup,
chatSessionId, chatId);
} else {
if (isBurn) {
listeners.getBroadcastItem(i).onNewBurnFileTransfer(
session.getSessionID(), isGroup, chatSessionId, chatId);
} else {
listeners.getBroadcastItem(i).onNewFileTransfer(session.getSessionID());
listeners.getBroadcastItem(i).onNewFileTransferReceived(
session.getSessionID(),
session.shouldAutoAccept(),
isGroup, chatSessionId, chatId, timeLen);
}
}
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Can't notify listener", e);
}
}
}
listeners.finishBroadcast();
}
}
/**
* Receive a new file transfer invitation
*
* @param session File transfer session
* @param isGroup is group file transfer
*/
public void receiveResumeFileTransferInvitation(
FileSharingSession session, boolean isGroup, String fileTransferId) {
if (logger.isActivated()) {
logger.info("Resume file transfer invitation from " + session.getRemoteContact());
}
String chatId = null;
if (session instanceof HttpFileTransferSession) {
chatId = ((HttpFileTransferSession) session).getContributionID();
if (logger.isActivated()) {
logger.info("Receive Resume HTTP file transfer invitation chatid: " + chatId);
}
} else if (isGroup) {
chatId = ((TerminatingGroupFileSharingSession) session).getGroupChatSession()
.getContributionID();
if (logger.isActivated()) {
logger.info("Receive Resume group MSRP file transfer invitation chatid: "
+ chatId);
}
}
// Extract number from contact
String number = PhoneUtils.extractNumberFromUri(session.getRemoteContact());
// Update rich messaging history -- Deepak
// RichMessagingHistory.getInstance().addFileTransfer(number,
// session.getSessionID(), FileTransfer.Direction.INCOMING, session.getContent());
// Add session in the list
FileTransferImpl sessionApi = new FileTransferImpl(session);
FileTransferServiceImpl.addFileTransferSession(sessionApi);
// Broadcast intent related to the received invitation
Intent intent = new Intent(FileTransferIntent.ACTION_RESUME_FILE);
intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
intent.putExtra(FileTransferIntent.EXTRA_CONTACT, number);
intent.putExtra(FileTransferIntent.EXTRA_DISPLAY_NAME, session.getRemoteDisplayName());
intent.putExtra(FileTransferIntent.EXTRA_TRANSFER_ID, session.getSessionID());
intent.putExtra(FileTransferIntent.RESUMED_TRANSFER_ID, fileTransferId);
intent.putExtra(FileTransferIntent.EXTRA_FILENAME, session.getContent().getName());
intent.putExtra(FileTransferIntent.EXTRA_FILESIZE, session.getContent().getSize());
intent.putExtra(FileTransferIntent.EXTRA_FILETYPE, session.getContent().getEncoding());
/** @} */
if (session instanceof HttpFileTransferSession) {
intent.putExtra(
"chatSessionId", ((HttpFileTransferSession) session).getChatSessionID());
if (isGroup) {
intent.putExtra("chatId", chatId);
}
intent.putExtra("isGroupTransfer", isGroup);
} else if (isGroup) {
String chatSessionId = ((TerminatingGroupFileSharingSession) session)
.getGroupChatSession().getSessionID();
if (logger.isActivated()) {
logger.info("Resume file transfer invitation: " + "Chatsessionid: "
+ chatSessionId);
}
intent.putExtra("chatSessionId", chatSessionId);
intent.putExtra("chatId", chatId);
intent.putExtra("isGroupTransfer", isGroup);
}
AndroidFactory.getApplicationContext().sendBroadcast(intent);
// Notify file transfer invitation listeners about resume File
/*
* synchronized(lock) { final int N = listeners.beginBroadcast(); for (int i=0; i
* < N; i++) { try {
* listeners.getBroadcastItem(i).onNewFileTransfer(session.getSessionID()); }
* catch(Exception e) { if (logger.isActivated()) {
* logger.error("Can't notify listener", e); } } } listeners.finishBroadcast(); }
*/
}
/**
* Receive a new HTTP file transfer invitation outside of an existing chat session
*
* @param session File transfer session
*/
public void receiveFileTransferInvitation(
FileSharingSession session, ChatSession chatSession) {
if (logger.isActivated()) {
logger.info("FTS Receive file transfer invitation from1 "
+ session.getRemoteContact());
}
// Update rich messaging history
if (chatSession.isGroupChat()) {
// RichMessagingHistory.getInstance().updateFileTransferChatId(
// chatSession.getFirstMessage().getMessageId(),
// chatSession.getContributionID());
}
// Add session in the list
FileTransferImpl sessionApi = new FileTransferImpl(session);
addFileTransferSession(sessionApi);
// Display invitation
receiveFileTransferInvitation(session, chatSession.isGroupChat());
// Display invitation
/*
* TODO receiveFileTransferInvitation(session, chatSession.isGroupChat());
*
* // Update rich messaging history
* RichMessaging.getInstance().addIncomingChatSessionByFtHttp(chatSession);
*
* // Add session in the list ImSession sessionApi = new ImSession(chatSession);
* MessagingApiService.addChatSession(sessionApi);
*/
}
public static PauseResumeFileObject getPauseInfo(String transferId) {
PauseResumeFileObject object = null;
for (int j = 0; j < mFileTransferPauseResumeData.size(); j++) {
object = FileTransferServiceImpl.mFileTransferPauseResumeData.get(j);
if (object.mFileTransferId.equals(transferId)) {
if (logger.isActivated()) {
logger.info("getPauseInfo, FileTransfer Id & currentBytesTransferred"
+ object.mFileTransferId);
}
return object;
}
}
if (logger.isActivated()) {
logger.info("getPauseInfo , Check databse");
}
object = RichMessagingHistory.getInstance().getPauseInfo(transferId);
if (object != null && object.mFileTransferId != null) {
mFileTransferPauseResumeData.add(object);
}
if (logger.isActivated()) {
logger.info("getPauseInfo , After check databse" + object);
}
return object;
}
public static PauseResumeFileObject getHashPauseInfo(String hashSelector) {
try {
if (logger.isActivated()) {
logger.info("getHashPauseInfo, entry hashSelector " + hashSelector);
}
for (int j = 0; j < mFileTransferPauseResumeData.size(); j++) {
PauseResumeFileObject object = FileTransferServiceImpl.mFileTransferPauseResumeData
.get(j);
if (object.hashSelector.equals(hashSelector)) {
if (logger.isActivated()) {
logger.info("getPauseInfo, hashSelector Id & currentBytesTransferred"
+ object.hashSelector);
}
return object;
}
}
if (logger.isActivated()) {
logger.info("getPauseInfo , Return null");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Returns the configuration of the file transfer service
*
* @return Configuration
*/
public FileTransferServiceConfiguration getConfiguration() {
return new FileTransferServiceConfiguration(
RcsSettings.getInstance().getWarningMaxFileTransferSize(),
RcsSettings.getInstance().getMaxFileTransferSize(),
RcsSettings.getInstance().isFileTransferAutoAccepted(),
RcsSettings.getInstance().isFileTransferThumbnailSupported(),
RcsSettings.getInstance().getMaxFileIconSize(),
RcsSettings.getInstance().getMaxFileTransferSessions());
}
public static void addFileTransferPauseResumeData(
String fileTransferId,
String path,
long fileSize,
String contact,
String hash,
String mimeType,
int transferType) {
if (logger.isActivated()) {
logger.info("addFileTransferPauseResumeData fileTransferId " + fileTransferId
+ " path : " + path + "fileSize : " + fileSize
+ "contact :" + contact + "hash:" + hash);
}
PauseResumeFileObject filePauseDdata = new PauseResumeFileObject();
filePauseDdata.bytesTransferrred = 0;
filePauseDdata.mFileTransferId = fileTransferId;
filePauseDdata.mPath = path;
filePauseDdata.mSize = fileSize;
filePauseDdata.mContact = contact;
filePauseDdata.hashSelector = hash;
filePauseDdata.mMimeType = mimeType;
filePauseDdata.mTransferType = transferType;
mFileTransferPauseResumeData.add(filePauseDdata);
try {
RichMessagingHistory.getInstance().updateFileTransferProgressCode(
fileTransferId, 0, fileSize, path, contact, hash);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public IFileTransfer resumeGroupFileTransfer(String chatId, String fileTranferId,
IFileTransferListener listener) throws ServerApiException {
if (logger.isActivated()) {
logger.info("resumeGroupFile file " + fileTranferId);
}
PauseResumeFileObject pauseResumeObject = getPauseInfo(fileTranferId);
if (pauseResumeObject == null) {
if (logger.isActivated()) {
logger.info("resumeGroupFile return null ");
}
return null;
}
String filename = pauseResumeObject.mPath;
if (logger.isActivated()) {
logger.info("resumeGroupFile file contact:" + "filename:" + filename);
}
// Test IMS connection
ServerApiUtils.testIms();
// Query Db whether FT is incoming/outgoing //Deepak
try {
// Initiate the session
FileDescription desc = FileFactory.getFactory().getFileDescription(filename);
MmContent content = ContentManager.createMmContentFromUrl(filename, desc.getSize());
FileSharingSession session = null;
List fileParticipants = RichMessagingHistory.getInstance().getFileTransferContacts(
fileTranferId);
if (logger.isActivated() && fileParticipants != null) {
logger.info("resumeGroupFile file participants:" + fileParticipants + " size:"
+ fileParticipants.size());
}
session = Core.getInstance().getImService().initiateGroupFileTransferSession(
fileParticipants, content, null, chatId, null);
final FileSharingSession resumedSession = session;
resumedSession.fileTransferPaused();
resumedSession.setOldFileTransferId(fileTranferId);
resumedSession.setSessionId(fileTranferId);
String direction = RichMessagingHistory.getInstance().getFtDirection(fileTranferId);
if (logger.isActivated()) {
logger.info("resumeGroupFile file direction:" + direction);
}
if (direction.equals("1")) {
resumedSession.setReceiveOnly(false);
} else {
resumedSession.setReceiveOnly(true);
}
// Add session listener
FileTransferImpl sessionApi = new FileTransferImpl(resumedSession);
sessionApi.addEventListener(listener);
if (pauseResumeObject != null && direction.equals("1")) {
if (logger.isActivated()) {
logger.info("resumeGroupFile file pauseResumeObject:"
+ pauseResumeObject + " & new Id is"
+ sessionApi.getTransferId());
}
pauseResumeObject.mFileTransferId = sessionApi.getTransferId();
}
// Update Filetransfer Id rich messaging history
if (direction.equals("1"))
RichMessagingHistory.getInstance().updateFileTransferId(fileTranferId,
sessionApi.getTransferId());
// Start the session
Thread t = new Thread() {
public void run() {
resumedSession.startSession();
}
};
t.start();
// Add session in the list
addFileTransferSession(sessionApi);
return sessionApi;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Transfers a file to a contact. The parameter file contains the complete filename
* including the path to be transferred. The parameter contact supports the following
* formats: MSISDN in national or international format, SIP address, SIP-URI or
* Tel-URI. If the format of the contact is not supported an exception is thrown.
*
* @param contact Contact
* @param filename Filename to transfer
* @param fileicon Filename of the file icon associated to the file to be transfered
* @param listenet File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer resumeFileTransfer(
String fileTranferId, IFileTransferListener listener) throws ServerApiException {
if (logger.isActivated()) {
logger.info("resumeFile file " + fileTranferId);
}
RichMessagingHistory rmHistory = RichMessagingHistory.getInstance();
InstantMessagingService imService = Core.getInstance().getImService();
PauseResumeFileObject pauseResumeObject = getPauseInfo(fileTranferId);
if (pauseResumeObject == null) {
if (logger.isActivated()) {
logger.info("resumeFile return null ");
}
return null;
}
String contact = pauseResumeObject.mContact;
String filename = pauseResumeObject.mPath;
String chatId = rmHistory.getFileTransferChatId(fileTranferId);
if (logger.isActivated()) {
logger.info("resumeFile file contact:" + contact + " filename:" + filename);
}
// Test IMS connection
ServerApiUtils.testIms();
// Query Db whether FT is incoming/outgoing //Deepak
try {
// Initiate the session
final FileSharingSession resumedSession;
FileDescription desc = FileFactory.getFactory().getFileDescription(filename);
MmContent content = ContentManager.createMmContentFromUrl(filename, desc.getSize());
List<String> contacts = PhoneUtils.generateContactsList(pauseResumeObject.mContact);
if (pauseResumeObject.mContact.equals(chatId)) {
// not file transfer in group chat
resumedSession = imService.initiateExtendedTransferSession(
null, contacts, content, null, 0, pauseResumeObject.mTransferType);
} else {
resumedSession = imService.initiateExtendedTransferSession(
chatId, contacts, content, null, 0, pauseResumeObject.mTransferType);
}
resumedSession.fileTransferPaused();
resumedSession.setOldFileTransferId(fileTranferId);
resumedSession.setSessionId(fileTranferId);
String direction = rmHistory.getFtDirection(fileTranferId);
if (logger.isActivated()) {
logger.info("resumeFile file direction:" + direction + "contact:" + contact);
}
if (direction.equals("1")) {
resumedSession.setReceiveOnly(false);
} else {
resumedSession.setReceiveOnly(true);
}
((OriginatingExtendedFileSharingSession)resumedSession).setPauseInfo(pauseResumeObject);
// Add session listener
FileTransferImpl sessionApi = new FileTransferImpl(resumedSession);
sessionApi.addEventListener(listener);
// Start the session
Thread t = new Thread() {
public void run() {
resumedSession.startSession();
}
};
t.start();
// Add session in the list
addFileTransferSession(sessionApi);
return sessionApi;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Transfers a file to a contact. The parameter file contains the complete filename
* including the path to be transferred. The parameter contact supports the following
* formats: MSISDN in national or international format, SIP address, SIP-URI or
* Tel-URI. If the format of the contact is not supported an exception is thrown.
*
* @param contact Contact
* @param filename Filename to transfer
* @param fileicon Filename of the file icon associated to the file to be transfered
* @param listenet File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer transferFile(
String contact,
String filename,
String fileicon,
IFileTransferListener listener) throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Transfer file " + filename + " to " + contact);
}
// Test IMS connection
ServerApiUtils.testIms();
try {
// Initiate the session
FileDescription desc = FileFactory.getFactory().getFileDescription(filename);
if (logger.isActivated()) {
logger.info("FTS Transfer file " + filename + " size " + desc.getSize());
}
MmContent content = ContentManager.createMmContentFromUrl(filename, desc.getSize());
final FileSharingSession session = Core.getInstance().getImService()
.initiateFileTransferSession(contact, content, fileicon, null, null); // TODO
if (content.getEncoding().contains("vnd.gsma.rcspushlocation"))
session.setGeoLocFile();
// Add session listener
FileTransferImpl sessionApi = new FileTransferImpl(session);
sessionApi.addEventListener(listener);
// Update rich messaging history
RichMessagingHistory.getInstance().addFileTransfer(contact, session.getSessionID(),
FileTransfer.Direction.OUTGOING, session.getContent());
if (session.getTimeLen() > 0) {
RichMessagingHistory.getInstance().updateFileTransferDuration(
session.getSessionID(), session.getTimeLen());
}
addFileTransferPauseResumeData(
session.getSessionID(),
filename,
session.getContent().getSize(),
contact,
"",
content.getEncoding(),
FileTransferLog.Type.CHAT);
// Start the session
Thread t = new Thread() {
public void run() {
session.startSession();
}
};
t.start();
// Add session in the list
addFileTransferSession(sessionApi);
return sessionApi;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Transfer a file to a group of contacts outside of an existing group chat
*
* @param contacts List of contact
* @param file File to be transfered
* @param thumbnail Thumbnail option
* @return File transfer session
* @throws ServerApiException
*/
public IFileTransfer transferFileToGroup(
String chatId, List<String> contacts, String filename,
String fileicon, int timeLen, IFileTransferListener listener)
throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Transfer file " + filename + " to " + contacts);
logger.info("FTS Transfer file CHATID: " + chatId);
}
// Test IMS connection
ServerApiUtils.testIms();
try {
// Initiate the session
FileDescription desc = FileFactory.getFactory().getFileDescription(filename);
MmContent content = ContentManager.createMmContentFromUrl(filename, desc.getSize());
final FileSharingSession session = Core.getInstance().getImService()
.initiateGroupFileTransferSession(contacts, content, fileicon, chatId, null);
if (timeLen > 0) {
session.setTimeLen(timeLen);
}
if (content.getEncoding().contains("vnd.gsma.rcspushlocation"))
session.setGeoLocFile();
// Add session in the list
FileTransferImpl sessionApi = new FileTransferImpl(session);
sessionApi.addEventListener(listener);
logger.info("ABC Transfer file ContribitionID: " + session.getContributionID());
// Update rich messaging history
RichMessagingHistory.getInstance().addOutgoingGroupFileTransfer(
chatId,
session.getSessionID(),
session.getContent(),
null,
session.getRemoteContact());
RichMessagingHistory.getInstance().updateFileTransferDuration(
session.getSessionID(), timeLen);
addFileTransferPauseResumeData(
session.getSessionID(),
filename,
session.getContent().getSize(),
"",
"",
content.getEncoding(),
FileTransferLog.Type.CHAT);
// Start the session
Thread t = new Thread() {
public void run() {
session.startSession();
}
};
t.start();
addFileTransferSession(sessionApi);
return sessionApi;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Transfers a file to a contact. The parameter file contains the complete filename
* including the path to be transferred. The parameter contact supports the following
* formats: MSISDN in national or international format, SIP address, SIP-URI or
* Tel-URI. If the format of the contact is not supported an exception is thrown.
*
* @param contact Contact
* @param filename Filename to transfer
* @param fileicon Filename of the file icon associated to the file to be transfered
* @param duration Video media file duration
* @param type Specified transfer file
* @param listener File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer transferFileEx(
String contact,
String filename,
String fileicon,
int duration,
String type,
IFileTransferListener listener) throws ServerApiException {
List<String> contacts = PhoneUtils.generateContactsList(contact);
return transferFileEx(null, contacts, filename, fileicon, duration, type, listener);
}
/**
* Transfers a file to multiple contacts. The parameter file contains the complete filename
* including the path to be transferred. The parameter contact supports the following
* formats: MSISDN in national or international format, SIP address, SIP-URI or
* Tel-URI. If the format of the contact is not supported an exception is thrown.
*
* @param contacts Multiple contacts list
* @param filename Filename to transfer
* @param fileicon Filename of the file icon associated to the file to be transfered
* @param duration Video media file duration
* @param type Specified transfer file
* @param listener File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer transferFileToMultiple(
List<String> contacts,
String filename,
String fileicon,
int duration,
String type,
IFileTransferListener listener) throws ServerApiException {
return transferFileEx(null, contacts, filename, fileicon, duration, type, listener);
}
/**
* Transfers a file to group chat. The parameter file contains the complete filename
* including the path to be transferred. The parameter contact supports the following
* formats: MSISDN in national or international format, SIP address, SIP-URI or
* Tel-URI. If the format of the contact is not supported an exception is thrown.
*
* @param chatId Identifier of group chat
* @param contacts Contact
* @param filename Filename to transfer
* @param fileicon Filename of the file icon associated to the file to be transfered
* @param duration Video media file duration
* @param type Specified transfer file
* @param listener File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer transferFileToGroupEx(
String chatId,
String filename,
String fileicon,
int duration,
String type,
IFileTransferListener listener) throws ServerApiException {
return transferFileEx(chatId, null, filename, fileicon, duration, type, listener);
}
/**
* Prosecute file to specific service number.
*
* @param contacts Contact
* @param transferId file identifier
* @param listener File transfer event listener
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer prosecuteFile(
String contact,
String transferId,
IFileTransferListener listener) throws ServerApiException {
RichMessagingHistory rmHistory = RichMessagingHistory.getInstance();
PauseResumeFileObject info = rmHistory.getPauseInfo(transferId);
String extraContent =
"Spam-From: " + ChatUtils.formatCpimSipUri(info.mContact) + SipUtils.CRLF +
"Spam-To: " + ImsModule.IMS_USER_PROFILE.getPublicUri() + SipUtils.CRLF +
"DateTime: " + DateUtils.encodeDate(rmHistory.getFileTimeStamp(transferId));
List<String> contacts = PhoneUtils.generateContactsList(contact);
return transferFileEx(
null, contacts, info.mPath, extraContent, 0, FileTransfer.Type.PROSECUTE, listener);
}
private IFileTransfer transferFileEx(
String chatId,
List<String> contacts,
String filename,
String fileicon,
int duration,
String type,
IFileTransferListener listener) throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Transfer file " + filename + " to " + contacts + "with Timelen "
+ duration);
}
// Test IMS connection
ServerApiUtils.testIms();
InstantMessagingService imService = Core.getInstance().getImService();
RichMessagingHistory rmHistory = RichMessagingHistory.getInstance();
int sessionType = FileTransferLog.Type.CHAT;
if (type.equals(FileTransfer.Type.PUBACCOUNT)) {
sessionType = FileTransferLog.Type.PUBLIC;
} else
if (type.equals(FileTransfer.Type.BURNED)) {
sessionType = FileTransferLog.Type.BURN;
}
String extraContent = fileicon;
if (type.equals(FileTransfer.Type.PROSECUTE)) {
fileicon = null;
}
try {
// Initiate the session
FileDescription desc = FileFactory.getFactory().getFileDescription(filename);
MmContent content = ContentManager.createMmContentFromUrl(filename, desc.getSize());
final FileSharingSession session = imService.initiateExtendedTransferSession(
chatId, contacts, content, null, duration, sessionType);
String transferId = session.getSessionID();
// Add session listener
FileTransferImpl sessionApi = new FileTransferImpl(session);
sessionApi.addEventListener(listener);
if (content.getEncoding().contains("vnd.gsma.rcspushlocation"))
session.setGeoLocFile();
String contact = PhoneUtils.generateContactsText(contacts);
if (type.equals(FileTransfer.Type.NORMAL)) {
} else
if (type.equals(FileTransfer.Type.BURNED)) {
session.setBurnMessage(true);
OriginatingExtendedFileSharingSession exSession =
(OriginatingExtendedFileSharingSession)session;
List<String> extraTags = new ArrayList<String>();
extraTags.add(FeatureTags.FEATURE_CPM_BURNED_MSG);
exSession.setExtraTags(extraTags);
} else
if (type.equals(FileTransfer.Type.PUBACCOUNT)) {
session.setPublicChatFile(true);
OriginatingExtendedFileSharingSession exSession =
(OriginatingExtendedFileSharingSession)session;
List<String> extraTags = new ArrayList<String>();
extraTags.add(FeatureTags.FEATURE_CMCC_IARI_PUBLIC_ACCOUNT);
exSession.setExtraTags(extraTags);
exSession.setPreferService(FeatureTags.FEATURE_CMCC_URN_PUBLIC_ACCOUNT);
} else
if (type.equals(FileTransfer.Type.PROSECUTE)) {
OriginatingExtendedFileSharingSession exSession =
(OriginatingExtendedFileSharingSession)session;
exSession.setExtraContent(extraContent, "text-plain;charset=UTF8");
}
rmHistory.addExtendedFileTransfer(
chatId,
contact,
transferId,
FileTransfer.Direction.OUTGOING,
sessionType,
content);
// Update rich messaging history
if (duration > 0) {
rmHistory.updateFileTransferDuration(transferId, duration);
}
addFileTransferPauseResumeData(
transferId,
filename,
content.getSize(),
contact,
"",
content.getEncoding(),
sessionType);
// Start the session
Thread t = new Thread() {
public void run() {
session.startSession();
}
};
t.start();
// Add session in the list
addFileTransferSession(sessionApi);
return sessionApi;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Returns the list of file transfers in progress
*
* @return List of file transfer
* @throws ServerApiException
*/
public List<IBinder> getFileTransfers() throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Get file transfer sessions");
}
try {
ArrayList<IBinder> result = new ArrayList<IBinder>(ftSessions.size());
for (Enumeration<IFileTransfer> e = ftSessions.elements(); e.hasMoreElements();) {
IFileTransfer sessionApi = e.nextElement();
result.add(sessionApi.asBinder());
}
return result;
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Unexpected error", e);
}
throw new ServerApiException(e.getMessage());
}
}
/**
* Returns a current file transfer from its unique ID
*
* @return File transfer
* @throws ServerApiException
*/
public IFileTransfer getFileTransfer(String transferId) throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Get file transfer session " + transferId);
}
return ftSessions.get(transferId);
}
/**
* Registers a file transfer invitation listener
*
* @param listener New file transfer listener
* @throws ServerApiException
*/
public void addNewFileTransferListener(INewFileTransferListener listener)
throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Add a file transfer invitation listener");
}
listeners.register(listener);
}
/**
* Unregisters a file transfer invitation listener
*
* @param listener New file transfer listener
* @throws ServerApiException
*/
public void removeNewFileTransferListener(INewFileTransferListener listener)
throws ServerApiException {
if (logger.isActivated()) {
logger.info("FTS Remove a file transfer invitation listener");
}
listeners.unregister(listener);
}
/**
* File Transfer delivery status. In FToHTTP, Delivered status is done just after
* download information are received by the terminating, and Displayed status is done
* when the file is downloaded. In FToMSRP, the two status are directly done just
* after MSRP transfer complete.
*
* @param ftSessionId File transfer session Id
* @param status status of File transfer
*/
public void handleFileDeliveryStatus(String ftSessionId, String status, String contact) {
if (logger.isActivated()) {
logger.info("FTS handleFileDeliveryStatus contact: " + contact + " FtId: "
+ ftSessionId + " Status: " + status);
}
if (status.equalsIgnoreCase(ImdnDocument.DELIVERY_STATUS_DELIVERED)) {
// Update rich messaging history
RichMessagingHistory.getInstance().updateFileTransferStatus(ftSessionId,
FileTransfer.State.DELIVERED);
// Notify File transfer delivery listeners
final int N = listeners.beginBroadcast();
if (logger.isActivated()) {
logger.info("FTS handleFileDeliveryStatus N is: " + N);
}
for (int i = 0; i < N; i++) {
try {
listeners.getBroadcastItem(i).onFileDeliveredReport(ftSessionId, contact);
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Can't notify listener", e);
}
}
}
listeners.finishBroadcast();
if (RcsSettings.getInstance().supportOP01()) {
if (logger.isActivated()) {
logger.info("LMM FT is null");
}
Intent intent = new Intent(FileTransferIntent.ACTION_DELIVERY_STATUS);
intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
intent.putExtra(ChatIntent.EXTRA_CONTACT, contact);
intent.putExtra("msgId", ftSessionId);
intent.putExtra("status", status);
AndroidFactory.getApplicationContext().sendBroadcast(intent);
}
} else if (status.equalsIgnoreCase(ImdnDocument.DELIVERY_STATUS_DISPLAYED)) {
// Update rich messaging history
RichMessagingHistory.getInstance().updateFileTransferStatus(ftSessionId,
FileTransfer.State.DISPLAYED);
// Notify File transfer delivery listeners
final int N = listeners.beginBroadcast();
if (logger.isActivated()) {
logger.info("FTS handleFileDeliveryStatus N: " + N);
}
for (int i = 0; i < N; i++) {
try {
listeners.getBroadcastItem(i).onFileDisplayedReport(ftSessionId, contact);
} catch (Exception e) {
if (logger.isActivated()) {
logger.error("FTS Can't notify listener", e);
}
}
}
listeners.finishBroadcast();
}
}
/**
* Returns the maximum number of file transfer session simultaneously
*
* @return numenr of sessions
*/
public int getMaxFileTransfers() {
return RcsSettings.getInstance().getMaxFileTransferSessions();
}
/**
* Returns service version
*
* @return Version
* @see Build.VERSION_CODES
* @throws ServerApiException
*/
public int getServiceVersion() throws ServerApiException {
return Build.API_VERSION;
}
}
| [
"peishengguo@yydrobot.com"
] | peishengguo@yydrobot.com |
142de997a8a24d26d374aa6f35195ba883728370 | 0242186ce2ae143a4b00e7ab76ef3aab0872a02d | /scb-ui-zk/src/main/java/com/jzaoralek/scb/ui/pages/courseapplication/vm/CourseApplicationUserVM.java | a65acc2f6baad24b43a38d4de053eefb9c2a3b6b | [] | no_license | jzaoralek/Swimming-Club-Bohumin | 0eec16434c2fa0f0f18afbe1b50507bf02f44caf | 0f533cf99b2a1c00c6baaee69eff9318e1f134fe | refs/heads/master | 2023-07-19T19:17:31.822460 | 2023-04-03T18:57:20 | 2023-04-03T18:57:20 | 59,950,553 | 1 | 0 | null | 2023-07-07T21:39:42 | 2016-05-29T15:36:45 | Java | UTF-8 | Java | false | false | 8,912 | java | package com.jzaoralek.scb.ui.pages.courseapplication.vm;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.Init;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.bind.annotation.QueryParam;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import com.jzaoralek.scb.dataservice.domain.Course;
import com.jzaoralek.scb.dataservice.domain.CourseApplication;
import com.jzaoralek.scb.dataservice.domain.CourseLocation;
import com.jzaoralek.scb.dataservice.domain.CourseParticipant;
import com.jzaoralek.scb.dataservice.exception.ScbValidationException;
import com.jzaoralek.scb.dataservice.service.CourseApplicationService;
import com.jzaoralek.scb.dataservice.service.CourseService;
import com.jzaoralek.scb.dataservice.utils.SecurityUtils;
import com.jzaoralek.scb.ui.common.WebConstants;
import com.jzaoralek.scb.ui.common.WebPages;
import com.jzaoralek.scb.ui.common.template.SideMenuComposer.ScbMenuItem;
import com.jzaoralek.scb.ui.common.utils.JasperUtil;
import com.jzaoralek.scb.ui.common.utils.WebUtils;
import com.jzaoralek.scb.ui.common.vm.BaseVM;
import com.jzaoralek.scb.ui.pages.courseparticipant.vm.CourseParticipantListVM;
/**
* VM pro prihhlaseni ucastnika na kurz.
*
*/
public class CourseApplicationUserVM extends BaseVM {
private static final Logger LOG = LoggerFactory.getLogger(CourseParticipantListVM.class);
@WireVariable
private CourseApplicationService courseApplicationService;
@WireVariable
private CourseService courseService;
private CourseParticipant courseParticipant;
private CourseApplication application;
private List<CourseLocation> courseLocationList;
private List<Course> courseListAll;
private List<Course> courseList;
private boolean courseSelectionRequired;
private Set<Course> courseSelected;
private boolean editMode = true;
private boolean securedMode = false;
private CourseLocation courseLocationSelected;
@Init
public void init(@QueryParam(WebConstants.UUID_PARAM) String uuid, @QueryParam(WebConstants.FROM_PAGE_PARAM) String fromPage) {
setMenuSelected(ScbMenuItem.SEZNAM_UCASTNIKU_U);
setReturnPage(fromPage);
if (!StringUtils.hasText(uuid)) {
// na vstupu neni uuid ucastnika
showInvalidRequest();
return;
}
this.courseParticipant = courseService.getCourseParticipantByUuid(UUID.fromString(uuid));
if (this.courseParticipant == null) {
// na zaklade uuid nebyl nalezen zadny ucastnik
showInvalidRequest();
return;
}
this.courseSelectionRequired = configurationService.isCourseSelectionRequired();
if (!this.courseSelectionRequired) {
// vyber kurzu neni povolen
showInvalidRequest();
return;
}
this.application = new CourseApplication();
this.application.fillYearFromTo(configurationService.getCourseApplicationYear());
// seznam mist konani
this.courseLocationList = courseService.getCourseLocationAll();
// seznam vsech active kurzu
this.courseListAll = courseService.getAllActive(this.application.getYearFrom(), this.application.getYearTo(), true);
this.pageHeadline = this.courseParticipant.getContact().getCompleteName() + " - " + Labels.getLabel("txt.ui.loginToCourse");
}
@NotifyChange("courseList")
@Command
public void courseLocationSelectCmd() {
if (this.courseListAll == null || this.courseListAll.isEmpty() || this.courseLocationSelected == null) {
return;
}
if (this.courseList == null) {
this.courseList = new ArrayList<>();
}
this.courseList.clear();
for (Course courseItem : this.courseListAll) {
if (courseItem.getCourseLocation().getUuid().toString().equals(this.courseLocationSelected.getUuid().toString())) {
this.courseList.add(courseItem);
}
}
}
@NotifyChange("*")
@Command
public void submit() {
Course courseSelected = this.courseSelected.iterator().next();
if (courseSelected == null) {
return;
}
// kontrola zda-li jit neni ucastnik zarazen do kurzu
List<CourseParticipant> courseParticipantInCourseList = courseService.getByCourseParticListByCourseUuid(courseSelected.getUuid(), true);
for (CourseParticipant item : courseParticipantInCourseList) {
if (item.getUuid().toString().equals(this.courseParticipant.getUuid().toString())) {
WebUtils.showNotificationWarning(Labels.getLabel("msg.ui.warn.participantAlreadyInCourse", new Object[] {courseSelected.getName()}));
return;
}
}
createNewCourseApplication(courseService.getCourseParticipantByUuid(courseParticipant.getUuid()));
WebUtils.showNotificationInfoAfterRedirect(Labels.getLabel("msg.ui.warn.participantLoggedToCourse", new Object[] {courseParticipant.getContact().getCompleteName(), courseSelected.getName()}));
detail(courseParticipant.getUuid());
}
public String getCourseRowColor(Course course) {
if (course == null) {
return null;
}
if (this.securedMode) {
return "";
}
if (course.isFullOccupancy()) {
return "background: #F0F0F0";
}
return "";
}
private void detail(final UUID uuid) {
if (uuid == null) {
throw new IllegalArgumentException("uuid is null");
}
String targetPage = WebPages.USER_PARTICIPANT_DETAIL.getUrl();
WebPages fromPage = WebPages.USER_PARTICIPANT_LIST;
Executions.sendRedirect(targetPage + "?"+WebConstants.UUID_PARAM+"="+uuid.toString() + "&" + WebConstants.FROM_PAGE_PARAM + "=" + fromPage);
}
private void createNewCourseApplication(CourseParticipant courseParticipant) {
this.application.setCourseParticRepresentative(SecurityUtils.getLoggedUser());
this.application.setCourseParticipant(courseParticipant);
// pokud byl vybran kurz, potreba zkontrolovat zda-li uz neni zaplnen
if (this.courseSelectionRequired && this.courseSelected != null && !this.courseSelected.isEmpty()) {
Course selectedCourseDb = courseService.getByUuid(this.courseSelected.iterator().next().getUuid());
if (selectedCourseDb == null) {
WebUtils.showNotificationWarning(Labels.getLabel("msg.ui.warn.courseIsDeleted", new Object[] {this.courseSelected.iterator().next().getName()}));
// reload seznamu kurzu
this.courseList = courseService.getAll(application.getYearFrom(), application.getYearTo(), true);
this.courseSelected.clear();
return;
}
if (selectedCourseDb.isFullOccupancy()) {
WebUtils.showNotificationWarning(Labels.getLabel("msg.ui.warn.courseIsFull", new Object[] {this.courseSelected.iterator().next().getName()}));
// reload seznamu kurzu
this.courseList = courseService.getAll(application.getYearFrom(), application.getYearTo(), true);
this.courseSelected.clear();
return;
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Creating application: " + application);
}
try {
courseApplicationService.store(application);
WebUtils.showNotificationInfo(Labels.getLabel("msg.ui.info.applicationSend"));
// prihlaseni rovnou do kurzu
if (this.courseSelected != null && !this.courseSelected.isEmpty()) {
courseService.storeCourseParticipants(Arrays.asList(application.getCourseParticipant()), this.courseSelected.iterator().next().getUuid());
application.getCourseParticipant().setCourseList(new ArrayList<>(this.courseSelected));
}
byte[] byteArray = JasperUtil.getReport(application, Labels.getLabel("txt.ui.menu.applicationWithYear", new Object[] {application.getYearFrom()}), configurationService);
this.attachment = buildCourseApplicationAttachment(application, byteArray);
sendMail(application, this.pageHeadline);
} catch (ScbValidationException e) {
LOG.warn("ScbValidationException caught for application: " + application);
WebUtils.showNotificationError(e.getMessage());
}
}
private void showInvalidRequest() {
WebUtils.showNotificationError(Labels.getLabel("msg.ui.error.invalidRequest"));
}
public List<CourseLocation> getCourseLocationList() {
return courseLocationList;
}
public List<Course> getCourseListAll() {
return courseListAll;
}
public List<Course> getCourseList() {
return courseList;
}
public boolean isCourseSelectionRequired() {
return courseSelectionRequired;
}
public boolean isEditMode() {
return editMode;
}
public boolean isSecuredMode() {
return securedMode;
}
public Set<Course> getCourseSelected() {
return courseSelected;
}
public void setCourseSelected(Set<Course> courseSelected) {
this.courseSelected = courseSelected;
}
public CourseLocation getCourseLocationSelected() {
return courseLocationSelected;
}
public void setCourseLocationSelected(CourseLocation courseLocationSelected) {
this.courseLocationSelected = courseLocationSelected;
}
}
| [
"jakub.zaoralek@gmail.com"
] | jakub.zaoralek@gmail.com |
3e20cc935d8e400085ea071fb9ef2ddcc2198b59 | b22f15f6cf70b13459ccab00819c6e46b3cafbdc | /src/main/java/apache/catalina/authenticator/FormAuthenticator.java | 53648287e81370f9fbf733e8e554c28e5c485033 | [] | no_license | wp771910012/tomcat-explore | f5a24efbd0f2434f80c3cfc83a002a2cf6b4bab5 | 34a89d2056eceb7e6c70708ab39fdda537f23b6e | refs/heads/master | 2022-06-22T02:52:58.279711 | 2019-06-06T01:58:42 | 2019-06-06T01:58:42 | 185,329,534 | 0 | 0 | null | 2022-06-17T02:13:10 | 2019-05-07T05:50:21 | Java | UTF-8 | Java | false | false | 17,805 | java | /*
* $Header: /home/cvs/jakarta-tomcat-4.0/catalina/src/share/org/apache/catalina/authenticator/FormAuthenticator.java,v 1.20 2002/03/14 20:58:24 remm Exp $
* $Revision: 1.20 $
* $Date: 2002/03/14 20:58:24 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package apache.catalina.authenticator;
import java.io.IOException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.HttpRequest;
import org.apache.catalina.HttpResponse;
import org.apache.catalina.Realm;
import org.apache.catalina.Session;
import org.apache.catalina.deploy.LoginConfig;
/**
* An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED
* Authentication, as described in the Servlet API Specification, Version 2.2.
*
* @author Craig R. McClanahan
* @version $Revision: 1.20 $ $Date: 2002/03/14 20:58:24 $
*/
public class FormAuthenticator
extends AuthenticatorBase {
// ----------------------------------------------------- Instance Variables
/**
* Descriptive information about this implementation.
*/
protected static final String info =
"org.apache.catalina.authenticator.FormAuthenticator/1.0";
// ------------------------------------------------------------- Properties
/**
* Return descriptive information about this Valve implementation.
*/
public String getInfo() {
return (this.info);
}
// --------------------------------------------------------- Public Methods
/**
* Authenticate the user making this request, based on the specified
* login configuration. Return <code>true</code> if any specified
* constraint has been satisfied, or <code>false</code> if we have
* created a response challenge already.
*
* @param request Request we are processing
* @param response Response we are creating
* @param login Login configuration describing how authentication
* should be performed
*
* @exception IOException if an input/output error occurs
*/
public boolean authenticate(HttpRequest request,
HttpResponse response,
LoginConfig config)
throws IOException {
// References to objects we will need later
HttpServletRequest hreq =
(HttpServletRequest) request.getRequest();
HttpServletResponse hres =
(HttpServletResponse) response.getResponse();
Session session = null;
// Have we already authenticated someone?
Principal principal = hreq.getUserPrincipal();
if (principal != null) {
if (debug >= 1)
log("Already authenticated '" +
principal.getName() + "'");
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (ssoId != null)
associate(ssoId, getSession(request, true));
return (true);
}
// Have we authenticated this user before but have caching disabled?
if (!cache) {
session = getSession(request, true);
if (debug >= 1)
log("Checking for reauthenticate in session " + session);
String username =
(String) session.getNote(Constants.SESS_USERNAME_NOTE);
String password =
(String) session.getNote(Constants.SESS_PASSWORD_NOTE);
if ((username != null) && (password != null)) {
if (debug >= 1)
log("Reauthenticating username '" + username + "'");
principal =
context.getRealm().authenticate(username, password);
if (principal != null) {
session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
register(request, response, principal,
Constants.FORM_METHOD,
username, password);
return (true);
}
if (debug >= 1)
log("Reauthentication failed, proceed normally");
}
}
// Is this the re-submit of the original request URI after successful
// authentication? If so, forward the *original* request instead.
if (matchRequest(request)) {
session = getSession(request, true);
if (debug >= 1)
log("Restore request from session '" + session.getId() + "'");
principal = (Principal)
session.getNote(Constants.FORM_PRINCIPAL_NOTE);
register(request, response, principal, Constants.FORM_METHOD,
(String) session.getNote(Constants.SESS_USERNAME_NOTE),
(String) session.getNote(Constants.SESS_PASSWORD_NOTE));
String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE);
if (ssoId != null)
associate(ssoId, session);
if (restoreRequest(request, session)) {
if (debug >= 1)
log("Proceed to restored request");
return (true);
} else {
if (debug >= 1)
log("Restore of original request failed");
hres.sendError(HttpServletResponse.SC_BAD_REQUEST);
return (false);
}
}
// Acquire references to objects we will need to evaluate
String contextPath = hreq.getContextPath();
String requestURI = request.getDecodedRequestURI();
response.setContext(request.getContext());
// Is this a request for the login page itself? Test here to avoid
// displaying it twice (from the user's perspective) -- once because
// of the "save and redirect" and once because of the "restore and
// redirect" performed below.
String loginURI = contextPath + config.getLoginPage();
if (requestURI.equals(loginURI)) {
if (debug >= 1)
log("Requesting login page normally");
return (true); // Display the login page in the usual manner
}
// Is this a request for the error page itself? Test here to avoid
// an endless loop (back to the login page) if the error page is
// within the protected area of our security constraint
String errorURI = contextPath + config.getErrorPage();
if (requestURI.equals(errorURI)) {
if (debug >= 1)
log("Requesting error page normally");
return (true); // Display the error page in the usual manner
}
// Is this the action request from the login page?
boolean loginAction =
requestURI.startsWith(contextPath) &&
requestURI.endsWith(Constants.FORM_ACTION);
// No -- Save this request and redirect to the form login page
if (!loginAction) {
session = getSession(request, true);
if (debug >= 1)
log("Save request in session '" + session.getId() + "'");
saveRequest(request, session);
if (debug >= 1)
log("Redirect to login page '" + loginURI + "'");
hres.sendRedirect(hres.encodeRedirectURL(loginURI));
return (false);
}
// Yes -- Validate the specified credentials and redirect
// to the error page if they are not correct
Realm realm = context.getRealm();
String username = hreq.getParameter(Constants.FORM_USERNAME);
String password = hreq.getParameter(Constants.FORM_PASSWORD);
if (debug >= 1)
log("Authenticating username '" + username + "'");
principal = realm.authenticate(username, password);
if (principal == null) {
if (debug >= 1)
log("Redirect to error page '" + errorURI + "'");
hres.sendRedirect(hres.encodeRedirectURL(errorURI));
return (false);
}
// Save the authenticated Principal in our session
if (debug >= 1)
log("Authentication of '" + username + "' was successful");
if (session == null)
session = getSession(request, true);
session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
// If we are not caching, save the username and password as well
if (!cache) {
session.setNote(Constants.SESS_USERNAME_NOTE, username);
session.setNote(Constants.SESS_PASSWORD_NOTE, password);
}
// Redirect the user to the original request URI (which will cause
// the original request to be restored)
requestURI = savedRequestURL(session);
if (debug >= 1)
log("Redirecting to original '" + requestURI + "'");
if (requestURI == null)
hres.sendError(HttpServletResponse.SC_BAD_REQUEST,
sm.getString("authenticator.formlogin"));
else
hres.sendRedirect(hres.encodeRedirectURL(requestURI));
return (false);
}
// ------------------------------------------------------ Protected Methods
/**
* Does this request match the saved one (so that it must be the redirect
* we signalled after successful authentication?
*
* @param request The request to be verified
*/
protected boolean matchRequest(HttpRequest request) {
// Has a session been created?
Session session = getSession(request, false);
if (session == null)
return (false);
// Is there a saved request?
SavedRequest sreq = (SavedRequest)
session.getNote(Constants.FORM_REQUEST_NOTE);
if (sreq == null)
return (false);
// Is there a saved principal?
if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null)
return (false);
// Does the request URI match?
HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
String requestURI = hreq.getRequestURI();
if (requestURI == null)
return (false);
return (requestURI.equals(sreq.getRequestURI()));
}
/**
* Restore the original request from information stored in our session.
* If the original request is no longer present (because the session
* timed out), return <code>false</code>; otherwise, return
* <code>true</code>.
*
* @param request The request to be restored
* @param session The session containing the saved information
*/
protected boolean restoreRequest(HttpRequest request, Session session) {
// Retrieve and remove the SavedRequest object from our session
SavedRequest saved = (SavedRequest)
session.getNote(Constants.FORM_REQUEST_NOTE);
session.removeNote(Constants.FORM_REQUEST_NOTE);
session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
if (saved == null)
return (false);
// Modify our current request to reflect the original one
request.clearCookies();
Iterator cookies = saved.getCookies();
while (cookies.hasNext()) {
request.addCookie((Cookie) cookies.next());
}
request.clearHeaders();
Iterator names = saved.getHeaderNames();
while (names.hasNext()) {
String name = (String) names.next();
Iterator values = saved.getHeaderValues(name);
while (values.hasNext()) {
request.addHeader(name, (String) values.next());
}
}
request.clearLocales();
Iterator locales = saved.getLocales();
while (locales.hasNext()) {
request.addLocale((Locale) locales.next());
}
request.clearParameters();
if ("POST".equalsIgnoreCase(saved.getMethod())) {
Iterator paramNames = saved.getParameterNames();
while (paramNames.hasNext()) {
String paramName = (String) paramNames.next();
String paramValues[] =
(String[]) saved.getParameterValues(paramName);
request.addParameter(paramName, paramValues);
}
}
request.setMethod(saved.getMethod());
request.setQueryString(saved.getQueryString());
request.setRequestURI(saved.getRequestURI());
return (true);
}
/**
* Save the original request information into our session.
*
* @param request The request to be saved
* @param session The session to contain the saved information
*/
private void saveRequest(HttpRequest request, Session session) {
// Create and populate a SavedRequest object for this request
HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
SavedRequest saved = new SavedRequest();
Cookie cookies[] = hreq.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++)
saved.addCookie(cookies[i]);
}
Enumeration names = hreq.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Enumeration values = hreq.getHeaders(name);
while (values.hasMoreElements()) {
String value = (String) values.nextElement();
saved.addHeader(name, value);
}
}
Enumeration locales = hreq.getLocales();
while (locales.hasMoreElements()) {
Locale locale = (Locale) locales.nextElement();
saved.addLocale(locale);
}
Map parameters = hreq.getParameterMap();
Iterator paramNames = parameters.keySet().iterator();
while (paramNames.hasNext()) {
String paramName = (String) paramNames.next();
String paramValues[] = (String[]) parameters.get(paramName);
saved.addParameter(paramName, paramValues);
}
saved.setMethod(hreq.getMethod());
saved.setQueryString(hreq.getQueryString());
saved.setRequestURI(hreq.getRequestURI());
// Stash the SavedRequest in our session for later use
session.setNote(Constants.FORM_REQUEST_NOTE, saved);
}
/**
* Return the request URI (with the corresponding query string, if any)
* from the saved request so that we can redirect to it.
*
* @param session Our current session
*/
private String savedRequestURL(Session session) {
SavedRequest saved =
(SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE);
if (saved == null)
return (null);
StringBuffer sb = new StringBuffer(saved.getRequestURI());
if (saved.getQueryString() != null) {
sb.append('?');
sb.append(saved.getQueryString());
}
return (sb.toString());
}
}
| [
"wangpeng1@beingmate.com"
] | wangpeng1@beingmate.com |
8f5cd6d7d086056a8be25c6f97961f338ac4ce9f | 2c65c53ef5390bd70fd2ddb9bbc2b19027f2479f | /kangaroo-weixin-toolkit/src/main/java/io/github/pactstart/weixin/mp/message/inbound/LocationMessage.java | 1872c2a44cb35fd7d1ab882ae3e354a3f0b1b3a8 | [] | no_license | zt6220493/kangaroo | f37cdaa815708fb56e33d8f4ed7d83885551011a | 16c8a9f7589ec33f01559d3308f8dd8e49493afe | refs/heads/master | 2022-12-28T04:50:48.186699 | 2019-09-25T10:40:27 | 2019-09-25T10:40:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 836 | java | package io.github.pactstart.weixin.mp.message.inbound;
import org.dom4j.Element;
/**
* Created by Rex.Lei on 2017/7/28.
*/
public class LocationMessage extends AbstractReceivedMessage {
private String locationX;
private String locationY;
private String scale;
private String label;
@Override
public void readMore(Element root) {
this.locationX = root.elementText("Location_X");
this.locationY = root.elementText("Location_Y");
this.scale = root.elementText("Scale");
this.label = root.elementText("Label");
}
public String getLocationX() {
return locationX;
}
public String getLocationY() {
return locationY;
}
public String getScale() {
return scale;
}
public String getLabel() {
return label;
}
}
| [
"1203208955@qq.com"
] | 1203208955@qq.com |
3db26b095452cc61c8f7ab806f864ada218428c9 | e51c210ccf72a8ac1414791d8af552662c3fb034 | /ptolemy/diva/src/main/java/diva/canvas/connector/ArcConnector.java | 25c08d2771971193ebca5cdcc4453ed360020aec | [] | no_license | eclipselabs/passerelle | 0187efa4fba411265ab58d60b5d83e74af09b203 | e327dea8f4188e4bfe5ef4a76dd2476ad6f5664d | refs/heads/master | 2021-01-18T09:26:07.614275 | 2017-06-28T10:05:12 | 2017-06-28T10:05:12 | 36,805,342 | 5 | 3 | null | 2015-08-04T18:43:19 | 2015-06-03T13:27:15 | Java | UTF-8 | Java | false | false | 19,043 | java | /*
Copyright (c) 1998-2005 The Regents of the University of California
All rights reserved.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the above
copyright notice and the following two paragraphs appear in all copies
of this software.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
PROVIDED HEREUNDER IS ON AN BASIS, AND THE UNIVERSITY OF
CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
ENHANCEMENTS, OR MODIFICATIONS.
PT_COPYRIGHT_VERSION_2
COPYRIGHTENDKEY
*/
package diva.canvas.connector;
import java.awt.geom.Arc2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import diva.canvas.CanvasUtilities;
import diva.canvas.Figure;
import diva.canvas.Site;
import diva.canvas.TransformContext;
import diva.canvas.toolbox.LabelFigure;
/** A Connector that draws itself in an arc. The connector
* draws itself approximately through the center of the figures
* that own the sites to which it is connected. The curvature of the
* arc can be specified in one of two ways, depending on which
* variable of the arc's shape remain constant as the distance
* between the two figures at the ends of the arc is varied:
*
* <ol>
* <li> Constant incident angle: The angle at which the arc connects
* to the figure remains constant. This is the default behaviour,
* and the default angle is 45 degrees.
*
* <li> Constant displacement at the maximum arc point, from
* the straight line drawn between the two end points of the
* connector. The default displacement is 20 (not for any good reason,
* but is has to be something...).
* </ul>
*
* <P>Currently, only the first is supported.
*
* <p> The connector uses an instance of PaintedPath to draw itself,
* so see that class for a more detailed description of the paint- and
* stroke-related methods.
*
* @version $Id: ArcConnector.java,v 1.19 2005/07/08 19:54:48 cxh Exp $
* @author Edward Lee
* @author John Reekie
* @Pt.AcceptedRating Red
*/
public class ArcConnector extends AbstractConnector {
// The minimum exit angle that a self-loop can take
private static double MINSELFLOOPANGLE = Math.PI * 0.6;
/** The arc shape that defines the connector shape
*/
private Arc2D _arc;
/** The flag that says whether this connector is a "self-loop"
*/
private boolean _selfloop;
/** The exit angle of the arc. This is the *difference* of the
* angle of the line between the center of the head and tail
* objects, and the angle at which the arc "exits" the figure
* on the tail end. This parameter is used as the primary means
* of controlling the shape or the arc.
*/
private double _exitAngle = Math.PI / 5;
/** The previous exit angle of the arc. This is used when the arc
* switches between a self-loop and a non-self-loop.
*/
private double _previousAngle = Math.PI * 0.75;
/** The calculated parameters of the arc
*/
private double _centerX;
private double _centerY;
private double _radius;
private double _startAngle;
private double _extentAngle;
/** The angle between the two ends of the arc.
*/
private double _gamma = 0.0;
/** The threshold for when a source and a destination of an arc
* are considered close to one another. This determines how self-loops
* get drawn.
*/
protected static final double _CLOSE_THRESHOLD = 5.0;
/** The midpoint site. */
private ArcMidpointSite _midpointSite;
/** The arc displacement
*/
//// private double _displacement = 20.0;
/** Create a new arc connector between the given
* sites. The connector is drawn with a width of one
* and in black, and at the default incident angle of
* 45 degrees (PI/4 radians).
*/
public ArcConnector(Site tail, Site head) {
super(tail, head);
_arc = new Arc2D.Double();
setShape(_arc);
route();
}
/** Get the angle at which the arc leaves the tail figure.
*/
public double getAngle() {
return _exitAngle;
}
/** Get the angle that determines the orientation of a
* self-loop. This method should be used when saving an arc
* to an external representation, if the arc is a self-loop.
*/
public double getGamma() {
return _gamma;
}
/** Return the midpoint of the arc.
* @return The midpoint of the arc.
*/
public Point2D getArcMidpoint() {
// Hm... I don't know why I need the PI/2 here -- johnr
return new Point2D.Double(_centerX
+ (_radius * Math.sin(_startAngle + (_extentAngle / 2)
+ (Math.PI / 2))), _centerY
+ (_radius * Math.cos(_startAngle + (_extentAngle / 2)
+ (Math.PI / 2))));
}
/** Get the site that marks the midpoint of the connector.
* @return A site representing the midpoint of the arc.
*/
public Site getMidpointSite() {
if (_midpointSite == null) {
// The 0 is an ID. What role does this serve? EAL
_midpointSite = new ArcMidpointSite(this, 0);
}
return _midpointSite;
}
/** Get the flag saying whether this arc is to be drawn as a self-loop
*/
public boolean getSelfLoop() {
return _selfloop;
}
/** Tell the connector to reposition its label if it has one.
* The label is currently only positioned at the center of the arc.
*/
public void repositionLabel() {
LabelFigure label = getLabelFigure();
if (label != null) {
Point2D pt = getArcMidpoint();
label.translateTo(pt);
// FIXME: Need a way to override the positioning.
label.autoAnchor(_arc);
}
}
/** Tell the connector to route itself between the
* current positions of the head and tail sites.
*/
public void route() {
repaint();
TransformContext currentContext = getTransformContext();
Site headSite = getHeadSite();
Site tailSite = getTailSite();
Figure tailFigure = tailSite.getFigure();
Figure headFigure = headSite.getFigure();
Point2D headPt;
Point2D tailPt;
// Get the transformed head and tail points. Sometimes
// people will call this before the connector is added
// to a container, so deal with it
if (currentContext != null) {
tailPt = tailSite.getPoint(currentContext);
headPt = headSite.getPoint(currentContext);
} else {
tailPt = tailSite.getPoint();
headPt = headSite.getPoint();
}
// Figure out the centers of the attached figures
Point2D tailCenter;
// Figure out the centers of the attached figures
Point2D headCenter;
if (tailFigure != null) {
tailCenter = CanvasUtilities.getCenterPoint(tailFigure,
currentContext);
} else {
tailCenter = tailPt;
}
if (headFigure != null) {
headCenter = CanvasUtilities.getCenterPoint(headFigure,
currentContext);
} else {
headCenter = headPt;
}
// Change self-loop mode if necessary
boolean selfloop = _selfloop;
if ((tailFigure != null) && (headFigure != null)) {
selfloop = (tailFigure == headFigure);
}
if (selfloop && !_selfloop) {
setSelfLoop(true);
} else if (!selfloop && _selfloop) {
setSelfLoop(false);
}
// Figure out the angle between the centers. If a selfloop,
// use the angle that was previously stored.
double gamma;
double x = headCenter.getX() - tailCenter.getX();
double y = headCenter.getY() - tailCenter.getY();
if (_selfloop) {
gamma = _gamma;
} else {
gamma = Math.atan2(y, x);
}
// Tell the sites to adjust their positions
double alpha = _exitAngle;
double beta = (Math.PI / 2.0) - alpha;
double headNormal = gamma - alpha - Math.PI;
double tailNormal = gamma + alpha;
tailSite.setNormal(tailNormal);
headSite.setNormal(headNormal);
// Recompute the head and tail points
if (currentContext != null) {
tailPt = tailSite.getPoint(currentContext);
headPt = headSite.getPoint(currentContext);
} else {
tailPt = tailSite.getPoint();
headPt = headSite.getPoint();
}
// Adjust for decorations on the ends
if (getHeadEnd() != null) {
getHeadEnd().setNormal(headNormal);
getHeadEnd().setOrigin(headPt.getX(), headPt.getY());
getHeadEnd().getConnection(headPt);
}
if (getTailEnd() != null) {
getTailEnd().setNormal(tailNormal);
getTailEnd().setOrigin(tailPt.getX(), tailPt.getY());
getTailEnd().getConnection(tailPt);
}
// Figure out the angle yet again (!)
x = headPt.getX() - tailPt.getX();
y = headPt.getY() - tailPt.getY();
if (_selfloop && (tailFigure != null) && (headFigure != null)) {
// In this case, don't remember the modified gamma!
this._gamma = gamma;
gamma = Math.atan2(y, x);
} else {
gamma = Math.atan2(y, x);
this._gamma = gamma;
}
// Finally! Now that we have angle between the head and
// tail of the connector, figure out what the center
// of the arc is. First, compute assuming that gamma is
// zero.
double dx = Math.sqrt((x * x) + (y * y)) / 2.0;
double dy = -dx * Math.tan(beta);
// That's the offset from the tail point to the center
// of the arc's circle. Rotate it through gamma.
double dxdash = (dx * Math.cos(gamma)) - (dy * Math.sin(gamma));
double dydash = (dx * Math.sin(gamma)) + (dy * Math.cos(gamma));
// Get the center
double centerX = tailPt.getX() + dxdash;
double centerY = tailPt.getY() + dydash;
double radius = Math.sqrt((dx * dx) + (dy * dy));
// Remember some parameters for later use
this._centerX = centerX;
this._centerY = centerY;
this._radius = radius;
this._startAngle = ((3 * Math.PI) / 2) - alpha - gamma;
// NOTE: I don't know why I need to do this, I screwed
// up the math somewhere... -- hjr
if (_exitAngle < 0) {
_startAngle += Math.PI;
}
// Draw self loops correctly.
if (false && _selfloop) {
if (alpha < 0.0) {
_extentAngle = (2.0 * alpha) + (2 * Math.PI);
} else {
_extentAngle = (2.0 * alpha) - (2 * Math.PI);
}
} else {
_extentAngle = (2.0 * alpha);
}
// Set the arc
_arc.setArcByCenter(centerX, centerY, radius, _startAngle / Math.PI
* 180, _extentAngle / Math.PI * 180, Arc2D.OPEN);
// Move the label
repositionLabel();
// Woo-hoo!
repaint();
}
/** Set the angle at which the arc leaves the tail figure, in
* radians. Because of the sign of the geometry, an arc with
* positive angle and with an arrowhead on its head will appear
* to be drawn counter-clockwise, and an arc with a negative
* angle will appear to be drawn clockwise. As a general rule,
* angles should be somewhat less than PI/2, and PI/4 a good
* general maximum figure. If the angle is outside the range -PI
* to PI, then it is corrected to lie within that range.
*/
public void setAngle(double angle) {
while (angle > Math.PI) {
angle -= (2.0 * Math.PI);
}
while (angle < -Math.PI) {
angle += (2.0 * Math.PI);
}
_exitAngle = angle;
}
/** Set the angle that determines the orientation of a self-loop.
* This value is roughly equal to the angle of the tangent to the
* loop at it's mid-point. This method is only intended for use
* when creating self-loop arcs from a saved representation.
*/
public void setGamma(double gamma) {
_gamma = gamma;
}
/** Set the flag that says that this arc is drawn as a "self-loop."
* Apart from changing (slightly) the way the arc geometry is
* determined, this method resets some internal variables so that
* the arc doesn't get into a "funny state" when switching between
* self-loops and non-self-loops.
*
* Not, however, that this method should only be called when the
* arc changes, otherwise manipulation won't work properly. Use
* getSelfLoop() to test the current state of this flag.
*/
public void setSelfLoop(boolean selfloop) {
// If becoming a self-loop, use the current angle if it is
// wide enough, otherwise use the minimum angle or the
// previous record angle, whichever is largest.
double temp = _exitAngle;
if (selfloop) {
if ((_exitAngle > 0) && (_exitAngle < MINSELFLOOPANGLE)) {
setAngle(Math.max(_previousAngle, MINSELFLOOPANGLE));
} else if ((_exitAngle < 0) && (_exitAngle > -MINSELFLOOPANGLE)) {
setAngle(Math.min(-_previousAngle, -MINSELFLOOPANGLE));
}
} else {
// If switching to a non-selfloop, use the previous angle if
// it is small. If it is large, use the current angle
if (_previousAngle < MINSELFLOOPANGLE) {
setAngle(_previousAngle);
}
}
_previousAngle = temp;
_selfloop = selfloop;
}
/** Translate the connector. This method is implemented, since
* controllers may wish to translate connectors when the
* sites at both ends are moved the same distance.
*/
public void translate(double x, double y) {
Rectangle2D bounds = _arc.getBounds();
repaint();
_arc.setFrame(bounds.getX() + x, bounds.getY() + y, bounds.getWidth(),
bounds.getHeight());
if (getLabelFigure() != null) {
getLabelFigure().translate(x, y);
}
repaint();
}
/** Translate the midpoint of the arc. This method is not exact,
* but attempts to alter the shape of the arc so that the
* midpoint moves by something close to the given amount.
*/
public void translateMidpoint(double dx, double dy) {
// Calculate some parameters
TransformContext currentContext = getTransformContext();
Site headSite = getHeadSite();
Site tailSite = getTailSite();
Figure tailFigure = tailSite.getFigure();
Figure headFigure = headSite.getFigure();
Point2D headPt;
Point2D tailPt;
// Get the transformed head and tail points
if (currentContext != null) {
tailPt = tailSite.getPoint(currentContext);
headPt = headSite.getPoint(currentContext);
} else {
tailPt = tailSite.getPoint();
headPt = headSite.getPoint();
}
// Figure out the centers of the attached figures
Point2D tailCenter;
// Figure out the centers of the attached figures
Point2D headCenter;
if (tailFigure != null) {
tailCenter = CanvasUtilities.getCenterPoint(tailFigure,
currentContext);
} else {
tailCenter = tailPt;
}
if (headFigure != null) {
headCenter = CanvasUtilities.getCenterPoint(headFigure,
currentContext);
} else {
headCenter = headPt;
}
// Figure out the angle between the centers
double x = headCenter.getX() - tailCenter.getX();
double y = headCenter.getY() - tailCenter.getY();
double gamma;
if (_selfloop) {
gamma = _gamma;
} else {
gamma = Math.atan2(y, x);
}
// Project the displacement onto the normal of the chord.
double beta = Math.atan2(dy, dx);
double magnitude = Math.sqrt((dx * dx) + (dy * dy));
double shift = -magnitude * Math.sin(gamma - beta);
double rotate = magnitude * Math.cos(gamma - beta);
// Guess at an amount to change the angle by
double delta;
double absangle = Math.abs(_exitAngle);
double newangle;
if (!_selfloop) {
if (absangle < (Math.PI / 4)) {
delta = shift / 75.0;
} else if (absangle < (Math.PI / 2)) {
delta = shift / 120.0;
} else if (absangle < (Math.PI * 0.65)) {
delta = shift / 400.0;
} else if (absangle < (Math.PI * 0.80)) {
delta = shift / 1000.0;
} else if (absangle < (Math.PI * 0.90)) {
delta = shift / 4000.0;
} else {
delta = shift / 10000.0;
}
newangle = _exitAngle + delta;
} else {
if (absangle < (Math.PI * 0.75)) {
delta = shift / 100.0;
} else if (absangle < (Math.PI * 0.85)) {
delta = shift / 300.0;
} else if (absangle < (Math.PI * 0.90)) {
delta = shift / 1000.0;
} else if (absangle < (Math.PI * 0.95)) {
delta = shift / 4000.0;
} else {
delta = shift / 10000;
}
newangle = _exitAngle + delta;
if ((newangle > 0) && (newangle < (Math.PI * 0.6))) {
newangle = Math.PI * 0.6;
} else if ((newangle < 0) && (newangle > (-Math.PI * 0.6))) {
newangle = -Math.PI * 0.6;
}
// That was for changing the size of the self-loop. This next
// part is for changing the exit angle.
if ((tailFigure != null) && (headFigure != null)) {
double phi = rotate / _radius / 2.0;
if (newangle < 0) {
_gamma += phi;
} else {
_gamma -= phi;
}
}
}
setAngle(newangle);
}
}
| [
"erwindl0@gmail.com"
] | erwindl0@gmail.com |
de6764b6722dea8656343cb5907a461ed9bb6a63 | ecd0b298f0a7893b575dd2e6a513673f60a60d1b | /app/src/main/java/com/stockly/android/fragments/kyc/EmploymentFragment.java | dee875eed3f38d54d884cfae050dc188a5f19fb0 | [
"Apache-2.0"
] | permissive | webclinic017/ribbit-android | 1ce898c2fbbe111f46c36a59b00cba089eaaa295 | 292cdfccaca32567bb7c954ce5caf911248834ed | refs/heads/main | 2023-09-04T05:47:18.518300 | 2021-10-28T23:14:06 | 2021-10-28T23:14:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,278 | java | package com.stockly.android.fragments.kyc;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.stockly.android.R;
import com.stockly.android.dao.UserDao;
import com.stockly.android.databinding.FragmentEmploymentBinding;
import com.stockly.android.fragments.NetworkFragment;
import com.stockly.android.models.RetrofitError;
import com.stockly.android.models.User;
import com.stockly.android.session.UserSession;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import javax.inject.Inject;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.Single;
/**
* EmploymentFragment
* This Fragment class represents employment info required from user.
* If employed or not, what is current status? etc.
*/
@AndroidEntryPoint
public class EmploymentFragment extends NetworkFragment {
private FragmentEmploymentBinding mBinding;
@Inject
UserDao userDao;
@Inject
UserSession mUserSession;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handleBackPress(this, new FundingSourceFragment());
}
@Override
protected int getLayoutId() {
return R.layout.fragment_employment;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBinding = FragmentEmploymentBinding.bind(view);
setUpToolBar(mBinding.toolbar.toolbar);
getUser();
mBinding.radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
mBinding.next.setEnabled(group.getCheckedRadioButtonId() != -1);
});
mBinding.next.setOnClickListener(view1 -> {
if (mBinding.radioGroup.getCheckedRadioButtonId() == -1) {
// no radio buttons are checked
Toast.makeText(requireActivity(), "Please select One", Toast.LENGTH_SHORT).show();
} else {
int id = mBinding.radioGroup.getCheckedRadioButtonId();
RadioButton button = (RadioButton) requireActivity().findViewById(id);
updateEmploymentStatus(getString(button.getText().toString()));
}
});
}
/**
* update user's employment status by passing
*
* @param employment
*/
private void updateEmploymentStatus(String employment) {
mBinding.next.startAnimation();
HashMap<String, Object> body = new HashMap<>();
body.put("employment_status", employment);
body.put("profile_completion", "employed");
enqueue(getApi().updateProfile(body), new NetworkFragment.CallBack<User>() {
@Override
public void onSuccess(User user) {
updateUser(user);
mBinding.next.revertAnimation();
if (employment.equalsIgnoreCase("employed")) {
replaceFragment(new EmploymentInfoFragment());
} else {
replaceFragment(new FamilyFragment());
}
}
@Override
public boolean onError(RetrofitError error, boolean isInternetIssue) {
mBinding.next.revertAnimation();
return super.onError(error, isInternetIssue);
}
});
}
/**
* get User from local DB.
*/
public void getUser() {
// DB User
Single<User> userById = userDao.getUserById(mUserSession.getUserID());
requestSingle(userById, new CallBackSingle<User>() {
@Override
public void onSuccess(@NotNull User user) {
updateUI(user);
}
@Override
public void onError(@NotNull Throwable e) {
Log.d(">>>", "onError: " + e.getMessage());
super.onError(e);
}
});
}
/**
* update UI from user existing records
*
* @param user
*/
public void updateUI(User user) {
if (user.employmentStatus.equalsIgnoreCase("employed")) {
mBinding.employed.setChecked(true);
} else if (user.employmentStatus.equalsIgnoreCase("unemployed")) {
mBinding.unEmployed.setChecked(true);
} else if (user.employmentStatus.equalsIgnoreCase("retired")) {
mBinding.retired.setChecked(true);
} else if (user.employmentStatus.equalsIgnoreCase("student")) {
mBinding.student.setChecked(true);
}
}
/**
* It will return value to send to server by passing key to it.
*
* @param key
* @return value
*/
public String getString(String key) {
String value = "";
if (key.equalsIgnoreCase("Employed")) {
value = "employed";
} else if (key.equalsIgnoreCase("Unemployed")) {
value = "unemployed";
} else if (key.equalsIgnoreCase("Retired")) {
value = "retired";
} else if (key.equalsIgnoreCase("Student")) {
value = "student";
}
return value;
}
}
| [
"hitoshi@alpaca.markets"
] | hitoshi@alpaca.markets |
6271a44897c4f2dbe3c8cc4fd68b5a4a5bfd6125 | 7e449a62a4a0bd281e59052c2424c2118f2961a1 | /Array/app/src/test/java/com/kirill/array/ExampleUnitTest.java | d266acd8063e5df414602582ab72776cd1a936ef | [] | no_license | kirillherz/learning-android | 15da32d38d9e41006aa081808f6ea6e42fe19ba3 | 228b17984ada9c1773095ba8bdbec262260f04ca | refs/heads/master | 2021-05-02T16:06:14.612998 | 2018-09-27T22:01:42 | 2018-09-27T22:01:42 | 120,668,471 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package com.kirill.array;
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() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"kirill.herz@gmail.com"
] | kirill.herz@gmail.com |
451bbef33bc2a0b68e55ed9a2b7c83736baa9ad7 | d7302c4b16b1aeb5974271dd6c62a2f7b35342d3 | /desktop-functional-tests/src/test/java/com/e2e/jcrew/runner/E2EGuestUser7RunnerTest.java | 26a9d80210f2454221ac7208d0061968cad70a6b | [] | no_license | 9LPittu/Omniture-Automation | 55f82084ae40f1624d2089dd029310ecab54fca4 | 07d52c366a5688eeb9c69db0929c2dabfdec0feb | refs/heads/master | 2022-07-12T19:52:35.218272 | 2018-07-19T17:33:52 | 2018-07-19T17:33:52 | 194,112,044 | 0 | 0 | null | 2022-06-29T17:28:42 | 2019-06-27T14:37:49 | Java | UTF-8 | Java | false | false | 537 | java | package com.e2e.jcrew.runner;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {"features/e2e/jcrew"},
tags = {"@e2e-guestuser-7"},
glue = {"com.jcrew.steps"},
format = {
"json:target/JC_E2E_GuestUser_Testdata_Sheet_7.json",
"pretty",
"html:target/cucumber/JC_E2E_GuestUser_Testdata_Sheet_7"
}
)
public class E2EGuestUser7RunnerTest {
} | [
"vbonker@csc.com"
] | vbonker@csc.com |
5c4b09360ad814034bd578d8c0a085acc461c990 | e2768cad07cd04f5802311af202c84474528d574 | /src/Services/Verification/PostVerification.java | 1d1dc61af61a6da8312e0cb1b6749da951c0dcfa | [] | no_license | Youssef-MSF/LinkedClubs | 766b1dcdcff693624261640a16beb60103d819db | 7d6b59d30b89c531d9122b53205bae84178530ac | refs/heads/main | 2023-03-11T04:30:36.028863 | 2021-02-28T00:28:07 | 2021-02-28T00:28:07 | 334,297,743 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,325 | java | package Services.Verification;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import DAO.DaoNotification;
import DAO.DaoPost;
import Services.Entities.Club;
import Services.Entities.Notification;
import Services.Entities.Post;
public class PostVerification {
// Variables
private HashMap<String, String> err = new HashMap<String, String>();
private DaoPost daoPostImp;
private DaoNotification daoNotificationImp;
// Constructors
public PostVerification(DaoPost daoPostImp, DaoNotification daoNotificationImp) {
this.daoPostImp = daoPostImp;
this.daoNotificationImp = daoNotificationImp;
}
// Verification function
public Post verifyPost(HttpServletRequest request) throws IOException, ServletException {
// Get the current project path
String applicationPath = request.getServletContext().getRealPath("");
// Get the upload folder for profile images
String profileImagesUploadDirectory = applicationPath + File.separator + "Images" + File.separator
+ "postFiles";
// Getting files
Part postImagePart = request.getPart("postFile");
// Getting parameters
String postDescription = (String) request.getParameter("description");
String postFileLink = (String) postImagePart.getSubmittedFileName();
// Get the notification
NotificationVerify notificationVerifyForm = new NotificationVerify(this.daoNotificationImp, this.daoPostImp);
Notification notification = notificationVerifyForm.notificationVerify(request);
// Create post object
Post post = new Post();
// Call verification functions
verifyPostDescription(postDescription, post);
verifyFileLink(postImagePart, postFileLink, post);
HttpSession session = request.getSession();
Club club = (Club) session.getAttribute("club");
post.setClub(club);
if (err.isEmpty()) {
if (!(postFileLink.equals(""))) {
postImagePart.write(profileImagesUploadDirectory + File.separator + postFileLink);
}
// Setting the date of the post
post.setPublishedDate(new java.util.Date());
// Set the notification to the post
post.setNotification(notification);
// Inserting the post in the dataBase
post = this.daoPostImp.add(post);
}
return post;
}
// functions
public void verifyPostDescription(String postDescription, Post post) {
// Setting post description
post.setPostDescription(postDescription);
// Sometimes we will have a post width description sometimes not
}
public void verifyFileLink(Part postImagePart, String fileLink, Post post) {
// Setting post image
post.setFileLink(fileLink);
// Verify the type of the file
if (!postImagePart.getContentType().equals("application/octet-stream")) {
post.setFileType(postImagePart.getContentType());
}
try {
if (post.getPostDescription().isEmpty() && post.getFileLink().isEmpty())
throw new Exception("Please make sure to insert a valid post information");
} catch (Exception e) {
err.put("errPost", e.getMessage());
// TODO: handle exception
}
}
// Getters and Setters
public HashMap<String, String> getErr() {
return err;
}
public void setErr(HashMap<String, String> err) {
this.err = err;
}
} | [
"Djossef.msf@gmail.com"
] | Djossef.msf@gmail.com |
85bebf3891e64aefded3b031171500fb2701e202 | 515b0c97189e93a3a352950787ff841af3fbb558 | /app/src/main/java/com/rival/hs/rival_android/ListActivity.java | effb5b28c7295488c06dbb683da4b17c25611e14 | [] | no_license | thewayhj/rival_android | a29ca00d40e1f46c680cf653204a060b4f0a6b23 | ee9b8c9760c045f53aec7c361023e4585e5e0e33 | refs/heads/master | 2021-01-17T20:51:41.516848 | 2017-03-22T07:45:39 | 2017-03-22T07:45:39 | 84,150,658 | 0 | 0 | null | 2017-03-20T05:04:15 | 2017-03-07T03:33:56 | Java | UTF-8 | Java | false | false | 1,963 | java | package com.rival.hs.rival_android;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
/**
* Created by HeeJoongKim on 2017-03-20.
*/
public class ListActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sportlist);
ListView listview ;
ListViewAdapter adapter;
// Adapter 생성
adapter = new ListViewAdapter() ;
// 리스트뷰 참조 및 Adapter달기
listview = (ListView) findViewById(R.id.listview1);
listview.setAdapter(adapter);
// 첫 번째 아이템 추가.
adapter.addItem(ContextCompat.getDrawable(this, R.drawable.kakaotalk_20170318_154059975),
"Box", "Account Box Black 36dp") ;
// 두 번째 아이템 추가.
adapter.addItem(ContextCompat.getDrawable(this, R.drawable.kakaotalk_20170318_154059975),
"Circle", "Account Circle Black 36dp") ;
// 세 번째 아이템 추가.
adapter.addItem(ContextCompat.getDrawable(this, R.drawable.kakaotalk_20170318_154059975),
"Ind", "Assignment Ind Black 36dp") ;
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
// get item
ListViewItem item = (ListViewItem) parent.getItemAtPosition(position) ;
String titleStr = item.getTitle() ;
String descStr = item.getDesc() ;
Drawable iconDrawable = item.getIcon() ;
// TODO : use item data.
}
}) ;
}
}
| [
"tnwndvhrrurr@paran.com"
] | tnwndvhrrurr@paran.com |
9ed16ee5706d4eb73fe99e0158082ef1cf2ac84d | bd2139703c556050403c10857bde66f688cd9ee6 | /skara/570/webrev.00/bots/merge/src/main/java/org/openjdk/skara/bots/merge/MergeBot.java | 2ad899c9ece84a5ff118a1fddc17ae2a562e643a | [] | no_license | isabella232/cr-archive | d03427e6fbc708403dd5882d36371e1b660ec1ac | 8a3c9ddcfacb32d1a65d7ca084921478362ec2d1 | refs/heads/master | 2023-02-01T17:33:44.383410 | 2020-12-17T13:47:48 | 2020-12-17T13:47:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 25,011 | java | /*
* Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package org.openjdk.skara.bots.merge;
import org.openjdk.skara.bot.*;
import org.openjdk.skara.forge.*;
import org.openjdk.skara.vcs.*;
import org.openjdk.skara.jcheck.JCheckConfiguration;
import java.io.IOException;
import java.io.File;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Files;
import java.net.URLEncoder;
import java.time.DayOfWeek;
import java.time.Month;
import java.time.temporal.WeekFields;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.logging.Logger;
class MergeBot implements Bot, WorkItem {
private final Logger log = Logger.getLogger("org.openjdk.skara.bots");;
private final Path storage;
private final HostedRepositoryPool pool;
private final HostedRepository target;
private final HostedRepository fork;
private final List<Spec> specs;
private final Clock clock;
private final Map<String, Set<Integer>> hourly = new HashMap<>();
private final Map<String, Set<Integer>> daily = new HashMap<>();
private final Map<String, Set<Integer>> weekly = new HashMap<>();
private final Map<String, Set<Month>> monthly = new HashMap<>();
private final Map<String, Set<Integer>> yearly = new HashMap<>();
MergeBot(Path storage, HostedRepository target, HostedRepository fork,
List<Spec> specs) {
this(storage, target, fork, specs, new Clock() {
public ZonedDateTime now() {
return ZonedDateTime.now();
}
});
}
MergeBot(Path storage, HostedRepository target, HostedRepository fork,
List<Spec> specs, Clock clock) {
this.storage = storage;
this.pool = new HostedRepositoryPool(storage.resolve("seeds"));
this.target = target;
this.fork = fork;
this.specs = specs;
this.clock = clock;
}
final static class Spec {
final static class Frequency {
static enum Interval {
HOURLY,
DAILY,
WEEKLY,
MONTHLY,
YEARLY;
boolean isHourly() {
return this.equals(HOURLY);
}
boolean isDaily() {
return this.equals(DAILY);
}
boolean isWeekly() {
return this.equals(WEEKLY);
}
boolean isMonthly() {
return this.equals(MONTHLY);
}
boolean isYearly() {
return this.equals(YEARLY);
}
}
private final Interval interval;
private final DayOfWeek weekday;
private final Month month;
private final int day;
private final int hour;
private final int minute;
private Frequency(Interval interval, DayOfWeek weekday, Month month, int day, int hour, int minute) {
this.interval = interval;
this.weekday = weekday;
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
}
static Frequency hourly(int minute) {
return new Frequency(Interval.HOURLY, null, null, -1, -1, minute);
}
static Frequency daily(int hour) {
return new Frequency(Interval.DAILY, null, null, -1, hour, -1);
}
static Frequency weekly(DayOfWeek weekday, int hour) {
return new Frequency(Interval.WEEKLY, weekday, null, -1, hour, -1);
}
static Frequency monthly(int day, int hour) {
return new Frequency(Interval.MONTHLY, null, null, day, hour, -1);
}
static Frequency yearly(Month month, int day, int hour) {
return new Frequency(Interval.YEARLY, null, month, day, hour, -1);
}
boolean isHourly() {
return interval.isHourly();
}
boolean isDaily() {
return interval.isDaily();
}
boolean isWeekly() {
return interval.isWeekly();
}
boolean isMonthly() {
return interval.isMonthly();
}
boolean isYearly() {
return interval.isYearly();
}
DayOfWeek weekday() {
return weekday;
}
Month month() {
return month;
}
int day() {
return day;
}
int hour() {
return hour;
}
int minute() {
return minute;
}
}
private final HostedRepository fromRepo;
private final Branch fromBranch;
private final Branch toBranch;
private final Frequency frequency;
Spec(HostedRepository fromRepo, Branch fromBranch, Branch toBranch) {
this(fromRepo, fromBranch, toBranch, null);
}
Spec(HostedRepository fromRepo, Branch fromBranch, Branch toBranch, Frequency frequency) {
this.fromRepo = fromRepo;
this.fromBranch = fromBranch;
this.toBranch = toBranch;
this.frequency = frequency;
}
HostedRepository fromRepo() {
return fromRepo;
}
Branch fromBranch() {
return fromBranch;
}
Branch toBranch() {
return toBranch;
}
Optional<Frequency> frequency() {
return Optional.ofNullable(frequency);
}
}
private static void deleteDirectory(Path dir) throws IOException {
Files.walk(dir)
.map(Path::toFile)
.sorted(Comparator.reverseOrder())
.forEach(File::delete);
}
private Repository cloneAndSyncFork(Path to) throws IOException {
var repo = pool.materialize(fork, to);
// Sync personal fork
var remoteBranches = repo.remoteBranches(target.url().toString());
for (var branch : remoteBranches) {
var fetchHead = repo.fetch(target.url(), branch.hash().hex());
repo.push(fetchHead, fork.url(), branch.name());
}
// Must fetch once to update refs/heads
repo.fetchAll();
return repo;
}
@Override
public boolean concurrentWith(WorkItem other) {
if (!(other instanceof MergeBot)) {
return true;
}
var otherBot = (MergeBot) other;
return !target.name().equals(otherBot.target.name());
}
@Override
public void run(Path scratchPath) {
try {
var sanitizedUrl =
URLEncoder.encode(fork.webUrl().toString(), StandardCharsets.UTF_8);
var dir = storage.resolve(sanitizedUrl);
var repo = cloneAndSyncFork(dir);
var prTarget = fork.forge().repository(target.name()).orElseThrow(() ->
new IllegalStateException("Can't get well-known repository " + target.name())
);
var prs = prTarget.pullRequests();
var currentUser = prTarget.forge().currentUser();
for (var spec : specs) {
var toBranch = spec.toBranch();
var fromRepo = spec.fromRepo();
var fromBranch = spec.fromBranch();
var targetName = Path.of(target.name()).getFileName();
var fromName = Path.of(fromRepo.name()).getFileName();
var fromDesc = targetName.equals(fromName) ? fromBranch.name() : fromName + ":" + fromBranch.name();
// Check if merge conflict pull request is present
var shouldMerge = true;
var title = "Merge " + fromDesc;
var marker = "<!-- AUTOMATIC MERGE PR -->";
for (var pr : prs) {
if (pr.title().equals(title) &&
pr.targetRef().equals(toBranch.name()) &&
pr.body().startsWith(marker) &&
currentUser.equals(pr.author())) {
// Yes, this could be optimized do a merge "this turn", but it is much simpler
// to just wait until the next time the bot runs
shouldMerge = false;
if (pr.labels().contains("ready") && !pr.labels().contains("sponsor")) {
var comments = pr.comments();
var integrateComments =
comments.stream()
.filter(c -> c.author().equals(currentUser))
.filter(c -> c.body().equals("/integrate"))
.collect(Collectors.toList());
if (integrateComments.isEmpty()) {
pr.addComment("/integrate");
} else {
var lastIntegrateComment = integrateComments.get(integrateComments.size() - 1);
var id = lastIntegrateComment.id();
var botUserId = "43336822";
var replyMarker = "<!-- Jmerge command reply message (" + id + ") -->";
var replies = comments.stream()
.filter(c -> c.author().id().equals(botUserId))
.filter(c -> c.body().startsWith(replyMarker))
.collect(Collectors.toList());
if (replies.isEmpty()) {
// No reply yet, just wait
} else {
// Got a reply and the "sponsor" label is not present, check for error
// and if we should add the `/integrate` command again
var lastReply = replies.get(replies.size() - 1);
var lines = lastReply.body().split("\n");
var errorPrefix = "@openjdk-bot Your merge request cannot be fulfilled at this time";
if (lines.length > 1 && lines[1].startsWith(errorPrefix)) {
// Try again
pr.addComment("/integrate");
}
// Other reply, potentially due to rebase issue, just
// wait for the labeler to add appropriate labels.
}
}
}
}
}
if (spec.frequency().isPresent()) {
var now = clock.now();
var desc = toBranch.name() + "->" + fromRepo.name() + ":" + fromBranch.name();
var freq = spec.frequency().get();
if (freq.isHourly()) {
if (!hourly.containsKey(desc)) {
hourly.put(desc, new HashSet<Integer>());
}
var minute = now.getMinute();
var hour = now.getHour();
if (freq.minute() == minute && !hourly.get(desc).contains(hour)) {
hourly.get(desc).add(hour);
} else {
shouldMerge = false;
}
} else if (freq.isDaily()) {
if (!daily.containsKey(desc)) {
daily.put(desc, new HashSet<Integer>());
}
var hour = now.getHour();
var day = now.getDayOfYear();
if (freq.hour() == hour && !daily.get(desc).contains(day)) {
daily.get(desc).add(day);
} else {
shouldMerge = false;
}
} else if (freq.isWeekly()) {
if (!weekly.containsKey(desc)) {
weekly.put(desc, new HashSet<Integer>());
}
var weekOfYear = now.get(WeekFields.ISO.weekOfYear());
var weekday = now.getDayOfWeek();
var hour = now.getHour();
if (freq.weekday().equals(weekday) &&
freq.hour() == hour &&
!weekly.get(desc).contains(weekOfYear)) {
weekly.get(desc).add(weekOfYear);
} else {
shouldMerge = false;
}
} else if (freq.isMonthly()) {
if (!monthly.containsKey(desc)) {
monthly.put(desc, new HashSet<Month>());
}
var day = now.getDayOfMonth();
var hour = now.getHour();
var month = now.getMonth();
if (freq.day() == day && freq.hour() == hour &&
!monthly.get(desc).contains(month)) {
monthly.get(desc).add(month);
} else {
shouldMerge = false;
}
} else if (freq.isYearly()) {
if (!yearly.containsKey(desc)) {
yearly.put(desc, new HashSet<Integer>());
}
var month = now.getMonth();
var day = now.getDayOfMonth();
var hour = now.getHour();
var year = now.getYear();
if (freq.month().equals(month) &&
freq.day() == day &&
freq.hour() == hour &&
!yearly.get(desc).contains(year)) {
yearly.get(desc).add(year);
} else {
shouldMerge = false;
}
}
}
if (!shouldMerge) {
log.info("Will not merge " + fromRepo.name() + ":" + fromBranch.name() + " to " + toBranch.name());
continue;
}
// Checkout the branch to merge into
repo.checkout(toBranch, false);
var remoteBranch = new Branch(repo.upstreamFor(toBranch).orElseThrow(() ->
new IllegalStateException("Could not get remote branch name for " + toBranch.name())
));
repo.merge(remoteBranch); // should always be a fast-forward merge
log.info("Trying to merge " + fromRepo.name() + ":" + fromBranch.name() + " to " + toBranch.name());
log.info("Fetching " + fromRepo.name() + ":" + fromBranch.name());
var fetchHead = repo.fetch(fromRepo.url(), fromBranch.name());
var head = repo.resolve(toBranch.name()).orElseThrow(() ->
new IOException("Could not resolve branch " + toBranch.name())
);
if (repo.contains(toBranch, fetchHead)) {
log.info("Nothing to merge");
continue;
}
var isAncestor = repo.isAncestor(head, fetchHead);
log.info("Merging into " + toBranch.name());
IOException error = null;
try {
repo.merge(fetchHead);
} catch (IOException e) {
error = e;
}
if (error == null) {
log.info("Pushing successful merge");
if (!isAncestor) {
repo.commit("Automatic merge of " + fromDesc + " into " + toBranch,
"duke", "duke@openjdk.org");
}
try {
repo.push(toBranch, target.url().toString(), false);
} catch (IOException e) {
// A failed push can result in the local and remote branch diverging,
// re-create the repository from the remote.
// No need to create a pull request, just retry the merge and the push
// the next run.
deleteDirectory(dir);
repo = cloneAndSyncFork(dir);
}
} else {
log.info("Got error: " + error.getMessage());
log.info("Aborting unsuccesful merge");
var status = repo.status();
repo.abortMerge();
var fromRepoName = Path.of(fromRepo.webUrl().getPath()).getFileName();
var branchDesc = Integer.toString(prs.size() + 1);
repo.push(fetchHead, fork.url(), branchDesc, true);
log.info("Creating pull request to alert");
var mergeBase = repo.mergeBase(fetchHead, head);
var message = new ArrayList<String>();
message.add(marker);
message.add("<!-- " + fetchHead.hex() + " -->");
var commits = repo.commits(mergeBase.hex() + ".." + fetchHead.hex(), true).asList();
var numCommits = commits.size();
var are = numCommits > 1 ? "are" : "is";
var s = numCommits > 1 ? "s" : "";
message.add("Hi all,");
message.add("");
message.add("this is an _automatically_ generated pull request to notify you that there " +
are + " " + numCommits + " commit" + s + " from the branch `" + fromDesc + "`" +
"that can **not** be merged into the branch `" + toBranch.name() + "`:");
message.add("");
var unmerged = status.stream().filter(entry -> entry.status().isUnmerged()).collect(Collectors.toList());
if (unmerged.size() <= 10) {
var files = unmerged.size() > 1 ? "files" : "file";
message.add("The following " + files + " contains merge conflicts:");
message.add("");
for (var fileStatus : unmerged) {
message.add("- " + fileStatus.source().path().orElseThrow());
}
} else {
message.add("Over " + unmerged.size() + " files contains merge conflicts.");
}
message.add("");
var project = JCheckConfiguration.from(repo, head).map(conf -> conf.general().project());
if (project.isPresent()) {
message.add("All Committers in this [project](https://openjdk.java.net/census#" + project + ") " +
"have access to my [personal fork](" + fork.nonTransformedWebUrl() + ") and can " +
"therefore help resolve these merge conflicts (you may want to coordinate " +
"who should do this).");
} else {
message.add("All users with access to my [personal fork](" + fork.nonTransformedWebUrl() + ") " +
"can help resolve these merge conflicts " +
"(you may want to coordinate who should do this).");
}
message.add("The following paragraphs will give an example on how to solve these " +
"merge conflicts and push the resulting merge commit to this pull request.");
message.add("The below commands should be run in a local clone of your " +
"[personal fork](https://wiki.openjdk.java.net/display/skara#Skara-Personalforks) " +
"of the [" + target.name() + "](" + target.nonTransformedWebUrl() + ") repository.");
message.add("");
var localBranchName = "openjdk-bot-" + branchDesc;
message.add("```bash");
message.add("# Ensure target branch is up to date");
message.add("$ git checkout " + toBranch.name());
message.add("$ git pull " + target.nonTransformedWebUrl() + " " + toBranch.name());
message.add("");
message.add("# Fetch and checkout the branch for this pull request");
message.add("$ git fetch " + fork.nonTransformedWebUrl() + " +" + branchDesc + ":" + localBranchName);
message.add("$ git checkout " + localBranchName);
message.add("");
message.add("# Merge the target branch");
message.add("$ git merge " + toBranch.name());
message.add("```");
message.add("");
message.add("When you have resolved the conflicts resulting from the `git merge` command " +
"above, run the following commands to create a merge commit:");
message.add("");
message.add("```bash");
message.add("$ git add paths/to/files/with/conflicts");
message.add("$ git commit -m 'Merge " + fromDesc + "'");
message.add("```");
message.add("");
message.add("");
message.add("When you have created the merge commit, run the following command to push the merge commit " +
"to this pull request:");
message.add("");
message.add("```bash");
message.add("$ git push " + fork.nonTransformedWebUrl() + " " + localBranchName + ":" + branchDesc);
message.add("```");
message.add("");
message.add("_Note_: if you are using SSH to push commits to GitHub, then change the URL in the above `git push` command accordingly.");
message.add("");
message.add("Thanks,");
message.add("J. Duke");
var prFromFork = fork.createPullRequest(prTarget,
toBranch.name(),
branchDesc,
title,
message);
var prFromTarget = target.pullRequest(prFromFork.id());
prFromTarget.addLabel("failed-auto-merge");
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public String toString() {
return "MergeBot@(" + target.name() + ")";
}
@Override
public List<WorkItem> getPeriodicItems() {
return List.of(this);
}
}
| [
"robin.westberg@oracle.com"
] | robin.westberg@oracle.com |
9fc1417891303b1319d87f3fbb94e191c2a112b9 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/8/8_19bec45754ed815c9204335702d68815eaed856f/EventTest/8_19bec45754ed815c9204335702d68815eaed856f_EventTest_s.java | 403346495a070356e0361879705d602d6ee5282c | [] | 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 | 18,019 | java | /*
* Copyright 2009 Google 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.google.gwt.user.client;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.DoubleClickEvent;
import com.google.gwt.event.dom.client.DoubleClickHandler;
import com.google.gwt.event.dom.client.HasDoubleClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.user.client.Event.NativePreviewEvent;
import com.google.gwt.user.client.Event.NativePreviewHandler;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
/**
* Test Case for {@link Event}.
*/
public class EventTest extends GWTTestCase {
/**
* An EventPreview used for testing.
*/
@SuppressWarnings("deprecation")
private static class TestEventPreview implements EventPreview {
private boolean doCancel;
private boolean isFired = false;
/**
* Construct a new {@link TestEventPreview}.
*
* @param doCancel if true, cancel the event
*/
public TestEventPreview(boolean doCancel) {
this.doCancel = doCancel;
}
@Deprecated
public boolean onEventPreview(Event event) {
assertFalse(isFired);
isFired = true;
return !doCancel;
}
public void assertIsFired(boolean expected) {
assertEquals(expected, isFired);
}
}
/**
* A NativePreviewHandler used for testing.
*/
private static class TestNativePreviewHandler implements NativePreviewHandler {
private boolean doCancel;
private boolean doPreventCancel;
private boolean isFired = false;
/**
* Construct a new {@link TestNativePreviewHandler}.
*
* @param doCancel if true, cancel the event
* @param doPreventCancel if true, prevent the event from being canceled
*/
public TestNativePreviewHandler(boolean doCancel, boolean doPreventCancel) {
this.doCancel = doCancel;
this.doPreventCancel = doPreventCancel;
}
public void onPreviewNativeEvent(NativePreviewEvent event) {
assertFalse(isFired);
isFired = true;
if (doCancel) {
event.cancel();
}
if (doPreventCancel) {
event.consume();
}
}
public void assertIsFired(boolean expected) {
assertEquals(expected, isFired);
}
}
/**
* A custom {@link Label} used for testing.
*/
private static class TestLabel extends Label implements
HasDoubleClickHandlers {
public HandlerRegistration addDoubleClickHandler(DoubleClickHandler handler) {
return addDomHandler(handler, DoubleClickEvent.getType());
}
}
/**
* Debug information used to test events.
*/
private static class EventInfo {
private int fireCount = 0;
}
@Override
public String getModuleName() {
return "com.google.gwt.user.User";
}
/**
* Test that concurrent removal of a {@link NativePreviewHandler} does not
* trigger an exception. The handler should not actually be removed until the
* end of the event loop.
*/
public void testConcurrentRemovalOfNativePreviewHandler() {
// Add handler0
final TestNativePreviewHandler handler0 = new TestNativePreviewHandler(
false, false);
final HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
// Add handler 1
final TestNativePreviewHandler handler1 = new TestNativePreviewHandler(
false, false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
handler0.assertIsFired(false);
reg0.removeHandler();
}
};
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
assertTrue(Event.fireNativePreviewEvent(null));
// Verify both handlers fired even though one was removed
handler0.assertIsFired(true);
handler1.assertIsFired(true);
reg1.removeHandler();
}
/**
* Test that a double click results in exactly two click events, one real and
* one simulated. See issue 3392 for more info.
*/
public void testDoubleClickEvent() {
TestLabel label = new TestLabel();
RootPanel.get().add(label);
// Add some handlers
final EventInfo clickInfo = new EventInfo();
label.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
clickInfo.fireCount++;
}
});
final EventInfo dblclickInfo = new EventInfo();
label.addDoubleClickHandler(new DoubleClickHandler() {
public void onDoubleClick(DoubleClickEvent event) {
dblclickInfo.fireCount++;
}
});
// Fire a click event
NativeEvent clickEvent = Document.get().createClickEvent(0, 0, 0, 0, 0,
false, false, false, false);
label.getElement().dispatchEvent(clickEvent);
NativeEvent dblclickEvent = Document.get().createDblClickEvent(0, 0, 0, 0,
0, false, false, false, false);
label.getElement().dispatchEvent(dblclickEvent);
// Verify the results
if (isInternetExplorer()) {
assertEquals(2, clickInfo.fireCount);
} else {
assertEquals(1, clickInfo.fireCount);
}
assertEquals(1, dblclickInfo.fireCount);
RootPanel.get().remove(label);
}
/**
* Test that {@link Event#fireNativePreviewEvent(NativeEvent)} returns the
* correct value if the native event is canceled.
*/
public void testFireNativePreviewEventCancel() {
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(true,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(true,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
assertFalse(Event.fireNativePreviewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
}
/**
* Test that {@link Event#fireNativePreviewEvent(NativeEvent)} returns the
* correct value if the native event is prevented from being canceled, even if
* another handler cancels the event.
*/
public void testFireNativePreviewEventPreventCancel() {
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
true);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(true,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
assertTrue(Event.fireNativePreviewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
}
/**
* Test that {@link Event#fireNativePreviewEvent(NativeEvent)} fires handlers
* in reverse order, and that the legacy EventPreview fires only if it is at
* the top of the stack.
*/
@SuppressWarnings("deprecation")
public void testFireNativePreviewEventReverseOrder() {
final TestEventPreview preview0 = new TestEventPreview(false);
final TestEventPreview preview1 = new TestEventPreview(false);
final TestNativePreviewHandler handler0 = new TestNativePreviewHandler(
false, false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
preview0.assertIsFired(false);
preview1.assertIsFired(true);
assertFalse(event.isFirstHandler());
}
};
final TestNativePreviewHandler handler1 = new TestNativePreviewHandler(
false, false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
handler0.assertIsFired(false);
preview0.assertIsFired(false);
preview1.assertIsFired(true);
assertFalse(event.isFirstHandler());
}
};
final TestNativePreviewHandler handler2 = new TestNativePreviewHandler(
false, false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
handler0.assertIsFired(false);
handler1.assertIsFired(false);
preview0.assertIsFired(false);
preview1.assertIsFired(true);
assertFalse(event.isFirstHandler());
}
};
final TestNativePreviewHandler handler3 = new TestNativePreviewHandler(
false, false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
super.onPreviewNativeEvent(event);
handler0.assertIsFired(false);
handler1.assertIsFired(false);
handler2.assertIsFired(false);
preview0.assertIsFired(false);
preview1.assertIsFired(true);
assertFalse(event.isFirstHandler());
}
};
DOM.addEventPreview(preview0);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
HandlerRegistration reg2 = Event.addNativePreviewHandler(handler2);
HandlerRegistration reg3 = Event.addNativePreviewHandler(handler3);
DOM.addEventPreview(preview1);
assertTrue(DOM.previewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
handler2.assertIsFired(true);
handler3.assertIsFired(true);
preview0.assertIsFired(false);
preview1.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
reg2.removeHandler();
reg3.removeHandler();
DOM.removeEventPreview(preview0);
DOM.removeEventPreview(preview1);
}
/**
* Test removal of a {@link NativePreviewHandler} works.
*/
public void testFireNativePreviewEventRemoval() {
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(false,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
reg1.removeHandler();
assertTrue(Event.fireNativePreviewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(false);
reg0.removeHandler();
}
/**
* Test that {@link Event#fireNativePreviewEvent(NativeEvent)} returns the
* correct value if the native event is not canceled.
*/
public void testFireNativePreviewEventWithoutCancel() {
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(false,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
assertTrue(Event.fireNativePreviewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
}
/**
* Test that {@link Event#fireNativePreviewEvent(NativeEvent)} returns the
* correct value if no handlers are present.
*/
public void testFireNativePreviewEventWithoutHandlers() {
assertTrue(Event.fireNativePreviewEvent(null));
}
/**
* Test that legacy EventPreview and NativePreviewHandlers can both cancel the
* event.
*/
@Deprecated
public void testLegacyEventPreviewCancelByBoth() {
// Add handlers
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(true,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
// Add legacy EventPreview
TestEventPreview preview = new TestEventPreview(true);
DOM.addEventPreview(preview);
// Fire the event
assertFalse(DOM.previewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
preview.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
DOM.removeEventPreview(preview);
}
/**
* Test that legacy EventPreview can cancel the event.
*/
@Deprecated
public void testLegacyEventPreviewCancelByEventPreview() {
// Add handlers
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(false,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
// Add legacy EventPreview
TestEventPreview preview = new TestEventPreview(true);
DOM.addEventPreview(preview);
// Fire the event
assertFalse(DOM.previewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
preview.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
DOM.removeEventPreview(preview);
}
/**
* Test that legacy EventPreview still fires after the NativeHandler cancels
* the event.
*/
@Deprecated
public void testLegacyEventPreviewCancelByHandler() {
// Add handlers
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(true,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
// Add legacy EventPreview
TestEventPreview preview = new TestEventPreview(false);
DOM.addEventPreview(preview);
// Fire the event
assertFalse(DOM.previewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
preview.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
DOM.removeEventPreview(preview);
}
/**
* Test that legacy EventPreview still fires after the NativeHandlers without
* canceling the event.
*/
@Deprecated
public void testLegacyEventPreviewWithoutCancel() {
// Add handlers
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(false,
false);
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(false,
false);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
// Add legacy EventPreview
TestEventPreview preview = new TestEventPreview(false);
DOM.addEventPreview(preview);
// Fire the event
assertTrue(DOM.previewEvent(null));
handler0.assertIsFired(true);
handler1.assertIsFired(true);
preview.assertIsFired(true);
reg0.removeHandler();
reg1.removeHandler();
DOM.removeEventPreview(preview);
}
/**
* Test the accessors in {@link NativePreviewEvent}.
*/
public void testNativePreviewEventAccessors() {
// cancelNativeEvent
{
NativePreviewEvent event = new NativePreviewEvent();
assertFalse(event.isCanceled());
event.cancel();
assertTrue(event.isCanceled());
}
// preventCancelNativeEvent
{
NativePreviewEvent event = new NativePreviewEvent();
assertFalse(event.isConsumed());
event.consume();
assertTrue(event.isConsumed());
}
// revive
{
NativePreviewEvent event = new NativePreviewEvent();
event.cancel();
event.consume();
assertTrue(event.isCanceled());
assertTrue(event.isConsumed());
event.revive();
assertFalse(event.isCanceled());
assertFalse(event.isConsumed());
}
}
/**
* Test that the singleton instance of {@link NativePreviewEvent} is revived
* correctly.
*/
public void testReviveNativePreviewEvent() {
// Fire the event and cancel it
TestNativePreviewHandler handler0 = new TestNativePreviewHandler(true, true);
HandlerRegistration reg0 = Event.addNativePreviewHandler(handler0);
Event.fireNativePreviewEvent(null);
handler0.assertIsFired(true);
reg0.removeHandler();
// Fire the event again, but don't cancel it
TestNativePreviewHandler handler1 = new TestNativePreviewHandler(false,
false) {
@Override
public void onPreviewNativeEvent(NativePreviewEvent event) {
assertFalse(event.isCanceled());
assertFalse(event.isConsumed());
assertTrue(event.isFirstHandler());
super.onPreviewNativeEvent(event);
}
};
HandlerRegistration reg1 = Event.addNativePreviewHandler(handler1);
assertTrue(Event.fireNativePreviewEvent(null));
handler1.assertIsFired(true);
reg1.removeHandler();
}
private native boolean isInternetExplorer() /*-{
return navigator.userAgent.toLowerCase().indexOf("msie") != -1;
}-*/;
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
ac74f804fdb2923d060ef6cc79b00a068f4027d3 | 859fa294bb1a8e2ad97363ab208a967dceeefe00 | /api/src/main/java/exceptions/UniqueIdentifierException.java | 05da7f6449ad56a7fd679a0b76024a5c5cc87374 | [
"MIT"
] | permissive | mainzed/labelingsystem-server | 52521944c562d8f7aedc6c5cb1c864ccf5df945f | c73ca9c22fd8efecca3f7d188d15bcd50fc64e00 | refs/heads/master | 2023-04-10T16:04:07.643126 | 2021-05-06T00:06:23 | 2021-05-06T00:06:23 | 65,379,362 | 4 | 1 | MIT | 2022-09-01T22:28:40 | 2016-08-10T12:06:31 | Java | UTF-8 | Java | false | false | 514 | java | package exceptions;
/**
* EXCEPTION for UUIDs
*
* @author Florian Thiery M.Sc.
* @author i3mainz - Institute for Spatial Information and Surveying Technology
* @version 05.02.2015
*/
public class UniqueIdentifierException extends Exception {
/**
* EXCEPTION for UUIDs
* @param message
*/
public UniqueIdentifierException(String message) {
super(message);
}
/**
* EXCEPTION for UUIDs
*/
public UniqueIdentifierException() {
super();
}
}
| [
"web@florian-thiery.de"
] | web@florian-thiery.de |
7f7b2e29aae0227e914228310828108c4199fcc2 | b49d1dbc5240fe3ca2a53589deb88a4975b585f4 | /src/main/java/homework/v3/HomeWork.java | c4d65e6e1f512774e2b804481cda9b173b4504b9 | [] | no_license | Alexander-Orekhov/serialize-study-util | 48346017ab76c00108b730df71d58c05b7bdbb72 | d5e8ba2b6ec95573702db8e98f05e58545684d0d | refs/heads/master | 2023-06-12T10:17:43.036798 | 2021-07-07T13:51:06 | 2021-07-07T13:51:06 | 382,568,549 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,896 | java | package homework.v3;
/**
* Задание
* 1) Составить файл с JSON-объектом, который "разложен" в пакете homework.v3.classwork.entity.
* Определить какой элемент является корневым
* Дать имя файлу homework.parameters.json
* Сделать файл с минимум пятью элементами
* 2) Заполнить его значениями (как пример "parameters.v1.json")
* 3) Считать получившийся homework.parameters.json в память
* 4) Сериализовать его с помощью встроенного механиза сериализации в файл с именем homework.parameters.ser
* 5) Сериализовать его с использованием интерфейса Externalizable в файл с именем homework.parameters.exter
* 6) Считать данные из файла homework.parameters.ser в память и сохранить в формате JSON в файл с именем homework.result.ser.parameters.json
* 7) Считать данные из файла homework.parameters.exter в память и сохранить в формате JSON в файл с именем homework.result.exter.parameters.json
* 8) Убедиться, что файлы homework.result.ser.parameters.json и homework.result.exter.parameters.json
* совпадают с homework.parameters.json
* 9) Составленную в п.1 сущность представить в виде xsd-схемы и
* выполнить генерацию классов аналогично классам из пакета classwork.entity.jaxb
* * можно сделать и с json-схемой, пренципиально механизм не поменяется.
* */
public class HomeWork {
}
| [
"100HzJugin@gmail.com"
] | 100HzJugin@gmail.com |
96181c1ef5e01ba182b6f6c1466ade720d336c05 | e0faf4764025e002aafafa8c71f04bea8595cbc9 | /ArryStudent.java | fccab73d21a685efb141e99255cc1d46c43cf0dc | [] | no_license | kkchaudhary11/SimplePrograms | 8fa685b101f9ba473bd1d0e115f1ffebb089e6b8 | e9ed2d128e094b84ef0b210bf6fdc69e8b2d8128 | refs/heads/master | 2021-01-19T06:29:19.308426 | 2017-04-17T09:42:26 | 2017-04-17T09:42:26 | 87,465,109 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,732 | java | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by Kamal Kant on 03-04-2017.
*/
public class ArryStudent {
String[][] students = new String[10][10];
public void getArray() {
Scanner scanner = new Scanner(System.in);
//initialize name of students
students[0][0] = "ram";
students[0][1] = "shyam";
students[0][2] = "hussen";
students[0][3] = "pawan";
students[0][4] = "rashmi";
students[0][5] = "swati";
students[0][6] = "aditya";
students[0][7] = "pallivi";
students[0][8] = "harris";
students[0][9] = "peter";
//initialize marks
for (int i = 0; i < students.length; i++) {
System.out.print(i + 1 + ". Enter marks for " + students[0][i] + " : ");
students[1][i] = scanner.next();
}
}
public void display() {
int highest = 0;
String name;
//compare marks
for (int i = 0; i < students.length; i++) {
String mark = students[1][i];
if (Integer.parseInt(mark) > highest) {
highest = Integer.parseInt(mark);
}
}
//find students with highest marks
for (int i = 0; i < students.length; i++) {
String mark = students[1][i];
if (Integer.parseInt(mark) == highest) {
name = students[0][i];
System.out.println("Highest Scorer : " + name);
}
}
}
public static void main(String[] args) {
ArryStudent arrySort = new ArryStudent();
arrySort.getArray();
arrySort.display();
}
}
| [
"kkchaudhary11@gmail.com"
] | kkchaudhary11@gmail.com |
bcc7c9e55f7ae959b4d19c34bab92037ecb53298 | f0516e7ead693d34cc2d6ba0dc8b75629c3c0cf2 | /Android/AxModel/src/com/futureconcepts/ax/model/data/ISO3166.java | f0934f38df53640811032ec3b3aac33645c90213 | [] | no_license | radtek/mobile | 453a26bbdd20c05706a132aa2753e3d4e1cb1eef | 14a1c29a0ed76302dbb481ab65cb26e9d73ec8ca | refs/heads/master | 2022-01-07T04:35:20.305749 | 2019-05-14T00:36:06 | 2019-05-14T00:36:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,560 | java | package com.futureconcepts.ax.model.data;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
//import android.util.Log;
public class ISO3166 extends BaseTable
{
public static final String CODE = "Code";
public static final String NAME = "Name";
public static final String IDD = "IDD";
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/ISO3166");
/**
* The MIME type of {@link #CONTENT_URI} providing a directory of notes.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.futureconcepts.ISO3166";
/**
* The MIME type of a {@link #CONTENT_URI} sub-directory of a single note.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.futureconcepts.ISO3166";
public ISO3166(Context context, Cursor cursor)
{
super(context, cursor);
}
@Override
public void close()
{
super.close();
}
@Override
public Uri getContentUri()
{
return CONTENT_URI;
}
public String getName()
{
return getModelString(NAME);
}
public static ISO3166 query(Context context, Uri uri)
{
ISO3166 result = null;
try
{
result = new ISO3166(context, context.getContentResolver().query(uri, null, null, null, null));
if (result.getCount() == 1)
{
result.moveToFirst();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
}
| [
"dave.arnold@cascade.org"
] | dave.arnold@cascade.org |
89a031b749ab5eba8a1390f8aee76aef1a30f455 | 59eb0b3599197023c3f1832114932fc5d6536dfd | /MSsdk/src/main/java/com/eetrust/http/XMLBuildUtils.java | df2b237bdeb3245bcff5c669f99606bc40fef04f | [] | no_license | chenmeng91/DocSecritySDkProduct | c316e78f0ee03f0dda9d6a0d5f4f5f00f8cbcc9a | 4a525c5ffb82282c0397300018f907c0429d7c74 | refs/heads/master | 2021-08-09T15:36:34.433430 | 2017-11-12T08:18:25 | 2017-11-12T08:18:25 | 110,415,885 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,682 | java | package com.eetrust.http;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.util.Xml;
import com.eetrust.bean.DeptBean;
import com.eetrust.bean.IssueGrantXMLBean;
import com.eetrust.bean.UserBean;
import com.eetrust.bean.UserLog;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
/**
* Created by sunh on 16-10-31.
*/
public class XMLBuildUtils {
public static String buildDocIssueXMLString(Context context, IssueGrantXMLBean xmlBean) throws Exception {
if (HttpUrl.loginName == null) {
String loginNameSP = getLoginNameSP(context);
if (loginNameSP != null && !loginNameSP.equals("")) {
HttpUrl.loginName = loginNameSP;
}
}
String count = null;
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer);
// 相当于写入<?xml version="1.0" encoding="UTF-8"?>
serializer.startDocument("utf-8", true);
//写入跟元素的起始标签
serializer.startTag(null, "archivesInfo");
serializer.startTag(null, "docissue");
serializer.startTag(null, "archives");
setTag("identifier", xmlBean.getIdentifier(), serializer);
setTag("name", xmlBean.getName(), serializer);
setTag("createuser", HttpUrl.loginName, serializer);
setTag("confidential", HttpFields.ARCHIVES_CONFIDENTIAL, serializer);
setTag("archivesFrom", HttpFields.ARCHIVES_FROM, serializer);
setTag("IsCreateCryptKey", HttpFields.ARCHIVES_IS_CREATE_CRYPT_KEY, serializer);
serializer.endTag(null, "archives");
serializer.startTag(null, "docs");
serializer.startTag(null, "doc");
setTag("identifier", xmlBean.getIdentifier(), serializer);
setTag("name", xmlBean.getName(), serializer);
setTag("retVersion","true",serializer);
serializer.endTag(null, "doc");
serializer.endTag(null, "docs");
serializer.endTag(null, "docissue");
//写入跟元素的结束标签
serializer.endTag(null, "archivesInfo");
//结束文档的写入
serializer.endDocument();
count = writer.toString();
writer.flush();
writer.close();
Log.d("docIssue--->", count);
return count;
}
public static String buildRightGrantXMLString(Context context, String archiveId, List<UserBean> userBeens, final List<DeptBean> deptBeens) throws IOException {
if (HttpUrl.loginName == null) {
String loginNameSP = getLoginNameSP(context);
if (loginNameSP != null && !loginNameSP.equals("")) {
HttpUrl.loginName = loginNameSP;
}
}
String count = null;
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer);
serializer.startDocument("utf-8", true);
serializer.startTag(null, "rights");
serializer.startTag(null, "grantuser");
setTag("loginname", HttpUrl.loginName, serializer);
serializer.endTag(null, "grantuser");
serializer.startTag(null, "archives");
setTag("id", archiveId + "", serializer);
serializer.endTag(null, "archives");
if(deptBeens!=null&&deptBeens.size()>0){
serializer.startTag(null, "depts");
for (DeptBean deptBean: deptBeens){
serializer.startTag(null, "dept");
setTag("id", deptBean.getOuterid(), serializer);
setTag("rights", deptBean.getRights(), serializer);
serializer.endTag(null, "dept");
}
serializer.endTag(null, "depts");
}
if(userBeens!=null&&userBeens.size()>0){
serializer.startTag(null, "users");
for(UserBean userBean:userBeens){
serializer.startTag(null, "user");
// setTag("loginname", userBean.getIdentifier(), serializer);
setTag("id", userBean.getIdentifier(), serializer);
setTag("rights",userBean.getRights(), serializer);
serializer.endTag(null, "user");
}
serializer.endTag(null, "users");
}
serializer.endTag(null, "rights");
serializer.endDocument();
count = writer.toString();
writer.flush();
writer.close();
Log.d("Log_Send--->", count);
return count;
}
private static void setTag(String tagName, String tagText, XmlSerializer serializer) throws IOException {
serializer.startTag(null, tagName);
serializer.text(tagText);
serializer.endTag(null, tagName);
}
/**
* 获取SP保存的loginName
*
* @param context 传进来的上下文
* @return 服务器地址
*/
private static String getLoginNameSP(Context context) {
//获取当前context的SP
SharedPreferences sp = context.getSharedPreferences(HttpFields.SDS_SP_NAME, Context.MODE_PRIVATE);
//根据key获取value
return sp.getString(HttpFields.SDS_LOGIN_NAME, "");
}
public static String buildLogSendXMLString(List<UserLog> userLogs) throws Exception {
String count = null;
StringWriter writer = new StringWriter();
XmlSerializer serializer = Xml.newSerializer();
serializer.setOutput(writer);
serializer.startDocument("utf-8", true);
serializer.startTag(null, "userLogs");
for (UserLog userLog:userLogs){
serializer.startTag(null, "doc");
setTag("archivesID", userLog.getArchivesID() + "", serializer);
setTag("docID", userLog.getDocID() + "", serializer);
setTag("oper", userLog.getOper() + "", serializer);
setTag("online", userLog.getOnline() + "", serializer);
setTag("result", userLog.getResult() + "", serializer);
if(!"1".equals(userLog.getResult()+"")){//成功后没有这个节点
setTag("memo", userLog.getMemo() + "", serializer);
}
setTag("clientIP", userLog.getClientIP() + "", serializer);
setTag("opertime", userLog.getOpertime() + "", serializer);
serializer.endTag(null, "doc");
}
serializer.endTag(null, "userLogs");
serializer.endDocument();
count = writer.toString();
writer.flush();
writer.close();
Log.d("Log_Send--->", count);
return count;
}
}
| [
"2550661451@qq.com"
] | 2550661451@qq.com |
e73b05520f45fa26ea1d9cfb35194dc7003a8657 | 09572e2cb6203a40ee2e49e66f78c0b16fc4043e | /app/src/main/java/com/myxh/leetcode/math/L9_PalindromeNumber.java | bf2d2253cf69e5b7abd59dc036ac2c817f349c29 | [
"MIT"
] | permissive | myxh/LeetCode-Practice | db4b5fa68f8320918a56c06158e7b2353db0010c | 02a6744961e0bd0b60b01d2271f9eb3997933170 | refs/heads/master | 2020-05-17T23:17:53.949967 | 2019-09-05T07:11:26 | 2019-09-05T07:11:26 | 184,027,545 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,243 | java | package com.myxh.leetcode.math;
/**
* Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
*
* Example 1:
*
* Input: 121
* Output: true
* Example 2:
*
* Input: -121
* Output: false
* Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
* Example 3:
*
* Input: 10
* Output: false
* Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
* Follow up:
*
* Could you solve it without converting the integer to a string?
*/
public class L9_PalindromeNumber {
public static void main(String[] args) {
}
/**
*
* Runtime: 6 ms, faster than 100.00% of Java online submissions for Roman to Integer.
* Memory Usage: 34.7 MB, less than 100.00% of Java online submissions for Roman to Integer.
*/
public static boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int result = 0;
int tmp = x;
while (tmp > 0) {
result = result * 10 + tmp % 10;
tmp = tmp / 10;
}
if (result == x) {
return true;
}
return false;
}
}
| [
"myxhchen@gmail.com"
] | myxhchen@gmail.com |
13f6361c89fe3afc0ad09651be84fa94f0bd5cca | b31120cefe3991a960833a21ed54d4e10770bc53 | /modules/org.clang.analysis/src/org/clang/analysis/analyses/threadSafety/til/Future.java | 80540393a33d00c76d9fc3785aa45fcacfdd3e1e | [] | no_license | JianpingZeng/clank | 94581710bd89caffcdba6ecb502e4fdb0098caaa | bcdf3389cd57185995f9ee9c101a4dfd97145442 | refs/heads/master | 2020-11-30T05:36:06.401287 | 2017-10-26T14:15:27 | 2017-10-26T14:15:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,468 | java | /**
* This file was converted to Java from the original LLVM source file. The original
* source file follows the LLVM Release License, outlined below.
*
* ==============================================================================
* LLVM Release License
* ==============================================================================
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2003-2017 University of Illinois at Urbana-Champaign.
* All rights reserved.
*
* Developed by:
*
* LLVM Team
*
* University of Illinois at Urbana-Champaign
*
* http://llvm.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal with
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of the LLVM Team, University of Illinois at
* Urbana-Champaign, nor the names of its contributors may be used to
* endorse or promote products derived from this Software without specific
* prior written permission.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE
* SOFTWARE.
*
* ==============================================================================
* Copyrights and Licenses for Third Party Software Distributed with LLVM:
* ==============================================================================
* The LLVM software contains code written by third parties. Such software will
* have its own individual LICENSE.TXT file in the directory in which it appears.
* This file will describe the copyrights, license, and restrictions which apply
* to that code.
*
* The disclaimer of warranty in the University of Illinois Open Source License
* applies to all code in the LLVM Distribution, and nothing in any of the
* other licenses gives permission to use the names of the LLVM Team or the
* University of Illinois to endorse or promote products derived from this
* Software.
*
* The following pieces of software have additional or alternate copyrights,
* licenses, and/or restrictions:
*
* Program Directory
* ------- ---------
* Autoconf llvm/autoconf
* llvm/projects/ModuleMaker/autoconf
* Google Test llvm/utils/unittest/googletest
* OpenBSD regex llvm/lib/Support/{reg*, COPYRIGHT.regex}
* pyyaml tests llvm/test/YAMLParser/{*.data, LICENSE.TXT}
* ARM contributions llvm/lib/Target/ARM/LICENSE.TXT
* md5 contributions llvm/lib/Support/MD5.cpp llvm/include/llvm/Support/MD5.h
*/
package org.clang.analysis.analyses.threadSafety.til;
import org.clank.support.*;
import org.clang.analysis.analyses.threadSafety.til.*;
/// Placeholder for an expression that has not yet been created.
/// Used to implement lazy copy and rewriting strategies.
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 414,
FQN="clang::threadSafety::til::Future", NM="_ZN5clang12threadSafety3til6FutureE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6FutureE")
//</editor-fold>
public class Future extends /*public*/ SExpr implements Destructors.ClassWithDestructor {
/*public:*/
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::classof">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 416,
FQN="clang::threadSafety::til::Future::classof", NM="_ZN5clang12threadSafety3til6Future7classofEPKNS1_5SExprE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6Future7classofEPKNS1_5SExprE")
//</editor-fold>
public static boolean classof(/*const*/ SExpr /*P*/ E) {
return E.opcode() == TIL_Opcode.COP_Future;
}
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::FutureStatus">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 418,
FQN="clang::threadSafety::til::Future::FutureStatus", NM="_ZN5clang12threadSafety3til6Future12FutureStatusE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6Future12FutureStatusE")
//</editor-fold>
public enum FutureStatus implements Native.ComparableLower {
FS_pending(0),
FS_evaluating(FS_pending.getValue() + 1),
FS_done(FS_evaluating.getValue() + 1);
//<editor-fold defaultstate="collapsed" desc="hidden">
public static FutureStatus valueOf(int val) {
FutureStatus out = (val < 0) ? Values._VALUES[-val] : Values.VALUES[val];
assert out != null : "no value for " + val;
assert out.value == val : "asked [" + val + "] got " + out + ":" + out.value + "]";
return out;
}
private static final class Values {
private static final FutureStatus[] VALUES;
private static final FutureStatus[] _VALUES; // [0] not used
static {
int max = 0;
int min = 0;
for (FutureStatus kind : FutureStatus.values()) {
if (kind.value > max) { max = kind.value; }
if (kind.value < min) { min = kind.value; }
}
_VALUES = new FutureStatus[min < 0 ? (1-min) : 0];
VALUES = new FutureStatus[max >= 0 ? (1+max) : 0];
for (FutureStatus kind : FutureStatus.values()) {
if (kind.value < 0) {
if (_VALUES[-kind.value] == null) {
_VALUES[-kind.value] = kind;
} else {
assert true: "Must not replace " + _VALUES[-kind.value] + " by " + kind + ". Switch to int-based enum or filter valid.";
}
} else {
if (VALUES[kind.value] == null) {
VALUES[kind.value] = kind;
} else {
assert true: "Must not replace " + VALUES[kind.value] + " by " + kind + ". Switch to int-based enum or filter valid.";
}
}
}
}
}
private final /*uint*/int value;
private FutureStatus(int val) { this.value = (/*uint*/int)val;}
public /*uint*/int getValue() { return value;}
@Override public boolean $less(Object obj) { return Unsigned.$less_uint(value, ((FutureStatus)obj).value);}
@Override public boolean $lesseq(Object obj) { return Unsigned.$lesseq_uint(value, ((FutureStatus)obj).value);}
//</editor-fold>
};
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::Future">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 424,
FQN="clang::threadSafety::til::Future::Future", NM="_ZN5clang12threadSafety3til6FutureC1Ev",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6FutureC1Ev")
//</editor-fold>
public Future() {
// : SExpr(COP_Future), Status(FS_pending), Result(null)
//START JInit
super(TIL_Opcode.COP_Future);
this.Status = FutureStatus.FS_pending;
this.Result = null;
//END JInit
}
/*private:*/
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::~Future">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 427,
FQN="clang::threadSafety::til::Future::~Future", NM="_ZN5clang12threadSafety3til6FutureD0Ev",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6FutureD0Ev")
//</editor-fold>
public/*private*/ /*virtual*/ void $destroy() { throw new UnsupportedOperationException("Deleted");}
/*public:*/
// A lazy rewriting strategy should subclass Future and override this method.
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::compute">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 431,
FQN="clang::threadSafety::til::Future::compute", NM="_ZN5clang12threadSafety3til6Future7computeEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6Future7computeEv")
//</editor-fold>
public /*virtual*/ SExpr /*P*/ compute() {
return null;
}
// Return the result of this future if it exists, otherwise return null.
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::maybeGetResult">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 434,
FQN="clang::threadSafety::til::Future::maybeGetResult", NM="_ZNK5clang12threadSafety3til6Future14maybeGetResultEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZNK5clang12threadSafety3til6Future14maybeGetResultEv")
//</editor-fold>
public SExpr /*P*/ maybeGetResult() /*const*/ {
return Result;
}
// Return the result of this future; forcing it if necessary.
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::result">
@Converted(kind = Converted.Kind.MANUAL_COMPILATION,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 439,
FQN="clang::threadSafety::til::Future::result", NM="_ZN5clang12threadSafety3til6Future6resultEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6Future6resultEv")
//</editor-fold>
public SExpr /*P*/ result() {
switch (Status) {
case FS_pending:
return force();
case FS_evaluating:
return null; // infinite loop; illegal recursion.
case FS_done:
default:
return Result;
}
}
/*template <class V> TEMPLATE*/
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::traverse">
@Converted(kind = Converted.Kind.MANUAL_SEMANTIC,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 451,
FQN="clang::threadSafety::til::Future::traverse", NM="Tpl__ZN5clang12threadSafety3til6Future8traverseERT_NS3_5R_CtxE",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=Tpl__ZN5clang12threadSafety3til6Future8traverseERT_NS3_5R_CtxE")
//</editor-fold>
public </*class*/ V extends VisitReducer> boolean/*V.R_SExpr*/ traverse(final V /*&*/ Vs, SimpleReducerBase.TraversalKind/*V.R_Ctx*/ Ctx) {
assert ((Result != null)) : "Cannot traverse Future that has not been forced.";
return Vs.traverse(Result, Ctx);
}
/*template <class C> TEMPLATE*/
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::compare">
@Converted(kind = Converted.Kind.MANUAL_SEMANTIC,
source = "${LLVM_SRC}/llvm/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h", line = 457,
FQN="clang::threadSafety::til::Future::compare", NM="Tpl__ZNK5clang12threadSafety3til6Future7compareEPKS2_RT_",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=Tpl__ZNK5clang12threadSafety3til6Future7compareEPKS2_RT_")
//</editor-fold>
public </*class*/ C extends Comparator<?>> boolean/*C.CType*/ compare(/*const*/ Future /*P*/ E, final C /*&*/ Cmp) /*const*/ {
if (!(Result != null) || !(E.Result != null)) {
return Cmp.comparePointers(this, E);
}
return Cmp.compare(Result, E.Result);
}
/*private:*/
//<editor-fold defaultstate="collapsed" desc="clang::threadSafety::til::Future::force">
@Converted(kind = Converted.Kind.AUTO,
source = "${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp", line = 48,
FQN="clang::threadSafety::til::Future::force", NM="_ZN5clang12threadSafety3til6Future5forceEv",
cmd="jclank.sh -java-options=${SPUTNIK}/modules/org.clang.analysis/llvmToClangType ${LLVM_SRC}/llvm/tools/clang/lib/Analysis/ThreadSafetyTIL.cpp -nm=_ZN5clang12threadSafety3til6Future5forceEv")
//</editor-fold>
private SExpr /*P*/ force() {
Status = FutureStatus.FS_evaluating;
Result = compute();
Status = FutureStatus.FS_done;
return Result;
}
private FutureStatus Status;
private SExpr /*P*/ Result;
@Override public String toString() {
return "" + "Status=" + Status // NOI18N
+ ", Result=" + Result // NOI18N
+ super.toString(); // NOI18N
}
}
| [
"voskresensky.vladimir@gmail.com"
] | voskresensky.vladimir@gmail.com |
4258fcae9ddd2e099968ec4919676bb1468a4245 | 0e1353ecdebfe678ad8a69610c2e509e44b9c920 | /src/test/java/rest/RenameMeResourceTest.java | a7d1bc86ed4200e25dc37a47b7d51e7a47a41f7d | [] | no_license | 1337k1ng/Eksamensprojekt | 3601b651fbe0d1b318d816e0316ad32670218a52 | fed29bb8f0d143ea65c7dc3e943692975aeaaed4 | refs/heads/master | 2023-02-20T23:14:47.368760 | 2021-01-23T20:14:28 | 2021-01-23T20:14:28 | 332,295,042 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,873 | java | package rest;
import entities.RenameMe;
import entities.Role;
import entities.User;
import utils.EMF_Creator;
import io.restassured.RestAssured;
import static io.restassured.RestAssured.given;
import io.restassured.http.ContentType;
import io.restassured.parsing.Parser;
import java.net.URI;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import static org.hamcrest.Matchers.equalTo;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
//Uncomment the line below, to temporarily disable this test
//@Disabled
public class RenameMeResourceTest {
private static final int SERVER_PORT = 7777;
private static final String SERVER_URL = "http://localhost/jpareststarter/api";
private static RenameMe r1, r2;
static final URI BASE_URI = UriBuilder.fromUri(SERVER_URL).port(SERVER_PORT).build();
private static HttpServer httpServer;
private static EntityManagerFactory emf;
static HttpServer startServer() {
ResourceConfig rc = ResourceConfig.forApplication(new ApplicationConfig());
return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, rc);
}
@BeforeAll
public static void setUpClass() {
//This method must be called before you request the EntityManagerFactory
EMF_Creator.startREST_TestWithDB();
emf = EMF_Creator.createEntityManagerFactoryForTest();
httpServer = startServer();
//Setup RestAssured
RestAssured.baseURI = SERVER_URL;
RestAssured.port = SERVER_PORT;
RestAssured.defaultParser = Parser.JSON;
}
@AfterAll
public static void closeTestServer() {
//System.in.read();
//Don't forget this, if you called its counterpart in @BeforeAll
EMF_Creator.endREST_TestWithDB();
httpServer.shutdownNow();
}
// Setup the DataBase (used by the test-server and this test) in a known state BEFORE EACH TEST
//TODO -- Make sure to change the EntityClass used below to use YOUR OWN (renamed) Entity class
@BeforeEach
public void setUp() {
EntityManager em = emf.createEntityManager();
r1 = new RenameMe("Some txt", "More text");
r2 = new RenameMe("aaa", "bbb");
try {
em.getTransaction().begin();
em.createNamedQuery("RenameMe.deleteAllRows").executeUpdate();
em.persist(r1);
em.persist(r2);
em.getTransaction().commit();
em.getTransaction().begin();
//Delete existing users and roles to get a "fresh" database
em.createQuery("delete from User").executeUpdate();
em.createQuery("delete from Role").executeUpdate();
Role userRole = new Role("user");
Role adminRole = new Role("admin");
User user = new User("user", "test");
user.addRole(userRole);
User admin = new User("admin", "test");
admin.addRole(adminRole);
User both = new User("user_admin", "test");
both.addRole(userRole);
both.addRole(adminRole);
em.persist(userRole);
em.persist(adminRole);
em.persist(user);
em.persist(admin);
em.persist(both);
//System.out.println("Saved test data to database");
em.getTransaction().commit();
} finally {
em.close();
}
}
//This is how we hold on to the token after login, similar to that a client must store the token somewhere
private static String securityToken;
//Utility method to login and set the returned securityToken
private static void login(String role, String password) {
String json = String.format("{username: \"%s\", password: \"%s\"}", role, password);
securityToken = given()
.contentType("application/json")
.body(json)
//.when().post("/api/login")
.when().post("/login")
.then()
.extract().path("token");
//System.out.println("TOKEN ---> " + securityToken);
}
@Test
public void testServerIsUp() {
given().when().get("/info").then().statusCode(200);
}
//This test assumes the database contains two rows
@Test
@Disabled
public void testDummyMsg() throws Exception {
given()
.contentType("application/json")
.get("/xxx/").then()
.assertThat()
.statusCode(HttpStatus.OK_200.getStatusCode())
.body("msg", equalTo("Hello World"));
}
@Test
@Disabled
public void testCount() throws Exception {
given()
.contentType("application/json")
.get("/xxx/count").then()
.assertThat()
.statusCode(HttpStatus.OK_200.getStatusCode())
.body("count", equalTo(2));
}
@Test
public void testFilms() throws Exception {
login("user_admin", "test");
given()
.contentType("application/json")
.accept(ContentType.JSON)
.header("x-access-token", securityToken)
.when()
.get("/info/filmsparallel").then()
.assertThat()
.statusCode(HttpStatus.OK_200.getStatusCode())
.body("title", equalTo("A New Hope"));
}
}
| [
"Madsjohanbech@live.dk"
] | Madsjohanbech@live.dk |
64019442ae9670a3814f6a432e663632da6cebba | 0b9ecdc9825b6abbe1af7f6746f31df34a6334f7 | /Project_1/src/edu/nyu/cs/pjm419/FindWords.java | c4ad936e8beae513ae2804d2c7887d3e1d951727 | [] | no_license | petermountanos/data-structures | 620174df27fb569c6789feae42eb609f6c10ac89 | 6abf6ba8424c53d0f3c20f0909225ff50b3ce96d | refs/heads/master | 2021-01-10T05:32:18.593234 | 2015-11-20T03:04:47 | 2015-11-20T03:04:47 | 46,535,582 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,502 | java | package edu.nyu.cs.pjm419;
import java.io.*;
import java.util.*;
/**
* Class which provides a user interface for the FindWords program.
* The program needs to be called with a single command line argument
* that contains the filename of a dictionary to be used for the program.
*
* The user is then prompted for a set of letters, and the program produces
* all of the possible words that can be created from those letters, which
* also are present in the dictionary.
*
* Note: The extra credit *has* been implemented
*
* @author Peter Mountanos (pjm419)
* @version September 29, 2014
*/
public class FindWords {
/**
* Main Method for FindWords. It is responsible for the
* execution of the entire program.
*
* @param args an array containing command line arguments
* the program expects one command line argument,
* which contains the name of the file of the dict-
* ionary to be used.
*/
public static void main(String[] args) {
// validate command-line argument
if (args.length < 1){
System.err.printf("Error:\t invalid number of arguments\n"
+ "Usage:\t FindWords <dictionaryFileName>\n\n");
System.exit(1);
}
else if (!new File(args[0]).exists()){
System.err.printf("Error:\t the filename given as command line input could not be found\n\n");
System.exit(1);
}
// instantiate file object
File dictFile = new File(args[0]);
// instantiate DictionaryList object to store vocabulary based on dictFile input
DictionaryList wordDict = new DictionaryList(dictFile);
// only run program if there's a dictionary with stuff in it
if (wordDict.size() > 0){
// instantiate SetOfLetters object to store user input string
SetOfLetters letterSet = new SetOfLetters(getUserInput(), wordDict);
// print sorted list of permutations to console
letterSet.printPermutations();
}
else {
System.err.println("<"+dictFile+"> is an empty dictionary. Try again with a useful dictionary.");
System.exit(1);
}
}
/**
* Function that obtains string of letters from user input.
*
* This function has certain preconditions. The string given
* by the user must contain only letters, and it must be in the
* range [2,10]. If these preconditions don't hold true, it will
* print a message to the user and exit.
*
* @return string representing lower case letters to be permuted
*/
public static String getUserInput(){
// get user input
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a string of 2-10 characters (letters only, no spaces, commas, or any other characters).");
String letters = scan.nextLine();
scan.close();
// validate user input
if (letters.length() < 2 || letters.length() > 10){
System.err.printf("Error: \"%s\" has incorrect number of letters\n\n", letters);
System.exit(1);
}
if (!isLetters(letters)){
System.err.printf("Error: \"%s\" is not filled with only letters\n\n", letters);
System.exit(1);
}
// return String meeting postcondition
return letters.toLowerCase();
}
/**
* Helper method to determine if a string contains only
* letters.
* @param s string to be analyzed
* @return true if string contains only letters, false otherwise
*/
public static boolean isLetters(String s){
char[] charLetters = s.toCharArray();
// validate each char is a letter
for (char ch: charLetters){
if (!Character.isLetter(ch)){
return false;
}
}
return true;
}
}
| [
"peter.mountanos@nyu.edu"
] | peter.mountanos@nyu.edu |
3f0f766417a0002d0be1f7b793031c495a03ac4c | dad731890d1c6ebdbd7342c8560b7b86ceae017e | /Atividade Herança e Polimorfismo/src/Calculador.java | 2cd1c678552a3de55f5c5f0840030a131736f384 | [] | no_license | aafavelino/Projetos_LP2 | 218d7da2b265fb6973caa4b74bad2a5af3433ff9 | 9796fdd4be1f89302609c74a107739443c24da06 | refs/heads/master | 2020-05-21T19:10:03.511793 | 2016-10-27T14:28:29 | 2016-10-27T14:28:29 | 64,983,960 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 567 | java |
public class Calculador {
public static void main(String[] args) {
// TODO Auto-generated method stub
Quadrado quadrado1 = new Quadrado(3.0,3.0);
Quadrado quadrado2 = new Quadrado(10.0,10.0);
Retangulo retangulo1 = new Retangulo(2.0, 7.0);
Retangulo retangulo2 = new Retangulo(5.0, 3.0);
Figura [] figuras = new Figura[4];
figuras[0] = quadrado1;
figuras[1] = quadrado2;
figuras[2] = retangulo1;
figuras[3] = retangulo2;
FiguraComplexa figura_complexa = new FiguraComplexa(figuras);
System.out.println(figura_complexa.calculaArea());
}
}
| [
"adelino-afonso@hotmail.com"
] | adelino-afonso@hotmail.com |
c81d6b52873e870eb537fc84c1a74869e2ca1c65 | be9c963364914fb73bf2ab8e18095f653ad9a77f | /src/main/java/com/seye/analysis/cpp/struct/RelationShipData.java | 98ae0f36dda23be9908a4e1c3691123ad83845a8 | [] | no_license | gitHubwhl562916378/analysis | 167d45f5e2ca2bd58bc1d8dff6edac14e302d1e6 | 7bc9d34232f88f3146c592b2f0fe7ca2482e029d | refs/heads/master | 2022-12-10T09:33:19.699170 | 2020-09-10T09:42:26 | 2020-09-10T09:42:26 | 294,368,710 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 554 | java | package com.seye.analysis.cpp.struct;
import com.sun.jna.Structure;
@Structure.FieldOrder({"id","natural_person_id","snap_scene_id","camera_id","id_in_scene","ts"})
public class RelationShipData extends Structure
{
public String id;
public String natural_person_id;
public String snap_scene_id;
public int camera_id;
public int id_in_scene;
public long ts;
public static class RelationShipDataVal implements Structure.ByValue {
}
public static class RelationShipDataRef implements Structure.ByReference {
}
}
| [
"wanghualin@yourangroup.com"
] | wanghualin@yourangroup.com |
2a6dedfca1af7ef070f36b0cb8cd1bc639aaa18d | 058830d19bada5a6a1979c2064ad4fc6c45a03a9 | /src/main/java/com/ddup/exception/ICustomizeErrorCode.java | bfc793d2e9b1a2f53f5f117ea82ff6deaad3aaa4 | [] | no_license | HolyShitQ/Daydayup | dcfbdaf3daece7584ee6bac4a8ad3a0588be3f9f | 538094c5d6086e1f16523a0b0b92ae83b707d641 | refs/heads/master | 2022-08-11T22:24:39.028675 | 2020-03-25T15:13:37 | 2020-03-25T15:13:37 | 196,533,540 | 2 | 0 | null | 2022-06-21T01:54:23 | 2019-07-12T07:45:48 | Java | UTF-8 | Java | false | false | 119 | java | package com.ddup.exception;
public interface ICustomizeErrorCode {
String getMessage();
Integer getCode();
}
| [
"1070628782@qq.com"
] | 1070628782@qq.com |
76d4e3b92c6b47bccdf70545b7f233ad8837093a | 9972dffcd44cd24deaec76d826707a832c993f67 | /src/main/java/io/github/chermehdi/slackspringbootstarter/core/SlackMessage.java | f2e976cdb7bbcab66a8af02becca85009e5ae070 | [] | no_license | chermehdi/spring-boot-starter-slack | 822808395000f6c37b655b91590acd1b51e741dc | 29ca78ae9e85707eb1246fbdf2b8766ae3436e8a | refs/heads/master | 2020-04-07T13:07:45.493025 | 2018-11-20T13:30:52 | 2018-11-20T13:30:52 | 158,394,225 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 780 | java | package io.github.chermehdi.slackspringbootstarter.core;
/**
* The slack message that is going to be sent to the workspace,
*
* @author chermehdi
*/
public interface SlackMessage {
/**
* the username to be displayed in the workspace channel
*/
String getUserName();
/**
* the icon to be displayed along the message
*/
String getIconUrl();
/**
* the actual message, this can be a simple text message or a complex one (containing attachments,
* markdown ..)
*/
String getMessage();
/**
* the channel the messages are going to be sent to
*/
String getChannel();
/**
* if set to true than it should notify the Slack API that this message contains markdown content
* to displayed accordingly
*/
boolean isMarkdown();
}
| [
"mehdi.cheracher@gmail.com"
] | mehdi.cheracher@gmail.com |
989fe6bad9653200d3c11b769a73318aa15a3a59 | 66dc781e5290bc38246eb7e8f6abbf170560b029 | /learnspringwebapp/src/main/java/tamil/learn/springframework/learnspringwebapp/model/Author.java | 5aa30e80b4155b12fdb40c79c84182d3fb748798 | [
"Apache-2.0"
] | permissive | murugan425/learn-spring-5 | 6f0eba00e905202b2d124a82e10c8af506ee176d | 4d6e1bbf530af7203ea6e6d6565c86fdd8d163cc | refs/heads/master | 2022-05-03T12:58:47.073793 | 2019-01-04T10:11:16 | 2019-01-04T10:11:16 | 102,354,634 | 1 | 1 | Apache-2.0 | 2022-03-31T17:45:42 | 2017-09-04T11:33:35 | Java | UTF-8 | Java | false | false | 1,820 | java | /* Created by Murugan_Nagarajan on 9/13/2017 */
package tamil.learn.springframework.learnspringwebapp.model;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
@Entity
public class Author {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer authorId;
private String authorName;
@ManyToMany(mappedBy = "authors")
private Set<Book> books = new HashSet<>();
public Author() {
}
public Author(String authorName) {
this.authorName = authorName;
}
public Author(Integer authorId, String authorName, Set<Book> books) {
this.authorId = authorId;
this.authorName = authorName;
this.books = books;
}
public Integer getAuthorId() {
return authorId;
}
public void setAuthorId(Integer authorId) {
this.authorId = authorId;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Author author = (Author) o;
return authorId != null ? authorId.equals(author.authorId) : author.authorId == null;
}
@Override
public int hashCode() {
return authorId != null ? authorId.hashCode() : 0;
}
@Override
public String toString() {
return "Author{" +
"authorId=" + authorId +
", authorName='" + authorName + '\'' +
", books=" + books +
'}';
}
}
| [
"murugan425@gmail.com"
] | murugan425@gmail.com |
fb953c1d4160edd7c9d8566dc021344364e0d530 | 2e3582b1f9df35541e38b4db1f0a2cfc8ec15db8 | /microCloud-fegin-service/src/main/java/com/tyb1222/fegin/config/FeignClientConfig.java | 652855278e22412dd999b999bc8f96f250860f96 | [] | no_license | tyb1222/SpringCloud | 954604c7b47d806ef5184436375063e36b84e3f7 | 31269af74cac6e7b8c5e7f5a499ebdc662128fc1 | refs/heads/master | 2020-05-15T16:22:28.028052 | 2019-04-30T09:25:55 | 2019-04-30T09:25:55 | 182,388,256 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 532 | java | package com.tyb1222.fegin.config;
import feign.Logger;
import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignClientConfig {
// @Bean
// public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor(){
// return new BasicAuthRequestInterceptor("tyb","tyb1222");
// }
// @Bean
// public Logger.Level getFeignLogLevel(){
// return Logger.Level.FULL;
// }
}
| [
"153026583@163.com"
] | 153026583@163.com |
7499c58fde8a649a240f095479986502382f180f | b906dd28ef56f5470830f2b1786aabd0a45c84b3 | /v6-websocket-server/src/main/java/com/company/websocket/util/ClientRequest.java | 3e555de6fd9d494b003b14f7790021a8898290ba | [] | no_license | rucky2013/websocket-server | 4c93967ca54c68ff74cd41b640babbeb798f09e5 | 12d5fae4a499024c9b7cab7cad1e4866eb94bbcc | refs/heads/master | 2021-05-07T06:43:19.675628 | 2017-10-30T07:51:00 | 2017-10-30T07:51:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,069 | java | package com.company.websocket.util;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.gson.Gson;
public class ClientRequest {
private static Gson gson = new Gson();
private String sessionId;
private int serviceId;
private String userName;
private String message;
public String getSessionId() {
return sessionId;
}
public ClientRequest setSessionId(String sessionId) {
this.sessionId = sessionId;
return this;
}
public int getServiceId() {
return serviceId;
}
public ClientRequest setServiceId(int serviceId) {
this.serviceId = serviceId;
return this;
}
public String getUserName() {
return userName;
}
public ClientRequest setUserName(String userName) {
this.userName = userName;
return this;
}
public String getMessage() {
return message;
}
public ClientRequest setMessage(String message) {
this.message = message;
return this;
}
}
| [
"roy2010@163.com"
] | roy2010@163.com |
fa72cdfa2149f57837a4e0033c71d4936c61048b | c4f1df08c096f0587fbe58d630de93a7f185af90 | /src/main/java/org/loyer/komoo/service/impl/Kmp017unitTestServiceImpl.java | bcbad11607fc6da97633c42c2fe8508f6286959e | [] | no_license | Schlatter076/komoo-MP-Spring-myBatis-Maven | 1215b16ac758068e678d5109cd57f07e424b1b33 | 244cba27ebbb1134001791df024a4a5a24a84cd4 | refs/heads/master | 2022-12-22T21:25:09.126183 | 2019-11-07T08:31:47 | 2019-11-07T08:31:47 | 206,925,128 | 0 | 0 | null | 2022-12-16T09:44:05 | 2019-09-07T06:17:45 | Java | UTF-8 | Java | false | false | 1,243 | java | package org.loyer.komoo.service.impl;
import java.math.BigInteger;
import java.util.List;
import org.loyer.komoo.beans.TestData;
import org.loyer.komoo.dao.Ikmp017unitTestDao;
import org.loyer.komoo.service.ITestDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Kmp017unitTestServiceImpl implements ITestDataService {
@Autowired
private Ikmp017unitTestDao dao;
public void setDao(Ikmp017unitTestDao dao) {
this.dao = dao;
}
@Override
public List<TestData> getAllByDate(String date) {
return dao.selectAllByDate(date);
}
@Override
public int getStepById(BigInteger id) {
return dao.selectStepById(id);
}
@Override
public String getProductNumById(BigInteger id) {
return dao.selectProductNumById(id);
}
@Override
public List<BigInteger> getIdsBydate(String date) {
return dao.selectIdsBydate(date);
}
@Override
public TestData getTestDataById(BigInteger id) {
return getTestDataById(id);
}
@Override
public void addOne(TestData data) {
dao.insertOne(data);
}
@Override
public List<TestData> getAllByDateAndStep(String date, int step) {
return null;
}
}
| [
"schlatter076@163.com"
] | schlatter076@163.com |
13326e4206c04a6aa3df4752f9fd44415b713b0b | 792a2ada782005cbd8cbc2bebca5e17ce2b029dc | /java/design-patterns/src/test/java/structural/adapter/AdapterPatternTest.java | 5343b2bdacf4d4d382f0d4bf859acff19bbd089c | [] | no_license | AlexanderScherbatiy/samples | e372e5056a5e94dc0ecf5069a669488306dadc0f | 911434ff272694cb4a6550b3cd6d0c0db8e0250f | refs/heads/master | 2022-10-25T18:04:03.254373 | 2022-06-02T16:14:14 | 2022-06-02T16:14:14 | 74,009,096 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 753 | java | package structural.adapter;
import org.junit.Test;
import java.util.StringTokenizer;
import static org.junit.Assert.*;
public class AdapterPatternTest {
@Test
public void testAdapterPattern() {
StringTokenizer tokenizer = new StringTokenizer("Hello World");
Iterable<String> iterable = new IterableAdapter(tokenizer);
int i = 0;
for (String str : iterable) {
switch (i) {
case 0:
assertEquals("Hello", str);
break;
case 1:
assertEquals("World", str);
break;
default:
fail("Wrong string number!");
}
i++;
}
}
}
| [
"alexander.scherbatiy@yandex.com"
] | alexander.scherbatiy@yandex.com |
ee85173dc9f7fc6a5b45aa005ff2925bf487bf38 | 5dfe6a6ddfc17cf87b4040dfeecabbf29dc845cf | /src/main/java/com/collectorthrd/web/filter/CsrfCookieGeneratorFilter.java | c25de0362b81cd3a41b8d19b2d890a4fe89c8de4 | [] | no_license | rhanberrycatalyst/CollectorXmen | 8dba7157f58a1765ce73a4609f17af4087d0c044 | 878d6b33761648bddaa5fdf0b5db8ecc7448fdc8 | refs/heads/master | 2021-01-10T05:11:05.504757 | 2016-01-15T19:57:31 | 2016-01-15T19:57:31 | 49,043,906 | 0 | 1 | null | 2020-09-18T11:33:37 | 2016-01-05T05:22:11 | Java | UTF-8 | Java | false | false | 1,473 | java | package com.collectorthrd.web.filter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Filter used to put the CSRF token generated by Spring Security in a cookie for use by AngularJS.
*/
public class CsrfCookieGeneratorFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// Spring put the CSRF token in session attribute "_csrf"
CsrfToken csrfToken = (CsrfToken) request.getAttribute("_csrf");
// Send the cookie only if the token has changed
String actualToken = request.getHeader("X-CSRF-TOKEN");
if (actualToken == null || !actualToken.equals(csrfToken.getToken())) {
// Session cookie that will be used by AngularJS
String pCookieName = "CSRF-TOKEN";
Cookie cookie = new Cookie(pCookieName, csrfToken.getToken());
cookie.setMaxAge(-1);
cookie.setHttpOnly(false);
cookie.setPath("/");
response.addCookie(cookie);
}
filterChain.doFilter(request, response);
}
}
| [
"rhanberry@Richards-iMac.lan"
] | rhanberry@Richards-iMac.lan |
a3cb171036dd156f6f45e557ef696ebcadb92bff | 94e4fcde10d0a31432450b1ef14bdfc130247817 | /src/main/java/com/zzz/mt/sql/impl/InsertSqlCreator.java | 0a5dadcb2260a2c5e342e967b8e6cf5c58427132 | [] | no_license | haosijiahsj/MtDao | ade731d0c61022e1a23dc40118eb55bd68bf01aa | 5dad7680e19a3fc93be8e450e313a19876ffa308 | refs/heads/master | 2021-01-15T10:29:52.479426 | 2017-08-18T08:29:14 | 2017-08-18T08:29:14 | 99,582,280 | 1 | 0 | null | 2017-08-16T08:54:32 | 2017-08-07T13:43:18 | Java | UTF-8 | Java | false | false | 2,105 | java | package com.zzz.mt.sql.impl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.zzz.mt.mapping.MapperHandler;
import com.zzz.mt.mapping.MapperColumnResult;
import com.zzz.mt.mapping.MapperResult;
import com.zzz.mt.sql.SingleParamSqlCreator;
import com.zzz.mt.support.SqlType;
import org.apache.log4j.Logger;
import java.util.*;
/**
* Created by 胡胜钧 on 8/5 0005.
*/
public class InsertSqlCreator extends SingleParamSqlCreator {
private Logger logger = Logger.getLogger(InsertSqlCreator.class);
private String sql;
public InsertSqlCreator() {}
@Override
public String createUserSql() {
valueMap = new HashMap<>();
int i = 0;
for (Object value : parameters) {
valueMap.put(++i, value);
}
logger.info("sql statement: " + this.sql);
return this.sql;
}
@Override
public String createPreparedSql() {
valueMap = new HashMap<>();
MapperResult mapperResult = new MapperHandler(parameter, SqlType.INSERT).getMapperResult();
StringBuilder sqlBuilder = new StringBuilder("INSERT INTO ");
List<MapperColumnResult> columnResults = mapperResult.getMapperColumnResults();
List<String> questionMarks = Lists.newArrayList();
List<String> columnNames = Lists.newArrayList();
int i = 0;
for (MapperColumnResult rs : columnResults) {
columnNames.add("`" + rs.getColumnName() + "`");
questionMarks.add("?");
valueMap.put(++i, rs.getValue());
}
sqlBuilder.append("`").append(mapperResult.getTableName()).append("`")
.append("(").append(Joiner.on(", ").join(columnNames)).append(")")
.append(" VALUES ")
.append("(").append(Joiner.on(", ").join(questionMarks)).append(")");
String sql = sqlBuilder.toString();
logger.info("sql statement:" + sql);
return sql;
}
@SuppressWarnings("unchecked")
@Override
public String createPreparedSqlFromMap() {
return sql;
}
}
| [
"1017547773@qq.com"
] | 1017547773@qq.com |
e79f5d327ece7b9047ffe3e1599b8aba47495774 | d7c5121237c705b5847e374974b39f47fae13e10 | /airspan.netspan/src/main/java/Netspan/NBI_18_0/Lte/TrafficManagementProfileGetResult.java | 439019298c5b7c4055f1b55ac28b4e571815c89b | [] | no_license | AirspanNetworks/SWITModules | 8ae768e0b864fa57dcb17168d015f6585d4455aa | 7089a4b6456621a3abd601cc4592d4b52a948b57 | refs/heads/master | 2022-11-24T11:20:29.041478 | 2020-08-09T07:20:03 | 2020-08-09T07:20:03 | 184,545,627 | 1 | 0 | null | 2022-11-16T12:35:12 | 2019-05-02T08:21:55 | Java | UTF-8 | Java | false | false | 2,411 | java |
package Netspan.NBI_18_0.Lte;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TrafficManagementProfileGetResult complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="TrafficManagementProfileGetResult">
* <complexContent>
* <extension base="{http://Airspan.Netspan.WebServices}WsResponse">
* <sequence>
* <element name="TrafficManagementProfileResult" type="{http://Airspan.Netspan.WebServices}TrafficManagementProfileResult" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TrafficManagementProfileGetResult", propOrder = {
"trafficManagementProfileResult"
})
public class TrafficManagementProfileGetResult
extends WsResponse
{
@XmlElement(name = "TrafficManagementProfileResult")
protected List<TrafficManagementProfileResult> trafficManagementProfileResult;
/**
* Gets the value of the trafficManagementProfileResult property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the trafficManagementProfileResult property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getTrafficManagementProfileResult().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TrafficManagementProfileResult }
*
*
*/
public List<TrafficManagementProfileResult> getTrafficManagementProfileResult() {
if (trafficManagementProfileResult == null) {
trafficManagementProfileResult = new ArrayList<TrafficManagementProfileResult>();
}
return this.trafficManagementProfileResult;
}
}
| [
"ggrunwald@airspan.com"
] | ggrunwald@airspan.com |
5a92c62e233d0ec9a2e23ee1e491829f1996b82b | f2d4da478c206d4e5beef831edb79d9ee64dc4ee | /app/src/androidTest/java/com/simplifiededtech/iplmatchlivescore/ExampleInstrumentedTest.java | bcae05eaa74d7264f6b8e77b0f5e9a72e41c28b9 | [] | no_license | pankajkcodes/IPLMatchLiveScore | 0fe4cda131f04663e98f1b47632ca67f72b20a7b | 39dce4818cd5a5bc02d41fd6b4c1e69c6a6387d6 | refs/heads/master | 2023-07-03T09:05:37.754116 | 2021-08-03T04:44:51 | 2021-08-03T04:44:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package com.simplifiededtech.iplmatchlivescore;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.simplifiededtech.iplmatchlivescore", appContext.getPackageName());
}
} | [
"pankajkcodes@gmail.com"
] | pankajkcodes@gmail.com |
d775f940537fbc58e2218a42c4354c5d0aa32929 | 03d61086047f041168f9a77b02a63a9af83f0f3f | /newrelic/src/main/java/com/newrelic/agent/deps/org/apache/http/impl/cookie/BrowserCompatSpec.java | ec800b936352d170a72a4fde527f2e6e9dd53fea | [] | no_license | masonmei/mx2 | fa53a0b237c9e2b5a7c151999732270b4f9c4f78 | 5a4adc268ac1e52af1adf07db7a761fac4c83fbf | refs/heads/master | 2021-01-25T10:16:14.807472 | 2015-07-30T21:49:33 | 2015-07-30T21:49:35 | 39,944,476 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,666 | java | //
// Decompiled by Procyon v0.5.29
//
package com.newrelic.agent.deps.org.apache.http.impl.cookie;
import com.newrelic.agent.deps.org.apache.http.message.BufferedHeader;
import java.util.ArrayList;
import com.newrelic.agent.deps.org.apache.http.message.BasicHeaderElement;
import com.newrelic.agent.deps.org.apache.http.message.BasicHeaderValueFormatter;
import com.newrelic.agent.deps.org.apache.http.HeaderElement;
import com.newrelic.agent.deps.org.apache.http.util.CharArrayBuffer;
import com.newrelic.agent.deps.org.apache.http.message.ParserCursor;
import com.newrelic.agent.deps.org.apache.http.FormattedHeader;
import com.newrelic.agent.deps.org.apache.http.util.Args;
import java.util.List;
import com.newrelic.agent.deps.org.apache.http.Header;
import com.newrelic.agent.deps.org.apache.http.cookie.MalformedCookieException;
import com.newrelic.agent.deps.org.apache.http.cookie.CookieOrigin;
import com.newrelic.agent.deps.org.apache.http.cookie.Cookie;
import com.newrelic.agent.deps.org.apache.http.cookie.CookieAttributeHandler;
import com.newrelic.agent.deps.org.apache.http.annotation.NotThreadSafe;
@NotThreadSafe
public class BrowserCompatSpec extends CookieSpecBase
{
private static final String[] DEFAULT_DATE_PATTERNS;
private final String[] datepatterns;
public BrowserCompatSpec(final String[] datepatterns, final BrowserCompatSpecFactory.SecurityLevel securityLevel) {
if (datepatterns != null) {
this.datepatterns = datepatterns.clone();
}
else {
this.datepatterns = BrowserCompatSpec.DEFAULT_DATE_PATTERNS;
}
switch (securityLevel) {
case SECURITYLEVEL_DEFAULT: {
this.registerAttribHandler("path", new BasicPathHandler());
break;
}
case SECURITYLEVEL_IE_MEDIUM: {
this.registerAttribHandler("path", new BasicPathHandler() {
public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
}
});
break;
}
default: {
throw new RuntimeException("Unknown security level");
}
}
this.registerAttribHandler("domain", new BasicDomainHandler());
this.registerAttribHandler("max-age", new BasicMaxAgeHandler());
this.registerAttribHandler("secure", new BasicSecureHandler());
this.registerAttribHandler("comment", new BasicCommentHandler());
this.registerAttribHandler("expires", new BasicExpiresHandler(this.datepatterns));
this.registerAttribHandler("version", new BrowserCompatVersionAttributeHandler());
}
public BrowserCompatSpec(final String[] datepatterns) {
this(datepatterns, BrowserCompatSpecFactory.SecurityLevel.SECURITYLEVEL_DEFAULT);
}
public BrowserCompatSpec() {
this(null, BrowserCompatSpecFactory.SecurityLevel.SECURITYLEVEL_DEFAULT);
}
public List<Cookie> parse(final Header header, final CookieOrigin origin) throws MalformedCookieException {
Args.notNull(header, "Header");
Args.notNull(origin, "Cookie origin");
final String headername = header.getName();
if (!headername.equalsIgnoreCase("Set-Cookie")) {
throw new MalformedCookieException("Unrecognized cookie header '" + header.toString() + "'");
}
HeaderElement[] helems = header.getElements();
boolean versioned = false;
boolean netscape = false;
for (final HeaderElement helem : helems) {
if (helem.getParameterByName("version") != null) {
versioned = true;
}
if (helem.getParameterByName("expires") != null) {
netscape = true;
}
}
if (netscape || !versioned) {
final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
CharArrayBuffer buffer;
ParserCursor cursor;
if (header instanceof FormattedHeader) {
buffer = ((FormattedHeader)header).getBuffer();
cursor = new ParserCursor(((FormattedHeader)header).getValuePos(), buffer.length());
}
else {
final String s = header.getValue();
if (s == null) {
throw new MalformedCookieException("Header value is null");
}
buffer = new CharArrayBuffer(s.length());
buffer.append(s);
cursor = new ParserCursor(0, buffer.length());
}
helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
}
return this.parse(helems, origin);
}
public List<Header> formatCookies(final List<Cookie> cookies) {
Args.notEmpty(cookies, "List of cookies");
final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
buffer.append("Cookie");
buffer.append(": ");
for (int i = 0; i < cookies.size(); ++i) {
final Cookie cookie = cookies.get(i);
if (i > 0) {
buffer.append("; ");
}
final String cookieName = cookie.getName();
final String cookieValue = cookie.getValue();
if (cookie.getVersion() > 0 && (!cookieValue.startsWith("\"") || !cookieValue.endsWith("\""))) {
BasicHeaderValueFormatter.INSTANCE.formatHeaderElement(buffer, new BasicHeaderElement(cookieName, cookieValue), false);
}
else {
buffer.append(cookieName);
buffer.append("=");
if (cookieValue != null) {
buffer.append(cookieValue);
}
}
}
final List<Header> headers = new ArrayList<Header>(1);
headers.add(new BufferedHeader(buffer));
return headers;
}
public int getVersion() {
return 0;
}
public Header getVersionHeader() {
return null;
}
public String toString() {
return "compatibility";
}
static {
DEFAULT_DATE_PATTERNS = new String[] { "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE, dd-MMM-yy HH:mm:ss zzz", "EEE MMM d HH:mm:ss yyyy", "EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MMM-yyyy HH-mm-ss z", "EEE, dd MMM yy HH:mm:ss z", "EEE dd-MMM-yyyy HH:mm:ss z", "EEE dd MMM yyyy HH:mm:ss z", "EEE dd-MMM-yyyy HH-mm-ss z", "EEE dd-MMM-yy HH:mm:ss z", "EEE dd MMM yy HH:mm:ss z", "EEE,dd-MMM-yy HH:mm:ss z", "EEE,dd-MMM-yyyy HH:mm:ss z", "EEE, dd-MM-yyyy HH:mm:ss z" };
}
}
| [
"dongxu.m@gmail.com"
] | dongxu.m@gmail.com |
50f75ccc8e5f6beede96dfc70e4487d65cd02ff0 | 72ca888dbe685698cd9c05f1ec86ca9326f78ac8 | /common/src/main/java/us/myles/ViaVersion/api/rewriters/ComponentRewriter.java | 93353b032ba313437e00b86bb252357ad9397d08 | [
"MIT"
] | permissive | moker59/ViaVersion | dabdebacc8d60748dd02d71bae699534e2ee3b4f | 076c5e52650c4d6a5f81129c055ad4c89371b257 | refs/heads/master | 2021-01-08T10:40:13.743849 | 2020-07-23T14:12:42 | 2020-07-23T14:12:42 | 242,006,124 | 0 | 0 | MIT | 2020-02-20T22:43:21 | 2020-02-20T22:43:20 | null | UTF-8 | Java | false | false | 5,414 | java | package us.myles.ViaVersion.api.rewriters;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import us.myles.ViaVersion.api.protocol.ClientboundPacketType;
import us.myles.ViaVersion.api.protocol.Protocol;
import us.myles.ViaVersion.api.remapper.PacketRemapper;
import us.myles.ViaVersion.api.type.Type;
import us.myles.ViaVersion.util.GsonUtil;
// Packets using components:
// ping (status)
// disconnect (play and login)
// chat
// bossbar
// open window
// combat event
// title
// tablist
// teams
// scoreboard
// player info
// map data
// declare commands
// advancements
// update sign
/**
* Handles json chat components, containing methods to override certain parts of the handling.
* Also contains methods to register a few of the packets using components.
*/
public class ComponentRewriter {
protected final Protocol protocol;
public ComponentRewriter(Protocol protocol) {
this.protocol = protocol;
}
/**
* Use empty constructor if no packet registering is needed.
*/
public ComponentRewriter() {
this.protocol = null;
}
public void registerChatMessage(ClientboundPacketType packetType) {
protocol.registerOutgoing(packetType, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> processText(wrapper.passthrough(Type.COMPONENT)));
}
});
}
public void registerBossBar(ClientboundPacketType packetType) {
protocol.registerOutgoing(packetType, new PacketRemapper() {
@Override
public void registerMap() {
map(Type.UUID);
map(Type.VAR_INT);
handler(wrapper -> {
int action = wrapper.get(Type.VAR_INT, 0);
if (action == 0 || action == 3) {
processText(wrapper.passthrough(Type.COMPONENT));
}
});
}
});
}
public void registerCombatEvent(ClientboundPacketType packetType) {
protocol.registerOutgoing(packetType, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> {
if (wrapper.passthrough(Type.VAR_INT) == 2) {
wrapper.passthrough(Type.VAR_INT);
wrapper.passthrough(Type.INT);
processText(wrapper.passthrough(Type.COMPONENT));
}
});
}
});
}
public void registerTitle(ClientboundPacketType packetType) {
protocol.registerOutgoing(packetType, new PacketRemapper() {
@Override
public void registerMap() {
handler(wrapper -> {
int action = wrapper.passthrough(Type.VAR_INT);
if (action >= 0 && action <= 2) {
processText(wrapper.passthrough(Type.COMPONENT));
}
});
}
});
}
public JsonElement processText(String value) {
JsonElement root = GsonUtil.getJsonParser().parse(value);
processText(root);
return root;
}
public void processText(JsonElement element) {
if (element == null || element.isJsonNull()) return;
if (element.isJsonArray()) {
processAsArray(element);
return;
}
if (element.isJsonPrimitive()) {
handleText(element.getAsJsonPrimitive());
return;
}
JsonObject object = element.getAsJsonObject();
JsonPrimitive text = object.getAsJsonPrimitive("text");
if (text != null) {
handleText(text);
}
JsonElement translate = object.get("translate");
if (translate != null) {
handleTranslate(object, translate.getAsString());
JsonElement with = object.get("with");
if (with != null) {
processAsArray(with);
}
}
JsonElement extra = object.get("extra");
if (extra != null) {
processAsArray(extra);
}
JsonObject hoverEvent = object.getAsJsonObject("hoverEvent");
if (hoverEvent != null) {
handleHoverEvent(hoverEvent);
}
}
protected void handleText(JsonPrimitive text) {
// To override if needed
}
protected void handleTranslate(JsonObject object, String translate) {
// To override if needed
}
// To override if needed (don't forget to call super if needed)
protected void handleHoverEvent(JsonObject hoverEvent) {
String action = hoverEvent.getAsJsonPrimitive("action").getAsString();
if (action.equals("show_text")) {
JsonElement value = hoverEvent.get("value");
processText(value != null ? value : hoverEvent.get("contents"));
} else if (action.equals("show_entity")) {
JsonObject contents = hoverEvent.getAsJsonObject("contents");
if (contents != null) {
processText(contents.get("name"));
}
}
}
private void processAsArray(JsonElement element) {
for (JsonElement jsonElement : element.getAsJsonArray()) {
processText(jsonElement);
}
}
}
| [
"kennytv@t-online.de"
] | kennytv@t-online.de |
f7b388b3d95e1e39fb64424bcd50ebb9609dc842 | 14cef03f2d5152f3ba398ec6244708e7095d8439 | /src/test/java/org/btech/AppTest.java | 99ca348a1de41e7d11ba8812593f9e9220ee706d | [] | no_license | boubadi/users-list | 2c642461fefe0e94dc858703d6147c8b54f4e2dd | ab0ce590e012b1d8a4e7e49df119ff6618b379cd | refs/heads/master | 2020-12-24T21:11:52.981905 | 2016-04-26T20:04:32 | 2016-04-26T20:04:32 | 57,156,538 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 637 | java | package org.btech;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| [
"Boubacar.Diouf@gmail.com"
] | Boubacar.Diouf@gmail.com |
5f049857513303d07f0a632c2b4c0e1efa6a5dda | 3eca1c3ef6f62e8c81ee88616bef9e58e2daa624 | /src/org/usfirst/frc/team4778/robot/commands/autonomous/Auto.java | 7b86fc84a3c0c8343535d9acb2cb02b1fa8832ad | [] | no_license | Stormbots4778/4778-Stronghold | c8376ebaf99a0e3546d4e97bf7c69b70fcfb28fc | a31bb1ba6464f9783f42092ce3ff56e657c80130 | refs/heads/master | 2020-04-15T15:22:26.923600 | 2017-01-12T22:41:25 | 2017-01-12T22:41:25 | 50,460,881 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,343 | java | package org.usfirst.frc.team4778.robot.commands.autonomous;
import org.usfirst.frc.team4778.robot.RobotMap;
import org.usfirst.frc.team4778.robot.commands.BallRoller;
import org.usfirst.frc.team4778.robot.commands.Delay;
import org.usfirst.frc.team4778.robot.commands.Move;
import org.usfirst.frc.team4778.robot.commands.SetBallArm;
import org.usfirst.frc.team4778.robot.commands.TurnToAngle;
import edu.wpi.first.wpilibj.command.CommandGroup;
public class Auto extends CommandGroup {
public Auto(int defenseId, boolean shouldScore) {
init();
runBreach();
if(shouldScore) {
runScore(defenseId);
}
}
public void init() { // Initialization code goes here
System.out.println("-init Auto");
RobotMap.ahrs.reset();
RobotMap.ahrs.resetDisplacement();
RobotMap.leftdrive.reset();
RobotMap.rightdrive.reset();
System.out.println("-end-init Auto");
}
public void runBreach() {
// Defense crossing code goes here
}
public void runScore(int defenseId) {
// Scoring code goes here
switch (defenseId) {
case 0:
addSequential(new SetBallArm(true));
addSequential(new TurnToAngle(59));
addSequential(new Move(135.5));
addSequential(new SetBallArm(false));
addSequential(new Delay(750));
addSequential(new BallRoller(-1), 2);
case 1:
addSequential(new Move(138));
addSequential(new TurnToAngle(59));
addSequential(new Move(74));
addParallel(new SetBallArm(true));
addSequential(new BallRoller(-1), 2000);
break;
case 2:
addSequential(new Move(17));
addSequential(new TurnToAngle(-31));
addSequential(new Move(112));
addSequential(new TurnToAngle(59));
addSequential(new Move(74));
addParallel(new SetBallArm(true));
addSequential(new BallRoller(-1), 2000);
break;
case 3:
addSequential(new Move(70));
addSequential(new TurnToAngle(33));
addSequential(new Move(98));
addSequential(new TurnToAngle(-57));
addSequential(new Move(41));
addParallel(new SetBallArm(true));
addSequential(new BallRoller(-1), 2000);
break;
case 4:
addSequential(new Move(153));
addSequential(new TurnToAngle(59));
addSequential(new Move(41));
addParallel(new SetBallArm(true));
addSequential(new BallRoller(-1), 2000);
break;
}
}
}
| [
"ethan@ejohnsons.com"
] | ethan@ejohnsons.com |
21faa22ccbbf8b7c3c7476bc876687989bef9a93 | 3d25eb97f35a3c338b32e849ec3057edf55ab450 | /src/main/java/cn/tomoya/module/user/controller/UserController.java | 66cb93880a5aecd68bc5ac4a26951afe7c884ace | [
"MIT"
] | permissive | insiston/pybbs | 7c0dc77ef82fa82c5e67619683363a2e77a912a2 | 3125e3e548f53d86621658b73a8dc38f601d30fe | refs/heads/master | 2021-01-12T14:42:51.275562 | 2016-10-26T14:40:59 | 2016-10-26T14:40:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,589 | java | package cn.tomoya.module.user.controller;
import cn.tomoya.common.BaseController;
import cn.tomoya.common.config.SiteConfig;
import cn.tomoya.module.collect.service.CollectService;
import cn.tomoya.module.reply.service.ReplyService;
import cn.tomoya.module.topic.service.TopicService;
import cn.tomoya.module.user.entity.User;
import cn.tomoya.module.user.service.UserService;
import cn.tomoya.util.FileUploadEnum;
import cn.tomoya.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by tomoya.
* Copyright (c) 2016, All Rights Reserved.
* http://tomoya.cn
*/
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
@Autowired
private SiteConfig siteConfig;
@Autowired
private TopicService topicService;
@Autowired
private ReplyService replyService;
@Autowired
private UserService userService;
@Autowired
private CollectService collectService;
@Autowired
private FileUtil fileUtil;
/**
* 个人资料
*
* @param username
* @param model
* @return
*/
@RequestMapping("/{username}")
public String profile(@PathVariable String username, Model model) {
User currentUser = userService.findByUsername(username);
if (currentUser != null) {
model.addAttribute("user", getUser());
model.addAttribute("currentUser", currentUser);
model.addAttribute("collectCount", collectService.countByUser(currentUser));
model.addAttribute("topicPage", topicService.findByUser(1, 7, currentUser));
model.addAttribute("replyPage", replyService.findByUser(1, 7, currentUser));
model.addAttribute("pageTitle", currentUser.getUsername() + " 个人主页");
} else {
model.addAttribute("pageTitle", "用户未找到");
}
return render("/user/info");
}
/**
* 用户发布的所有话题
* @param username
* @return
*/
@RequestMapping("/{username}/topics")
public String topics(@PathVariable String username, Integer p, HttpServletResponse response, Model model) {
User currentUser = userService.findByUsername(username);
if (currentUser != null) {
model.addAttribute("currentUser", currentUser);
model.addAttribute("page", topicService.findByUser(p == null ? 1 : p, siteConfig.getPageSize(), currentUser));
return render("/user/topics");
} else {
renderText(response, "用户不存在");
return null;
}
}
/**
* 用户发布的所有回复
* @param username
* @return
*/
@RequestMapping("/{username}/replies")
public String replies(@PathVariable String username, Integer p, HttpServletResponse response, Model model) {
User currentUser = userService.findByUsername(username);
if (currentUser != null) {
model.addAttribute("currentUser", currentUser);
model.addAttribute("page", replyService.findByUser(p == null ? 1 : p, siteConfig.getPageSize(), currentUser));
return render("/user/replies");
} else {
renderText(response, "用户不存在");
return null;
}
}
/**
* 用户收藏的所有话题
* @param username
* @return
*/
@RequestMapping("/{username}/collects")
public String collects(@PathVariable String username, Integer p, HttpServletResponse response, Model model) {
User currentUser = userService.findByUsername(username);
if (currentUser != null) {
model.addAttribute("currentUser", currentUser);
model.addAttribute("page", collectService.findByUser(p == null ? 1 : p, siteConfig.getPageSize(), currentUser));
return render("/user/collects");
} else {
renderText(response, "用户不存在");
return null;
}
}
/**
* 进入用户个人设置页面
* @param model
* @return
*/
@RequestMapping(value = "/setting", method = RequestMethod.GET)
public String setting(Model model) {
model.addAttribute("user", getUser());
return render("/user/setting");
}
/**
* 更新用户的个人设置
* @param email
* @param url
* @param signature
* @param response
* @return
*/
@RequestMapping(value = "/setting", method = RequestMethod.POST)
public String updateUserInfo(String email, String url, String signature, @RequestParam("avatar") MultipartFile avatar, HttpServletResponse response) throws IOException {
User user = getUser();
user.setEmail(email);
user.setSignature(signature);
user.setUrl(url);
String requestUrl = fileUtil.uploadFile(avatar, FileUploadEnum.AVATAR);
if(!StringUtils.isEmpty(requestUrl)) {
user.setAvatar(requestUrl);
}
userService.updateUser(user);
return redirect(response, "/user/" + user.getUsername());
}
}
| [
"liuyangyang@ichefeng.com"
] | liuyangyang@ichefeng.com |
a812757a6aedac5faca044c948992deec9cbe11a | 524f7bba8e6f7283b278a469466e538c7f63701e | /贝王-App源码/MStore安卓/mdwmall/src/main/java/com/qianseit/westore/ui/CustomListSelectorPopupWindow.java | 0d0c95c49868915af3c776a4e349623580f958cb | [] | no_license | xiongdaxionger/BSLIFE | e63e3582f6eec8c95636be39839c5f29b69b36ee | 198a8c15ad32de493404022b9e00b0fe7202de08 | refs/heads/master | 2020-05-16T10:00:49.652335 | 2019-04-24T08:56:29 | 2019-04-24T08:56:29 | 182,962,206 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,859 | java | package com.qianseit.westore.ui;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.beiwangfx.R;
public abstract class CustomListSelectorPopupWindow extends PopupWindow {
private Activity mActivity;
private View mView;
private TextView mTitleTextView;
private ListView mListView;
private List<CustomListSelectorBean> mLists;
private CustomListSelectorAdapter mAdapter;
private int mSelectedPosition = 0;
private String mTitle;
public CustomListSelectorPopupWindow(Activity activity, String title, List<CustomListSelectorBean> lists) {
this.mActivity = activity;
this.mLists = lists;
mTitle = title;
this.init();
}
private void init() {
this.mView = View.inflate(mActivity, R.layout.popup_custom_selector, null);
this.mView.setFocusable(true);
this.mView.setFocusableInTouchMode(true);
this.mView.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (isShowing()) {
dismiss();
return true;
}
return false;
}
});
this.setContentView(mView);
WindowManager wm = (WindowManager) mView.getContext().getSystemService(Context.WINDOW_SERVICE);
this.setWidth(wm.getDefaultDisplay().getWidth() * 4 / 5);
this.setHeight(LayoutParams.WRAP_CONTENT);
this.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
this.setTouchable(true);
this.setFocusable(true);
this.setOutsideTouchable(true);
this.update();
mTitleTextView = (TextView) this.mView.findViewById(R.id.title);
mTitleTextView.setText(mTitle);
mListView = (ListView) this.mView.findViewById(R.id.listView1);
mListView.setAdapter((mAdapter = new CustomListSelectorAdapter()));
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
onSelected(position);
dismiss();
}
});
mView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (isShowing()) {
dismiss();
}
}
});
}
@Override
public void dismiss() {
WindowManager.LayoutParams params = mActivity.getWindow().getAttributes();
params.alpha = 1f;
mActivity.getWindow().setAttributes(params);
super.dismiss();
}
@Override
public void showAtLocation(View parent, int gravity, int x, int y) {
beginShow();
super.showAtLocation(parent, gravity, x, y);
}
@Override
public void showAsDropDown(View anchor) {
// TODO Auto-generated method stub
beginShow();
super.showAsDropDown(anchor);
}
@Override
public void showAsDropDown(View anchor, int xoff, int yoff) {
// TODO Auto-generated method stub
beginShow();
super.showAsDropDown(anchor, xoff, yoff);
}
@SuppressLint("NewApi")
@Override
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
// TODO Auto-generated method stub
beginShow();
super.showAsDropDown(anchor, xoff, yoff, gravity);
}
void beginShow() {
WindowManager.LayoutParams params = mActivity.getWindow().getAttributes();
params.alpha = 0.7f;
mActivity.getWindow().setAttributes(params);
}
public void onSelected(int position) {
if (mLists == null || mLists.size() <= position || position < 0) {
return;
}
for (int i = 0; i < mLists.size(); i++) {
mLists.get(i).mSelected = position == i;
}
mSelectedPosition = position;
onItemSelected(mLists.get(position));
}
private class CustomListSelectorAdapter extends BaseAdapter {
private ViewHolder mHolder;
@Override
public int getCount() {
return mLists.size();
}
@Override
public Object getItem(int position) {
return mLists.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
mHolder = new ViewHolder();
convertView = View.inflate(mActivity, R.layout.item_custom_list_selector_popup, null);
mHolder.mSelect = (Button) convertView.findViewById(R.id.button1);
mHolder.mTitle = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder) convertView.getTag();
}
CustomListSelectorBean nBean = mLists.get(position);
mHolder.mSelect.setSelected(nBean.mSelected);
mHolder.mTitle.setText(nBean.mName);
return convertView;
}
private class ViewHolder {
public TextView mTitle;
public Button mSelect;
}
}
public void notifyDataSetChanged() {
this.mAdapter.notifyDataSetChanged();
}
public abstract void onItemSelected(CustomListSelectorBean selectedBean);
public static class CustomListSelectorBean {
public String mID = "";
public String mName = "";
public String mType = "";
public boolean mSelected = false;
public CustomListSelectorBean(String id, String type, String name, boolean selected) {
mID = id;
mType = type;
mName = name;
mSelected = selected;
}
public CustomListSelectorBean(String id, String name, boolean selected) {
mID = id;
mType = "";
mName = name;
mSelected = selected;
}
}
}
| [
"xiongerxiongda@gmail.com"
] | xiongerxiongda@gmail.com |
4fd61ccea6ce06325b3986ec1dd298758fb9a171 | 38d4b3225c277fbc4af16ea2fc6293f2a7ffce23 | /net/AES.java | b8c1dd2df32b5be736dca322120b3f8e9c7207a6 | [] | no_license | xuanhu/CloudManagement | d646d67768cbf17eb880c23cac40690b0bf164f8 | 409a6958610270f681f0148a3e2b79ed2e46b911 | refs/heads/master | 2021-08-24T13:19:48.591767 | 2017-11-21T07:26:16 | 2017-11-21T07:26:16 | 111,513,282 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,751 | java | package com.tg.cloudmanagement.net;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
public static byte[] raw = {0x61,0x53,0x47,0x4A,0x4C,0x47,0x59,0x45,0x57,0x45,0x52,0x57,0x52,0x52,0x45,0x57};
public static String Decrypt(String sSrc) throws Exception {
try {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original,"utf-8");
return originalString;
} catch (Exception e) {
System.out.println(e.toString());
return null;
}
} catch (Exception ex) {
System.out.println(ex.toString());
return null;
}
}
public static String Encrypt(String sSrc) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byte2hex(encrypted).toUpperCase();
}
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
}
| [
"spirit369958"
] | spirit369958 |
5c1ba1b4af29ad7b06a6829bd4e71db966b22262 | 829aa3f591a09025801fa5c2b097b7544cfb18fa | /src/main/java/io/hops/site/dto/ClusterServiceDTO.java | 9dadb6f9a587ab40e38b744828e86c2615f9f4c5 | [] | no_license | isabella232/hops-site | 5e64c86b1046b104e6077b2815c4cc635d05cda8 | 2ba3535f15e855d817857d0824e7437ffe8f8707 | refs/heads/master | 2023-03-21T17:51:06.812574 | 2018-10-05T08:17:15 | 2018-10-05T08:17:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,984 | java | package io.hops.site.dto;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
public class ClusterServiceDTO {
@XmlRootElement
public static class Register {
private String delaTransferAddress;
private String delaClusterAddress;
public Register() {
}
public Register(String delaTransferAddress, String delaClusterAddress) {
this.delaTransferAddress = delaTransferAddress;
this.delaClusterAddress = delaClusterAddress;
}
public String getDelaTransferAddress() {
return delaTransferAddress;
}
public void setDelaTransferAddress(String delaTransferAddress) {
this.delaTransferAddress = delaTransferAddress;
}
public String getDelaClusterAddress() {
return delaClusterAddress;
}
public void setDelaClusterAddress(String delaClusterAddress) {
this.delaClusterAddress = delaClusterAddress;
}
}
@XmlRootElement
public static class HeavyPing {
private List<String> upldDSIds;
private List<String> dwnlDSIds;
public HeavyPing() {
}
public HeavyPing(List<String> upldDSIds, List<String> dwnlDSIds) {
this.upldDSIds = upldDSIds;
this.dwnlDSIds = dwnlDSIds;
}
public List<String> getUpldDSIds() {
return upldDSIds;
}
public void setUpldDSIds(List<String> upldDSIds) {
this.upldDSIds = upldDSIds;
}
public List<String> getDwnlDSIds() {
return dwnlDSIds;
}
public void setDwnlDSIds(List<String> dwnlDSIds) {
this.dwnlDSIds = dwnlDSIds;
}
}
@XmlRootElement
public static class Ping {
private int upldDSSize;
private int dwnlDSSize;
public int getUpldDSSize() {
return upldDSSize;
}
public void setUpldDSSize(int upldDSSize) {
this.upldDSSize = upldDSSize;
}
public int getDwnlDSSize() {
return dwnlDSSize;
}
public void setDwnlDSSize(int dwnlDSSize) {
this.dwnlDSSize = dwnlDSSize;
}
}
}
| [
"ormenisan.adrian@gmail.com"
] | ormenisan.adrian@gmail.com |
dc8534ba4d43f072ad85a210c59ae674c97463f8 | ca92abaec07e5e2673f56e20a43cdda6afe04ae3 | /app/src/main/java/com/example/admin/myapplicationmin/Model/LockerVO.java | 9fda0022b769c3d3ea5ff6dcfc13e674018aaf23 | [] | no_license | kalstjd96/delivery-app-mybatis-json-ClientApp-part | 7692045d3dabb2cb01bb177a43474fc17e345406 | 5340c3fca3dae755c8b46ae90abd890612de5914 | refs/heads/master | 2020-11-26T10:31:44.209140 | 2019-12-19T11:58:46 | 2019-12-19T11:58:46 | 229,044,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,879 | java | package com.example.admin.myapplicationmin.Model;
import java.io.Serializable;
public class LockerVO implements Serializable {
private String sno;
private String detail_no;
private String nfcid;
private String product_chk;
private String locker_chk;
private String lno;
private String l_name;
private String l_addr1;
private String l_addr2;
private String l_addr3;
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getDetail_no() {
return detail_no;
}
public void setDetail_no(String detail_no) {
this.detail_no = detail_no;
}
public String getNfcid() {
return nfcid;
}
public void setNfcid(String nfcid) {
this.nfcid = nfcid;
}
public String getProduct_chk() {
return product_chk;
}
public void setProduct_chk(String product_chk) {
this.product_chk = product_chk;
}
public String getLocker_chk() {
return locker_chk;
}
public void setLocker_chk(String locker_chk) {
this.locker_chk = locker_chk;
}
public String getLno() {
return lno;
}
public void setLno(String lno) {
this.lno = lno;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public String getL_addr1() {
return l_addr1;
}
public void setL_addr1(String l_addr1) {
this.l_addr1 = l_addr1;
}
public String getL_addr2() {
return l_addr2;
}
public void setL_addr2(String l_addr2) {
this.l_addr2 = l_addr2;
}
public String getL_addr3() {
return l_addr3;
}
public void setL_addr3(String l_addr3) {
this.l_addr3 = l_addr3;
}
}
| [
"kalstjd96@naver.com"
] | kalstjd96@naver.com |
7126ceede4821419081f907a4527143621125233 | d9477e8e6e0d823cf2dec9823d7424732a7563c4 | /jEdit/branches/4.3.x/org/gjt/sp/jedit/io/RegexEncodingDetector.java | 0415d5be547018e4cf7ed87c7da92b67e47db85c | [] | no_license | RobertHSchmidt/jedit | 48fd8e1e9527e6f680de334d1903a0113f9e8380 | 2fbb392d6b569aefead29975b9be12e257fbe4eb | refs/heads/master | 2023-08-30T02:52:55.676638 | 2018-07-11T13:28:01 | 2018-07-11T13:28:01 | 140,587,948 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,473 | java | /*
* :tabSize=8:indentSize=8:noTabs=false:
* :folding=explicit:collapseFolds=1:
*
* Copyright (C) 2008 Kazutoshi Satoda
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or 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 org.gjt.sp.jedit.io;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.nio.CharBuffer;
/**
* An encoding detector which finds regex pattern.
*
* This reads the sample in the system default encoding for first some
* lines and look for a regex pattern. This can fail if the
* stream cannot be read in the system default encoding or the
* pattern is not found at near the top of the stream.
*
* @since 4.3pre16
* @author Kazutoshi Satoda
*/
public class RegexEncodingDetector implements EncodingDetector
{
/**
* A regex pattern matches to "Charset names" specified for
* java.nio.charset.Charset.
* @see <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/nio/charset/Charset.html#names">Charset names</a>
*/
public static final String VALID_ENCODING_PATTERN
= "\\p{Alnum}[\\p{Alnum}\\-.:_]*";
private final Pattern pattern;
private final String replacement;
public RegexEncodingDetector(String pattern, String replacement)
{
this.pattern = Pattern.compile(pattern);
this.replacement = replacement;
}
public String detectEncoding(InputStream sample) throws IOException
{
InputStreamReader reader = new InputStreamReader(sample);
final int bufferSize = 1024;
char[] buffer = new char[bufferSize];
int readSize = reader.read(buffer, 0, bufferSize);
if (readSize > 0)
{
Matcher matcher = pattern.matcher(
CharBuffer.wrap(buffer, 0, readSize));
// Tracking of this implicit state within Matcher
// is required to know where is the start of
// replacement after calling appendReplacement().
int appendPosition = 0;
while (matcher.find())
{
String extracted = extractReplacement(
matcher, appendPosition, replacement);
if (EncodingServer.hasEncoding(extracted))
{
return extracted;
}
appendPosition = matcher.end();
}
}
return null;
}
/**
* Returns a replaced string for a Matcher which has been matched
* by find() method.
*/
private static String extractReplacement(
Matcher found, int appendPosition, String replacement)
{
/*
* It doesn't make sense to read before start, but
* appendReplacement() requires to to it.
*/
int found_start = found.start();
int found_end = found.end();
int source_length = found_end - found_start;
int length_before_match = found_start - appendPosition;
StringBuffer replaced = new StringBuffer(
length_before_match + (source_length * 2));
found.appendReplacement(replaced, replacement);
return replaced.substring(length_before_match);
}
}
| [
"Vampire0@6b1eeb88-9816-0410-afa2-b43733a0f04e"
] | Vampire0@6b1eeb88-9816-0410-afa2-b43733a0f04e |
ecc7ed0f42d5f42e80e0b90b16cc8f091946735a | 95f1a0351408d4c099213e3b088b96fca025995e | /leet-java/src/main/java/study/leet/tree/IsBalanceTree.java | b91379c848e41cd1354f7e38d3cb0d2247cd19b7 | [] | no_license | moneyache/leet | bb145dd791afc5d31590487bc78641ba9e5b811d | cd12698b7218545347561f0199f13bbdc44da252 | refs/heads/master | 2021-01-10T06:13:45.772564 | 2016-09-14T09:16:23 | 2016-09-14T09:16:23 | 48,754,691 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,100 | java | package study.leet.tree;
import java.util.LinkedList;
public class IsBalanceTree {
private LinkedList<Integer> leafNodeDepth;
public IsBalanceTree() {
// TODO Auto-generated constructor stub
leafNodeDepth=new LinkedList<>();
}
public Boolean isBalanceTree(TreeNode<String> treeNode) {
getLeafDepth(treeNode, 0);
if (leafNodeDepth.isEmpty()) {
return false;
}
int max=0,min=Integer.MAX_VALUE;
for (int leafDepth : leafNodeDepth) {
max=leafDepth>max?leafDepth:max;
min=leafDepth<min?leafDepth:min;
}
if ((max-min)>=2) {
return false;
}
return true;
}
private void getLeafDepth(TreeNode<String> treeNode,int level) {
if (treeNode==null) {
return;
}
level++;
if (treeNode.leftChild!=null) {
getLeafDepth(treeNode.leftChild,level);
}
if (treeNode.rightChild!=null) {
getLeafDepth(treeNode.rightChild,level);
}
if ((treeNode.leftChild==null)&&(treeNode.rightChild==null)) {
leafNodeDepth.add(level);
}
}
public void levelTraver(TreeNode<String> treeNode) {
LinkedList<TreeNode<String>> nodeQueue=new LinkedList<>();
if (treeNode==null) {
return;
}
nodeQueue.add(treeNode);
while (!nodeQueue.isEmpty()) {
TreeNode<String> current=nodeQueue.remove();
if (current.leftChild!=null) {
nodeQueue.add(treeNode.leftChild);
}
if (current.rightChild!=null) {
nodeQueue.add(treeNode.rightChild);
}
}
}
public static void main(String[] args) {
TreeNode<String> r1 = new TreeNode<>("1");
TreeNode<String> r2 = new TreeNode<>("2");
TreeNode<String> r3 = new TreeNode<>("3");
TreeNode<String> r4 = new TreeNode<>("4");
TreeNode<String> r5 = new TreeNode<>("5");
TreeNode<String> r6 = new TreeNode<>("6");
TreeNode<String> r7 = new TreeNode<>("6");
r1.leftChild = r2;
r1.rightChild = r7;
r6.rightChild = r3;
r2.leftChild = r4;
r2.rightChild = r5;
r5.rightChild= r6;
IsBalanceTree isBalanceTree=new IsBalanceTree();
//System.out.println(getMinDepth(r1)+"test:"+Math.min(0, 0));
System.out.println(isBalanceTree.isBalanceTree(r2));
}
}
| [
"chanteng@qq.com"
] | chanteng@qq.com |
9be695520edc347c3cf9d72b948ebbc99679d97e | 8fe36331d54a93195d5f1ba72f6fb3bcde4a63ea | /IG2Cast/app/src/main/java/android/ig2i/ig2cast/SlidingTabStrip.java | 5331f928e3a359584a2313f7fdf22d23658848b7 | [] | no_license | pachr/Android-Player | 3e2150f1378ffcdecf6d39355b7ace3b9fbbc883 | 3f77b0e9bbb44964b0869762c0b2ea7a07f4e7be | refs/heads/develop | 2021-01-01T03:57:37.168192 | 2016-06-03T14:10:18 | 2016-06-03T14:10:18 | 58,560,196 | 0 | 0 | null | 2016-06-03T14:10:18 | 2016-05-11T16:05:50 | Java | UTF-8 | Java | false | false | 6,346 | java | /*
* Copyright 2014 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.ig2i.ig2cast;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;
class SlidingTabStrip extends LinearLayout {
private static final int DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS = 0;
private static final byte DEFAULT_BOTTOM_BORDER_COLOR_ALPHA = 0x26;
private static final int SELECTED_INDICATOR_THICKNESS_DIPS = 3;
private static final int DEFAULT_SELECTED_INDICATOR_COLOR = 0xFF33B5E5;
private final int mBottomBorderThickness;
private final Paint mBottomBorderPaint;
private final int mSelectedIndicatorThickness;
private final Paint mSelectedIndicatorPaint;
private int mSelectedPosition;
private float mSelectionOffset;
private SlidingTabLayout.TabColorizer mCustomTabColorizer;
private final SimpleTabColorizer mDefaultTabColorizer;
SlidingTabStrip(Context context) {
this(context, null);
}
SlidingTabStrip(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
final float density = getResources().getDisplayMetrics().density;
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.colorForeground, outValue, true);
final int themeForegroundColor = outValue.data;
int defaultBottomBorderColor = setColorAlpha(themeForegroundColor,
DEFAULT_BOTTOM_BORDER_COLOR_ALPHA);
mDefaultTabColorizer = new SimpleTabColorizer();
mDefaultTabColorizer.setIndicatorColors(DEFAULT_SELECTED_INDICATOR_COLOR);
mBottomBorderThickness = (int) (DEFAULT_BOTTOM_BORDER_THICKNESS_DIPS * density);
mBottomBorderPaint = new Paint();
mBottomBorderPaint.setColor(defaultBottomBorderColor);
mSelectedIndicatorThickness = (int) (SELECTED_INDICATOR_THICKNESS_DIPS * density);
mSelectedIndicatorPaint = new Paint();
}
void setCustomTabColorizer(SlidingTabLayout.TabColorizer customTabColorizer) {
mCustomTabColorizer = customTabColorizer;
invalidate();
}
void setSelectedIndicatorColors(int... colors) {
// Make sure that the custom colorizer is removed
mCustomTabColorizer = null;
mDefaultTabColorizer.setIndicatorColors(colors);
invalidate();
}
void onViewPagerPageChanged(int position, float positionOffset) {
mSelectedPosition = position;
mSelectionOffset = positionOffset;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
final int height = getHeight();
final int childCount = getChildCount();
final SlidingTabLayout.TabColorizer tabColorizer = mCustomTabColorizer != null
? mCustomTabColorizer
: mDefaultTabColorizer;
// Thick colored underline below the current selection
if (childCount > 0) {
View selectedTitle = getChildAt(mSelectedPosition);
int left = selectedTitle.getLeft();
int right = selectedTitle.getRight();
int color = tabColorizer.getIndicatorColor(mSelectedPosition);
if (mSelectionOffset > 0f && mSelectedPosition < (getChildCount() - 1)) {
int nextColor = tabColorizer.getIndicatorColor(mSelectedPosition + 1);
if (color != nextColor) {
color = blendColors(nextColor, color, mSelectionOffset);
}
// Draw the selection partway between the tabs
View nextTitle = getChildAt(mSelectedPosition + 1);
left = (int) (mSelectionOffset * nextTitle.getLeft() +
(1.0f - mSelectionOffset) * left);
right = (int) (mSelectionOffset * nextTitle.getRight() +
(1.0f - mSelectionOffset) * right);
}
mSelectedIndicatorPaint.setColor(color);
canvas.drawRect(left, height - mSelectedIndicatorThickness, right,
height, mSelectedIndicatorPaint);
}
// Thin underline along the entire bottom edge
canvas.drawRect(0, height - mBottomBorderThickness, getWidth(), height, mBottomBorderPaint);
}
/**
* Set the alpha value of the {@code color} to be the given {@code alpha} value.
*/
private static int setColorAlpha(int color, byte alpha) {
return Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Blend {@code color1} and {@code color2} using the given ratio.
*
* @param ratio of which to blend. 1.0 will return {@code color1}, 0.5 will give an even blend,
* 0.0 will return {@code color2}.
*/
private static int blendColors(int color1, int color2, float ratio) {
final float inverseRation = 1f - ratio;
float r = (Color.red(color1) * ratio) + (Color.red(color2) * inverseRation);
float g = (Color.green(color1) * ratio) + (Color.green(color2) * inverseRation);
float b = (Color.blue(color1) * ratio) + (Color.blue(color2) * inverseRation);
return Color.rgb((int) r, (int) g, (int) b);
}
private static class SimpleTabColorizer implements SlidingTabLayout.TabColorizer {
private int[] mIndicatorColors;
@Override
public final int getIndicatorColor(int position) {
return mIndicatorColors[position % mIndicatorColors.length];
}
void setIndicatorColors(int... colors) {
mIndicatorColors = colors;
}
}
} | [
"kevin lawuy"
] | kevin lawuy |
d7cda70b0b2a95ff1065eb817417a2270cadeb03 | 1054465e1c9c1b95448a5b38feec775c035d5b44 | /app/src/main/java/cn/com/custom/widgetproject/activity/SplashActivity.java | 4d0e5fde31dd81888509e0a88bebbf739035bd15 | [] | no_license | stay4it2geek/Widgets_Project | 2f66450b8f4a22f922be87ad8deeaad7eb2a9519 | 94ee5dd92d998a40c70c7a052205acb71e076504 | refs/heads/master | 2020-12-05T03:16:56.354352 | 2016-08-19T01:50:05 | 2016-08-19T01:50:05 | 66,043,213 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,412 | java | package cn.com.custom.widgetproject.activity;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import com.google.gson.Gson;
import cn.com.custom.widgetproject.R;
import cn.com.custom.widgetproject.callback.CommonDialogCallback;
import cn.com.custom.widgetproject.callback.ResponseCallback;
import cn.com.custom.widgetproject.dialogs.CommonMessageDialog;
import cn.com.custom.widgetproject.manager.ApiManager;
import cn.com.custom.widgetproject.manager.StorageManager;
import cn.com.custom.widgetproject.model.SearchCategoryModel;
import cn.com.custom.widgetproject.utils.ConnectivityUtil;
import cn.com.custom.widgetproject.utils.JsonUtil;
import cn.com.custom.widgetproject.utils.StringUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* 启动画面
*/
public class SplashActivity extends AppCompatActivity {
//logo
private ImageView mImageLogo;
//错误信息提示对话框
private CommonMessageDialog commonErrorDialog;
private ArrayList<SearchCategoryModel.Geners> genersArrayList;
private UnCheckIconThread uncheckThread;
private CheckIconThread checkThread;
private SaveListThread saveListThread;
ArrayList<String> iconDefaultPath = new ArrayList<>();
ArrayList<String> iconHightPath = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mImageLogo = (ImageView) findViewById(R.id.iv_logo);
checkThread = new CheckIconThread();
uncheckThread = new UnCheckIconThread();
AnimationSet animationSet = new AnimationSet(true);
AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
alphaAnimation.setDuration(4000);
animationSet.addAnimation(alphaAnimation);
mImageLogo.startAnimation(animationSet);
animationSet.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
new Handler().post(new Runnable() {
@Override
public void run() {
requestSearchCategory();
}
});
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
class CheckIconThread extends Thread {
@Override
public void run() {
ArrayList<SearchCategoryModel.Geners> genersArrayList = JsonUtil.toObjectList(StorageManager.getGenresCategory(SplashActivity.this), SearchCategoryModel.Geners.class);
try {
for (SearchCategoryModel.Geners generses : genersArrayList) {
// DevUtil.e("generses", generses.icon_highlight);
URL url = new URL(generses.icon_highlight);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream inSream = conn.getInputStream();
//把图片保存到项目的根目录
File file = new File(Environment.getExternalStorageDirectory() + "/" + "hig" + StringUtils.substringAfterLast(generses.icon_highlight, "/"));
readAsFile(inSream, file);
iconHightPath.add(file.getAbsolutePath());
StorageManager.saveHighlightIconListsize(SplashActivity.this, iconHightPath.size() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class UnCheckIconThread extends Thread {
@Override
public void run() {
try {
ArrayList<SearchCategoryModel.Geners> genersArrayList = JsonUtil.toObjectList(StorageManager.getGenresCategory(SplashActivity.this), SearchCategoryModel.Geners.class);
for (SearchCategoryModel.Geners generses : genersArrayList) {
// DevUtil.e("generses2", generses.icon_default);
URL url = new URL(generses.icon_default);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(6 * 1000); // 注意要设置超时,设置时间不要超过10秒,避免被android系统回收
if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
InputStream inSream = conn.getInputStream();
//把图片保存到项目的根目录
File file = new File(Environment.getExternalStorageDirectory() + "/" + "def" + StringUtils.substringAfterLast(generses.icon_default, "/"));
readAsFile(inSream, file);
iconDefaultPath.add(file.getAbsolutePath());
StorageManager.saveDefaultIconListsize(SplashActivity.this, iconDefaultPath.size() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class SaveListThread extends Thread {
private SearchCategoryModel model;
public SaveListThread(SearchCategoryModel model) {
this.model = model;
}
@Override
public void run() {
try {
Gson gson = new Gson();
if (genersArrayList.size() == iconDefaultPath.size() && iconDefaultPath.size() == iconHightPath.size()) {
for (int i = 0; i < genersArrayList.size(); i++) {
model.genres.get(i).icon_default = model.genres.get(i).icon_default + "@" + iconDefaultPath.get(i);
model.genres.get(i).icon_highlight = model.genres.get(i).icon_highlight + "@" + iconHightPath.get(i);
}
StorageManager.saveTopPageNeedGenres(SplashActivity.this, gson.toJson(model.genres));
startNextActivity(false);
} else {
try {
checkThread.start();
if (!checkThread.isAlive()) {
checkThread.start();
}
checkThread.join();
uncheckThread.start();
if (!uncheckThread.isAlive()) {
uncheckThread.start();
}
uncheckThread.join();
saveListThread.start();
if (!saveListThread.isAlive()) {
saveListThread.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void readAsFile(InputStream inSream, File file) throws Exception {
FileOutputStream outStream = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inSream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.close();
inSream.close();
}
@Override
protected void onResume() {
super.onResume();
/**
* 进行网络检查,通过则检索数据,如果有错误对话框则让其消失
*/
if (commonErrorDialog != null && ConnectivityUtil.checkNetwork(this)) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
requestSearchCategory();
commonErrorDialog.dismiss();
}
}, 500);
}
}
/**
* 表示Error Dialog
*/
private void showErrorDialog(final String string, final boolean isShowTitle) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (commonErrorDialog == null) {
commonErrorDialog = new CommonMessageDialog(SplashActivity.this, string, R.string.dialog_title, isShowTitle);
commonErrorDialog.setCallback(new CommonDialogCallback() {
@Override
public void onConfirmClick() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
requestSearchCategory();
}
}, 2000);
dismissErrorProgress();
}
@Override
public void onCancleClick() {
SplashActivity.this.finish();
}
});
commonErrorDialog.show();
}
}
});
}
/**
* 隐藏Error Dialog
*/
private void dismissErrorProgress() {
if (commonErrorDialog != null) {
commonErrorDialog.dismiss();
commonErrorDialog = null;
}
}
/**
* 请求分类数据
*/
private void requestSearchCategory() {
ApiManager.getInstance(this).requestSearchCategoryModel(new ResponseCallback<SearchCategoryModel>() {
@Override
public void onFailure(Request request, Exception e) {
showErrorDialog(getResources().getString(R.string.error_net), true);
}
@Override
public void onResponse(Response response, SearchCategoryModel model) {
if (model != null) {
saveListThread = new SaveListThread(model);
Gson gson = new Gson();
StorageManager.saveGenresCategory(SplashActivity.this, gson.toJson(model.genres));
genersArrayList = JsonUtil.toObjectList(StorageManager.getGenresCategory(SplashActivity.this), SearchCategoryModel.Geners.class);
if (StringUtil.isEmpty(StorageManager.getTimeTamp(SplashActivity.this))) { //如果时间戳保存为空
//如果本地时间戳为空,则保存网络时间戳和网络分类字符串
StorageManager.saveTimeTamp(SplashActivity.this, model.timestamp);
try {
checkThread.start();
if (!checkThread.isAlive()) {
checkThread.start();
}
checkThread.join();
uncheckThread.start();
if (!uncheckThread.isAlive()) {
uncheckThread.start();
}
uncheckThread.join();
saveListThread.start();
if (!saveListThread.isAlive()) {
saveListThread.start();
}
} catch (InterruptedException e) {
if (Integer.parseInt(StorageManager.getDefaultIconListsize(SplashActivity.this)) != genersArrayList.size()
|| Integer.parseInt(StorageManager.getHighlightIconListsize(SplashActivity.this)) != genersArrayList.size()) {
startNextActivity(true);
} else {
startNextActivity(false);
}
}
} else {//如果时间戳保存不为空
if (!StringUtil.isEqual(StorageManager.getTimeTamp(SplashActivity.this), model.timestamp)) {
//如果本地时间戳与网络时间戳不一样,则保存网络时间戳
StorageManager.saveTimeTamp(SplashActivity.this, model.timestamp);
try {
checkThread.start();
if (!checkThread.isAlive()) {
checkThread.start();
}
checkThread.join();
uncheckThread.start();
if (!uncheckThread.isAlive()) {
uncheckThread.start();
}
uncheckThread.join();
saveListThread.start();
if (!saveListThread.isAlive()) {
saveListThread.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {//如果本地时间戳与网络时间戳一样,
if (Integer.parseInt(StorageManager.getDefaultIconListsize(SplashActivity.this)) != genersArrayList.size()
|| Integer.parseInt(StorageManager.getHighlightIconListsize(SplashActivity.this)) != genersArrayList.size()) {
startNextActivity(true);
} else {
startNextActivity(false);
}
}
}
} else {
//数据为空的处理,errorDialog或者是重新请求
showErrorDialog(getResources().getString(R.string.error_net), false);
}
}
});
}
private void startNextActivity(final boolean isNeedNetUrl) {
runOnUiThread(new Runnable() {
@Override
public void run() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.putExtra("isNeedNetUrl", isNeedNetUrl);
startActivity(intent);
SplashActivity.this.finish();
}
},2000);
}
});
}
}
| [
"stay4it2geek"
] | stay4it2geek |
bb6939dbc53a8c6c1dbd7aa30cf1509dbe489a23 | 43eeac615caccc1c3e7b51669200be347bee99ad | /src/main/java/com/springmvc/entity/ClassificationguideExample.java | 8f684a49c6f5cfa3c7382b725d2088feef1adc39 | [] | no_license | fengwenya2019/idea-garbage-systerm | 05bea6bb798489997e1c5ff2472e18079911e612 | 854253e7b8bd84386b900afdcec9ea18507974e0 | refs/heads/master | 2022-12-23T09:44:05.470579 | 2020-03-18T13:30:45 | 2020-03-18T13:30:45 | 248,239,004 | 0 | 0 | null | 2022-12-16T07:47:35 | 2020-03-18T13:27:40 | Java | UTF-8 | Java | false | false | 13,997 | java | package com.springmvc.entity;
import java.util.ArrayList;
import java.util.List;
public class ClassificationguideExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ClassificationguideExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andClassificationguideinfoIdIsNull() {
addCriterion("ClassificationGuideInfo_id is null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdIsNotNull() {
addCriterion("ClassificationGuideInfo_id is not null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_id =", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdNotEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_id <>", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdGreaterThan(Integer value) {
addCriterion("ClassificationGuideInfo_id >", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdGreaterThanOrEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_id >=", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdLessThan(Integer value) {
addCriterion("ClassificationGuideInfo_id <", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdLessThanOrEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_id <=", value, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdIn(List<Integer> values) {
addCriterion("ClassificationGuideInfo_id in", values, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdNotIn(List<Integer> values) {
addCriterion("ClassificationGuideInfo_id not in", values, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdBetween(Integer value1, Integer value2) {
addCriterion("ClassificationGuideInfo_id between", value1, value2, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoIdNotBetween(Integer value1, Integer value2) {
addCriterion("ClassificationGuideInfo_id not between", value1, value2, "classificationguideinfoId");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameIsNull() {
addCriterion("ClassificationGuideInfo_name is null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameIsNotNull() {
addCriterion("ClassificationGuideInfo_name is not null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameEqualTo(String value) {
addCriterion("ClassificationGuideInfo_name =", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameNotEqualTo(String value) {
addCriterion("ClassificationGuideInfo_name <>", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameGreaterThan(String value) {
addCriterion("ClassificationGuideInfo_name >", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameGreaterThanOrEqualTo(String value) {
addCriterion("ClassificationGuideInfo_name >=", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameLessThan(String value) {
addCriterion("ClassificationGuideInfo_name <", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameLessThanOrEqualTo(String value) {
addCriterion("ClassificationGuideInfo_name <=", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameLike(String value) {
addCriterion("ClassificationGuideInfo_name like", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameNotLike(String value) {
addCriterion("ClassificationGuideInfo_name not like", value, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameIn(List<String> values) {
addCriterion("ClassificationGuideInfo_name in", values, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameNotIn(List<String> values) {
addCriterion("ClassificationGuideInfo_name not in", values, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameBetween(String value1, String value2) {
addCriterion("ClassificationGuideInfo_name between", value1, value2, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoNameNotBetween(String value1, String value2) {
addCriterion("ClassificationGuideInfo_name not between", value1, value2, "classificationguideinfoName");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationIsNull() {
addCriterion("ClassificationGuideInfo_classification is null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationIsNotNull() {
addCriterion("ClassificationGuideInfo_classification is not null");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_classification =", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationNotEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_classification <>", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationGreaterThan(Integer value) {
addCriterion("ClassificationGuideInfo_classification >", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationGreaterThanOrEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_classification >=", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationLessThan(Integer value) {
addCriterion("ClassificationGuideInfo_classification <", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationLessThanOrEqualTo(Integer value) {
addCriterion("ClassificationGuideInfo_classification <=", value, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationIn(List<Integer> values) {
addCriterion("ClassificationGuideInfo_classification in", values, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationNotIn(List<Integer> values) {
addCriterion("ClassificationGuideInfo_classification not in", values, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationBetween(Integer value1, Integer value2) {
addCriterion("ClassificationGuideInfo_classification between", value1, value2, "classificationguideinfoClassification");
return (Criteria) this;
}
public Criteria andClassificationguideinfoClassificationNotBetween(Integer value1, Integer value2) {
addCriterion("ClassificationGuideInfo_classification not between", value1, value2, "classificationguideinfoClassification");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | [
"1462282654@qq.com"
] | 1462282654@qq.com |
1fbfd7b0bb103703e302c20278f8e45168856fa0 | e6003449ca4ea358511b923dd91c6a32f6abb64b | /AddJava/src/thread/DeadLockDemo.java | c0f7ea3163d0fa5ee3709e58b4e82c1ac83d24e1 | [] | no_license | Jiao-man-22/JAVA | 5fa286b457b69ac84a4035415e08fd37707c2726 | 8aaab7d926d7448a021aa501a6998ea2a9b11b81 | refs/heads/master | 2023-01-18T23:44:32.018920 | 2020-11-23T14:57:55 | 2020-11-23T14:57:55 | 263,896,187 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,672 | java | package thread;
/*线程死锁
* 一个 snychronized 修饰的方法 可以在多个线程之间进行同步
* 当一个线程进入snychronized 修饰的方法 其他线程就不能进入这个对象 的所有synchroniezd修饰的的方法,直到synchronied修饰的方法结束
*
* */
public class DeadLockDemo implements Runnable {
A a = new A();
B b = new B();
public DeadLockDemo() {
//设置当前 线程名称
Thread.currentThread().setName("Main====>Thread");
Thread thread = new Thread(this);
thread.start();
a.funA(b);
System.out.println("main线程运行完毕 ");
}
@Override
public void run() {
// TODO Auto-generated method stub
Thread.currentThread().setName("Test===>Thread");;
new Thread(this).start();
b.funB(a);
System.out.println("其它线程运行完毕 ");
}
}
class A{
synchronized void funA(B b) {
String name = Thread.currentThread().getName();
System.out.println(name+"进入 A.foo");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name +"调用 B类中的 last 方法 ");
b.last();
}
synchronized void last() {
System.out.println("A类中的last 方法 ");
}
}
class B{
synchronized void funB(A a) {
String name = Thread.currentThread().getName();
System.out.println(name+"进入 b.foo");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+"调用A类中的last 方法 ");
a.last();
}
synchronized void last() {
System.out.println("B类中的 last 方法 ");
}
}
| [
"2935996123@qq.com"
] | 2935996123@qq.com |
1060aaf2f72866134cc6dda60ee0ad9996212536 | 6f516315e7454a250ad09c6ac1a1bbffd284917b | /.svn/pristine/1a/1a4534e53bf3c358e0039dd9c241c9d2bfa54e7d.svn-base | 26d3f86336ec8591f027950255991c26c7c8c4ae | [] | no_license | tianxiao666/rno-gsm | ee50b243f012615487f6a8a30e90bc01f4c20517 | 9527fae599c4f5ddb4f7b19da78cc36f2f33919d | refs/heads/master | 2021-04-03T04:17:53.751162 | 2018-03-13T09:19:15 | 2018-03-13T09:19:15 | 125,024,357 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 538 | package com.hgicreate.rno.gsm.service.optimize;
import com.hgicreate.rno.gsm.model.Page;
import java.util.List;
import java.util.Map;
public interface AccordanceCheckService {
/**
*分页计算一致性检查
*/
List<Map<String,Object>> calculateAccordanceByPage(Map<String,Object> condition,Page page,String order) throws Exception;
/**
*分页查询一致性检查
*/
List<Map<String, Object>> inquireAccordanceByPage(Map<String, Object> condition, Page page,String order) throws Exception;
}
| [
"chao.xj@hgicreate.com"
] | chao.xj@hgicreate.com | |
ba69406a9d238417fcd4e24e15d0839620edcf18 | fd2193a1aaf54a8a68ab62e95e1de8e0f785d503 | /problems/src/main/java/utils/graph/Point.java | 35f161d1aa951d8ff0870a85de744c8101b8690b | [
"MIT"
] | permissive | yangyangv2/leet-code | a4903151343a4c835e3f4dc3b6531179d4d4edd5 | 6419661bba796e896017faa30575747d136685f7 | refs/heads/master | 2021-01-01T17:14:10.311219 | 2018-06-12T22:54:30 | 2018-06-12T22:54:30 | 98,030,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 261 | java | package utils.graph;
/**
* Created by yanya04 on 1/14/2018.
*/
public class Point
{
public int x;
public int y;
public Point()
{
x = 0;
y = 0;
}
public Point(int a, int b)
{
x = a;
y = b;
}
}
| [
"yang.yang@ca.com"
] | yang.yang@ca.com |
a1bfed7b11b34a3b34d3aa93c1eaa2c7b8c93ccc | 6baf1fe00541560788e78de5244ae17a7a2b375a | /hollywood/com.oculus.unifiedtelemetry-UnifiedTelemetry/sources/com/facebook/acra/anrreport/ANRReport.java | 09a3e6ec1eb63d5bde88069c8e70ea5316301f50 | [] | 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 | 16,497 | java | package com.facebook.acra.anrreport;
import X.AnonymousClass06;
import X.Mu;
import android.content.Context;
import com.facebook.acra.ACRA;
import com.facebook.acra.ErrorReporter;
import com.facebook.acra.FileGenerator;
import com.facebook.acra.PerformanceMarker;
import com.facebook.acra.anr.ANRDataProvider;
import com.facebook.acra.anr.IANRReport;
import com.facebook.acra.anr.SigquitRecord;
import com.facebook.acra.asyncbroadcastreceiver.AsyncBroadcastReceiverObserver;
import com.facebook.acra.constants.ErrorReportingConstants;
import com.squareup.okhttp.internal.DiskLruCache;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.annotation.Nullable;
public class ANRReport implements IANRReport {
public static final String LOG_TAG = "ANRReport";
public static final int MAXIMUM_NUMBER_OF_OTHER_PROCESSES_TO_REPORT = 5;
public ANRDataProvider mANRDataProvider;
public final Map<String, String> mANRProcessErrorProperties = new HashMap();
public Context mContext;
public int mCurrentAnrProcessStateIndex;
public final ErrorReporter mErrorReporter;
public final UUIDFileGenerator mFileGenerator;
public int mMaxUsedAnrProcessStateIndex;
public PerformanceMarker mPerformanceMarker;
public File mTracesFile;
public static class UUIDFileGenerator implements FileGenerator {
public final Context mContext;
public final String mDirectory;
public final String mExtension;
@Override // com.facebook.acra.FileGenerator
public File generate() {
return new File(this.mContext.getDir(this.mDirectory, 0), AnonymousClass06.A04(UUID.randomUUID().toString(), this.mExtension));
}
public UUIDFileGenerator(Context context, String str, String str2) {
this.mContext = context;
this.mExtension = str;
this.mDirectory = str2;
}
}
public static boolean deleteFile(File file) {
if (file == null) {
return true;
}
boolean delete = file.delete();
if (delete) {
return delete;
}
if (!file.exists()) {
return true;
}
Mu.A06(LOG_TAG, "Could not delete error report: %s", file.getName());
return delete;
}
private void addProcessErrorPropertiesToErrorReport() {
synchronized (this.mANRProcessErrorProperties) {
try {
if (this.mErrorReporter.addToAnrInProgressUpdateFile(this.mANRProcessErrorProperties)) {
this.mANRProcessErrorProperties.clear();
}
} catch (IOException unused) {
}
}
}
private void initializeProcessErrorPropertiesOnErrorReport() {
synchronized (this.mANRProcessErrorProperties) {
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTED, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTED));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_TIME, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_TIME));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_CAUSE, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_CAUSE));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_SYSTEM_ERROR_MSG, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_SYSTEM_ERROR_MSG));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_SYSTEM_TAG, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_SYSTEM_TAG));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_START_TIME, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_START_TIME));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_MAIN_THREAD_UNBLOCKED_UPTIME, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_MAIN_THREAD_UNBLOCKED_UPTIME));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_AM_CONFIRMATION_EXPIRED_UPTIME, this.mANRProcessErrorProperties.get(ErrorReportingConstants.ANR_AM_CONFIRMATION_EXPIRED_UPTIME));
for (int i = 1; i <= this.mMaxUsedAnrProcessStateIndex; i++) {
ErrorReporter.putCustomData(AnonymousClass06.A01(ErrorReportingConstants.ANR_OTHER_PROCESS_ERROR_PREFIX, i), this.mANRProcessErrorProperties.get(AnonymousClass06.A01(ErrorReportingConstants.ANR_OTHER_PROCESS_ERROR_PREFIX, i)));
}
this.mANRProcessErrorProperties.clear();
}
}
public static void purgeDirectory(File file) {
if (!(file == null || file.listFiles() == null)) {
File[] listFiles = file.listFiles();
for (File file2 : listFiles) {
if (file2.isDirectory()) {
purgeDirectory(file2);
}
deleteFile(file2);
}
}
}
@Override // com.facebook.acra.anr.IANRReport
public void finalizeAndTryToSendReport(long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.clear();
this.mCurrentAnrProcessStateIndex = 1;
}
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_RECOVERY_DELAY_TAG, String.valueOf(j));
if (this.mANRDataProvider != null) {
purgeDirectory(this.mContext.getDir(ErrorReporter.SIGQUIT_DIR, 0));
} else {
this.mErrorReporter.prepareReports(Integer.MAX_VALUE, null, true, ErrorReporter.CrashReportType.CACHED_ANR_REPORT);
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logAmExpiration(long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_AM_CONFIRMATION_EXPIRED_UPTIME, Long.toString(j));
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logExtraSigquit(long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_EXTRA_SIGQUIT_UPTIME, Long.toString(j));
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logMainThreadUnblocked(long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_MAIN_THREAD_UNBLOCKED_UPTIME, Long.toString(j));
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logOtherProcessAnr(String str, @Nullable String str2, @Nullable String str3, long j) {
synchronized (this.mANRProcessErrorProperties) {
int i = this.mCurrentAnrProcessStateIndex;
if (i < 5) {
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.append(',');
sb.append(j);
sb.append(',');
sb.append(str2);
sb.append(',');
sb.append(str3);
this.mANRProcessErrorProperties.put(AnonymousClass06.A01(ErrorReportingConstants.ANR_OTHER_PROCESS_ERROR_PREFIX, i), sb.toString());
addProcessErrorPropertiesToErrorReport();
int i2 = this.mCurrentAnrProcessStateIndex;
if (i2 > this.mMaxUsedAnrProcessStateIndex) {
this.mMaxUsedAnrProcessStateIndex = i2;
}
this.mCurrentAnrProcessStateIndex = i2 + 1;
}
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logProcessMonitorFailure(long j, int i) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_TIME, Long.toString(j));
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_FAILURE_CAUSE, Integer.toString(i));
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logProcessMonitorStart(long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTION_START_TIME, Long.toString(j));
this.mCurrentAnrProcessStateIndex = 1;
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logSigquitData(@Nullable String str, @Nullable String str2, long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_JAVA_CALLBACK_UPTIME, Long.toString(j));
if (!(str == null && str2 == null)) {
try {
this.mErrorReporter.amendANRReportWithSigquitData(str, str2);
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_WITH_SIGQUIT_TRACES, DiskLruCache.VERSION_1);
} catch (IOException e) {
Mu.A02(LOG_TAG, "Failed to save SIGQUIT", e);
}
}
addProcessErrorPropertiesToErrorReport();
}
}
@Override // com.facebook.acra.anr.IANRReport
public void logSystemInfo(@Nullable String str, @Nullable String str2, long j) {
synchronized (this.mANRProcessErrorProperties) {
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_PROCESS_ERROR_DETECTED, Long.toString(j));
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_SYSTEM_ERROR_MSG, str);
this.mANRProcessErrorProperties.put(ErrorReportingConstants.ANR_SYSTEM_TAG, str2);
addProcessErrorPropertiesToErrorReport();
}
}
public ANRReport(Context context, ErrorReporter errorReporter) {
this.mContext = context;
this.mErrorReporter = errorReporter;
this.mFileGenerator = new UUIDFileGenerator(context, ".cachedreport", ErrorReporter.SIGQUIT_DIR);
this.mCurrentAnrProcessStateIndex = 1;
this.mMaxUsedAnrProcessStateIndex = 0;
}
public FileGenerator getFileGenerator() {
return this.mFileGenerator;
}
public void setANRDataProvider(ANRDataProvider aNRDataProvider) {
this.mANRDataProvider = aNRDataProvider;
}
public void setPerformanceMarker(PerformanceMarker performanceMarker) {
this.mPerformanceMarker = performanceMarker;
}
@Override // com.facebook.acra.anr.IANRReport
public void startReport(boolean z, @Nullable String str, @Nullable String str2, int i, boolean z2, boolean z3, long j, long j2, long j3, long j4, @Nullable String str3, @Nullable String str4, boolean z4, boolean z5, @Nullable Long l) throws IOException {
String str5;
OutputStream outputStream;
long appStartTickTimeMs = j - this.mErrorReporter.getAppStartTickTimeMs();
long appStartTickTimeMs2 = j2 - this.mErrorReporter.getAppStartTickTimeMs();
PerformanceMarker performanceMarker = this.mPerformanceMarker;
if (performanceMarker != null) {
performanceMarker.markerStart();
}
initializeProcessErrorPropertiesOnErrorReport();
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTED_UPTIME, String.valueOf(j));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECT_TIME_TAG, String.valueOf(appStartTickTimeMs));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_RECOVERY_DELAY_TAG, ErrorReportingConstants.ANR_DEFAULT_RECOVERY_DELAY_VAL);
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTED_PRE_GKSTORE, String.valueOf(z));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTOR_ID, String.valueOf(i));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTOR_START_TIME, String.valueOf(appStartTickTimeMs2));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_STARTED_IN_FOREGROUND, String.valueOf(z2));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_STARTED_IN_FOREGROUND_V2, String.valueOf(z3));
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_JAVA_CALLBACK_UPTIME, String.valueOf(l));
if (j3 > 0) {
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTOR_ACTUAL_START_TIME, String.valueOf(j3 - this.mErrorReporter.getAppStartTickTimeMs()));
}
if (j4 > 0) {
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_DETECTOR_SWITCH_TIME, String.valueOf(j4 - this.mErrorReporter.getAppStartTickTimeMs()));
}
ErrorReporter.putCustomData(ErrorReportingConstants.BLACK_BOX_TRACE_ID, str);
ErrorReporter.putCustomData(ErrorReportingConstants.LONG_STALL_TRACE_ID, str2);
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_ASYNC_BROADCAST_RECEIVERS, AsyncBroadcastReceiverObserver.blameActiveReceivers());
OutputStream outputStream2 = null;
ErrorReporter.putCustomData(ErrorReportingConstants.FIRST_SIGQUIT_FROM_PROCESSES, null);
if (z5) {
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_SIGQUIT_RECORDS, SigquitRecord.getRecordsJson(l));
}
boolean flagValue = ACRA.getFlagValue(ACRA.SHOULD_DEDUP_DISK_PERSISTENCE_GK_CACHED);
if (z4) {
str5 = DiskLruCache.VERSION_1;
} else {
str5 = "0";
}
try {
ErrorReporter.putCustomData(ErrorReportingConstants.ANR_WITH_SIGQUIT_TRACES, str5);
if (str4 == null) {
if (flagValue) {
outputStream = new ByteArrayOutputStream();
} else {
File file = this.mTracesFile;
if (file == null) {
file = new UUIDFileGenerator(this.mContext, ErrorReporter.REPORTFILE_EXTENSION, ErrorReporter.SIGQUIT_DIR).generate();
this.mTracesFile = file;
}
outputStream = new FileOutputStream(file);
}
outputStream2 = outputStream;
if (str3 != null) {
PrintWriter printWriter = new PrintWriter(outputStream2);
if (!flagValue) {
printWriter.println(this.mErrorReporter.getAppVersionCode());
printWriter.println(this.mErrorReporter.getAppVersionName());
}
printWriter.write(str3);
printWriter.flush();
}
if (flagValue) {
this.mErrorReporter.prepareANRReport(outputStream2.toString(), this.mFileGenerator);
} else {
this.mTracesFile.getCanonicalPath();
this.mTracesFile.length();
this.mErrorReporter.prepareANRReport(this.mTracesFile, this.mFileGenerator);
}
} else {
this.mErrorReporter.prepareANRReport(new File(str4), this.mFileGenerator);
}
PerformanceMarker performanceMarker2 = this.mPerformanceMarker;
if (performanceMarker2 != null) {
performanceMarker2.markerEnd(2);
}
if (outputStream2 != null) {
outputStream2.close();
}
synchronized (this.mANRProcessErrorProperties) {
addProcessErrorPropertiesToErrorReport();
}
} catch (IOException e) {
PerformanceMarker performanceMarker3 = this.mPerformanceMarker;
if (performanceMarker3 != null) {
performanceMarker3.markerEnd(3);
}
throw e;
} catch (Throwable th) {
if (0 != 0) {
outputStream2.close();
}
throw th;
}
}
}
| [
"cyuubiapps@gmail.com"
] | cyuubiapps@gmail.com |
0a2cbf3d0ec705414c97c1ce73f79926457b054f | 81bfff445e88f330e059b9525e92c227bd6bb1e0 | /src/com/awarematics/postmedia/types/ev/geom/package-info.java | c3a475e591409b33aaec87fbac1e310c9968870d | [] | no_license | awarematics/mgeometry | 02a0bc2832102c3fcc47f66a301b4552ca9a57a0 | a9698cd43ec166146f1a3cb9dff4ceaa58b0f8e5 | refs/heads/master | 2023-04-27T11:16:11.956364 | 2022-08-29T12:12:40 | 2022-08-29T12:12:40 | 142,313,939 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 95 | java | /**
*
*/
/**
* @author kwnam
*
*/
package com.awarematics.postmedia.types.ev.geom; | [
"dingwindivid@gmail.com"
] | dingwindivid@gmail.com |
9374cbba3cba7117e768de532feda8969a88798e | b67986eeeb33bb0eec7d00652da092bbc1234612 | /app/src/main/java/com/example/konkor/adapter/ViewPageAdapter.java | ade21c2b71f44e462fab741b5f8fae12b336bf8f | [] | no_license | PersianBuddy/konkor | 19321e478ab2ba346611a9acbc41e922a69d4871 | 9bc0dbc1c56486fb343a0da127d0023bb418e913 | refs/heads/master | 2023-01-22T22:12:52.557021 | 2020-11-30T18:38:34 | 2020-11-30T18:38:34 | 311,754,745 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,121 | java | package com.example.konkor.adapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragmentsList;
private List <String> fragmentsTitle;
public ViewPageAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
fragmentsList = new ArrayList<>();
fragmentsTitle = new ArrayList<>();
}
@NonNull
@Override
public Fragment getItem(int position) {
return fragmentsList.get(position);
}
@Override
public int getCount() {
return 2;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return fragmentsTitle.get(position);
}
public void addFragment(Fragment fragment, String fragment_title){
fragmentsList.add(fragment);
fragmentsTitle.add(fragment_title);
}
}
| [
"mnajafi0014@gmail.com"
] | mnajafi0014@gmail.com |
a60b89b141ea19a18c37d6afc1a630f38c243255 | 0f5b1e7c7179bbfca6e55dd3ad02a53a4850b730 | /spring-candh/src/main/java/kr/co/demo/device/dao/DeviceDao.java | d624971fddd495a427cd5eda24b6372345bc9193 | [] | no_license | doukheeWon-gmail/spring3-project | f41506454d260cc06050dbf7fba93cc4a9266e6a | 6d7dd1d6d44f69b8e70b63ea270a4f70299c8c35 | refs/heads/master | 2023-04-03T19:40:52.940158 | 2021-04-16T06:54:52 | 2021-04-16T06:54:52 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 64 | java | package kr.co.demo.device.dao;
public interface DeviceDao {
}
| [
"fain9301@yahoo.com"
] | fain9301@yahoo.com |
c01da7716f34468319ed154125e1d3bb1317ed37 | 58b11f0c6af2b3d808208c842668d2245d6be013 | /src/main/java/com/capgemini/cn/demo/fileManage/vo/response/AccessoryFileVo.java | 3b46eaf05fa27e8bd93badc6e8c86dacccf6321d | [] | no_license | Ycatsoul/MyOffice_csd1 | c0764bbc03556151a9d51054e61e8e54a56cc4a7 | 585ca716ee18a386b1d2892922d291f55dd60bbe | refs/heads/master | 2022-05-20T18:07:18.610487 | 2019-10-30T02:11:09 | 2019-10-30T02:11:09 | 209,487,269 | 3 | 0 | null | 2020-10-13T16:08:36 | 2019-09-19T07:14:30 | Java | UTF-8 | Java | false | false | 515 | java | package com.capgemini.cn.demo.fileManage.vo.response;
import com.capgemini.cn.demo.fileManage.entity.FileType;
import lombok.Data;
import java.util.Date;
@Data
public class AccessoryFileVo {
private Long accessoryId;
//父级文件夹ID
private Long fileId;
private String accessoryName;
private Long accessorySize;
private FileType accessoryType;
private Date createDate;
private String accessoryPath;
private Long createUserId;
private String createUserName;
}
| [
"491689063@qq.com"
] | 491689063@qq.com |
d47bf02fbc268330f96ea3cb53833b93e342ad47 | 3a46d74a1cda92a2c2b854e5c6d3816481db329a | /src/outputProcessorStrategy/RejectMsg/RejectMsg.java | 8a81a2336b38af6390719ab1d5fa9dada223baee | [] | no_license | RamyaMadhihally/Object-Oriented-Design-Patterns | 5e43fa8ff3149ee46f9438ab28c63ae81090921e | db147966c31a3667dcd1b2f7067835a250ec34e9 | refs/heads/master | 2020-04-02T05:29:17.430055 | 2016-07-09T17:57:43 | 2016-07-09T17:57:43 | 62,960,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 107 | java | package outputProcessorStrategy.RejectMsg;
public interface RejectMsg {
public void displayRejectMsg();
}
| [
"rmadhiha@hawk.iit.edu"
] | rmadhiha@hawk.iit.edu |
ac6fbcd341b15c1d702c3e4ab1b7ee43f51ba539 | 0294c2c0d58ca302dc0d82f464e7d29529eedf64 | /piechart/src/test/java/com/zhpan/custom_pie_chart/ExampleUnitTest.java | a5b3ad180316ba317af49da7567a2de8a9fc4686 | [] | no_license | IRMobydick/CustomView | aba841ee5033a7c6cecab7af5298785af46b2457 | 88079ac26f5e15ef10997227d2ee25bb3f3e0660 | refs/heads/master | 2020-11-24T05:54:44.360195 | 2019-10-18T04:53:10 | 2019-10-18T04:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 387 | java | package com.zhpan.custom_pie_chart;
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);
}
} | [
"pan.zhang@alo7.com"
] | pan.zhang@alo7.com |
f3781a31bc025392bcb9b5070e269f89b603a8d5 | e19ec9029735f0a38a9245e9ac1c6a10af880238 | /src/main/java/com/ssi/HQLFilteration.java | db05fef022633cbae416471249912dc9f81b33c6 | [] | no_license | ssiedu/hibernate-first-21-05-19 | 8305e0c97fe20a6f6694173ecd9868b5c84da0a9 | 40a363a9601a444f58a3cc7a3cc709e80d02b5ee | refs/heads/master | 2022-12-03T10:16:08.973881 | 2019-05-25T10:05:06 | 2019-05-25T10:05:06 | 187,812,560 | 0 | 0 | null | 2022-11-24T07:02:17 | 2019-05-21T10:08:39 | Java | UTF-8 | Java | false | false | 562 | java | package com.ssi;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class HQLFilteration {
public static void main(String[] args) {
Session session=DataUtility.getSF().openSession();
Query query=session.createQuery("select rno,name,branch from Student order by rno desc");
List<Object[]> students=query.list();
for(Object ar[]:students){
for(Object obj:ar){
System.out.println(obj);
}
System.out.println("__________________________________");
}
session.close();
}
}
| [
"manoj.sarwate@ssiedu.in"
] | manoj.sarwate@ssiedu.in |
28ded8c3b3f3faf122400611cb442b0ae366ecc8 | e8a751f7618f7111800ad50f6eed2c46aae58a33 | /Leetcode_Java/src/main/java/leetcode/SearchInRotatedSortedArrayII_81.java | 36bdc0642ea27a271b8f226495486d21a5975bdf | [] | no_license | jiweiyu/LC | 2bd1bf2ee0d3fffeb38bf7e9518ca1849cc1da1b | cad086a55dd8b762c35770cca8a85e773f5983ac | refs/heads/master | 2023-06-17T06:00:09.423604 | 2021-07-13T23:32:33 | 2021-07-13T23:32:33 | 385,759,541 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,368 | java | package leetcode;
public class SearchInRotatedSortedArrayII_81 {
public boolean search(int[] nums, int target){
int start = 0, end = nums.length - 1, mid = -1;
while(start <= end) {
mid = (start + end) / 2;
if (nums[mid] == target) {
return true;
}
//If we know for sure right side is sorted or left side is unsorted
if (nums[mid] < nums[end] || nums[mid] < nums[start]) {
if (target > nums[mid] && target <= nums[end]) {
start = mid + 1;
} else {
end = mid - 1;
}
//If we know for sure left side is sorted or right side is unsorted
} else if (nums[mid] > nums[start] || nums[mid] > nums[end]) {
if (target < nums[mid] && target >= nums[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
//If we get here, that means nums[start] == nums[mid] == nums[end], then shifting out
//any of the two sides won't change the result but can help remove duplicate from
//consideration, here we just use end-- but left++ works too
} else {
end--;
}
}
return false;
}
}
| [
"ivy.jw.yu@gmail.com"
] | ivy.jw.yu@gmail.com |
387d438496311b93dcf2da45ae8d0e50333cc0ff | b8d0b4d6dd413ca9693c46754d73e3907a708a03 | /src/newdealQuiz/ArrayTest.java | 1f5e372f98abdbaac6cba3a7f873269d49d6be09 | [] | no_license | eunajjing/doit-java-algorithm | 4bdd4049c441c4e6dd66b6fc27f694112e3dd03f | 20ffa7f014e1119906288419cf24d20fbc411a80 | refs/heads/master | 2020-04-08T19:13:06.549148 | 2018-12-27T01:48:06 | 2018-12-27T01:48:06 | 159,645,176 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,002 | java | package newdealQuiz;
public class ArrayTest {
public static void main(String[] args) {
int[] score = new int[] {79,88,97,54,56,95};
int max = score[0]; //79
int min = score[0]; //79
for (int i = 1; i< score.length; i++) {
if (max < score[i]) {
max = score[i];
}
if (min > score[i]) {
min = score[i];
}
}
System.out.println("수학과 학생들의 기말고사 시험 점수 최대점은 "+max);
System.out.println("수학과 학생들의 기말고사 시험 점수 최하점은 "+min);
int sum=0;
float average = 0f;
int[] jumsu = {100,55,90,60,78};
for (int j = 0; j<jumsu.length; j++) {
sum += jumsu[j];
if (j == jumsu.length-1) {
average = (float) sum/jumsu.length;
break;
}
}
System.out.println("총 과목 수는 "+jumsu.length);
System.out.println("점수의 합은 "+sum);
System.out.println("점수의 평균은 "+average);
}
}
| [
"k_eaaaaa@naver.com"
] | k_eaaaaa@naver.com |
9b208858eb95edda9b152dbd9b16c3c175c1d6ab | ee461488c62d86f729eda976b421ac75a964114c | /tags/HtmlUnit-1dot1/htmlunit/src/java/com/gargoylesoftware/htmlunit/javascript/host/Input.java | 7b870e68dc25010a077a273edb7191df944b94c0 | [] | no_license | svn2github/htmlunit | 2c56f7abbd412e6d9e0efd0934fcd1277090af74 | 6fc1a7d70c08fb50fef1800673671fd9cada4899 | refs/heads/master | 2023-09-03T10:35:41.987099 | 2015-07-26T13:12:45 | 2015-07-26T13:12:45 | 37,107,064 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,490 | java | /*
* Copyright (C) 2002 Gargoyle Software Inc. All rights reserved.
*
* This file is part of HtmlUnit. For details on use and redistribution
* please refer to the license.html file included with these sources.
*/
package com.gargoylesoftware.htmlunit.javascript.host;
import org.w3c.dom.Element;
/**
* The javascript object that represents something that can be put in a form.
*
*@version $Revision$
*@author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
*/
public class Input extends HTMLElement {
/**
* Create an instance.
*/
public Input() {
}
/**
* Javascript constructor. This must be declared in every javascript file
* because the rhino engine won't walk up the hierarchy looking for
* constructors.
*/
public void jsConstructor() {
}
/**
* Return the value of the javascript attribute "value".
*
*@return The value of this attribute.
*/
public String jsGet_value() {
return getHtmlElementOrDie().getAttributeValue( "value" );
}
/**
* Set the value of the javascript attribute "value".
*
*@param newValue The new value.
*/
public void jsSet_value( final String newValue ) {
getHtmlElementOrDie().getElement().setAttribute( "value", newValue );
}
/**
* Return the value of the javascript attribute "name".
*
*@return The value of this attribute.
*/
public String jsGet_name() {
return getHtmlElementOrDie().getAttributeValue( "name" );
}
/**
* Return the value of the javascript attribute "form".
*
*@return The value of this attribute.
*/
public Form jsGet_form() {
return (Form)getHtmlElementOrDie().getEnclosingForm().getScriptObject();
}
/**
* Return the value of the javascript attribute "type".
*
*@return The value of this attribute.
*/
public String jsGet_type() {
return "Foobar";
}
/**
* Set the checked property. Although this property is defined in Input it
* doesn't make any sense for input's other than checkbox and radio. This
* implementation does nothing. The implementations in Checkbox and Radio
* actually do the work.
*
*@param checked True if this input should have the "checked" attribute
* set
*/
public void jsSet_checked( final boolean checked ) {
getLog().debug( "Input.jsSet_checked(" + checked
+ ") was called for class " + getClass().getName() );
}
/**
* Return the value of the checked property. Although this property is
* defined in Input it doesn't make any sense for input's other than
* checkbox and radio. This implementation does nothing. The
* implementations in Checkbox and Radio actually do the work.
*
*@return The checked property.
*/
public boolean jsGet_checked() {
getLog().warn( "Input.jsGet_checked() was called for class " + getClass().getName() );
return false;
}
/**
* Set the focus to this element.
*/
public void jsFunction_focus() {
getLog().debug( "Input.jsFunction_focus() not implemented" );
}
/**
* Remove focus from this element
*/
public void jsFunction_blur() {
getLog().debug( "Input.jsFunction_blur() not implemented" );
}
/**
* Click this element. This simulates the action of the user clicking with the mouse.
*/
public void jsFunction_click() {
getLog().debug( "Input.jsFunction_click() not implemented" );
}
/**
* Select this element.
*/
public void jsFunction_select() {
getLog().debug( "Input.jsFunction_select() not implemented" );
}
/**
* Return true if this element is disabled.
* @return True if this element is disabled.
*/
public boolean jsGet_disabled() {
return getHtmlElementOrDie().isAttributeDefined("disabled");
}
/**
* Set whether or not to disable this element
* @param disabled True if this is to be disabled.
*/
public void jsSet_disabled( final boolean disabled ) {
final Element xmlElement = getHtmlElementOrDie().getElement();
if( disabled ) {
xmlElement.setAttribute("disabled", "disabled");
}
else {
xmlElement.removeAttribute("disabled");
}
}
}
| [
"(no author)@5f5364db-9458-4db8-a492-e30667be6df6"
] | (no author)@5f5364db-9458-4db8-a492-e30667be6df6 |
12626d0fad1ee30b2f38477fd4a1736ca62d34c2 | 1edcfd79721056e54dc86716c1ba6429e21f78c9 | /libs/httpunit/src/com/meterware/httpunit/parsing/JTidyHTMLParser.java | 69325ec06b4c366fae025607363b4c17a2cf512a | [] | no_license | lencinhaus/pervads | bd548f6aab711152a6e465705dfa18fb915a594f | 237e93b3e4bf8094aaed9cc21c6fbb6161e5d6bb | refs/heads/master | 2021-01-25T07:18:38.399612 | 2015-03-24T00:37:06 | 2015-03-24T00:37:06 | 32,765,534 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,797 | java | package com.meterware.httpunit.parsing;
/********************************************************************************************************************
* $Id: JTidyHTMLParser.java 855 2008-03-31 08:54:13Z wolfgang_fahl $
*
* Copyright (c) 2002,2004,2008 Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/
import org.w3c.tidy.Tidy;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.html.HTMLDocument;
import org.xml.sax.SAXException;
import java.net.URL;
import java.io.IOException;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import com.meterware.httpunit.dom.HTMLDocumentImpl;
/**
*
* @author <a href="mailto:russgold@httpunit.org">Russell Gold</a>
**/
class JTidyHTMLParser implements HTMLParser {
public void parse( URL pageURL, String pageText, DocumentAdapter adapter ) throws IOException, SAXException {
try {
Document jtidyDocument = getParser( pageURL ).parseDOM( new ByteArrayInputStream( pageText.getBytes( UTF_ENCODING ) ), null );
HTMLDocument htmlDocument = new HTMLDocumentImpl();
NodeList nl = jtidyDocument.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node importedNode = nl.item(i);
if (importedNode.getNodeType() != Node.DOCUMENT_TYPE_NODE) htmlDocument.appendChild( htmlDocument.importNode( importedNode, true ) );
}
adapter.setDocument( htmlDocument );
} catch (UnsupportedEncodingException e) {
throw new RuntimeException( "UTF-8 encoding failed" );
}
}
public String getCleanedText( String string ) {
return (string == null) ? "" : string.replace( NBSP, ' ' );
}
public boolean supportsPreserveTagCase() {
return false;
}
public boolean supportsForceTagCase() {
return false;
}
public boolean supportsReturnHTMLDocument() {
return true;
}
public boolean supportsParserWarnings() {
return true;
}
final private static char NBSP = (char) 160; // non-breaking space, defined by JTidy
final private static String UTF_ENCODING = "UTF-8";
private static Tidy getParser( URL url ) {
Tidy tidy = new Tidy();
tidy.setCharEncoding( org.w3c.tidy.Configuration.UTF8 );
tidy.setQuiet( true );
tidy.setShowWarnings( HTMLParserFactory.isParserWarningsEnabled() );
if (!HTMLParserFactory.getHTMLParserListeners().isEmpty()) {
tidy.setErrout( new JTidyPrintWriter( url ) );
}
return tidy;
}
}
| [
"usrlorecarra@503f4af4-0e9e-6bd7-51a0-2f919e806bf0"
] | usrlorecarra@503f4af4-0e9e-6bd7-51a0-2f919e806bf0 |
b71d028535533b33621b430ea701ef3ac2f0a7ff | 2475a2762328f221b5a51f5290debf3fbcb8c663 | /app/src/main/java/com/vis/entertainment/adapters/PhotoResultsAdapter.java | 2ac37d9536b61e57dbd8bbc3ee95cd6efc5a8203 | [] | no_license | visrahane/WhereAreThey-AndroidApp | 48cdba79fb5a03c042d9fed4d74c087bf2015856 | 8da0023d90af011c06c3bc83b7684a543002a3d7 | refs/heads/master | 2020-03-10T14:54:00.806112 | 2018-04-27T17:58:21 | 2018-04-27T17:58:21 | 129,437,712 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,803 | java | package com.vis.entertainment.adapters;
import android.graphics.Bitmap;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.vis.entertainment.R;
import java.util.List;
public class PhotoResultsAdapter extends RecyclerView.Adapter<PhotoResultsAdapter.ViewHolder> {
private List<Bitmap> photoList;
private static final String TAG=PhotoResultsAdapter.class.getName();
public class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
private ImageView photoImageView;
public ViewHolder(View view) {
super(view);
photoImageView=view.findViewById(R.id.authorImg);
}
}
public PhotoResultsAdapter(List<Bitmap> photoList) {
this.photoList = photoList;
}
@Override
public PhotoResultsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.photos, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(PhotoResultsAdapter.ViewHolder holder, int position) {
Bitmap bitmap= photoList.get(position);
//holder.photoImageView.setImageBitmap(bitmap);
holder.photoImageView.setImageBitmap(bitmap);
//Picasso.get().load(result.getCategoryImageUrl()).into(holder.photoImageView);
}
@Override
public int getItemCount() {
return photoList.size();
}
}
| [
"rahane@usc.edu"
] | rahane@usc.edu |
f3d368481f5046f2a3ec4c3bba3ce163a2491531 | 4ee409920e2c65e9ab6f9b39ef261e0691bc0bae | /app/src/test/java/dhakre/fr/uha/minimaltodo/ExampleUnitTest.java | 4b1860794675c8d1ec19fbec7c4b57e205e1bde7 | [] | no_license | dhakre/MinimalTODO | 15632db56394ef268ecd2a5290c09a17f14fc370 | 3e094a15cd58aaa353154540d7db461ed37530c9 | refs/heads/master | 2021-01-25T09:20:35.882999 | 2017-06-09T03:13:47 | 2017-06-09T03:13:47 | 93,813,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 403 | java | package dhakre.fr.uha.minimaltodo;
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() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"sumitra.dhakre@uha.fr"
] | sumitra.dhakre@uha.fr |
f2d08cb32de4533388dee9ca2c4acee21bc77fe7 | 90f2457b8d17981612ab91d01c3892e4ea76c2d4 | /patientanalytics/src/main/java/com/patientanalytics/mapper/AdmissionCacheMapper.java | 390eba6c4d75b0d88b0cb542cce13557ad7d92b4 | [] | no_license | bigdatagists/MapReduceExamples | 310cf30173b77855e2b297b7948224c9d4d39283 | 8e62d4424bab6ac22a53cab0be64a8f68aebadb9 | refs/heads/master | 2021-01-10T22:17:18.119079 | 2016-10-17T17:16:39 | 2016-10-17T17:16:39 | 70,325,827 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,324 | java | package com.patientanalytics.mapper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class AdmissionCacheMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private List<String> patientCoreList = null;
private Map<String, Integer> admissionCountMap = null;
@Override
protected void setup(Context context) throws IOException,InterruptedException {
URI[] uris = context.getCacheFiles();
Path path = new Path(uris[0].getPath());
FileSystem fileSystem = FileSystem.get(context.getConfiguration());
if (fileSystem.exists(path)){
patientCoreList = new ArrayList<String>();
admissionCountMap = new HashMap<String, Integer>();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileSystem.open(path)));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
String[] lineArr = line.split("\t");
patientCoreList.add(lineArr[0]);
context.getCounter("admissionCache", "patientCount").increment(1L);
}
}
}
@Override
public void map(LongWritable offset, Text text, Context context) throws InterruptedException, IOException {
if (null != patientCoreList) {
String line = text.toString();
String patientId = line.split("\t")[0];
int count = patientCoreList.contains(patientId) ? admissionCountMap
.containsKey(patientId) ? admissionCountMap.get(patientId) + 1
: 1
: -1;
admissionCountMap.put(patientId, count);
}
context.getCounter("admissionCache", "admissionCountMap").setValue(admissionCountMap.size());
}
protected void cleanup(Context context) throws IOException, InterruptedException {
Iterator<Map.Entry<String, Integer>> it = admissionCountMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
context.write(new Text(entry.getKey()), new IntWritable(entry.getValue()));
}
}
} | [
"prejula06.pp@gmail.com"
] | prejula06.pp@gmail.com |
bcc0a7ba4558f90e0aa39050c616bc2e46ac96b2 | 8f69421f9a732fe205521b3a50823542c659c07c | /src/main/java/com/spring/consumer/controller/SoapConsumerController.java | fc7541cc5e358e1afd69f2dd8451542558e3097e | [] | no_license | lrbell17/SOAP-Geography-Consumer-Spring | 6bc079ba87ac46142579ca0a72a2fe9b5eb037cd | 4cb6df1b42da6cae54ac04ecd829331eb12c4fd7 | refs/heads/master | 2022-12-02T03:36:18.779821 | 2020-08-12T20:28:55 | 2020-08-12T20:28:55 | 287,105,544 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 732 | java | package com.spring.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.spring.consumer.service.SoapConsumerClient;
import com.spring.consumer.soap.State;
@RestController
public class SoapConsumerController {
@Autowired
private SoapConsumerClient client;
@GetMapping("/getState/{stateName}")
public Object getState(@PathVariable String stateName) {
State state = client.getStateFromSoap(stateName);
if (state == null) {
return "Invalid entry!";
}
else {
return state;
}
}
}
| [
"56008909+lrbell17@users.noreply.github.com"
] | 56008909+lrbell17@users.noreply.github.com |
7481cbd3f334ed4198b3ddfa132ba9d09cbab13f | 29e61326fac2be45dd4a610b96d77e74658d5fc4 | /stackoverflow-statistics/src/main/java/com/hadoxa/stowfl/statistics/hdx35/stepic/L4_2_s6_Reducer.java | 7c1e02ebd13e906c7b6b7dbc67f883c03f872da5 | [] | no_license | badunas/hadoxa-mapred | d74191248299856d35a89bd51a33763538a9a223 | 7a8ca9809fdf3fc03446b32c59fe5e120b087e20 | refs/heads/master | 2021-04-03T06:59:26.022010 | 2016-07-04T20:32:19 | 2016-07-04T20:32:19 | 62,585,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,178 | java | package com.hadoxa.stowfl.statistics.hdx35.stepic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by badun on 6/18/16.
*/
public class L4_2_s6_Reducer {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
String lastKey = null;
String lastCounter = "";
String key = null;
while((line = reader.readLine()) != null) {
String[] keyValue = line.split("\t");
key = keyValue[0];
if (lastKey == null) {
lastKey = key;
}
if (key.equals(lastKey)) {
lastKey = key;
String s = keyValue[1];
lastCounter += keyValue[1];
} else {
if (lastCounter.equals("A")) {
System.out.println(lastKey);
}
lastKey = key;
lastCounter = keyValue[1];
}
}
if (lastCounter.equals("A")) {
System.out.println(lastKey);
}
}
}
| [
"badun.artsiom@gmail.com"
] | badun.artsiom@gmail.com |
f8c0c9eed7c1861912c9b082de03e027c6a673eb | 70de28334d4afcf340425bd4b8dbc2fcdbe11fff | /app/src/main/java/cn/edu/hebiace/javajpk/activities/LBaseActivity.java | d6070ce9459bca440fa334a18ddef4dc12d857aa | [] | no_license | zhaozw/Javajpk | 3ebd18c19b1df2f1be2e82f1d933979717afd979 | acbca6d1658e785d1da6e257ea3164c9b9fd6115 | refs/heads/master | 2021-01-23T04:53:20.665153 | 2017-01-22T04:47:32 | 2017-01-22T04:47:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 849 | java | package cn.edu.hebiace.javajpk.activities;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import cn.edu.hebiace.javajpk.LApplication;
import cn.edu.hebiace.javajpk.core.AppAction;
/**
* Created by lpwxs on 15-12-3.
*/
public class LBaseActivity extends FragmentActivity {
// 上下文实例
public Context context;
// 应用全局的实例
public LApplication application;
// 核心层的Action实例
public AppAction appAction;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
application = (LApplication) this.getApplication();
appAction = application.getAppAction();
}
}
| [
"lpwxs818@gmail.com"
] | lpwxs818@gmail.com |
805b20bf837b635d91a468145a640b4a6498d6ff | 07e076d1ecff0ab63a31e609323a035f07442e35 | /ged-backend/src/main/java/com/loga/skeleton/repository/RevisionRepository.java | 65b7b256b4f85850a8a8f4dcf43c21d43f3b7f6e | [] | no_license | Semiatu/loga-GED | 3dfccdb66955ecffa8c77d3610aa22d6ff301b6b | 04dcf0858227a1fc6ebf6c956dc6d6ec3ee46462 | refs/heads/master | 2021-06-21T15:31:11.047318 | 2019-09-17T12:40:43 | 2019-09-17T12:40:43 | 209,047,077 | 0 | 0 | null | 2021-03-31T00:47:41 | 2019-09-17T12:24:39 | TypeScript | UTF-8 | Java | false | false | 226 | java | package com.loga.skeleton.repository;
import com.loga.bebase.repository.AbstractRepository;
import com.loga.skeleton.domain.entity.Revision;
public interface RevisionRepository extends AbstractRepository<Revision, Long> {
}
| [
"semiatulawal@gmail.com"
] | semiatulawal@gmail.com |
8346db596ebc6dcaae0d4ae875b4524d4ab1ef17 | e2877784d551b9c7e4159b4b8c9fa761de56c327 | /n12/src/main/java/com/example/n12/N12Application.java | 78076a78891f710cc4ee1856bb8e4ea9a192242c | [] | no_license | mournfulCoroner/javpatterns | 1b6659b0eb4c936e5d30708e983df25785ff56b6 | 498c8fec3bd5d4c5e14f7f94718ff7ac7676f0d8 | refs/heads/main | 2023-03-30T19:59:31.358209 | 2021-03-29T21:20:59 | 2021-03-29T21:20:59 | 349,373,362 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 302 | java | package com.example.n12;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class N12Application {
public static void main(String[] args) {
SpringApplication.run(N12Application.class, args);
}
}
| [
"linayn9@gmail.com"
] | linayn9@gmail.com |
f4036e801320e701c68be48e5d61c449667acb73 | 7c01992fc742191fe95e5cb15f8fc132a6ce4b44 | /src/main/java/com/posin/verdrawerlayout/view/LinearLayoutTwo.java | 19c5f7b6ad6e967ef1f3b26bf1b48478a3c67702 | [] | no_license | chenguitang/VerDrawerLayoutDemo | fb3761eeafbd5034ee22e2adc0cadd0a5917be93 | efaec0c7945fd9cccda3e2ddffede6723ea889cf | refs/heads/master | 2020-04-12T18:47:04.204970 | 2019-01-17T01:44:52 | 2019-01-17T01:44:52 | 162,690,341 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,127 | java | package com.posin.verdrawerlayout.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.LinearLayout;
/**
* FileName: LinearLayoutOne
* Author: Greetty
* Time: 2019/1/16 14:58
* Desc: TODO
*/
public class LinearLayoutTwo extends LinearLayout {
private static final String TAG = "LinearLayoutTwo";
public LinearLayoutTwo(Context context) {
super(context);
}
public LinearLayoutTwo(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.e(TAG, "dispatchTouchEvent");
// return super.dispatchTouchEvent(ev);
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
Log.e(TAG, "onInterceptTouchEvent");
// return super.onInterceptTouchEvent(ev);
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.e(TAG, "onTouchEvent");
return super.onTouchEvent(event);
}
}
| [
"782119927@qq.com"
] | 782119927@qq.com |
416fb26c460b51c155d1a68d548104c550019077 | 2c6b1399619c7facf16a0b14bad9244ccb424ee1 | /app/src/main/java/com/dicoding/picodiploma/vespa/MoveActivity.java | d0711a803dd23382c190f61b6b2ee5087d6dadd1 | [] | no_license | izzat170996/android-2 | ef15e38b889759dea101456c2ff9a3585e3d982d | 8c5adf269e43897d91d7b2caa3f8a0e5d5d3ea92 | refs/heads/master | 2022-04-27T12:15:25.242272 | 2020-04-29T09:09:43 | 2020-04-29T09:09:43 | 259,872,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,161 | java | package com.dicoding.picodiploma.vespa;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.dicoding.picodiploma.vespa.adapter.ListVespaAdapter;
import java.util.ArrayList;
import com.dicoding.picodiploma.vespa.Vespa;
import com.dicoding.picodiploma.vespa.VespasData;
public class MoveActivity extends AppCompatActivity {
public static String vespaNames = "vespa_names";
public static String vespaDetails = "vespa_details";
public static String vespaImage = "vespa_image";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_move);
TextView vespaNames = findViewById(R.id.tv_item_name);
TextView vespaDetails = findViewById(R.id.tv_item_detail);
ImageView vespaImages = findViewById(R.id.img_item_photo);
}
}
| [
"izzatannafs89@gmail.com"
] | izzatannafs89@gmail.com |
27bf36f52263ab2e3a1dad59f87c0acffe2c081d | 5469b56fe7286890906d2d3091b6fe019909ac4c | /Facebook_java+pdf/Average value by level in a tree.java | 6eb8bc3c835325fee24cf5aeee7bc58dbe96612d | [] | no_license | stjiao13/files | d4f959422f897ba3b5c0015a7036c5c11d529c5d | 83a2e6d201af0699ca511a3445179baf8208dd1c | refs/heads/master | 2020-04-19T08:34:38.051251 | 2019-02-25T16:54:43 | 2019-02-25T16:54:43 | 168,081,854 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 741 | java | 102相似题 bfs O(n) time and space
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<Integer> res=new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size=queue.size();
int average=0;
List<Integer> list=new LinkedList<>();
for(int i=0;i<size;i++){
TreeNode cur=queue.poll();
average+=cur.val;
if(cur.left!=null) queue.offer(cur.left);
if(cur.right!=null) queue.offer(cur.right);
}
res.add(average/size);
}
return res;
}
} | [
"yuriqiao@gmail.com"
] | yuriqiao@gmail.com |
137fcd483e04eba217e5f9c2f63e8e004a044abe | 0d39e46be7c84a4a38a56743744ec15994e8c8b1 | /src/main/java/com/example/googleactionswebhooks/hook/google/api/generic/GAType.java | c5da94d2f4b330f4c45fb6c9ba36a76912703234 | [] | no_license | ekim197711/google-actions-webhooks | 5c02832d23cfe81ca4fad55692c0ab6ec1a90182 | d259d7844d9ee5f995fb089e5a231955a46c8b21 | refs/heads/main | 2023-01-22T10:42:23.622969 | 2020-11-23T23:01:40 | 2020-11-23T23:01:40 | 309,348,932 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 323 | java | package com.example.googleactionswebhooks.hook.google.api.generic;
public enum GAType {
/**
* type unspecified, should not set this explicitly.
*/
TYPE_UNSPECIFIED,
/**
* Only update status of the order.
*/
ORDER_STATUS,
/**
* Update order snapshot.
*/
SNAPSHOT
}
| [
"mmni@protonmail.com"
] | mmni@protonmail.com |
e568be22284f90284a29e51e541b6a7dc3e824cb | b7326cd5db553e399a775034fce68cfc7fa159a1 | /AiqiyiWebProject/src/com/zsd/servlet/RegisterServlet.java | bb20d49f857050c332086c87876f048f72281dee | [] | no_license | my1019014341/s1 | 8f90ea9a923d3b0a3109f819aba36d4103e66fdc | fa677e173c4055cfae0b9a30e986693ba1d5d159 | refs/heads/master | 2021-01-25T16:58:43.061835 | 2017-10-22T04:32:49 | 2017-10-22T04:32:49 | 102,079,704 | 1 | 2 | null | null | null | null | GB18030 | Java | false | false | 1,461 | java | package com.zsd.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zsd.Interface.CustomerDao;
import com.zsd.customer.Customer;
import com.zsd.impl.CustomerMqlImpl;
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
req.setCharacterEncoding("UTF-8");
PrintWriter out = resp.getWriter();
CustomerDao cusdao = new CustomerMqlImpl();
Customer cus = new Customer();
cus.setTel(req.getParameter("tel"));
if(null!=cusdao.register(cus)){
if(cusdao.addCustomer(cus)>0){
cus= cusdao.selectCustomer(cus.getTel());
req.setAttribute("cus", cus);
req.getRequestDispatcher("change_details.jsp").forward(req, resp);
}else{
out.print("<script> alert('用户名添加失败') </script>");
resp.sendRedirect("main.jsp");
}
}else{
out.print("<script> alert('用户名已存在') </script>");
resp.sendRedirect("main.jsp");
}
out.close();
}
}
| [
"1019014341@qq.com"
] | 1019014341@qq.com |
67e2ca45362fc01bf2797e0b2fb63edb14d91dc4 | a2055edee58960aecd32ad54255b9bed19c1d0c8 | /客户端/PiCar/app/src/main/java/smarthome/Control_Activity.java | f009c8eabab091607c199e2473bed7baaeaff34a | [] | no_license | tangczc/PiRobot | 0d70759b38a59513eab531ac4b50080430a7927a | 307c590c214d0a6576b2a128675a0d939bb3a954 | refs/heads/master | 2020-03-12T04:10:10.926336 | 2018-04-21T04:52:32 | 2018-04-21T04:52:32 | 130,439,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,460 | java | package smarthome;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
import java.io.IOException;
import fufu.smarthome.R;
public class Control_Activity extends Activity {
private TcpClientConnector connector;
Button btn_left;
Button btn_up;
Button btn_right;
Button btn_down;
Button btn_stop;
ToggleButton tglbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.control);
btn_up = (Button)findViewById(R.id.forward);
btn_up.setOnClickListener(new ButtonEvent());
btn_left = (Button) findViewById(R.id.left);
btn_left.setOnClickListener(new ButtonEvent());
btn_right = (Button)findViewById(R.id.right);
btn_right.setOnClickListener(new ButtonEvent());
btn_down = (Button)findViewById(R.id.down);
btn_down.setOnClickListener(new ButtonEvent());
btn_stop = (Button) findViewById(R.id.stop);
btn_stop.setOnClickListener(new ButtonEvent());
tglbtn = (ToggleButton) findViewById(R.id.tglBtn);
tglbtn.setOnCheckedChangeListener(new TglBtnCheckedChangeEvents());
connector = TcpClientConnector.getInstance();
}
private class TglBtnCheckedChangeEvents implements ToggleButton.OnCheckedChangeListener {
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton == tglbtn ){
if (b == true){
connector.createConnect("192.168.12.1",2333);
}else{
try {
connector.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
private class ButtonEvent implements View.OnClickListener{
char[] data = new char[512];
public void onClick(View view) {
switch (view.getId()){
case R.id.forward:
try {
connector.send("0x01");
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.left:
try {
connector.send("0x03");
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.right:
try {
connector.send("0x04");
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.down:
try {
connector.send("0x02");
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try{
connector.send("0x00");
}catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}
| [
"Mytczc521@outlook.com"
] | Mytczc521@outlook.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.