text stringlengths 10 2.72M |
|---|
/*
* Copyright (c) 2013-2014, Neuro4j.org
*
* 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.neuro4j.studio.core.diagram.edit.parts;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ListCompartmentEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.DragDropEditPolicy;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.gmf.tooling.runtime.edit.policies.reparent.CreationEditPolicyWithCustomReparent;
import org.neuro4j.studio.core.diagram.edit.policies.LogicNodeLogicNodeErrorOutputCompartmentCanonicalEditPolicy;
import org.neuro4j.studio.core.diagram.edit.policies.LogicNodeLogicNodeErrorOutputCompartmentItemSemanticEditPolicy;
import org.neuro4j.studio.core.diagram.part.Messages;
import org.neuro4j.studio.core.diagram.part.Neuro4jVisualIDRegistry;
/**
* @generated
*/
public class LogicNodeLogicNodeErrorOutputCompartmentEditPart extends
ListCompartmentEditPart {
/**
* @generated
*/
public static final int VISUAL_ID = 7014;
/**
* @generated
*/
public LogicNodeLogicNodeErrorOutputCompartmentEditPart(View view) {
super(view);
}
/**
* @generated
*/
protected boolean hasModelChildrenChanged(Notification evt) {
return false;
}
/**
* @generated
*/
public String getCompartmentName() {
return Messages.LogicNodeLogicNodeErrorOutputCompartmentEditPart_title;
}
/**
* @generated
*/
protected void createDefaultEditPolicies() {
super.createDefaultEditPolicies();
installEditPolicy(
EditPolicyRoles.SEMANTIC_ROLE,
new LogicNodeLogicNodeErrorOutputCompartmentItemSemanticEditPolicy());
installEditPolicy(EditPolicyRoles.CREATION_ROLE,
new CreationEditPolicyWithCustomReparent(
Neuro4jVisualIDRegistry.TYPED_INSTANCE));
installEditPolicy(EditPolicyRoles.DRAG_DROP_ROLE,
new DragDropEditPolicy());
installEditPolicy(
EditPolicyRoles.CANONICAL_ROLE,
new LogicNodeLogicNodeErrorOutputCompartmentCanonicalEditPolicy());
}
/**
* @generated
*/
protected void setRatio(Double ratio) {
// if (getFigure().getParent().getLayoutManager() instanceof ConstrainedToolbarLayout) {
// super.setRatio(ratio);
// }
}
}
|
package dev.liambloom.softwareEngineering.chapter11.polygonComparable;
public class Square extends Rectangle {
// Constructors
public Square() {
super();
}
public Square(double s) {
super(s, s);
}
// Inherited
@Override
public String toString() {
return "Square and I am also a " + super.toString();
}
}
|
package com.cheese.radio.ui.media.anchor;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.cheese.radio.base.cycle.BaseActivity;
import static com.cheese.radio.inject.component.ActivityComponent.Router.author;
/**
* Created by 29283 on 2018/3/13.
*/
@Route(path = author)
public class AnchorActivity extends BaseActivity<AnchorModel> {
}
|
package Interfaces;
import Model.mTable; /*Untuk memanggil mTable.java dalam package Model*/
import java.util.List; /*Untuk memanggil package List pada java */
public interface InterfacesSewaBuku {
public List<mTable> GetAll();
}
|
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.*;
public class PrintFirstNonRepeatingChar {
// using integer array to print first non repeating character
public static char printFirstUniqChar(String str) {
if(str == null || str.length() == 0) {
return Character.MIN_VALUE;
}
int[] arr = new int[128];
char[] charArr = str.toCharArray();
for(int i = 0; i < charArr.length; i++) {
arr[charArr[i]]++;
}
for(int i = 0; i < charArr.length; i++) {
if(arr[charArr[i]] == 1){
return charArr[i];
}
}
return Character.MIN_VALUE;
}
// print first non repeating character using hashmap
public static char printFirstUniqCharHashMap(String str) {
if(str == null || str.length() == 0) {
return Character.MIN_VALUE;
}
HashMap<Character, Integer> map = new HashMap<>();
char[] charArr = str.toCharArray();
for(int i = 0; i < charArr.length; i++) {
if(!map.containsKey(charArr[i])) {
map.put(charArr[i], 1);
} else {
map.put(charArr[i], map.get(charArr[i]) + 1);
}
}
for(int i = 0; i < charArr.length; i++) {
if(map.get(charArr[i]) == 1) {
return charArr[i];
}
}
return Character.MIN_VALUE;
// // Using for-each loop
// for (Map.Entry elem : map.entrySet()) {
// //String key = (String)elem.getKey();
// if((int)elem.getValue() == 1) {
// //int value = ((int)elem.getValue() + 10);
// return (char)elem.getKey();
// }
// }
}
// main method
public static void main(String args[]) {
String str = "ssapna";
char ch = printFirstUniqChar(str);
System.out.println(ch);
char ch1 = printFirstUniqCharHashMap(str);
System.out.println(ch1);
}
} |
package com.si.ha.device.service;
import org.springframework.data.jpa.repository.JpaRepository;
import com.si.ha.device.Device;
public interface DeviceDao extends JpaRepository<Device, Long>{
}
|
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class MagicalThinking {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("C-small-test.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("C-small-out.out")));
int cases = Integer.parseInt(f.readLine());
// System.out.println(cases + " cases");
for (int i = 0; i < cases; i++) {
StringTokenizer st = new StringTokenizer(f.readLine());
st.nextToken();
int questions = Integer.parseInt(st.nextToken());
String friend = f.readLine();
String mine = f.readLine();
int correct = Integer.parseInt(f.readLine());
List<String> possibilities = new ArrayList<>();
for(int k = 0; k < Math.pow(2,questions); k++)
{
String format="%0"+questions+"d";
String poss = String.format(format,Integer.valueOf(Integer.toBinaryString(k)));
possibilities.add(poss);
}
String modifiedFriend = "";
for (int j = 0; j < friend.length(); j++) {
if (friend.charAt(j) == 'T') {
modifiedFriend += "1";
} else {
modifiedFriend += "0";
}
}
String modMine = "";
for (int j = 0; j < mine.length(); j++) {
if (mine.charAt(j) == 'T') {
modMine += "1";
} else {
modMine += "0";
}
}
List<String> successors = getSuccessors(possibilities, modifiedFriend, questions - correct);
// System.out.println(successors);
int maxCorr = 0;
String theOne = "";
for (String succ : successors) {
int corr = 0;
for (int j = 0; j < modMine.length(); j++) {
char succC = succ.charAt(j);
char myC = modMine.charAt(j);
if (succC == myC) {
corr++;
}
}
if (corr > maxCorr) {
maxCorr = corr;
theOne = succ;
}
}
out.println("Case #" + (i + 1) + ": " + maxCorr);
}
out.close();
}
private static List<String> getSuccessors(List<String> possiblities, String in, int changes) {
List<String> successors = new ArrayList<>();
for (String poss : possiblities) {
if (isPossible(poss, in, changes)) {
successors.add(poss);
}
}
return successors;
}
private static boolean isPossible(String poss, String in, int changes) {
int count = 0;
for (int i = 0; i < poss.length(); i++) {
char possC = poss.charAt(i);
char inC = in.charAt(i);
if (inC != possC) {
count++;
}
}
return changes == count;
}
}
|
package me.basiqueevangelist.datapackify.mixins;
import net.minecraft.village.TradeOffers;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(TradeOffers.SellSuspiciousStewFactory.class)
public interface SellSuspiciousStewFactoryAccessor {
@Accessor("multiplier")
@Mutable
void datapackify$setMultiplier(float mul);
}
|
/*
* Created on 22/08/2008
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package com.citibank.ods.persistence.pl.dao;
import com.citibank.ods.entity.pl.BaseTplProdAssetTypeEntity;
/**
* @author rcoelho
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public interface BaseTplProdAssetTypeDAO {
public BaseTplProdAssetTypeEntity find(
BaseTplProdAssetTypeEntity baseTplProdAssetTypeEntity_ );
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javafxtt.model;
/**
*
* @author LMI
*/
public class Player {
private int id;
private String name;
private String firstName;
private String team;
private String ranking;
public Player(int id, String name, String firstName, String team, String ranking) {
this.id = id;
this.name = name;
this.firstName = firstName;
this.team = team;
this.ranking = ranking;
}
public Player(String name, String firstName, String team, String ranking) {
this.name = name;
this.firstName = firstName;
this.team = team;
this.ranking = ranking;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public String getRanking() {
return ranking;
}
public void setRanking(String ranking) {
this.ranking = ranking;
}
}
|
/*
* 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 Interface;
import Exception.*;
import app.Sistema;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author PauloCardoso e Luis Brito
*/
public class Interface {
private static boolean flag1;
private static Sistema sistema;
private static String bookie; //Mudar para string
private static String apostador; //Mudar para string
private static int login;
public static void main(String[] args) {
flag1 = true;
bookie = "";
apostador = "";
sistema = new Sistema();
Scanner entrada = new Scanner(System.in);
int opcao = -1; //opcao scanner
try{
while(opcao!=2){
System.out.println("1-Entrar na aplicação");
System.out.println("2-Sair da aplicação");
opcao = Integer.parseInt(entrada.nextLine());
if(opcao == 1){
menuInicial();
}
if(login==1){ //bookie
parteBookie();
} else if(login==2){
parteApostador();
}
}
} catch(Exception e){
System.out.println("Erro no scanner");
}
}
public static void parteBookie(){
int opcao;
Scanner entrada = new Scanner(System.in);
try{
do{
//colocar o sistema a devolver notificaçoes
System.out.println("----Notificações----");
System.out.println(sistema.retornaNotificacoesBookie(bookie));
DadosMenuBookie();
opcao = Integer.parseInt(entrada.nextLine());
switch(opcao){
case 1: criarEvento();
break;
case 2: System.out.println(sistema.listaEventos());
break;
case 3: editarOdds();
break;
case 4: listaHistoricoEvento();
break;
case 5: mostrarInteresseEvento();
break;
case 6: listaApostas();
break;
case 7: finalizarEvento();
break;
case 8: testarCriteria();
break;
default:
break;
}
} while(opcao != 0);
} catch(Exception e){
System.out.println("Erro no scanner");
}
login = -1;
flag1 = true;
bookie = "";
}
public static void parteApostador(){
int opcao;
Scanner entrada = new Scanner(System.in);
try{
do{
System.out.println("----Notificações----");
System.out.println(sistema.retornaNotificacoesApostador(apostador));
DadosMenuApostador();
opcao = Integer.parseInt(entrada.nextLine());
switch(opcao){
case 1: System.out.println(sistema.listaEventos());
break;
case 2: criarAposta();
break;
case 3: verEstadoApostasEvento();
break;
case 4: depositar();
break;
case 5: levantar();
break;
case 6: consultarSaldo();
break;
default:
break;
}
} while(opcao != 0);
} catch(Exception e){
System.out.println("Erro no scanner");
}
login = -1;
flag1 = true;
apostador = "";
}
public static void Login(){
System.out.println("-- Bookie 1 | Apostador 2 --");
Scanner entrada = new Scanner(System.in);
String user, pw;
try{
int opcao = Integer.parseInt(entrada.nextLine());
switch(opcao){
case 1: System.out.print("Username: ");
user = entrada.nextLine();
System.out.print("Password: ");
pw = entrada.nextLine();
bookie = sistema.verificaBookie(user,pw);
if(!"".equals(bookie)){
login = 1;
flag1 = false;
}
break;
case 2: System.out.print("Username: ");
user = entrada.nextLine();
System.out.print("Password: ");
pw = entrada.nextLine();
apostador = sistema.verificaApostador(user,pw);
if(!"".equals(apostador)){
login = 2;
flag1 = false;
}
break;
}
} catch (NumberFormatException e) {
System.out.println("erro na leitura de dados");
}
}
public static void criarConta(){
Scanner entrada = new Scanner(System.in);
String nome;
String email;
String password;
String nickname;
int opcao;
System.out.println("Introduza o seu nome");
nome = entrada.nextLine();
System.out.println("Introduza o seu email");
email = entrada.nextLine();
System.out.println("Password");
password = entrada.nextLine();
System.out.println("Nome de Entrada");
nickname = entrada.nextLine();
System.out.println("Quer ser apostador(1) ou bookie (2)?");
opcao = Integer.parseInt(entrada.nextLine());
switch(opcao){
case 1: sistema.criarApostador(nome, email, password,nickname);
break;
case 2: sistema.criarBookie(nome, email, password,nickname);
break;
default: System.out.println("Introduziu dados errados");
break;
}
}
/*
BOOKIES
*/
public static void criarEvento(){
String[] equipas = new String[2];
float[] odds = new float[3];
Scanner in = new Scanner(System.in);
System.out.println("Equipa1");
equipas[0] = in.nextLine();
System.out.println("Equipa2");
equipas[1] = in.nextLine();
try{
System.out.println("Odd Vitoria Equipa1");
odds[0] = Float.parseFloat(in.nextLine());
System.out.println("Odd Empate");
odds[1] = Float.parseFloat(in.nextLine());
System.out.println("Odd Vitoria Equipa2");
odds[2] = Float.parseFloat(in.nextLine());
sistema.criarEvento(equipas,odds,bookie);
} catch(Exception e){
System.out.println("Evento Não Criado . Introduza odds do tipo inteiro,decimal");
}
}
public static void editarOdds(){
float[] odds = new float[3];
String[] equipas = new String[3];
int codigo;
Scanner in = new Scanner(System.in);
System.out.println("Introduza o código do evento");
codigo = Integer.parseInt(in.nextLine());
try{
System.out.println(sistema.showEvento(codigo));
equipas = sistema.getEquipas(codigo);
System.out.println("Odd Vitoria " + equipas[0]);
odds[0] = Float.parseFloat(in.nextLine());
System.out.println("Odd Empate");
odds[1] = Float.parseFloat(in.nextLine());
System.out.println("Odd Vitoria " + equipas[2]);
odds[2] = Float.parseFloat(in.nextLine());
sistema.editarOdds(codigo,odds,bookie);
} catch(BookieIncorretoException e ) {
System.out.println("O evento pertence a "+ e.getName());
}
catch(Exception e){
System.out.println("Não encontrou o evento");
}
}
public static void listaHistoricoEvento(){
Scanner in = new Scanner(System.in);
System.out.println("Qual o evento que pretende procurar informação?");
int codigo = Integer.parseInt(in.nextLine());
try{
System.out.println(sistema.listaHistoricoEvento(codigo));
} catch (NullPointerException e){
System.out.println("Evento não existente");
}
}
public static void mostrarInteresseEvento(){
Scanner in = new Scanner(System.in);
System.out.println("Qual é o Evento?");
try{
int codigo = Integer.parseInt(in.nextLine());
sistema.mostrarInteresse(codigo, bookie);
} catch(InputMismatchException e){
System.out.println("Não encontrou o evento");
}
}
public static void listaApostas(){
Scanner in = new Scanner(System.in);
System.out.println("Qual é o Evento?");
try{
int codigo = Integer.parseInt(in.nextLine());
System.out.println(sistema.listaApostas(codigo));
} catch(Exception e){
System.out.println("Evento não encontrado");
}
}
public static void finalizarEvento() {
Scanner in = new Scanner(System.in);
System.out.println("Qual é o Evento?");
try{
int codigo = Integer.parseInt(in.nextLine());
System.out.println(sistema.showEvento(codigo));
System.out.println("Vencedor?");
int vencedor = Integer.parseInt(in.nextLine());
sistema.finalizarEvento(codigo,vencedor,bookie);
} catch(BookieIncorretoException e ) {
System.out.println("O evento pertence a "+ e.getName());
} catch(NullPointerException e){
System.out.println("Evento não encontrado");
} catch(InputMismatchException e){
System.out.println("Erro na Leitura");
}
}
private static void testarCriteria(){
Scanner in = new Scanner(System.in);
System.out.println("Introduza critérios");
String linha = in.nextLine();
try{
System.out.println(sistema.testaCriteria(linha));
} catch(NullPointerException e){
System.out.println("Erro na busca de dados");
}
}
/*
APOSTADOR
*/
public static void criarAposta(){
int codigo,valor,opcao;
Scanner in = new Scanner(System.in);
System.out.println("Introduza o código do evento");
codigo = Integer.parseInt(in.nextLine());
System.out.println(sistema.showEvento(codigo));
System.out.println("Qual e a sua opcao: 0 - TeamA win | 1 - Draw | 2 - TeamB win");
opcao = Integer.parseInt(in.nextLine());
System.out.println("Que valor prentende apostar €:");
valor = Integer.parseInt(in.nextLine());
try{
try{
if(sistema.testarSaldo(apostador, valor)){
sistema.criarAposta(codigo,apostador,valor,opcao);
System.out.println("Criou uma aposta no Evento: " + codigo + " E apostou: "+valor +" Euros em: "+ sistema.escolha(codigo,opcao));
}
} catch(SemSaldoException e){
System.out.println(e.getMessage());
}
}catch(Exception e){
System.out.println("Não encontrou o evento");
}
}
public static void depositar(){
Scanner in = new Scanner(System.in);
System.out.println("Valor a depositar?");
int valor = Integer.parseInt(in.nextLine());
sistema.depositar(valor,apostador);
}
public static void levantar(){
Scanner in = new Scanner(System.in);
System.out.println("Valor a levantar?");
int valor = Integer.parseInt(in.nextLine());
try{
sistema.levantar(valor,apostador);
}catch(SemSaldoException e){
System.out.println(e.getMessage());
}
}
public static void consultarSaldo(){
System.out.println("Saldo: "+sistema.consultarSaldo(apostador)+"€");
}
public static void verEstadoApostasEvento(){
Scanner in = new Scanner(System.in);
System.out.println("Qual é o Evento?");
try{
int codigo = Integer.parseInt(in.nextLine());
System.out.println(sistema.verEstadoApostasEvento(codigo, apostador));
} catch(NullPointerException e){
System.out.println("Evento não encontrado");
}
}
/*
MENUS
*/
public static void DadosMenuBookie(){
System.out.println("\n\tBET ESS");
System.out.println("1 - Criar Evento");
System.out.println("2 - Mostrar Eventos");
System.out.println("3 - Editar Odds");
System.out.println("4 - Historico odds de um evento");
System.out.println("5 - Mostrar Interesse em Evento");
System.out.println("6 - Mostrar Lista de Apostas de Evento");
System.out.println("7 - Finalizar Evento");
System.out.println("8 - Teste Critérios");
System.out.println("0 - Menu Inicial");
System.out.print("Opcao:");
}
public static void DadosMenuApostador(){
System.out.println("\n\tBET ESS");
System.out.println("1 - Mostrar Eventos");
System.out.println("2 - Apostar em Evento");
System.out.println("3 - Ver Estado Apostas em Evento");
System.out.println("4 - Deposito");
System.out.println("5 - Levantamento");
System.out.println("6 - ConsultarSaldo");
System.out.println("0 - Menu Inicial");
System.out.print("Opcao: ");
}
public static void menuInicial(){
Scanner entrada = new Scanner(System.in);
int opcao; //opcao scanner
try{
while(flag1 == true){
System.out.println("1 - Registar");
System.out.println("2 - Login");
System.out.println("0 - Menu Inicial");
opcao = Integer.parseInt(entrada.nextLine());
switch(opcao){
case 1: criarConta();
break;
case 2: Login();
break;
default: flag1 = false;
break;
}
}
} catch (InputMismatchException e){
System.out.println("Introduza um caracter numérico");
}
}
}
|
package com.newlecture.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
/**
* JSP/Servlet을 뉴렉처 유튜브를 보며 배워보기
* 2020-10-27
* @author passw
*
*/
//anotation 으로 페이지 매핑 xml 3.0부터 가능
// notice-reg url을 담당하는 servlet코드
@WebServlet("/notice-reg")
public class NoticeReg extends HttpServlet{
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 사용자가 보내는 언어를 utf-8로 변경
resp.setCharacterEncoding("UTF-8");
// 사용자에게 받은 언어를 utf-8로 읽는 코드
resp.setContentType("text/html; charset=UTF-8");
PrintWriter out = resp.getWriter();
// // hello servlet 글자 앞에 1 ~ 100 까지 붙여서 출력
// for(int i=0; i<100; i++) {
// /*한글이 깨지는 이유
// * 1. 서버에서 한글을 지원하지않는 문자코드로 인코딩 한 경우
// * 2. 서버에서는 utf-8로 인코딩해서 보냈지만 브라우저가 다른 코드로 잘못 해석한 경우
// */
/**
* Post요청을 이용하여 많은 정보를 보내는 방법
*/
//notice-reg페이지에서 title과 content의 내용을 넘겨받는 코드
String title = req.getParameter("title");
String content = req.getParameter("content");
//사용자에게 다시 출력해주는 코드
out.println(title);
out.println(content);
}
}
|
/*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.cloud.cloudant.v1.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* The postSearchAnalyze options.
*/
public class PostSearchAnalyzeOptions extends GenericModel {
/**
* analyzer.
*/
public interface Analyzer {
/** arabic. */
String ARABIC = "arabic";
/** armenian. */
String ARMENIAN = "armenian";
/** basque. */
String BASQUE = "basque";
/** brazilian. */
String BRAZILIAN = "brazilian";
/** bulgarian. */
String BULGARIAN = "bulgarian";
/** catalan. */
String CATALAN = "catalan";
/** chinese. */
String CHINESE = "chinese";
/** cjk. */
String CJK = "cjk";
/** classic. */
String CLASSIC = "classic";
/** czech. */
String CZECH = "czech";
/** danish. */
String DANISH = "danish";
/** dutch. */
String DUTCH = "dutch";
/** email. */
String EMAIL = "email";
/** english. */
String ENGLISH = "english";
/** finnish. */
String FINNISH = "finnish";
/** french. */
String FRENCH = "french";
/** galician. */
String GALICIAN = "galician";
/** german. */
String GERMAN = "german";
/** greek. */
String GREEK = "greek";
/** hindi. */
String HINDI = "hindi";
/** hungarian. */
String HUNGARIAN = "hungarian";
/** indonesian. */
String INDONESIAN = "indonesian";
/** irish. */
String IRISH = "irish";
/** italian. */
String ITALIAN = "italian";
/** japanese. */
String JAPANESE = "japanese";
/** keyword. */
String KEYWORD = "keyword";
/** latvian. */
String LATVIAN = "latvian";
/** norwegian. */
String NORWEGIAN = "norwegian";
/** persian. */
String PERSIAN = "persian";
/** polish. */
String POLISH = "polish";
/** portuguese. */
String PORTUGUESE = "portuguese";
/** romanian. */
String ROMANIAN = "romanian";
/** russian. */
String RUSSIAN = "russian";
/** simple. */
String SIMPLE = "simple";
/** spanish. */
String SPANISH = "spanish";
/** standard. */
String STANDARD = "standard";
/** swedish. */
String SWEDISH = "swedish";
/** thai. */
String THAI = "thai";
/** turkish. */
String TURKISH = "turkish";
/** whitespace. */
String WHITESPACE = "whitespace";
}
protected String analyzer;
protected String text;
/**
* Builder.
*/
public static class Builder {
private String analyzer;
private String text;
private Builder(PostSearchAnalyzeOptions postSearchAnalyzeOptions) {
this.analyzer = postSearchAnalyzeOptions.analyzer;
this.text = postSearchAnalyzeOptions.text;
}
/**
* Instantiates a new builder.
*/
public Builder() {
}
/**
* Instantiates a new builder with required properties.
*
* @param analyzer the analyzer
* @param text the text
*/
public Builder(String analyzer, String text) {
this.analyzer = analyzer;
this.text = text;
}
/**
* Builds a PostSearchAnalyzeOptions.
*
* @return the new PostSearchAnalyzeOptions instance
*/
public PostSearchAnalyzeOptions build() {
return new PostSearchAnalyzeOptions(this);
}
/**
* Set the analyzer.
*
* @param analyzer the analyzer
* @return the PostSearchAnalyzeOptions builder
*/
public Builder analyzer(String analyzer) {
this.analyzer = analyzer;
return this;
}
/**
* Set the text.
*
* @param text the text
* @return the PostSearchAnalyzeOptions builder
*/
public Builder text(String text) {
this.text = text;
return this;
}
}
protected PostSearchAnalyzeOptions(Builder builder) {
com.ibm.cloud.sdk.core.util.Validator.notNull(builder.analyzer,
"analyzer cannot be null");
com.ibm.cloud.sdk.core.util.Validator.notNull(builder.text,
"text cannot be null");
analyzer = builder.analyzer;
text = builder.text;
}
/**
* New builder.
*
* @return a PostSearchAnalyzeOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the analyzer.
*
* analyzer.
*
* @return the analyzer
*/
public String analyzer() {
return analyzer;
}
/**
* Gets the text.
*
* text.
*
* @return the text
*/
public String text() {
return text;
}
}
|
package com.ziaan.scorm;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class CalendarBean
{
public CalendarBean()
{
calendar = Calendar.getInstance();
calendar.set(5, 1);
}
private int getMonthLastDay(int year, int month)
{
switch(month)
{
case 2: // '\002'
return (year % 4 != 0 || year % 100 == 0) && year % 400 != 0 ? 28 : 29;
case 4: // '\004'
case 6: // '\006'
case 9: // '\t'
case 11: // '\013'
return 30;
case 3: // '\003'
case 5: // '\005'
case 7: // '\007'
case 8: // '\b'
case 10: // '\n'
default:
return 31;
}
}
public int getLastDay()
{
int year = calendar.get(1);
int month = calendar.get(2) + 1;
return getMonthLastDay(year, month);
}
public int getLastMonthLastDay()
{
int year = calendar.get(1);
int month = calendar.get(2);
if ( month == 0)
{
year--;
month = 12;
}
return getMonthLastDay(year, month);
}
public void setYear(int value)
{
calendar.set(1, value);
}
public void setMonth(int value)
{
calendar.set(2, value - 1);
}
public int getYear()
{
return calendar.get(1);
}
public int getMonth()
{
return calendar.get(2) + 1;
}
public int getFirstOfMonth()
{
return calendar.get(7);
}
public boolean DateCheck(String dt)
{
boolean value = true;
try
{
DateFormat df = java.text.DateFormat.getDateInstance(3);
df.setLenient(false);
Date dt2 = df.parse(dt);
} catch(ParseException e)
{
value = false;
} catch(IllegalArgumentException e)
{
value = false;
}
return value;
}
public String DateFormat(String d_fmt, Date d)
{
SimpleDateFormat sdf = new SimpleDateFormat(d_fmt);
String value = sdf.format(d);
return value;
}
Calendar calendar;
}
|
package com.example.marta.zoo.animals;
/**
* Created by marta on 10/11/2017.
*/
public abstract class Animal {
private int cashValue;
private String name;
private int weight;
private int age;
public Animal(int cashValue, String name, int weight, int age) {
this.cashValue = cashValue;
this.name = name;
this.weight = weight;
this.age = age;
}
public int getCashValue() {
return this.cashValue;
}
public String getName() {
return this.name;
}
public int getWeight() {
return this.weight;
}
public int getAge() {
return this.age;
}
}
|
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession();
session.invalidate();
response.sendRedirect("signin.jsp");
// request.getRequestDispatcher("signin.jsp").include(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String uid=request.getParameter("uid");
String pass=request.getParameter("pass");
String pswd=null;
String fname = null;
String lname=null;
PrintWriter out=response.getWriter();
if(uid.isEmpty() && pass.isEmpty()){
request.setAttribute("error", "No data");
request.getRequestDispatcher("signin.jsp").forward(request, response);
}
else if(!(uid.matches("[0-9]+") && pass.matches("[a-zA-Z]+"))) {
request.setAttribute("error", "User id and password not in specified format(Invalid data).");
request.getRequestDispatcher("signin.jsp").forward(request, response);
}else {
Integer a=Integer.parseInt(uid);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * from user where userid="+a+"");
if(rs.next()){
pswd=rs.getString("password");
fname=rs.getString(1);
lname=rs.getString(2); }
if(pass.equals(pswd)) {
//out.println("Successful login");
HttpSession session=request.getSession();
session.setAttribute("user_id",a);
session.setAttribute("fname", fname);
session.setAttribute("lname", lname);
request.setAttribute("name", uid);
String fn = null;
request.setAttribute("fn", fname);
String ln = null;
request.setAttribute("ln", lname);
request.getRequestDispatcher("lsuccess.jsp").forward(request, response);
} else {
request.setAttribute("error", "Invalid credentials");
request.getRequestDispatcher("signin.jsp").forward(request, response);
}
/*String sql="select * from user where userid= ?";
PreparedStatement pstm=connection.prepareStatement(sql);
pstm.setInt(1,1357);
ResultSet rs=pstm.executeQuery();
if(rs.next()){
out.print(rs.getString("password"));
}
out.println("login successful"); */
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
out.println("SQLException: " + e.getMessage());
}
}
}
}
|
package lxy.liying.circletodo.task;
import java.util.List;
import java.util.Set;
import lxy.liying.circletodo.domain.SelectedColor;
/**
* =======================================================
* 版权:©Copyright LiYing 2015-2016. All rights reserved.
* 作者:liying
* 日期:2016/8/15 12:54
* 版本:1.0
* 描述:统计标记监听回调
* 备注:
* =======================================================
*/
public interface OnStatisticsListener {
/** 统计进度回调 */
void onProgress(int progress);
/** 统计完成回调 */
void onComplete(List<String> dateList, List<List<SelectedColor>> selectColorList, Set<SelectedColor> colorSet);
}
|
package scl.oms.outagemap;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
/**
* This static class is used to house geometry operations not provided with
* Esri's Java API
*
* @author jstewart
*/
public class GeometryTool {
/**
* The following method was derived from the following source:
* http://paulbourke.net/geometry/polygonmesh/ JAVA code submitted by Ramón
* Talavera Downloaded: 2015-06-11
*
* Modified by jstewart to use Esri Java API objects
*
* This method computes the area of a polygon.
*
*/
public static double getSignedPolygonArea(Polygon polygon) {
int i, j;
double area = 0.0;
for (i = 0; i < polygon.getPointCount(); i++) {
j = (i + 1) % polygon.getPointCount();
Point pointI = polygon.getPoint(i);
Point pointJ = polygon.getPoint(j);
area += pointI.getX() * pointJ.getY();
area -= pointI.getY() * pointJ.getX();
}
area /= 2.0;
return (area);
//return(area < 0 ? -area : area); for unsigned
}
/**
* The following method was derived from the following source:
* http://paulbourke.net/geometry/polygonmesh/ JAVA code submitted by Ramón
* Talavera Downloaded: 2015-06-11
*
* Modified by jstewart to use Esri Java API objects
*
* This method computes the center of mass of a polygon.
*
*/
public static Point getPolygonCenterOfMass(Polygon polygon) {
double centerX = 0.0, centerY = 0.0;
double area = GeometryTool.getSignedPolygonArea(polygon);
int i, j;
double factor = 0.0;
for (i = 0; i < polygon.getPointCount(); i++) {
j = (i + 1) % polygon.getPointCount();
Point pointI = polygon.getPoint(i);
Point pointJ = polygon.getPoint(j);
factor = (pointI.getX() * pointJ.getY() - pointJ.getX() * pointI.getY());
centerX += (pointI.getX() + pointJ.getX()) * factor;
centerY += (pointI.getY() + pointJ.getY()) * factor;
}
area *= 6.0;
factor = 1 / area;
centerX *= factor;
centerY *= factor;
return new Point(centerX, centerY);
}
/**
* This method removes all interior and all but the the largest exterior
* paths from a polygon. The result is the largest outside polygon.
* Additional interior and exterior paths are created when merging (using
* the union method) polygons.
*
* @param polygon
* @return the same polygon
*/
public static Polygon cleanPolygon(Polygon polygon) {
// remove any interior paths
if (polygon.getPathCount() > 1) {
for (int i = 0; i < polygon.getPathCount(); i++) {
if (!polygon.isExteriorRing(i)) {
polygon.removePath(i);
}
}
}
/*
remove all exterior paths except for the one with the greatest
number of points, which should be the 'outside' path ... a test of
existing data strongly indicates this process is valid for all cases,
else the first path is kept
*/
if (polygon.getPathCount() > 1) {
// find exterior path with greatest number of points
int indexOfLargestPath = 0;
int pointsInLargestPath = 0;
for (int i = 0; i < polygon.getPathCount(); i++) {
if (polygon.getPathSize(i) > pointsInLargestPath) {
pointsInLargestPath = polygon.getPathSize(i);
indexOfLargestPath = i;
}
}
for (int i = 0; i < polygon.getPathCount(); i++) {
if (i != indexOfLargestPath) {
polygon.removePath(i);
}
}
}
return polygon;
}
}
|
import javax.servlet.*;
import java.io.*;
import java.sql.*;
public class FormServlet implements Servlet
{
@Override
public void init( ServletConfig con )
{
System.out.println( "init method called" );
}
@Override
public void service( ServletRequest req,ServletResponse res )
throws ServletException,IOException
{
PrintWriter out = res.getWriter();
String name = req.getParameter( "p" );
String surname = req.getParameter( "surname" );
String address = req.getParameter( "address" );
try{
//load class
Class.forName( "com.mysql.jdbc.Driver" );
//create connection
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/testdb","root","12345" );
//create statement..
Statement ps = con.createStatement();
String sql = "insert into ser values( '"+name+"','"+surname+"','"+address+"' )";
int executeUpdate = ps.executeUpdate( sql );
if( executeUpdate != 0 )
{
out.println( "<body>" );
out.println( "<font color = \"Blue\"><h1>"+executeUpdate+" rows effected</h1></font>" );
out.println( "</body>" );
}
}catch( SQLException e )
{
out.println( "<body>" );
out.println( "<h1>Exception:"+e.getMessage()+"</h1>" );
out.println( "</body>" );
}catch( ClassNotFoundException e )
{
out.println( "<h1>Class not found</h1>" );
}
}//end of service method...
@Override
public ServletConfig getServletConfig( )
{
return null;
}
@Override
public String getServletInfo()
{
return "Servlet info method";
}
@Override
public void destroy()
{
}
} |
package com.git.cloud.iaas.firewall;
import com.git.cloud.iaas.firewall.service.FirewallNatService;
import com.git.cloud.iaas.firewall.service.FirewallPolicyService;
import com.git.cloud.iaas.firewall.service.FirewallServiceInsideHwImpl;
import com.git.cloud.iaas.firewall.service.FirewallServiceOutsideHsImpl;
public class FirewallServiceFactory {
/**
* 华为云内防火墙策略实例
*/
private static FirewallPolicyService firewallPolicyServiceInsideHwImpl;
/**
* 山石云外防火墙策略实例
*/
private static FirewallPolicyService firewallPolicyServiceOutsideHsImpl;
/**
* 山石云外防火墙Nat实例
*/
private static FirewallNatService firewallNatServiceOutsideHsImpl;
public static FirewallPolicyService getFirewallPolicyServiceInsideHw() {
if(firewallPolicyServiceInsideHwImpl == null) {
firewallPolicyServiceInsideHwImpl = new FirewallServiceInsideHwImpl();
}
return firewallPolicyServiceInsideHwImpl;
}
public static FirewallPolicyService getFirewallPolicyServiceOutsideHs() {
if(firewallPolicyServiceOutsideHsImpl == null) {
firewallPolicyServiceOutsideHsImpl = new FirewallServiceOutsideHsImpl();
}
return firewallPolicyServiceOutsideHsImpl;
}
public static FirewallNatService getFirewallNatServiceOutsideHs() {
if(firewallNatServiceOutsideHsImpl == null) {
firewallNatServiceOutsideHsImpl = new FirewallServiceOutsideHsImpl();
}
return firewallNatServiceOutsideHsImpl;
}
}
|
public class Student {
private String studentName;
private String studentProfession;
private int course;
private double gpa;
public Student(String studentName,String studentProfession,int course, double gpa){
this.course = course;
if(gpa<=5){
this.gpa = gpa;
}else{
System.out.println("Dundaj Unelgee buruu bna.");
}
this.studentName = studentName;
this.studentProfession = studentProfession;
}
public double getGpa() {
return gpa;
}
public int getCourse() {
return course;
}
public String getStudentName() {
return studentName;
}
public String getStudentProfession() {
return studentProfession;
}
public void setCourse(int course) {
this.course = course;
}
public void setGpa(double gpa) {
if(gpa<=5){
this.gpa = gpa;
}else{
System.out.println("Dundaj Unelgee buruu bna.");
}
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public void setStudentProfession(String studentProfession) {
this.studentProfession = studentProfession;
}
}
|
import java.io.File;
import java.util.Date;
import java.io.IOException;
public class IAndOFile {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f = new File("d:/Java/test.exe");
System.out.println("now file is: " + f);
System.out.println("judge exist: " + f.exists());
System.out.println("judge exist is Directory: " + f.isDirectory());
System.out.println("judge exist is file: " + f.isFile());
System.out.println("get file length: " + f.length());
long time = f.lastModified();
Date d = new Date(time);
System.out.println("get file last modify time: " + d);
f.setLastModified(0);
File f2 = new File("d:/Java/test/test.exe");
f.renameTo(f2);
System.out.println("put test.exe rename to haha.exe");
System.out.println("attention:need d:\\java exist test.exe,\r\n so get file length,time etc..");
File f3 = new File("d:/Java");
f3.list();
File[] fs = f3.listFiles();
f3.getParent();
f3.getParentFile();
f3.mkdir();
// f3.createNewFile();
f3.getParentFile().mkdir();
f3.listRoots();
f3.delete();
f3.deleteOnExit();
}
}
|
/*
* OpenCV for Android NDK
* Copyright (c) 2006-2009 SIProp Project http://www.siprop.org/
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it freely,
* subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*
*/
package org.siprop.opencv;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
/**
* Simple class for configuring which camera to use.
*
* @author Bill McCord
*/
public final class VideoEmulationConfiguration extends Activity {
public static final String EXTRA_IS_REMOTE_CAMERA = "IS_REMOTE_CAMERA";
public static final String EXTRA_REMOTE_CAMERA_ADDRESS = "REMOTE_CAMERA_ADDRESS";
public static final String EXTRA_REMOTE_CAMERA_PORT = "REMOTE_CAMERA_PORT";
public static final String EXTRA_OPENCV_ACTION = "OPENCV_ACTION";
public static final String EXTRA_CAMERA_OPTION = "CAMERA_OPTION";
public static final String FIND_CONTOURS = "FIND_CONTOURS";
public static final String TRACK_ALL_FACES = "TRACK_ALL_FACES";
public static final String TRACK_SINGLE_FACE = "TRACK_SINGLE_FACE";
public static final String C_SOCKET_CAMERA = "C_SOCKET_CAMERA";
public static final String JAVA_SOCKET_CAMERA = "JAVA_SOCKET_CAMERA";
private static final String DEFAULT_REMOTE_CAMERA = "192.168.0.102:9889";
private static final String TAG = "VideoEmulationConfiguration";
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
// init Camera.
setContentView(R.layout.config);
Button restoreDefaultCameraButton = (Button)findViewById(R.id.ResotreDefaultCameraButton);
restoreDefaultCameraButton.setOnClickListener(onRestoreDefaultCameraClick);
Button doneButton = (Button)findViewById(R.id.DoneButton);
doneButton.setOnClickListener(onDoneClick);
}
private OnClickListener onRestoreDefaultCameraClick = new OnClickListener() {
public void onClick(View arg0) {
((EditText)findViewById(R.id.RemoteSourceEditText)).setText(DEFAULT_REMOTE_CAMERA);
}
};
private OnClickListener onDoneClick = new OnClickListener() {
public void onClick(View arg0) {
boolean skipActivity = false;
String address = null;
String port = null;
String remoteCameraStr = ((EditText)findViewById(R.id.RemoteSourceEditText)).getText()
.toString();
String[] remoteCameraStrArr = remoteCameraStr.split(":");
if (remoteCameraStrArr.length == 2) {
address = remoteCameraStrArr[0];
port = remoteCameraStrArr[1];
} else {
skipActivity = true;
}
if (!skipActivity) {
Intent invoker = new Intent();
invoker.putExtra(EXTRA_REMOTE_CAMERA_ADDRESS, address);
invoker.putExtra(EXTRA_REMOTE_CAMERA_PORT, port);
RadioButton trackAllFacesRadioButton = (RadioButton)findViewById(R.id.TrackAllFacesRadioButton);
RadioButton findContoursRadioButton = (RadioButton)findViewById(R.id.FindContoursRadioButton);
if (trackAllFacesRadioButton.isChecked()) {
Log.v(TAG, "Track All Faces");
invoker.putExtra(EXTRA_OPENCV_ACTION, TRACK_ALL_FACES);
} else if (findContoursRadioButton.isChecked()) {
Log.v(TAG, "Find Contours");
invoker.putExtra(EXTRA_OPENCV_ACTION, FIND_CONTOURS);
} else {
Log.v(TAG, "Track Single Face");
invoker.putExtra(EXTRA_OPENCV_ACTION, TRACK_SINGLE_FACE);
}
CheckBox useCSocketCamera = (CheckBox)findViewById(R.id.UseCSocketCapture);
if (useCSocketCamera.isChecked()) {
invoker.putExtra(EXTRA_CAMERA_OPTION, C_SOCKET_CAMERA);
} else {
invoker.putExtra(EXTRA_CAMERA_OPTION, JAVA_SOCKET_CAMERA);
}
// Invoke the VideoEmulation activity after the camera
// is successfully configured.
invoker.setClass(getBaseContext(), VideoEmulation.class);
startActivity(invoker);
finish();
}
}
};
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package projecteuler;
import java.io.IOException;
/**
*
* @author Sachin tripathi
*/
public class CountingSundays {
public static void main(String args[]) throws IOException {
int count = 0, days_in_month, days_passed = 1;
for (int i = 1901; i < 2000; i++) {
for (int j = 1; j <= 12; j++) {
if (j == 4 || j == 6 || j == 9 || j == 11) {
days_in_month = 30;
} else if (j == 2) {
if (i % 400 == 0 || (i % 4 == 0 && i % 100 != 0)) {
days_in_month = 29;
} else {
days_in_month = 28;
}
} else {
days_in_month = 31;
}
if (days_passed % 7 == 0) {
count++;
}
days_passed += days_in_month;
}
}
System.out.println(count);
}
}
|
package com.alibaba.dubbo.rpc;
import com.alibaba.dubbo.common.Node;
//调用接口
public interface Invoker<T> extends Node {
//获取服务接口
Class<T> getInterface();
//方法调用
Result invoke(Invocation invocation) throws RpcException;
} |
package slimeknights.tconstruct.tools.common.entity;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import io.netty.buffer.ByteBuf;
import slimeknights.tconstruct.library.entity.EntityProjectileBase;
public class EntityArrow extends EntityProjectileBase {
// animation
public int roll = 0;
public int rollSpeed = 80;
public EntityArrow(World world) {
super(world);
}
public EntityArrow(World world, double d, double d1, double d2) {
super(world, d, d1, d2);
}
public EntityArrow(World world, EntityPlayer player, float speed, float inaccuracy, float power, ItemStack stack, ItemStack launchingStack) {
super(world, player, speed, inaccuracy, power, stack, launchingStack);
}
@Override
protected void onEntityHit(Entity entityHit) {
super.onEntityHit(entityHit);
if(!this.getEntityWorld().isRemote && entityHit instanceof EntityLivingBase) {
EntityLivingBase entityLivingBaseHit = (EntityLivingBase) entityHit;
entityLivingBaseHit.setArrowCountInEntity(entityLivingBaseHit.getArrowCountInEntity() + 1);
}
}
@Override
protected void playHitBlockSound(float speed, IBlockState state) {
this.playSound(SoundEvents.ENTITY_ARROW_HIT, 1.0F, 1.2F / (this.rand.nextFloat() * 0.2F + 0.9F));
}
@Override
public void readSpawnData(ByteBuf data) {
super.readSpawnData(data);
// animation stuff, it sometimes rotates left
int rollDir = rand.nextBoolean() ? -1 : 1;
rollSpeed = (int)((getSpeed() * 80) / 3) * rollDir;
}
}
|
package com.blurack.activities;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.blurack.R;
import com.blurack.constants.Constants;
import com.blurack.fragments.CocktailRecipesFragment;
import com.blurack.fragments.CraftBrandsFragment;
import com.blurack.fragments.FavRecipesFragment;
import com.blurack.fragments.HomeFragment;
import com.blurack.fragments.LocationMapFragment;
import com.blurack.fragments.ProductsFragment;
import com.blurack.fragments.ReservedProductsFragment;
import com.blurack.fragments.ShoppingListFragment;
import com.blurack.utils.Preferences;
import org.json.JSONException;
import org.json.JSONObject;
import cn.pedant.SweetAlert.SweetAlertDialog;
public class HomeActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setUpNavigationDrawer(toolbar);
populateUserData();
getSupportFragmentManager().addOnBackStackChangedListener(backStackListener);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer!=null && drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
private void setUpNavigationDrawer(Toolbar toolbar){
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
if(drawer!=null) {
drawer.addDrawerListener(toggle);
}
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if(navigationView!=null) {
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_home);
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, HomeFragment.newInstance()).commit();
}
private void populateUserData(){
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View header = navigationView.getHeaderView(0);
Preferences preferences = Preferences.getInstance(HomeActivity.this);
String userData = preferences.getString(Constants.TAG_USER_DATA);
TextView mUserName = (TextView) header.findViewById(R.id.textUserName);
TextView mUserEmail = (TextView) header.findViewById(R.id.textUserEmail);
if(userData!=null){
try {
JSONObject userObject = new JSONObject(userData);
String userName = String.format("%s %s",userObject.getString("first_name"),userObject.getString("last_name"));
mUserName.setText(userName);
mUserEmail.setText(userObject.getString("email"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
switch (id){
case R.id.nav_home:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, HomeFragment.newInstance()).commit();
break;
case R.id.nav_reserved:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, ReservedProductsFragment.newInstance(0)).commit();
break;
case R.id.nav_shop_list:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, ShoppingListFragment.newInstance()).commit();
break;
case R.id.nav_fav:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, FavRecipesFragment.newInstance()).commit();
break;
case R.id.nav_share:
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Hey I am using BluRack. You can download it from https://play.google.com/store/apps/details?id=com.blurack";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Download Blurack");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
break;
case R.id.nav_settings:
startActivity(new Intent(HomeActivity.this,ProfileActivity.class));
break;
case R.id.nav_logout:
Preferences preferences = Preferences.getInstance(HomeActivity.this);
preferences.clearSharedPref();
this.finish();
break;
case R.id.nav_cock:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, CocktailRecipesFragment.newInstance(2)).addToBackStack(null).commit();
break;
case R.id.nav_feat_prod:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, ProductsFragment.newInstance(1)).addToBackStack(null).commit();
break;
case R.id.nav_br_loc:
startActivity(new Intent(HomeActivity.this,LocationActivity.class));
break;
case R.id.nav_discb:
removeAllFromBackStack();
fragmentManager.beginTransaction().replace(R.id.content_frame, CraftBrandsFragment.newInstance(1)).addToBackStack(null).commit();
break;
}
setActionBarTitle(item.getTitle().toString());
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if(drawer!=null) {
drawer.closeDrawer(GravityCompat.START);
}
return true;
}
public void setActionBarTitle(String title) {
ActionBar actionBar = getSupportActionBar();
if(actionBar!=null){
actionBar.setTitle(title);
}
}
public void setActionBarBackground(int color) {
ActionBar actionBar = getSupportActionBar();
Drawable bg = new ColorDrawable(color);
if(actionBar!=null){
actionBar.setBackgroundDrawable(bg);
}
}
private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
setNavIcon();
}
};
protected void setNavIcon() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
Log.e("BackStack","Count:"+backStackEntryCount);
toggle.setDrawerIndicatorEnabled(backStackEntryCount == 1);
if(backStackEntryCount != 1) {
toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
public void removeAllFromBackStack(){
for (int i = 0; i < getSupportFragmentManager().getBackStackEntryCount(); i++) {
getSupportFragmentManager().popBackStack();
}
}
public void showHome(){
removeAllFromBackStack();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, HomeFragment.newInstance()).commit();
}
}
|
/*
* 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 br.ufsc.ine5605.clavicularioeletronico.excecoes;
/**
*
* @author Flávio
*/
public class ParametroNuloException extends IllegalArgumentException {
public ParametroNuloException(String nomeParametro) {
super("Parâmetro " + nomeParametro + " não pode ser nulo!");
}
}
|
package com.yc.education.service.impl;
import com.yc.education.mapper.RolesMapper;
import com.yc.education.model.Roles;
import com.yc.education.service.RolesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName RolesServiceImpl
* @Description TODO
* @Author QuZhangJing
* @Date 2019/2/28 9:56
* @Version 1.0
*/
@Service("RolesService")
public class RolesServiceImpl extends BaseService<Roles> implements RolesService {
@Autowired
private RolesMapper rolesMapper;
@Override
public List<Roles> findRoles() {
try {
return rolesMapper.findRoles();
}catch (Exception e){
return null;
}
}
@Override
public Roles findRolesByRoleName(String roleName) {
try {
return rolesMapper.findRolesByRoleName(roleName);
}catch (Exception e){
return null;
}
}
}
|
package com.restAssured.com.restAssured.Deepak;
import java.util.List;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import bin.BaseClass;
import bin.RestResponse;
import bin.Result;
import io.restassured.mapper.ObjectMapperType;
import io.restassured.response.Response;
public class restTest extends cf {
/**
* @Author: Deepak Prabhu
* @Date: 05/09/2017
*/
RestAssuredConfiguration restSpec = new RestAssuredConfiguration();
@BeforeTest
public void before(){
}
@Test
public void restAssuredTest() {
Response response = restSpec.getResponseType().queryParam("text", "Pradesh").get(Endpoint.QUERY_PARAM);
System.out.println(response.asString());
BaseClass b = response.as(BaseClass.class, ObjectMapperType.GSON);
List<Result> items = b.getRestResponse().getResult();
for(Result item: items)
{
if(item.getName().equalsIgnoreCase("Andhra Pradesh")){
updateTestLog(item.getCapital().toString(), "Hyderabad, India","PASS");
}else {
System.out.println("this is my change that needs to staged for commit");
}
}
}
}
|
package com.pisen.ott.launcher.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import com.pisen.ott.launcher.R;
/**
* 公用等待进度圈
*
* @author Liuhc
* @version 1.0 2015年4月30日 下午3:51:05
*/
public class OTTWiatProgress extends ImageView {
private Animation operatingAnim;
public OTTWiatProgress(Context context) {
super(context);
setDefaultImage();
}
public OTTWiatProgress(Context context, AttributeSet attrs) {
super(context, attrs);
setDefaultImage();
}
public OTTWiatProgress(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setDefaultImage();
}
private void setDefaultImage() {
if (getDrawable() == null) {
setImageResource(R.drawable.public_waiting);
}
}
public void cancel() {
Log.i("testMsg", this.hashCode() + "cancel");
clearAnimation();
/*if (operatingAnim != null) {
operatingAnim.cancel();
}*/
setVisibility(View.GONE);
}
public void show() {
setVisibility(View.VISIBLE);
Log.i("testMsg", this.hashCode() + "show");
operatingAnim = AnimationUtils.loadAnimation(getContext(), R.anim.rotation_wait);
// LinearInterpolator lin = new LinearInterpolator();
// operatingAnim.setInterpolator(lin);
startAnimation(operatingAnim);
}
public boolean isShown(){
return getVisibility() == View.VISIBLE;
}
}
|
package gil.server.data;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class PersonTest {
@Test
public void hasId() {
Integer id = 1;
Person programmer = new Person();
programmer.setId(id);
assertEquals(id, programmer.getId());
}
@Test
public void hasName() {
String name = "Gil Roman";
Person programmer = new Person();
programmer.setName(name);
assertEquals(name, programmer.getName());
}
@Test
public void hasEmail() {
String email = "gil@tdd.com";
Person programmer = new Person();
programmer.setEmail(email);
assertEquals(email, programmer.getEmail());
}
@Test
public void createsStringRepresentation() {
String expectedString = "1, Gil Roman, gil@tdd.com";
Person programmer = new Person();
programmer.setId(1);
programmer.setName("Gil Roman");
programmer.setEmail("gil@tdd.com");
assertEquals(expectedString, programmer.toString());
}
}
|
package hwarang.artg.mapper;
import java.util.List;
import hwarang.artg.member.model.TasteVO;
public interface TasteMapper {
public int insertTaste(TasteVO t);
public int updateTaste(TasteVO t);
public int deleteTaste(String taste_name);
public TasteVO selectTaste(String taste_name);
public List<TasteVO> selectAllTaste();
}
|
package Chinese.ChineseDecorator;
import Chinese.Chinese;
public class MagicMasala extends DishDecorator {
Chinese chinese;
public MagicMasala(Chinese chinese){
this.chinese = chinese;
}
@Override
public double cost() {
return 10.0 + chinese.cost();
}
@Override
public String getDescription() {
return chinese.getDescription() + ", MagicMasala";
}
}
|
package project.test;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import project.core.groupPage.GroupCard;
import project.core.groupPage.GroupProfilePage;
import project.core.homePage.HomePage;
import project.core.loginPage.LoginPage;
import project.model.TestBot;
public class JoinToGroup extends TestBase{
private static HomePage homePage;
private static TestBot bot = new TestBot("tests", "tests");
private String groupName = "Технополис OK (Mail.ru) и Политеха";
private String groupUrl = "https://ok.ru/technopolis";
private String joinStatus = "Вы в группе!";
@Before
public void login() {
homePage = new LoginPage().doLogin(bot);
}
@Test
public void joinToGroup() {
GroupCard cardByTitle = homePage.getLeftColumnContent()
.clickGroups()
.search(groupName)
.getCardByTitle(groupName);
String title = cardByTitle
.join();
Assert.assertEquals(joinStatus, title);
String href = cardByTitle.getHref();
Assert.assertEquals(groupUrl, href);
}
@After
public void quitFromGroup() {
goToUrl(groupUrl);
new GroupProfilePage().leaveGroup();
}
}
|
/*
* Created on 2004-05-24
*/
package com.esum.ebms.v2.msh;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.xml.soap.MimeHeader;
import javax.xml.soap.MimeHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.ebms.v2.packages.EbXMLMessage;
import com.esum.ebms.v2.packages.container.element.MessageHeader;
import com.esum.ebms.v2.service.ApplicationService;
import com.esum.ebms.v2.service.ResponseService;
import com.esum.ebms.v2.service.Routing;
import com.esum.ebms.v2.service.ServiceManager;
import com.esum.ebms.v2.service.ServiceUtil;
import com.esum.ebms.v2.service.transport.TransportException;
import com.esum.ebms.v2.service.transport.TransportType;
import com.esum.ebms.v2.service.transport.clazz.ClassTransport;
import com.esum.ebms.v2.service.transport.clazz.ClassTransportInfo;
public class HandlerUtil {
private static Logger log = LoggerFactory.getLogger(HandlerUtil.class);
/**
* 수신한 EbXMLMessage로부터 Routing정보를 뽑아낸다.
* Ping메시지에 대해 From, To정보를 가지고 To, From으로 라우팅 정보를 찾는다.
*/
public static Routing makeResponseRouting(EbXMLMessage message){
log.debug("enter makeResponseRouting()");
Routing routing = new Routing(message.getCPAId());
log.debug("toParty --> fromParty");
Iterator i = message.getToPartyIdList();
while(i.hasNext()){
MessageHeader.PartyId pi = (MessageHeader.PartyId)i.next();
String partyType = pi.getParyIdType();
partyType = (partyType==null || partyType.equals("null"))?"*":partyType;
routing.addFromParty(pi.getPartyId(), partyType);
log.debug("from party : id("+pi.getPartyId()+"), type("+pi.getParyIdType()+")");
}
routing.fromRole = (message.getToRole()==null || message.getToRole().equals(""))?"*":message.getToRole();
log.debug("fromParty --> toParty");
Iterator j = message.getFromPartyIdList();
while(j.hasNext()){
MessageHeader.PartyId pi = (MessageHeader.PartyId)j.next();
String partyType = pi.getParyIdType();
partyType = (partyType==null || partyType.equals("null"))?"*":partyType;
routing.addToParty(pi.getPartyId(), partyType);
log.debug("to party : id("+pi.getPartyId()+"), type("+pi.getParyIdType()+")");
}
routing.toRole = (message.getFromRole()==null || message.getFromRole().equals(""))?"*":message.getFromRole();
routing.service = message.getService().getService();
routing.serviceType = message.getService().getServiceType();
routing.action = message.getAction();
return routing;
}
/**
* 수신한 EbXMLMessage로부터 Routing정보를 뽑아낸다.
*/
public static Routing makeRouting(String traceId, EbXMLMessage message){
log.debug(traceId + "Making Routing from the ebXML message...");
Routing routing = new Routing(message.getCPAId());
Iterator i = message.getFromPartyIdList();
while(i.hasNext()) {
MessageHeader.PartyId pi = (MessageHeader.PartyId)i.next();
String partyType = pi.getParyIdType();
partyType = (partyType == null || partyType.equals("null")) ? "*" : partyType;
routing.addFromParty(pi.getPartyId(), partyType);
log.debug(traceId + "From: PartyId(" + pi.getPartyId() + "), type(" + pi.getParyIdType() + ")");
}
routing.fromRole = (message.getFromRole() == null
|| message.getFromRole().equals("")) ? "*" : message.getFromRole();
Iterator j = message.getToPartyIdList();
while(j.hasNext()) {
MessageHeader.PartyId pi = (MessageHeader.PartyId)j.next();
String partyType = pi.getParyIdType();
partyType = (partyType == null || partyType.equals("null")) ? "*" : partyType;
routing.addToParty(pi.getPartyId(), partyType);
log.debug(traceId + "To: PartyId(" + pi.getPartyId() + "), type(" + pi.getParyIdType() + ")");
}
routing.toRole = (message.getToRole() == null
|| message.getToRole().equals("")) ? "*" : message.getToRole();
routing.service = message.getService().getService();
routing.serviceType = message.getService().getServiceType();
routing.action = message.getAction();
return routing;
}
public static String getContentType(MimeHeaders mimeHeaders, String contentId) {
String contentType = null;
Iterator i = mimeHeaders.getAllHeaders();
while(i.hasNext()){
MimeHeader header = (MimeHeader)i.next();
if(header.getName().equals("Content-Type")) {
contentType = header.getValue();
break;
}
}
if (contentType != null) {
StringTokenizer tokens = new StringTokenizer(contentType, ";");
StringBuffer buffer = new StringBuffer();
if(tokens.countTokens() == 3) {
buffer.append(tokens.nextToken().trim()+";");
buffer.append(tokens.nextToken().trim()+";");
buffer.append(tokens.nextToken().trim()+";");
buffer.append("start=\""+contentId+"\"");
} else {
buffer.append(contentType);
}
return buffer.toString();
}
return null;
}
/**
* Single SOAP메시지의 경우 MIME Boundary를 생성하지 않는다. ebms에서 single인 경우 강제적으로 MIME을 생성 후
* content-type을 정의해야 한다. 이 루틴에서 content-type을 정의하도록 한다.
*/
public static String getContentType(String contentType, String contentId) {
if (contentType != null) {
StringTokenizer tokens = new StringTokenizer(contentType, ";");
StringBuffer buffer = new StringBuffer();
tokens.nextToken();
buffer.append("multipart/related"+"; ");
buffer.append(tokens.nextToken().trim()+";");
buffer.append("type=\"text/xml"+"\";");
buffer.append("start=\""+contentId+"\"");
return buffer.toString();
}
return null;
}
public static Object readObject(byte[] message) throws Exception {
log.debug("enter readObject(message)");
Object object = null;
ObjectInputStream objInput = null;
try{
objInput = new ObjectInputStream(new ByteArrayInputStream(message));
object = objInput.readObject();
log.debug("object received : "+object.getClass().getName());
}catch(Exception e){
throw new Exception("Cannot read object from message.");
}finally{
if(objInput!=null)
objInput.close();
}
return object;
}
public static Object readObject(ServletRequest request)
throws ServletException, IOException {
log.debug("enter readObject()");
ObjectInputStream objInput = null;
Object object = null;
try {
objInput = new ObjectInputStream(request.getInputStream());
object = objInput.readObject();
log.debug("object received : "+object.getClass().getName());
} catch (IOException e) {
throw e;
} catch (ClassNotFoundException e) {
throw new ServletException(e.toString());
} finally{
if(objInput!=null)
objInput.close();
}
return object;
}
/**
* 송신한 결과에 대한 ResponseService를 Adapter에게 전송하는 메소드.
* @param context ResponseService
* @throws TransportException
* @throws IOException
*/
public static void responseToAdapter(ResponseService context) throws TransportException {
TransportType transType = context.getTransportType();
if(transType.getTransportType()==TransportType.TRANSPORT_CLASS){
ClassTransport transport = ((ClassTransportInfo)transType).getClassTransport();
transport.response(ClassTransport.SERVICE_CONTEXT_TYPE, ServiceUtil.objectToBytes(context));
} else
throw new TransportException(TransportException.ERROR_NOT_SUPPORT_TRANSPORT_TYPE, "responseToAdapter()",
"Not supported TransportType : "+context.getClass().getName());
}
/**
* 해당되는 ContextID에게 EbXMLMessage를 전송한다.
*/
public static void sendToAdapter(String contextId, EbXMLMessage message)
throws TransportException {
if(contextId == null || contextId.trim().equals(""))
return;
ApplicationService appSvr = (ApplicationService)ServiceManager.getInstance().getService(contextId);
if (appSvr == null) {
throw new TransportException(TransportException.ERROR_EMPTY_APPLICATION_SERVICE, "sendToAdapter()",
"ApplicationService Error!! " + contextId +" adapter is not registered or not started yet.");
}
TransportType transType = appSvr.getTransportType();
if (transType.getTransportType() == TransportType.TRANSPORT_CLASS) {
ClassTransport transport = ((ClassTransportInfo)transType).getClassTransport();
transport.response(message);
} else
throw new TransportException(TransportException.ERROR_NOT_SUPPORT_TRANSPORT_TYPE, "sendToAdapter()",
"Not supported TransportType: "+message.getClass().getName());
}
}
|
package com.hackthon.kisainsur.src.guest.interfaces;
import com.hackthon.kisainsur.src.guest.models.TravelResponse;
import com.hackthon.kisainsur.src.main.models.DefaultResponse;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
public interface GuestRetrofitInterface {
// @GET("/test")
@GET("/travel/{travelNo}")
Call<TravelResponse> getTravel(@Path("travelNo") int travelNo);
@GET("/pushTravel/1/1")
Call<DefaultResponse> pushTravel();
@GET("/pushInputDone")
Call<DefaultResponse> pushInputDone();
@POST("/travel")
Call<DefaultResponse> postTravel(@Body RequestBody params);
}
|
//
// Decompiled by Procyon v0.5.36
//
package com.davivienda.sara.procesos.reintegros.notas.session;
import javax.xml.ws.WebServiceException;
import java.util.Date;
import com.davivienda.utilidades.conversion.FormatoFecha;
import com.davivienda.sara.constantes.TipoCuenta;
import java.math.BigDecimal;
import com.davivienda.utilidades.conversion.Fecha;
import java.util.logging.Level;
import com.davivienda.sara.entitys.Cajero;
import java.util.logging.Logger;
import com.davivienda.sara.entitys.Occa;
import javax.annotation.PostConstruct;
import com.davivienda.sara.entitys.config.ConfModulosAplicacionPK;
import com.davivienda.sara.entitys.config.ConfModulosAplicacion;
import com.davivienda.sara.config.SaraConfig;
import com.davivienda.utilidades.ws.gestor.cliente.InvocacionServicios;
import com.davivienda.sara.tablas.occa.servicio.OccaServicio;
import com.davivienda.sara.tablas.cajero.servicio.CajeroServicio;
import javax.annotation.Resource;
import javax.transaction.UserTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.ejb.TransactionManagementType;
import javax.ejb.TransactionManagement;
import javax.ejb.Local;
import javax.ejb.Stateless;
@Stateless
@Local({ ReintegrosNotasProcesosSessionLocal.class })
@TransactionManagement(TransactionManagementType.BEAN)
public class ReintegrosNotasProcesosSessionBean implements ReintegrosNotasProcesosSessionLocal
{
@PersistenceContext
private EntityManager em;
@Resource
private UserTransaction utx;
private CajeroServicio cajeroServicio;
private OccaServicio occaServicio;
private InvocacionServicios invocacionServicios;
String servidor;
String puerto;
String concepto;
String canal;
private static SaraConfig configApp;
public ReintegrosNotasProcesosSessionBean() {
this.servidor = "";
this.puerto = "";
this.concepto = "";
this.canal = "";
}
@PostConstruct
public void postConstructor() {
this.cajeroServicio = new CajeroServicio(this.em);
this.occaServicio = new OccaServicio(this.em);
this.servidor = ((ConfModulosAplicacion)this.em.find((Class)ConfModulosAplicacion.class, (Object)new ConfModulosAplicacionPK("SARA", "SARA.SERVIDOR_WS"))).getValor().trim();
this.puerto = ((ConfModulosAplicacion)this.em.find((Class)ConfModulosAplicacion.class, (Object)new ConfModulosAplicacionPK("SARA", "SARA.PUERTO_SERVIDOR_WS"))).getValor().trim();
this.iniciarLog();
this.concepto = "0016";
this.canal = "0";
}
private Integer obtenerCodigoTerminal(final Integer codigoOcca) {
Integer codTerminal = 0;
try {
final Occa occa = this.occaServicio.buscar(codigoOcca);
if (occa != null) {
codTerminal = occa.getCodigoTerminal();
}
}
catch (Exception ex) {
Logger.getLogger("globalApp").info("No se pudo obtener el CodigoTerminal de la occa" + ex.getMessage());
}
return codTerminal;
}
private Integer obtenerCodigoOcca(final Integer codigoCajero) {
Integer codTerminal = 0;
try {
final Cajero cajero = this.cajeroServicio.buscar(codigoCajero);
if (cajero != null) {
codTerminal = cajero.getOcca().getCodigoOcca();
}
}
catch (Exception ex) {
Logger.getLogger("globalApp").info("No se pudo obtener el CodigoOcca de el codigoCajero" + ex.getMessage());
}
return codTerminal;
}
private void iniciarLog() {
if (ReintegrosNotasProcesosSessionBean.configApp == null) {
try {
ReintegrosNotasProcesosSessionBean.configApp = SaraConfig.obtenerInstancia();
}
catch (IllegalAccessException ex) {
Logger.getLogger(ReintegrosNotasProcesosSessionBean.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
catch (Exception ex2) {
Logger.getLogger(ReintegrosNotasProcesosSessionBean.class.getName()).log(Level.SEVERE, ex2.getMessage(), ex2);
}
}
}
private String armarTalon(final Integer codigoCajero) {
String strCodigoCajero = "0";
String talon = "";
strCodigoCajero = codigoCajero.toString();
final Integer milisegundos = Fecha.getCalendarHoy().get(14);
if (codigoCajero < 10) {
strCodigoCajero = "000" + strCodigoCajero;
}
else if (codigoCajero < 100) {
strCodigoCajero = "00" + strCodigoCajero;
}
else if (codigoCajero < 1000) {
strCodigoCajero = "0" + strCodigoCajero;
}
talon = strCodigoCajero + milisegundos.toString().substring(1);
if (talon.length() == 4) {
talon += "0";
}
if (talon.length() == 5) {
talon += "0";
}
return talon;
}
private String armarTalonNotaCredito(String talon) {
for (int i = 0; talon.length() < 6; talon = "0" + talon, ++i) {}
return talon;
}
@Override
public String realizarNotaDebito(final Integer codigoCajero, final BigDecimal valor, final String cuenta, final Integer tipoCuenta, final String usuario, String concepto) {
String fechaActual = "";
String talon = "";
String respuesta = "";
String respuestaDescripcion = "";
Integer codigoOcca = 0;
Date fecha = null;
TipoCuenta tipoCuentaR = TipoCuenta.CuentaAhorros;
tipoCuentaR = TipoCuenta.getTipoCuenta(tipoCuenta);
try {
codigoOcca = this.obtenerCodigoOcca(codigoCajero);
fecha = Fecha.getCalendarHoy().getTime();
fechaActual = Fecha.aCadena(fecha, FormatoFecha.AAAAMMDD);
talon = this.armarTalon(codigoCajero);
respuesta = this.aplicarNotaDebito(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, tipoCuentaR, usuario, concepto);
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.FINE, "EN realizarNotaDebito " + tipoCuentaR.nombre + " para codigoCajero : " + codigoCajero.toString() + " por : " + valor.toString() + " Canal: " + this.canal + " la respuesta del webservice es " + respuesta);
respuestaDescripcion = respuesta;
if (respuesta != null && respuesta.length() > 0) {
if (respuesta.substring(0, 1).equals("M")) {
respuestaDescripcion = "NO se pudo Realizar la NotaDebito " + tipoCuentaR.nombre;
}
else if (respuesta.substring(0, 1).equals("B")) {
respuestaDescripcion = (respuestaDescripcion = respuestaDescripcion + "NotaDebito " + tipoCuentaR.nombre + "Realizado con Exito");
}
}
}
catch (Exception ex) {
respuestaDescripcion = "EN NotaDebito " + tipoCuentaR.nombre + "Error: " + ex.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaDebito " + tipoCuentaR.nombre + " Error: " + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
return respuesta;
}
public String aplicarNotaDebito(final Integer codigoCajero, final Integer codigoOcca, final BigDecimal valor, final String fechaActual, final String talon, final String cuenta, final TipoCuenta tipoCuenta, final String usuario,String concepto) {
String respuesta = "";
String respuestaDescripcion = "";
try {
this.invocacionServicios = new InvocacionServicios(this.servidor, this.puerto, codigoCajero);
this.invocacionServicios = new InvocacionServicios(this.servidor, this.puerto, this.obtenerCodigoTerminal(codigoOcca));
switch (tipoCuenta) {
case CuentaAhorros: {
respuesta = this.invocacionServicios.realizarNotaDebitoCtaAhorrosESB(codigoCajero, valor, fechaActual, talon, cuenta, usuario, concepto, this.canal);
break;
}
case CuentaCorriente: {
respuesta = this.invocacionServicios.realizarNotaDebitoCtaCorrienteESB(codigoCajero, valor, fechaActual, talon, cuenta, usuario, concepto, this.canal);
break;
}
}
}
catch (SecurityException ex) {
respuestaDescripcion = "EN NotaDebito " + tipoCuenta.nombre + " Error al ejecutar el requerimiento:" + ex.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaDebito " + tipoCuenta.nombre + "Error al ejecutar el requerimiento:" + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
catch (WebServiceException ex2) {
respuestaDescripcion = "EN NotaDebito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex2.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaDebito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex2.getMessage());
respuesta = "F" + respuestaDescripcion;
}
return respuesta;
}
@Override
public String realizarNotaCredito(final Integer codigoCajero, final BigDecimal valor, final String cuenta, final Integer tipoCuenta, final String usuario, String talon) {
String fechaActual = "";
String respuesta = "";
String respuestaDescripcion = "";
Integer codigoOcca = 0;
Date fecha = null;
TipoCuenta tipoCuentaR = TipoCuenta.CuentaAhorros;
tipoCuentaR = TipoCuenta.getTipoCuenta(tipoCuenta);
try {
codigoOcca = this.obtenerCodigoOcca(codigoCajero);
fecha = Fecha.getCalendarHoy().getTime();
fechaActual = Fecha.aCadena(fecha, FormatoFecha.AAAAMMDD);
talon = this.armarTalonNotaCredito(talon);
respuesta = this.aplicarNotaCredito(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, tipoCuentaR, usuario);
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.FINE, "EN realizarNotaCredito " + tipoCuentaR.nombre + " para codigoCajero : " + codigoCajero.toString() + " por : " + valor.toString() + "la respuesta del webservice es " + respuesta);
respuestaDescripcion = respuesta;
if (respuesta != null && respuesta.length() > 0) {
if (respuesta.substring(0, 1).equals("M")) {
respuestaDescripcion = "NO se pudo Realizar la NotaCredito " + tipoCuentaR.nombre;
}
else if (respuesta.substring(0, 1).equals("B")) {
respuestaDescripcion = (respuestaDescripcion = respuestaDescripcion + "NotaCredito " + tipoCuentaR.nombre + "Realizado con Exito");
}
}
}
catch (Exception ex) {
respuestaDescripcion = "EN NotaCredito " + tipoCuentaR.nombre + "Error: " + ex.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaCredito " + tipoCuentaR.nombre + " Error: " + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
return respuesta;
}
public String aplicarNotaCredito(final Integer codigoCajero, final Integer codigoOcca, final BigDecimal valor, final String fechaActual, final String talon, final String cuenta, final TipoCuenta tipoCuenta, final String usuario) {
String respuesta = "";
String respuestaDescripcion = "";
try {
this.invocacionServicios = new InvocacionServicios(this.servidor, this.puerto, this.obtenerCodigoTerminal(codigoOcca));
switch (tipoCuenta) {
case CuentaAhorros: {
respuesta = this.invocacionServicios.realizarNotaCreditoCtaAhorrosESB(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, usuario, this.concepto, this.canal);
break;
}
case CuentaCorriente: {
respuesta = this.invocacionServicios.realizarNotaCreditoCtaCorrienteESB(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, usuario, this.concepto, this.canal);
break;
}
}
}
catch (SecurityException ex) {
respuestaDescripcion = "EN NotaCredito " + tipoCuenta.nombre + " Error al ejecutar el requerimiento:" + ex.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaCredito " + tipoCuenta.nombre + "Error al ejecutar el requerimiento:" + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
catch (WebServiceException ex2) {
respuestaDescripcion = "EN NotaCredito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex2.getMessage();
ReintegrosNotasProcesosSessionBean.configApp.loggerApp.log(Level.SEVERE, "EN NotaCredito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex2.getMessage());
respuesta = "F" + respuestaDescripcion;
}
return respuesta;
}
public String aplicarNotaCredito(Integer codigoCajero, Integer codigoOcca, BigDecimal valor, String fechaActual, String talon, String cuenta, TipoCuenta tipoCuenta, String usuario, String concepto) {
String respuesta = "";
String respuestaDescripcion = "";
try {
invocacionServicios = new InvocacionServicios(servidor, puerto, obtenerCodigoTerminal(codigoOcca));
switch (tipoCuenta) {
case CuentaAhorros:
respuesta = invocacionServicios.realizarNotaCreditoCtaAhorrosESB(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, usuario, concepto, canal);
break;
case CuentaCorriente:
respuesta = invocacionServicios.realizarNotaCreditoCtaCorrienteESB(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, usuario, concepto, canal);
break;
default:
break;
}
} catch (SecurityException ex) {
respuestaDescripcion = "EN NotaCredito " + tipoCuenta.nombre + " Error al ejecutar el requerimiento:" + ex.getMessage();
configApp.loggerApp.log(java.util.logging.Level.SEVERE, "EN NotaCredito " + tipoCuenta.nombre + "Error al ejecutar el requerimiento:" + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
} catch (WebServiceException ex) {
respuestaDescripcion = "EN NotaCredito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex.getMessage();
configApp.loggerApp.log(java.util.logging.Level.SEVERE, "EN NotaCredito " + tipoCuenta.nombre + "Error al llamar al WS:" + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
return respuesta;
}
public String realizarNotaCredito(Integer codigoCajero, BigDecimal valor, String cuenta, Integer tipoCuenta, String usuario, String talon, String concepto) {
String fechaActual = "";
// String talon="";
String respuesta = "";
String respuestaDescripcion = "";
// String respuestaError="";
Integer codigoOcca = 0; //obtener valor de occa
Date fecha = null;
TipoCuenta tipoCuentaR = TipoCuenta.CuentaAhorros;
tipoCuentaR = TipoCuenta.getTipoCuenta(tipoCuenta);
try {
codigoOcca = obtenerCodigoOcca(codigoCajero);
fecha = com.davivienda.utilidades.conversion.Fecha.getCalendarHoy().getTime();
fechaActual = com.davivienda.utilidades.conversion.Fecha.aCadena(fecha, com.davivienda.utilidades.conversion.FormatoFecha.AAAAMMDD);
// talon=armarTalon(codigoCajero);
//REVISO QUE EL TALON SEA DE 4 CARACTERES
// if(talon.length()<4)
// {
//arma talon de 6 caracteres
talon = armarTalonNotaCredito(talon);
// }
respuesta = aplicarNotaCredito(codigoCajero, codigoOcca, valor, fechaActual, talon, cuenta, tipoCuentaR, usuario, concepto);
configApp.loggerApp.log(java.util.logging.Level.FINE, "EN realizarNotaCredito " + tipoCuentaR.nombre + " para codigoCajero : " + codigoCajero.toString() + " por : " + valor.toString() + "la respuesta del webservice es " + respuesta);
respuestaDescripcion = respuesta;
//respuestaError= respuesta;
if (respuesta != null) {
if (respuesta.length() > 0) {
if (respuesta.substring(0, 1).equals("M")) {
respuestaDescripcion = "NO se pudo Realizar la NotaCredito " + tipoCuentaR.nombre;
} else if (respuesta.substring(0, 1).equals("B")) {
respuestaDescripcion = respuestaDescripcion += "NotaCredito " + tipoCuentaR.nombre + "Realizado con Exito";
}
}
}
} catch (Exception ex) {
respuestaDescripcion = "EN NotaCredito " + tipoCuentaR.nombre + "Error: " + ex.getMessage();
configApp.loggerApp.log(java.util.logging.Level.SEVERE, "EN NotaCredito " + tipoCuentaR.nombre + " Error: " + ex.getMessage());
respuesta = "F" + respuestaDescripcion;
}
//
// finally
// {
//
// guardarHistoricoAjustes(usuario,codigoCajero,codigoOcca,"Ajuste Ingreso",fecha,valorAjuste,talon,respuestaError,respuestaDescripcion);
//
// }
return respuesta;
}
}
|
package com.example.front_end_of_clean_up_the_camera_app.MechantData;
public class MStoreManageUserComment {
private String userName;
private String commentDate;
private String commentContent;
private String commentGrade;
public MStoreManageUserComment(String userName,String commentGrade,String commentContent,String commentDate) {
this.userName=userName;
this.commentGrade=commentGrade;
this.commentContent=commentContent;
this.commentDate=commentDate;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName=userName;
}
public String getCommentDate() {
return commentDate;
}
public void setCommentDate(String commentDate) {
this.commentDate=commentDate;
}
public String getCommentContent() {
return commentContent;
}
public void setCommentContent(String commentContent) {
this.commentContent=commentContent;
}
public String getCommentGrade() {
return commentGrade;
}
public void setCommentGrade(String commentGrade) {
this.commentGrade=commentGrade;
}
}
|
package test;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.deeplearning4j.nn.modelimport.keras.KerasModelImport;
import org.deeplearning4j.nn.modelimport.keras.exceptions.InvalidKerasConfigurationException;
import org.deeplearning4j.nn.modelimport.keras.exceptions.UnsupportedKerasConfigurationException;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import com.thalmic.myo.Hub;
import com.thalmic.myo.Myo;
import com.thalmic.myo.enums.StreamEmgType;
public class Test {
// IMPORTANT VARIABLE
final static int rmsSampleNumber = 50;
// FRAME VARIABLE
static JFrame frame = new JFrame("Myo EV3");
public static void main(String[] args) {
// EV3 INIT
final EV3thread ev3thread[] = new EV3thread[1];
try {
// start the EV3 thread
ev3thread[0] = new EV3thread();
ev3thread[0].start();
frame.setFocusable(true);
// add key listener - only works if frame has focus
frame.addKeyListener(new EV3myKeyListener(ev3thread[0]));
// on window close
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
ev3thread[0].quit();
}
});
} catch (RemoteException | MalformedURLException | NotBoundException ex) {
ex.printStackTrace();
} finally {
// KERAS/DL4J (NEURAL NETWORK) INIT - LOAD MODEL AND WEIGHTS
final MultiLayerNetwork[] neuralNetworkModel = new MultiLayerNetwork[1];
try {
neuralNetworkModel[0] = KerasModelImport.importKerasSequentialModelAndWeights("../_models/model");
} catch (IOException | InvalidKerasConfigurationException | UnsupportedKerasConfigurationException ex) {
ex.printStackTrace();
} finally {
// LABEL DISPLAYING NEURAL NETWORK OUTPUT
final JLabel nnOutput = new JLabel("none");
// EMG VARIABLES
final ArrayList<ArrayList<byte[]>> emgSamples = new ArrayList<ArrayList<byte[]>>();
emgSamples.add(new ArrayList<byte[]>());
final ArrayList<ArrayList<int[]>> rmsValues = new ArrayList<ArrayList<int[]>>();
rmsValues.add(new ArrayList<int[]>());
final ArrayList<ArrayList<double[]>> orieSamples = new ArrayList<ArrayList<double[]>>();
orieSamples.add(new ArrayList<double[]>());
final ReentrantLock myoLock = new ReentrantLock();
// HTC FOR REAL EVENTS AND SCHEDULER AND TASK FOR FAKE EVENTS
final HubThreadClass[] htc = new HubThreadClass[1];
final ScheduledExecutorService fakeScheduler = Executors.newSingleThreadScheduledExecutor();
final Future<?>[] fakeTask = new Future<?>[1];
// GUI BUTTON VARS
final JButton buttonLiveStream = new JButton("Live stream");
final JButton buttonSave = new JButton("Save");
final JButton buttonLoadEMG = new JButton("Load");
final JButton buttonStopAndReset = new JButton("Stop and reset");
// MYO START LOGIC
final Hub hub = new Hub("com.example.emg-data-sample");
final Myo myo = hub.waitForMyo(1000);
final MyoDataCollector[] myoDataCollector = new MyoDataCollector[1];
final boolean[] liveStreamEnabled = new boolean[1];
System.out.println("Attempting to find a Myo...");
if (myo == null) {
buttonLiveStream.setEnabled(liveStreamEnabled[0]);
System.out.println("Unable to find a Myo!");
} else {
System.out.println("Connected to a Myo armband!");
// create and start a new thread
htc[0] = new HubThreadClass(hub);
htc[0].start();
// start streaming EMG
myo.setStreamEmg(StreamEmgType.STREAM_EMG_ENABLED);
// is live stream enabled
liveStreamEnabled[0] = true;
}
// GUI DRAWING GRAPHS
final ArrayList<int[]> emgDraw = new ArrayList<int[]>();
final ArrayList<int[]> emgRmsDraw = new ArrayList<int[]>();
final ArrayList<int[]> orieDraw = new ArrayList<int[]>();
final int width = 900;
final int height = 1000;
frame.getContentPane().setLayout(new GridLayout(13, 1));
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
final ArrayList<JFGEMG> jfgsEmg = new ArrayList<JFGEMG>();
for (int i = 0; i < 8; i++) {
jfgsEmg.add(new JFGEMG(emgDraw, emgRmsDraw, myoLock, i));
frame.getContentPane().add(jfgsEmg.get(i));
}
final ArrayList<JFGOrie> jfgsOrie = new ArrayList<JFGOrie>();
for (int i = 0; i < 3; i++) {
jfgsOrie.add(new JFGOrie(orieDraw, myoLock, i));
frame.getContentPane().add(jfgsOrie.get(i));
}
// STOP AND RESET BUTTON LOGIC
buttonStopAndReset.setEnabled(false);
buttonStopAndReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// cancel real events
if (myoDataCollector[0] != null) {
hub.removeListener(myoDataCollector[0]);
myoDataCollector[0] = null;
}
// cancel fake events
if (fakeTask[0] != null) {
fakeTask[0].cancel(false);
}
// stop the motors
if (ev3thread[0] != null) {
ev3thread[0].setIndex(8);
}
// clear the buffer
myoLock.lock();
emgSamples.get(0).clear();
rmsValues.get(0).clear();
orieSamples.get(0).clear();
myoLock.unlock();
// handle buttons
buttonLiveStream.setEnabled(liveStreamEnabled[0]);
buttonLoadEMG.setEnabled(true);
buttonSave.setEnabled(false);
buttonStopAndReset.setEnabled(false);
}
});
// LIVE STREAM BUTTON LOGIC
buttonLiveStream.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// MYO ADD LISTENER
myoDataCollector[0] = new MyoDataCollector(emgSamples, rmsValues, orieSamples, emgDraw,
emgRmsDraw, orieDraw, myoLock, jfgsEmg, jfgsOrie, width, rmsSampleNumber,
neuralNetworkModel[0], nnOutput, ev3thread[0]);
hub.addListener(myoDataCollector[0]);
// handle buttons
buttonLiveStream.setEnabled(false);
buttonLoadEMG.setEnabled(false);
buttonSave.setEnabled(true);
buttonStopAndReset.setEnabled(true);
}
});
// SAVE EMG AND ORIENTATION TO FILE TEXTBOX AND BUTTON LOGIC
final JTextField textFilenameSave = new JTextField("test", 10);
buttonSave.setEnabled(false);
buttonSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
myoLock.lock();
// clip the size or ArrayLists to match minimal size
emgSamples.set(0,
new ArrayList<byte[]>(emgSamples.get(0).subList(0, orieSamples.get(0).size())));
rmsValues.set(0, new ArrayList<int[]>(rmsValues.get(0).subList(0, orieSamples.get(0).size())));
String strEMG = "";
String strRMS = "";
String ending = "\n";
// format is:
// first readings (all channels),
// second readings (all channels),
// etc. + (newlines between all values)
for (int i = 0; i < emgSamples.get(0).size(); i++) {
for (int ii = 0; ii < emgSamples.get(0).get(i).length; ii++) {
if (i == emgSamples.get(0).size() - 1 && ii == emgSamples.get(0).get(i).length - 1) {
ending = "";
}
strEMG += Byte.toString(emgSamples.get(0).get(i)[ii]) + ending;
strRMS += Integer.toString(rmsValues.get(0).get(i)[ii]) + ending;
}
}
String strOrie = "";
ending = "\n";
for (int i = 0; i < orieSamples.get(0).size(); i++) {
for (int ii = 0; ii < orieSamples.get(0).get(i).length; ii++) {
if (i == orieSamples.get(0).size() - 1 && ii == orieSamples.get(0).get(i).length - 1) {
ending = "";
}
strOrie += Double.toString(orieSamples.get(0).get(i)[ii]) + ending;
}
}
myoLock.unlock();
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter("../_readings/EMG" + textFilenameSave.getText() + ".txt"));
writer.write(strEMG);
writer.close();
writer = new BufferedWriter(
new FileWriter("../_readings/RMS" + textFilenameSave.getText() + ".txt"));
writer.write(strRMS);
writer.close();
writer = new BufferedWriter(
new FileWriter("../_readings/IMU" + textFilenameSave.getText() + ".txt"));
writer.write(strOrie);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
// LOAD EMG AND ORIENTATION FROM FILE TEXTBOX AND BUTTON LOGIC
final JTextField textFilenameLoad = new JTextField("test", 10);
buttonLoadEMG.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// FAKE MYO LOGIC
try {
ArrayList<String> linesEmg = (ArrayList<String>) Files.readAllLines(Paths
.get("../_readings/EMG" + textFilenameLoad.getText() + ".txt").toAbsolutePath(),
Charset.defaultCharset());
ArrayList<String> linesImu = (ArrayList<String>) Files.readAllLines(Paths
.get("../_readings/IMU" + textFilenameLoad.getText() + ".txt").toAbsolutePath(),
Charset.defaultCharset());
final int readingsPerChannel = linesEmg.size() / 8;
final ArrayList<byte[]> fakiesEmg = new ArrayList<byte[]>();
final ArrayList<double[]> fakiesImu = new ArrayList<double[]>();
int counterEmg = 0;
int counterImu = 0;
for (int i = 0; i < readingsPerChannel; i++) {
// EMG
byte[] bytes = new byte[8];
for (int ii = 0; ii < 8; ii++) {
bytes[ii] = Byte.valueOf(linesEmg.get(counterEmg));
counterEmg++;
}
fakiesEmg.add(bytes);
// IMU
double[] doubles = new double[3];
for (int ii = 0; ii < 3; ii++) {
doubles[ii] = Double.valueOf(linesImu.get(counterImu));
counterImu++;
}
fakiesImu.add(doubles);
}
final MyoDataCollector dataCollector = new MyoDataCollector(emgSamples, rmsValues,
orieSamples, emgDraw, emgRmsDraw, orieDraw, myoLock, jfgsEmg, jfgsOrie, width,
rmsSampleNumber, neuralNetworkModel[0], nnOutput, ev3thread[0]);
final int[] firedCount = new int[1];
fakeTask[0] = fakeScheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
dataCollector.onEmgData(null, 0, fakiesEmg.get(firedCount[0]));
dataCollector.onImu(fakiesImu.get(firedCount[0]));
firedCount[0]++;
if (firedCount[0] == readingsPerChannel) {
// clear the buffer
myoLock.lock();
emgSamples.get(0).clear();
rmsValues.get(0).clear();
orieSamples.get(0).clear();
myoLock.unlock();
// handle buttons
buttonLiveStream.setEnabled(liveStreamEnabled[0]);
buttonLoadEMG.setEnabled(true);
buttonStopAndReset.setEnabled(false);
// stop calling
fakeTask[0].cancel(false);
}
}
}, 0, 5, TimeUnit.MILLISECONDS);
// handle buttons
buttonLiveStream.setEnabled(false);
buttonLoadEMG.setEnabled(false);
buttonStopAndReset.setEnabled(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
// COMPONENTS TO PANEL AND PANEL TO FRAME
JPanel panel = new JPanel();
panel.add(buttonLiveStream);
panel.add(textFilenameSave);
panel.add(buttonSave);
panel.add(textFilenameLoad);
panel.add(buttonLoadEMG);
panel.add(buttonStopAndReset);
frame.getContentPane().add(panel);
JPanel secondPanel = new JPanel();
secondPanel.add(nnOutput);
frame.getContentPane().add(secondPanel);
frame.setVisible(true);
}
}
}
}
|
package com.example.bob.health_helper.Community.presenter;
import com.example.bob.health_helper.Base.BaseMvpPresenter;
import com.example.bob.health_helper.Community.contract.NewAnsweredQuestionContract;
import com.example.bob.health_helper.NetService.Api.AnswerService;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
public class NewAnsweredQuestionPresenter extends BaseMvpPresenter<NewAnsweredQuestionContract.View>
implements NewAnsweredQuestionContract.Presenter{
private int curPage=0;
private boolean hasMore=false;
@Override
public void loadNewAnsweredQuestion() {
curPage=0;
Disposable disposable=AnswerService.getInstance().getNewestAnswers(curPage++)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(datas -> {
hasMore=!(datas.size()<10);
mView.onLoadNewAnsweredQuestionSuccess(datas,hasMore);
},
throwable ->mView.onLoadNewAnsweredQuestionFailed(throwable.getMessage()));
addSubscribe(disposable);
}
@Override
public void loadMoreNewAnsweredQuestion() {
if(hasMore){
Disposable disposable=AnswerService.getInstance().getNewestAnswers(curPage++)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(datas -> {
hasMore=!(datas.size()<10);
mView.onLoadMoreNewAnsweredQuestionSuccess(datas,hasMore);
},
throwable ->mView.onLoadMoreNewAnsweredQuestionFailed(throwable.getMessage()));
addSubscribe(disposable);
}
}
@Override
public void Like(String uid, int answerId) {
Disposable disposable=AnswerService.getInstance().publishLike(uid,answerId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(datas->mView.onLikeSuccess(datas),
throwable -> mView.onLikeFailed(throwable.getMessage()));
addSubscribe(disposable);
}
@Override
public void CancelLike(String uid, int answerId) {
Disposable disposable=AnswerService.getInstance().publishUnlike(uid,answerId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(datas->mView.onCancelLikeSuccess(datas),
throwable -> mView.onCancelLikeFailed(throwable.getMessage()));
addSubscribe(disposable);
}
}
|
package com.infiniteskills.mvc.controllers;
import com.infiniteskills.mvc.entity.Organization;
import com.infiniteskills.mvc.entity.Program;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.infiniteskills.mvc.repository.OrganizationRepository;
import com.infiniteskills.mvc.repository.ProgramRepository;
@Controller
public class IndexController {
private OrganizationRepository organizationDAO;
private ProgramRepository programDAO;
@Autowired(required = false)
public void setProgRepository(ProgramRepository progDAO) {
this.programDAO = progDAO;
}
@Autowired(required = false)
public void setProgRepository(OrganizationRepository orgDAO) {
this.organizationDAO = orgDAO;
}
@RequestMapping(path = "/", method = RequestMethod.GET)
public String goIndex() {
return "public/index";
}
@RequestMapping(value = "/reservation", method = RequestMethod.GET)
public String reservation() {
return "public/reservation";
}
@RequestMapping(value = "/regclient", method = RequestMethod.GET)
public String registrationClient(ModelMap model) {
List<Organization> lsOrg = organizationDAO.findAll();
for (Organization dept : lsOrg) {
System.out.println("name " + dept.getName());
}
List<Program> lsProg = programDAO.findAll();
for (Program tm : lsProg) {
System.out.println(tm.getName());
}
model.addAttribute("listOrg", lsOrg);
model.addAttribute("listProg", lsProg);
return "public/registrationclient";
}
@RequestMapping(value = "/testreg",method = RequestMethod.GET)
public String testReg(Model model) {
return "public/testreg";
}
@RequestMapping(value = "/testsucreg",method = RequestMethod.GET)
public String TestSucReg(Model model) {
return "public/testsuccsesreg";
}
}
|
package com.blog.Idao;
import java.util.List;
import com.blog.bean.DongTai;
import com.blog.util.DBUtil;
public interface IDongTaiDao {
/**
* 查询动态数量is_used=false
*/
public int getTotalCountfalse();
/**
* 查询动态is_used=false
*/
public List<DongTai> dongtaiByPagefalse(int currentPage, int pageSize);
/**
* 查询动态数量is_used=true
*/
public int getTotalCount();
/**
* 查询动态is_used=true
*/
public List<DongTai> dongtaiByPage(int currentPage, int pageSize);
/**
* 根据id把数据库修改is_used字段
*/
public boolean updateDongTaiByid(int id,int is_used);
/**
* 插入动态记录
*/
public boolean dongtaiAdd(int d_author,DongTai dongtai);
/**
* 根据 d_id查询动态详情
*/
public DongTai dongtaiDetails(int d_id);
/**
* 根据 d_id修改动态
*/
public boolean dongtaiXiuGai(DongTai dongtai);
/**
* 根据 d_author访问量排行
*/
public boolean dongtai(int d_id);
public List<DongTai> dongtaiByd_liulang(int currentPage, int pageSize);
public int getTotalCountShouSuo(String shousuo);
public List<DongTai> dongtaiShouSuo(String shousuo,int currentPage, int pageSize);
}
|
/*
* 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 health.expert.system;
import com.jfoenix.controls.JFXButton;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.animation.TranslateTransition;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Duration;
/**
*
* @author ONYEKA
*/
public class FXMLDocumentController implements Initializable {
@FXML
private AnchorPane ambul;
@FXML
private ImageView minimize;
@FXML
private ImageView cancel;
@FXML
private JFXButton exit;
@FXML
private BorderPane mainborderpane;
@FXML
private ImageView bbbbb;
public void settw(Node b){
mainborderpane.setCenter(b);
}
@FXML
private void diagn(ActionEvent e){
try {
Parent root = FXMLLoader.load(getClass().getResource("themainthing.fxml"));
mainborderpane.setCenter(root);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
@FXML
private void pat(ActionEvent e){
try {
Parent root = FXMLLoader.load(getClass().getResource("level_ofsick.fxml"));
mainborderpane.setCenter(root);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
@FXML
private void minimize(MouseEvent event){
if (event.getSource()==minimize) {
((Stage) exit.getScene().getWindow()).setIconified(true);
}
}
@FXML
private void exit(MouseEvent event){
System.exit(0);
} @FXML
private void exit1(MouseEvent event){
System.exit(0);
}
@FXML
private void dasg(ActionEvent e){
try {
Parent root = FXMLLoader.load(getClass().getResource("dashboard.fxml"));
mainborderpane.setCenter(root);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
Parent root = FXMLLoader.load(getClass().getResource("dashboard.fxml"));
mainborderpane.setCenter(root);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
TranslateTransition transision=new TranslateTransition();
transision.setDuration(Duration.millis(4000));
transision.setNode(bbbbb);
transision.setByX(300);
transision.setCycleCount(TranslateTransition.INDEFINITE);
transision.setAutoReverse(true);
transision.play();
// TODO
}
}
|
/*
* 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 q2_2019;
/**
*
* @author keera
*/
public class Q2_2019 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String output="";
for (int i = 1; i <= 7; i++) {
for (int j = 1; j <= 29; j++) {
output = output +"#";
}
output =output+"\n";
}
System.out.println(output);
}
}
|
package com.example.nowdiary.Model;
import java.io.Serializable;
import java.util.Date;
public class HistoryDetail implements Serializable {
private String id;
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDateEditted() {
return dateEditted;
}
public void setDateEditted(Date dateEditted) {
this.dateEditted = dateEditted;
}
private Date dateEditted;
}
|
package com.sample.problem.writer;
public class WriterFactory {
public Writer getWriter(WriterType type) {
switch (type) {
case DB_WRITER:
return new DBWriter();
default:
return new ConsoleWriter();
}
}
}
|
package pushMessage;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import lombok.Data;
import lombok.ToString;
import java.util.Map;
/**
* @program: left-box
* @description:
* @author: Payton Wang
* @date: 2019-10-03 12:20
**/
@Data
@ToString
@JsonAppend
public class WxSmallTemplate {
private String access_token;
private String touser;
private String template_id;
private String page;
private String form_id;
private pushMessage.Data data;
private String emphasis_keyword;
} |
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class Handson3Reducer extends Reducer<Text, Text, Text, IntWritable> {
@Override
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
String maxPopulationCityName = "";
String minPopulationCityName = "";
int maxValue = Integer.MIN_VALUE;
int minValue = Integer.MAX_VALUE;
for (Text value : values) {
String[] array = value.toString().split(",");
int population = Integer.valueOf(array[1]);
if (population > maxValue) {
maxPopulationCityName = array[0];
maxValue = population;
}
if (population < minValue) {
minPopulationCityName = array[0];
minValue = population;
}
}
context.write(new Text(key + " " + minPopulationCityName), new IntWritable(minValue));
context.write(new Text(key + " " + maxPopulationCityName), new IntWritable(maxValue));
}
} |
package com.example.qunxin.erp.activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.qunxin.erp.R;
import com.example.qunxin.erp.UserBaseDatus;
import com.example.qunxin.erp.modle.ShangpinBaseDatus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import swipedelete.utils.CommonAdapter;
import swipedelete.utils.ViewHolder;
public class AdddiaoboxuanzeshangpinActivity extends AppCompatActivity {
ListView shangpinType;
ListView shangpinsListView;
Button selectBtn;
Button enterBtn;
View backBtn;
RelativeLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_xuanzeshangpin);
initView();
}
String refundDepotName = "";
String refundDepot = "";
String buyDepotName = "";
String buyDepot = "";
String busNo;
boolean isAuto;
void initView() {
shangpinType = findViewById(R.id.add_caigoudingdan_shagnpinType);
shangpinsListView = findViewById(R.id.add_caigoudingdan_shangpins_listView);
container = findViewById(R.id.container);
selectBtn = findViewById(R.id.select);
enterBtn = findViewById(R.id.enter);
backBtn = findViewById(R.id.back);
Intent intent = getIntent();
refundDepot = intent.getStringExtra("refundDepot");
refundDepotName = intent.getStringExtra("refundDepotName");
buyDepot = intent.getStringExtra("buyDepot");
buyDepotName = intent.getStringExtra("buyDepotName");
isAuto = intent.getBooleanExtra("isAuto", false);
new Thread(new Runnable() {
@Override
public void run() {
loadModelType();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
loadModelShangpin();
}
}).start();
enterBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isAuto == false) {
Intent intent = new Intent(AdddiaoboxuanzeshangpinActivity.this, AddDiaobodanAfterActivity.class);
intent.putExtra("refundDepot", refundDepot);
intent.putExtra("refundDepotName", refundDepotName);
intent.putExtra("buyDepot", buyDepot);
intent.putExtra("buyDepotName", buyDepotName);
intent.putExtra("count", caculateCount());
intent.putExtra("aList", JsonParse());
startActivity(intent);
finish();
} else {
Intent intent = new Intent();
int sum = enter();
intent.putExtra("price", sum);
intent.putExtra("count", caculateCount());
intent.putExtra("lists", JsonParse());
setResult(1, intent);
finish();
}
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
/**
*要执行的操作
*/
if (typeNameLists.get(0).getTextView() != null)
typeNameLists.get(0).getTextView().setTextColor(Color.parseColor("#FF5FC6FD"));
}
}, 200);//3秒后执行Runnable中的run方法
}
int sum = 0;
int enter() {
for (int i = 0; i < lists.size(); i++) {
sum += lists.get(i).getTotal() * lists.get(i).getPrice();
}
return sum;
}
String JsonParse() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < lists.size(); i++) {
JSONObject jsonObject = new JSONObject();
try {
if (lists.get(i).getChukuCount() == 0) continue;
jsonObject.put("proId", lists.get(i).getProId());
jsonObject.put("total", lists.get(i).getChukuCount());
jsonObject.put("remarks", lists.get(i).getRemarks());
String content = String.valueOf(jsonObject);
buffer.append(content).append(",");
} catch (JSONException e) {
e.printStackTrace();
}
}
String s = buffer.toString();
return "[" + s.substring(0, s.length() - 1) + "]";
}
void loadModelType() {
AdddiaoboxuanzeshangpinActivity.TypeNameClass typeNameClass = new AdddiaoboxuanzeshangpinActivity.TypeNameClass();
typeNameClass.setTypeName("所有");
typeNameClass.setId("");
typeNameLists.add(typeNameClass);
final String contentType = "application/x-www-form-urlencoded";
final String url = UserBaseDatus.getInstance().url + "api/app/proType/list";
final String data = "signa=" + UserBaseDatus.getInstance().getSign();
Map map = UserBaseDatus.getInstance().isSuccessPost(url, data, contentType);
if ((boolean) (map.get("isSuccess"))) {
JSONObject json = (JSONObject) map.get("json");
try {
JSONArray jsonArray = json.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String typeName = jsonObject.getString("typeName");
String id = jsonObject.getString("id");
AdddiaoboxuanzeshangpinActivity.TypeNameClass typeNameClass1 = new AdddiaoboxuanzeshangpinActivity.TypeNameClass();
typeNameClass1.setTypeName(typeName);
typeNameClass1.setId(id);
typeNameLists.add(typeNameClass1);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
loadViewType();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//左边分类
List<AdddiaoboxuanzeshangpinActivity.TypeNameClass> typeNameLists = new ArrayList<>();
class TypeNameClass {
String typeName;
String id;
TextView textView;
public TextView getTextView() {
return textView;
}
public void setTextView(TextView textView) {
this.textView = textView;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
boolean isClick = true;
void loadViewType() {
shangpinType.setAdapter(new CommonAdapter<AdddiaoboxuanzeshangpinActivity.TypeNameClass>(AdddiaoboxuanzeshangpinActivity.this, typeNameLists, R.layout.item_shangpintype) {
@Override
public void convert(final ViewHolder holder, final AdddiaoboxuanzeshangpinActivity.TypeNameClass typeName, final int position, View convertView) {
final TextView textView = holder.getView(R.id.txt);
textView.setText(typeName.getTypeName());
typeName.setTextView(textView);
holder.setOnClickListener(R.id.txt, new View.OnClickListener() {
@Override
public void onClick(View v) {
type = typeNameLists.get(position).getId();
lists.clear();
if (isClick == false) return;
new Thread(new Runnable() {
@Override
public void run() {
isClick = false;
loadModelShangpin();
}
}).start();
for (int i = 0; i < typeNameLists.size(); i++) {
if (i == position) {
typeNameLists.get(i).getTextView().setTextColor(Color.parseColor("#FF5FC6FD"));
} else {
typeNameLists.get(i).getTextView().setTextColor(Color.parseColor("#FFD2D2D2"));
}
}
}
});
}
});
}
String kehuName = "";
String depotName = "";
String kehuId;
String depot;
String pageSize = "10";
String pageNum = "1";
String type = "";
List<ShangpinBaseDatus> lists = new ArrayList<>();
void loadModelShangpin() {
String signa = UserBaseDatus.getInstance().getSign();
final String contentTypeList = "application/x-www-form-urlencoded";
final String url = UserBaseDatus.getInstance().url + "api/app/proProduct/getBusinessProProductList";
String jsonString = "depot=" + refundDepot + "&&signa=" + signa + "&&pageSize=" + pageSize + "&&pageNum=" + pageNum +
"&&type=" + type;
Log.d("jsonString", jsonString);
Map map = UserBaseDatus.getInstance().isSuccessPost(url, jsonString, contentTypeList);
if ((boolean) (map.get("isSuccess"))) {
JSONObject json = (JSONObject) map.get("json");
try {
JSONObject jsonData = json.getJSONObject("data");
JSONArray jsonArray = jsonData.getJSONArray("rows");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String typeName = jsonObject.getString("proName");
String price = jsonObject.getString("price");
String id = jsonObject.getString("id");
String proNo = jsonObject.getString("proNo");
String norms = jsonObject.getString("norms");
String property = jsonObject.getString("property");
String unit = jsonObject.getString("unit");
String depot = jsonObject.getString("depot");
String maxTotalStr = jsonObject.getString("stockTotal");
if (maxTotalStr.equals("null")) {
continue;
}
if (maxTotalStr.equals("0")) {
continue;
}
int maxTotal = jsonObject.getInt("stockTotal");
ShangpinBaseDatus datus = new ShangpinBaseDatus();
datus.setPrice(Float.parseFloat(price));
datus.setProName(typeName);
datus.setProId(id);
datus.setImgRes(R.mipmap.shop_icon);
datus.setProNo(proNo);
datus.setNorms(norms);
datus.setProperty(property);
datus.setUnit(unit);
datus.setMaxTotal(maxTotal);
lists.add(datus);
}
for (int j = 0; j < lists.size(); j++) {
System.out.println(lists.get(j));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
loadViewShangpin();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ImageView nodatusImage;
void loadViewShangpin() {
if (lists.size() == 0) {
if (nodatusImage == null) {
nodatusImage = new ImageView(this);
}
nodatusImage.setImageResource(R.drawable.nodatus);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(300, 300);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
layoutParams.topMargin = 30;
nodatusImage.setLayoutParams(layoutParams);
if (nodatusImage.getParent() == null) {
container.addView(nodatusImage);
}
} else {
container.removeView(nodatusImage);
}
shangpinsListView.setAdapter(new CommonAdapter<ShangpinBaseDatus>(AdddiaoboxuanzeshangpinActivity.this, lists, R.layout.item_addcaigoudingdan_xuanzeshangpin) {
@Override
public void convert(final ViewHolder holder, ShangpinBaseDatus shangpinDatus, final int position, View convertView) {
final int[] amount = {0};
holder.setText(R.id.name, shangpinDatus.getProName());
holder.setText(R.id.price, shangpinDatus.getPrice() + "¥");
holder.setImageResource(R.id.listview_iv, shangpinDatus.getImgRes());
final TextView etAmount = holder.getView(R.id.etAmount);
holder.setText(R.id.etAmount, shangpinDatus.getChukuCount() + "");
holder.setOnClickListener(R.id.ll_content, new View.OnClickListener() {
@Override
public void onClick(View v) {
ShangpinBaseDatus datus = lists.get(position);
String id = datus.getProId();
TextView etAmount = holder.getView(R.id.etAmount);
datus.setTotal(Integer.parseInt(etAmount.getText().toString()));
show(datus.getProName(), datus.getMaxTotal() + "", position, etAmount);
}
});
holder.setOnClickListener(R.id.btnIncrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
amount[0] = Integer.parseInt(etAmount.getText().toString());
amount[0]++;
holder.setText(R.id.etAmount, amount[0] + "");
ShangpinBaseDatus datus = lists.get(position);
datus.setChukuCount(amount[0]);
TextChange();
etAmount.clearFocus();
}
});
holder.setOnClickListener(R.id.btnDecrease, new View.OnClickListener() {
@Override
public void onClick(View v) {
amount[0] = Integer.parseInt(etAmount.getText().toString());
if (amount[0] <= 0) {
return;
}
amount[0]--;
holder.setText(R.id.etAmount, amount[0] + "");
ShangpinBaseDatus datus = lists.get(position);
datus.setChukuCount(amount[0]);
TextChange();
etAmount.clearFocus();
}
});
etAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String string = etAmount.getText().toString();
if ("".equals(string)) return;
amount[0] = Integer.parseInt(etAmount.getText().toString());
ShangpinBaseDatus datus = lists.get(position);
if (amount[0] > datus.getMaxTotal()) {
amount[0] = datus.getMaxTotal();
holder.setText(R.id.etAmount, amount[0] + "");
Toast.makeText(mContext, "已经设置成最大库存数量", Toast.LENGTH_SHORT).show();
}
datus.setChukuCount(amount[0]);
TextChange();
}
});
}
});
isClick = true;
}
Dialog dialog;
public void show(String name, final String stockTotal, final int position, final TextView countText) {
dialog = new Dialog(this, R.style.ActionSheetDialogStyle);
//填充对话框的布局
LinearLayout inflate = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.bottom_dialog_diaoboshangpin, null);
//初始化控件
TextView nameText = (TextView) inflate.findViewById(R.id.name);
TextView stockTotalText = (TextView) inflate.findViewById(R.id.stockTotal);
final TextView chukuCountText = (TextView) inflate.findViewById(R.id.chukuCount);
View finishBtn = inflate.findViewById(R.id.finish);
nameText.setText(name);
stockTotalText.setText(stockTotal);
//将布局设置给Dialog
dialog.setContentView(inflate);
//获取当前Activity所在的窗体
Window dialogWindow = dialog.getWindow();
//设置Dialog从窗体底部弹出
dialogWindow.setGravity(Gravity.BOTTOM);
//获得窗体的属性
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//lp.y = 20;//设置Dialog距离底部的距离
//将属性设置给窗体
lp.x = 0; // 新位置X坐标
lp.y = 0; // 新位置Y坐标
lp.width = (int) getResources().getDisplayMetrics().widthPixels; // 宽度
inflate.measure(0, 0);
lp.height = inflate.getMeasuredHeight();
lp.alpha = 9f; // 透明度
dialogWindow.setAttributes(lp);
dialogWindow.setAttributes(lp);
finishBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ("".equals(chukuCountText.getText().toString())) return;
int chukuCount = Integer.parseInt(chukuCountText.getText().toString());
ShangpinBaseDatus datus = lists.get(position);
datus.setChukuCount(chukuCount);
countText.setText(chukuCount + "");
dialog.dismiss();
}
});
dialog.show();//显示对话框
}
void TextChange() {
int sumCount = caculateCount();
selectBtn.setText("已选商品(" + sumCount + ")件");
if (sumCount <= 0) {
enterBtn.setEnabled(false);
} else {
enterBtn.setEnabled(true);
}
}
int caculateCount() {
int sumCount = 0;
for (int i = 0; i < lists.size(); i++) {
sumCount += lists.get(i).getChukuCount();
}
return sumCount;
}
}
|
package io.breen.socrates.model.event;
import io.breen.socrates.model.wrapper.SubmissionWrapperNode;
import io.breen.socrates.util.ObservableChangedEvent;
/**
* The event that is generated by a SubmissionWrapperNode when all of its children that are
* SubmittedFileWrapperNodes become completed (causing the Submission to be complete), or when at
* least one child becomes not complete from being complete (causing the Submission to be not
* complete).
*/
public class SubmissionCompletedChangeEvent extends ObservableChangedEvent<SubmissionWrapperNode> {
public final boolean isNowComplete;
public SubmissionCompletedChangeEvent(SubmissionWrapperNode source, boolean isNowComplete) {
super(source);
this.isNowComplete = isNowComplete;
}
@Override
public String toString() {
return "SubmissionCompletedChangeEvent(source=" + source + ", isNowComplete=" +
isNowComplete + ")";
}
}
|
package ru.forpda.example.an21utools.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import ru.forpda.example.an21utools.util.LogHelper;
/**
* Created by max on 12.11.2014.
*/
public abstract class MusicWidgetBase extends AppWidgetProvider {
public static final String MUSIC_WIDGET_COMMAND = "ru.forpda.example.an21utools.musicwidgetclick";
private static LogHelper Log = new LogHelper(MusicWidgetBase.class);
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d("onEnabled");
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d("onDisabled");
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
Log.d("onUpdate");
RemoteViews widgetView = new RemoteViews(context.getPackageName(), getWidgetId());
Intent testIntent = new Intent(context, this.getClass());
testIntent.setAction(MUSIC_WIDGET_COMMAND);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, testIntent, 0);
widgetView.setOnClickPendingIntent(getWidgetCleckabelViewId(), pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds,widgetView);
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Log.d("onDelete");
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equalsIgnoreCase(MUSIC_WIDGET_COMMAND)){
onClick(context);
}
}
/**
* Получить ид лайота виджета
* @return
*/
protected abstract int getWidgetId();
/**
* получит ид кликательной области внутри лайоута виджета
* @return
*/
protected abstract int getWidgetCleckabelViewId();
/**
* То что делаем при клике
* @param context
*/
protected abstract void onClick(Context context);
}
|
package Beans;
import javax.persistence.Embeddable;
@Embeddable
public class Aliean_Name {
private String fname;
private String mlame;
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMlame() {
return mlame;
}
public void setMlame(String mlame) {
this.mlame = mlame;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
private String lname;
@Override
public String toString() {
return "Aliean_Name [fname=" + fname + ", mlame=" + mlame + ", lname=" + lname + "]";
}
}
|
package com.examples;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
public class Problem037Test {
private final Problem037 problemToTest = new Problem037();
@Test
@DisplayName("Tests for arrays")
void arrayproblemToTests() {
assertThat(problemToTest.generatePowerSet(generateSet(0)), is(expected0));
assertThat(problemToTest.generatePowerSet(generateSet(1)), is(generateExpected1()));
assertThat(problemToTest.generatePowerSet(generateSet(2)), is(generateExpected2()));
assertThat(problemToTest.generatePowerSet(generateSet(3)), is(generateExpected3()));
assertThat(problemToTest.generatePowerSet(generateSet(4)), is(generateExpected4()));
}
@Test
@DisplayName("Tests for lists")
void listproblemToTests() {
assertThat(problemToTest.generatePowerSet(generateList(0)), is(expected0));
assertThat(problemToTest.generatePowerSet(generateList(1)), is(generateExpected1()));
assertThat(problemToTest.generatePowerSet(generateList(2)), is(generateExpected2()));
assertThat(problemToTest.generatePowerSet(generateList(3)), is(generateExpected3()));
assertThat(problemToTest.generatePowerSet(generateList(4)), is(generateExpected4()));
}
private Integer[] generateSet(int setSize) {
List<Integer> result = new ArrayList<Integer>(0);
for (int counter = 1; counter <= setSize; counter++)
result.add(counter);
return result.toArray(new Integer[result.size()]);
}
private List<Integer> generateList(int setSize) {
List<Integer> result = new ArrayList<Integer>(0);
for (int counter = 1; counter <= setSize; counter++)
result.add(counter);
return result;
}
List<List<Integer>> expected0 = Arrays.asList(new ArrayList<Integer>(0));
private List<List<Integer>> generateExpected1() {
List<List<Integer>> expected = new ArrayList<List<Integer>>(0);
List<Integer> item0 = new ArrayList<Integer>(0);
List<Integer> item1 = new ArrayList<Integer>(Arrays.asList(1));
expected.add(item0);
expected.add(item1);
return expected;
}
private List<List<Integer>> generateExpected2() {
List<List<Integer>> expected = new ArrayList<List<Integer>>(0);
List<Integer> item0 = new ArrayList<Integer>(0);
List<Integer> item1 = new ArrayList<Integer>(Arrays.asList(1));
List<Integer> item2 = new ArrayList<Integer>(Arrays.asList(2));
List<Integer> item3 = new ArrayList<Integer>(Arrays.asList(1, 2));
expected.add(item0);
expected.add(item1);
expected.add(item2);
expected.add(item3);
return expected;
}
private List<List<Integer>> generateExpected3() {
List<List<Integer>> expected = new ArrayList<List<Integer>>(0);
List<Integer> item0 = new ArrayList<Integer>(0);
List<Integer> item1 = new ArrayList<Integer>(Arrays.asList(1));
List<Integer> item2 = new ArrayList<Integer>(Arrays.asList(2));
List<Integer> item3 = new ArrayList<Integer>(Arrays.asList(3));
List<Integer> item4 = new ArrayList<Integer>(Arrays.asList(1, 2));
List<Integer> item5 = new ArrayList<Integer>(Arrays.asList(1, 3));
List<Integer> item6 = new ArrayList<Integer>(Arrays.asList(2, 3));
List<Integer> item7 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
expected.add(item0);
expected.add(item1);
expected.add(item2);
expected.add(item3);
expected.add(item4);
expected.add(item5);
expected.add(item6);
expected.add(item7);
return expected;
}
private List<List<Integer>> generateExpected4() {
List<List<Integer>> expected = new ArrayList<List<Integer>>(0);
List<Integer> item0 = new ArrayList<Integer>(0);
List<Integer> item1 = new ArrayList<Integer>(Arrays.asList(1));
List<Integer> item2 = new ArrayList<Integer>(Arrays.asList(2));
List<Integer> item3 = new ArrayList<Integer>(Arrays.asList(3));
List<Integer> item4 = new ArrayList<Integer>(Arrays.asList(4));
List<Integer> item5 = new ArrayList<Integer>(Arrays.asList(1, 2));
List<Integer> item6 = new ArrayList<Integer>(Arrays.asList(1, 3));
List<Integer> item7 = new ArrayList<Integer>(Arrays.asList(2, 3));
List<Integer> item8 = new ArrayList<Integer>(Arrays.asList(1, 4));
List<Integer> item9 = new ArrayList<Integer>(Arrays.asList(2, 4));
List<Integer> item10 = new ArrayList<Integer>(Arrays.asList(3, 4));
List<Integer> item11 = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
List<Integer> item12 = new ArrayList<Integer>(Arrays.asList(1, 2, 4));
List<Integer> item13 = new ArrayList<Integer>(Arrays.asList(1, 3, 4));
List<Integer> item14 = new ArrayList<Integer>(Arrays.asList(2, 3, 4));
List<Integer> item15 = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
expected.add(item0);
expected.add(item1);
expected.add(item2);
expected.add(item3);
expected.add(item4);
expected.add(item5);
expected.add(item6);
expected.add(item7);
expected.add(item8);
expected.add(item9);
expected.add(item10);
expected.add(item11);
expected.add(item12);
expected.add(item13);
expected.add(item14);
expected.add(item15);
return expected;
}
}
|
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import com.google.gson.JsonObject;
import com.google.gson.JsonArray;
public class GetMovieTitles {
public static void main(String args[]){
String[] movieTitles = getMovieTitles("spiderman or batman");
if(movieTitles.length > 0) {
for (String title : movieTitles) {
System.out.println(title);
}
} else {
System.out.println("Not Found");
}
}
static String[] getMovieTitles(String substr) {
substr = substr.replace(" ", "%20");
String resp;
int pageNumber = 1;
int totalPage = 1;
List<String> titles = new ArrayList<String>();
while(pageNumber <= totalPage) {
try{
URL url = new URL("https://jsonmock.hackerrank.com/api/movies/search/?Title=" + substr+"&page="+pageNumber);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
while ((resp = in.readLine()) != null) {
Gson gson = new Gson();
JsonObject obj = gson.fromJson(resp, JsonObject.class);
totalPage = obj.get("total_pages").getAsInt();
JsonArray data = obj.getAsJsonArray("data");
for(int i=0;i<data.size();i++){
//System.out.println(data.get(i));
String title = data.get(i).getAsJsonObject().get("Title").getAsString();
titles.add(title);
//System.out.println(title);
}
}
in.close();
pageNumber++;
//System.out.println(titles);
} catch (Exception e) {
e.printStackTrace();
}
}
Collections.sort(titles);
return titles.toArray(new String[0]);
}
}
|
package ben.tek.code.labcorp.model;
import org.springframework.stereotype.Component;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Component
public abstract class Employee {
public static final int WORK_DAY_MAX = 260;
protected String firstName;
protected String lastName;
protected String phoneNumber;
protected int workDays = 0;
protected float vacationDays = (float) 0.0;
public abstract void work(int days);
public abstract void takeVacation(float days);
protected void work(int days, float VACATION_DAY_MAX) {
if(this.workDays + days > WORK_DAY_MAX) {
this.vacationDays = this.vacationDays + (((WORK_DAY_MAX - this.workDays) * VACATION_DAY_MAX)/WORK_DAY_MAX);
this.workDays = WORK_DAY_MAX;
}
else {
this.workDays = this.workDays + days;
this.vacationDays = this.vacationDays + ((((float)days) * VACATION_DAY_MAX)/WORK_DAY_MAX);
}
}
protected void takeVacation(float days, float VACATION_DAY_MAX) {
if(days > this.vacationDays) {
this.vacationDays = (float)0;
}
else {
this.vacationDays = this.vacationDays - days;
}
}
abstract String getTitle();
abstract String getSalaryType();
}
|
package ua.epam.provider.encryptor;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Objects;
public class Encryptor {
public static String encrypt(String password, String email) {
String generatedPassword;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Objects.requireNonNull(md).update(email.getBytes(StandardCharsets.UTF_8));
byte[] bytes = md.digest(password.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte aByte : bytes) {
sb.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
generatedPassword = sb.toString();
return generatedPassword;
}
} |
package controlador;
public class GenerarTiempoLlegadaClientes {
}
|
package com.likewater.articleone.adapters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.likewater.articleone.models.Rep;
import com.likewater.articleone.ui.RepDetailFragment;
import java.util.ArrayList;
public class RepPagerAdapter extends FragmentPagerAdapter{
private ArrayList<Rep> mRep;
public RepPagerAdapter(FragmentManager fm, ArrayList<Rep> reps){
super(fm);
mRep = reps;
}
@Override
public Fragment getItem(int position){
return RepDetailFragment.newInstance(mRep.get(position));
}
@Override
public int getCount(){
return mRep.size();
}
@Override
public CharSequence getPageTitle(int position){
return mRep.get(position).getName();
}
} |
package me.lightlord323dev.cursedvaults.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Khalid on 2/2/2018.
*/
public class LocationUtils {
public static String serializeLocation(Location loc) {
return loc.getWorld().getName() + ";" + loc.getBlockX() + ";" + loc.getBlockY() + ";" + loc.getBlockZ() + ";" + loc.getYaw() + ";" + loc.getPitch();
}
public static Location deserializeLocation(String s) {
String[] info = s.split(";");
return new Location(Bukkit.getWorld(info[0]), Integer.valueOf(info[1]), Integer.valueOf(info[2]), Integer.valueOf(info[3]), Float.valueOf(info[4]), Float.valueOf(info[5]));
}
}
|
package de.fu_berlin.cdv.chasingpictures.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
/**
* This is largely copied from Mapbox' {@link com.mapbox.mapboxsdk.overlay.GpsLocationProvider GpsLocationProvider}.
*
* @author Simon Kalt
*/
public class LocationHelper {
/**
* The default minimum time interval for location updates (5 seconds).
*/
public static final int DEFAULT_MIN_TIME = 5000;
/**
* The default minimum distance for location updates (5 meters).
*/
public static final int DEFAULT_MIN_DISTANCE = 5;
private final Map<LocationListener, ListenerInfo> listeners = new HashMap<>();
private LocationManager mLocationManager;
/**
* Constructs a new location helper.
*
* @param context The current context
*/
public LocationHelper(@NonNull Context context) {
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
/**
* Returns the last known location with the highest available accuracy.
* <p/>
* TODO: Only update in specified interval?
*/
@Nullable
public Location getLastKnownLocation() {
return getLocation(false);
}
private Location getLocation(boolean registerListeners) {
Location location = null;
for (final String provider : mLocationManager.getProviders(true)) {
if (LocationManager.GPS_PROVIDER.equals(provider)
|| LocationManager.PASSIVE_PROVIDER.equals(provider)
|| LocationManager.NETWORK_PROVIDER.equals(provider)) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(provider);
if (location == null)
location = lastKnownLocation;
else if (lastKnownLocation != null && lastKnownLocation.getAccuracy() > location.getAccuracy())
location = lastKnownLocation;
if (registerListeners) {
for (Map.Entry<LocationListener, ListenerInfo> entry : listeners.entrySet()) {
ListenerInfo info = entry.getValue();
LocationListener listener = entry.getKey();
if (location != null)
listener.onLocationChanged(location);
if (!info.updatesStarted) {
mLocationManager.requestLocationUpdates(provider, info.minTime, info.minDistance, listener);
info.updatesStarted = true;
}
}
}
}
}
return location;
}
//region Starting and stopping location updates
/**
* Start location updates for the given listener.
*
* @param newListener
* @param minTime
* @param minDistance
* @return
*/
public LocationHelper startLocationUpdates(@NonNull LocationListener newListener, long minTime, float minDistance) {
if (!listeners.containsKey(newListener)) {
addListener(newListener, minTime, minDistance);
getLocation(true);
}
return this;
}
/**
* Stop location updates on all registered listeners.
*/
public void stopAllLocationUpdates() {
for (Map.Entry<LocationListener, ListenerInfo> entry : listeners.entrySet()) {
mLocationManager.removeUpdates(entry.getKey());
}
listeners.clear();
}
/**
* Stop location updates on the given listener.
*
* @param listener Listener to stop location updates for
*/
public void stopLocationUpdates(LocationListener listener) {
mLocationManager.removeUpdates(listener);
listeners.remove(listener);
}
//endregion
//region Internals
/**
* Add a listener to the local reference of listeners.
*
* @param listener Listener to add
*/
private void addListener(LocationListener listener, long minTime, float minDistance) {
listeners.put(listener, new ListenerInfo(minTime, minDistance));
}
/**
* Remove a listener from the local reference of listeners.
*
* @param listener Listener to removeg
*/
private void removeListener(LocationListener listener) {
if (listener != null)
listeners.remove(listener);
}
/**
* Info about location listeners.
*/
private static class ListenerInfo {
public final long minTime;
public final float minDistance;
public boolean updatesStarted;
private ListenerInfo(long minTime, float minDistance) {
this.minTime = minTime;
this.minDistance = minDistance;
}
}
//endregion
}
|
package hudson.plugins.parameterizedtrigger;
import hudson.model.Hudson;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import java.util.HashMap;
import java.util.Map;
public class GlobalNodeProperties {
private static final Map<String, String> NODE_PROPERTIES = new HashMap<String, String>();
private static void updateGlobalNodeProperties() {
//clear current properties
NODE_PROPERTIES.clear();
//get latest global properties
for (NodeProperty<?> nodeProperty : Hudson.getInstance()
.getGlobalNodeProperties()) {
if (nodeProperty instanceof EnvironmentVariablesNodeProperty) {
NODE_PROPERTIES.putAll(((EnvironmentVariablesNodeProperty) nodeProperty).getEnvVars());
}
}
}
public static Map<String, String> getProperties() {
updateGlobalNodeProperties();
return NODE_PROPERTIES;
}
public static String getValue(String key) {
updateGlobalNodeProperties();
if (key == null) {
return null;
} else {
return NODE_PROPERTIES.get(key);
}
}
} |
/**
* @Author: Joakim Olsson <lomo133>
* @Date: 2018-11-04T23:40:00+01:00
* @Last modified by: lomo133
* @Last modified time: 2018-11-04T23:40:25+01:00
*/
import java.util.Scanner;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int testCases = Integer.parseInt(in.nextLine());
while (testCases > 0) {
String pattern = in.nextLine();
try {
Pattern.compile(pattern);
System.out.println("Valid");
} catch (PatternSyntaxException E) {
System.out.println("Invalid");
}
testCases--;
}
}
}
|
public class DateTime
{
private int month;
private int day;
private int year;
private int daysPerMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
private int hour;
private int minute;
private int second;
public DateTime(int theMonth, int theDay, int theYear, int theHour, int theMinute, int theSecond)
{
month = checkMonth(theMonth);
year = checkYear(theYear);
day = checkDay(theDay);
setTime(theHour,theMinute,theSecond);
System.out.printf("Date object constructor for date %s\n", this);
}
private int checkMonth(int testMonth)
{
if(testMonth > 0 && testMonth <= 12)
return testMonth;
else
{
System.out.printf("Invalid month (%d) set to 1.", testMonth);
return 1;
}
}
private int checkYear(int testYear)
{
if(testYear > 1000 && testYear <= 9999)
return testYear;
else
{
System.out.printf("Invalid year (%d) set to 1900.", testYear);
return 1900;
}
}
private int checkDay(int testDay)
{
if(testDay > 0 && testDay <= daysPerMonth[month])
return testDay;
if(month == 2 && testDay == 29 && leap() == true)
return testDay;
System.out.printf("Invalid day (%d) set to 1.",testDay);
return 1;
}
// return String.format("%d/%d/%d\n",month,day,year);
public String toUniversalString()
{
return String.format("%d/%d/%d - %02d:%02d:%02d\n",month,day,year,getHour(),getMinute(),getSecond());
}
public String toString()
{
return String.format("%d/%d/%d - %d:%02d:%02d %s\n",month, day, year,((getHour() == 0 || getHour() == 12) ? 12: getHour() % 12), getMinute(), getSecond(), (getHour() < 12 ? "AM" : "PM"));
}
public boolean leap()
{
if(year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
return true;
else
return false;
}
public void nextDay()
{
if((day + 1) > daysPerMonth[month])
{
if (month == 2 && day + 1 == 29 && leap() == true)
{
day = checkDay(day + 1);
}
else
{
day = checkDay(1);
nextMonth();
}
}
else
{
day = checkDay(day + 1);
}
}
public void nextMonth()
{
if((month + 1) > 12)
{
month = checkMonth(1);
nextYear();
}
else
{
month = checkMonth(month + 1);
}
}
public void nextYear()
{
year = checkYear(year + 1);
}
public DateTime()
{
this(0,0,0);
}
public DateTime(int h)
{
this(h,0,0);
}
public DateTime(int h, int m)
{
this(h,m,0);
}
public DateTime(int h, int m, int s)
{
setTime(h,m,s);
}
public DateTime(DateTime time)
{
this(time.getHour(), time.getMinute(), time.getSecond());
}
public void setTime(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h)
{
hour = ((h >= 0 && h < 24) ? h : 0);
}
public void setMinute(int m)
{
minute = ((m >= 0 && m < 60) ? m : 0);
}
public void setSecond(int s)
{
second = ((s >= 0 && s < 60) ? s : 0);
}
public int getHour()
{
return hour;
}
public int getMinute()
{
return minute;
}
public int getSecond()
{
return second;
}
public void nextSecond()
{
if(second + 1 == 60)
{
setSecond(0);
nextMinute();
}
else
{
setSecond(second + 1);
}
}
public void nextMinute()
{
if(minute + 1 == 60)
{
setMinute(0);
nextHour();
}
else
{
setMinute(minute + 1);
}
}
public void nextHour()
{
if(hour + 1 == 24)
{
setHour(0);
nextDay();
}
else
{
setHour(hour + 1);
}
}
}
|
package com.huadin.huadin;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.huadin.adapter.PersonManagerAdapter;
import com.huadin.database.UserData;
import com.huadin.entity.Person;
import com.huadin.utils.Const;
import com.huadin.utils.DriverUtil;
import com.huadin.utils.ExceptionUtil;
import com.huadin.utils.LogUtil;
import com.huadin.utils.NetworkUtil;
import com.huadin.utils.SnackbarUtil;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.litepal.crud.DataSupport;
import java.sql.SQLException;
import java.util.List;
@EActivity(R.layout.activity_person_manager)
public class PersonManagerActivity extends BaseActivity
{
private static final String TAG = "PersonManagerActivity";
private PersonManagerAdapter mAdapter;
private List<Person> mList;
private boolean networkState;
@ViewById(R.id.person_listView)
ListView listView;
@ViewById(R.id.tvTitle)
TextView tvTitle;
@ViewById(R.id.title_btn_back)
Button back;
@ViewById(R.id.person_progressBar)
ProgressBar mBar;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_person_manager);
}
@AfterViews
public void setTitle()
{
tvTitle.setText(R.string.person_manager_person);
if (networkState = NetworkUtil.isNetwork(this))
{
mBar.setVisibility(View.VISIBLE);
registerForContextMenu(listView);
getPersonFromSocket();
}else
{
//无网络
SnackbarUtil.showSnackbar(listView,R.string.network_emport);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
getMenuInflater().inflate(R.menu.permission_update , menu);
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final int pos = menuInfo.position;
switch (item.getItemId())
{
case R.id.permission_update:
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(R.string.permission_dialog_title);
dialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
try
{
Person person = mList.get(pos);
//修改自己的权限
String loginName_1 = person.getLoginName();
String loginName_2 = DataSupport.findFirst(UserData.class).getLoginName();
if (loginName_1.equals(loginName_2))
{
//修改自己
SnackbarUtil.showSnackbar(listView,R.string.person_activity_updtae);
return;
}else
{
alterPermission(person);//修改其他人
}
mBar.setVisibility(View.VISIBLE);
}catch (Exception e)
{
ExceptionUtil.handleException(e);
}
}
});
dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
dialog.show();
break;
}
return true;
}
@Background
public void alterPermission(Person person)
{
int index = person.isPermission()? 0:1;
String sql = "update person set user_permission ='" + (index)
+ "' where login_name ='" + person.getLoginName() + "'";
try
{
if (DriverUtil.update(sql , null) > 0)
{
//成功
alterSuccess(person , Const.STATUS_OK);
}
} catch (SQLException e)
{
//服务器异常
ExceptionUtil.handleException(e);
alterSuccess(person , Const.STATUS_FALL);
}
}
@UiThread
public void alterSuccess(Person person , int index)
{
mBar.setVisibility(View.GONE);
if (index == Const.STATUS_OK)
{
SnackbarUtil.showSnackbar(listView,R.string.update_success);
person.setPermission(!person.isPermission());
mAdapter.notifyDataSetChanged();
}else if (index == Const.STATUS_FALL)
{
SnackbarUtil.showSnackbar(listView,R.string.register_socket_error);
}
}
@Click(R.id.title_btn_back)
public void toBack()
{
finish();
}
@Background
public void getPersonFromSocket()
{
String sql = "select * from person";
mList = DriverUtil.queryPerson(sql);
setListView();
}
@ItemClick(R.id.person_listView)
public void showDetailPerson(int position)
{
Person person = mList.get(position);
Intent intent = new Intent(this , ShowDetailPersonActivity_.class);
intent.putExtra("person" , person);
startActivity(intent);
}
@UiThread
public void setListView()
{
mBar.setVisibility(View.GONE);
if (mList != null)
{
mAdapter = new PersonManagerAdapter(this , mList);
listView.setAdapter(mAdapter);
}else
{
SnackbarUtil.showSnackbar(listView,R.string.register_socket_error);
}
}
@Override
protected void loading(boolean isNetwork)
{
if ( !networkState && isNetwork)
{
networkState = true;
getPersonFromSocket();
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
LogUtil.log(TAG ,"onDestroy-PersonManagerActivity");
}
}
|
package cn.hzw.graffiti;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
/**
* 来自 伍玉南 的装逼小尾巴 on 17/12/22.
* 生成马赛克底图的工具
*/
public class MosaicUtils {
/**
* 马赛克效果
*
* @param bitmap 原图
* @return 马赛克图片
*/
public static Bitmap getMosaic(Bitmap bitmap) {
if(bitmap == null) return null;
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int radius = 40; //模糊半径
Bitmap mosaicBitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(mosaicBitmap);
int horCount = (int) Math.ceil(width / (float) radius);
int verCount = (int) Math.ceil(height / (float) radius);
Paint paint = new Paint();
paint.setAntiAlias(true);
for (int horIndex = 0; horIndex < horCount; ++horIndex) {
for (int verIndex = 0; verIndex < verCount; ++verIndex) {
int l = radius * horIndex;
int t = radius * verIndex;
int r = l + radius;
if (r > width) {
r = width;
}
int b = t + radius;
if (b > height) {
b = height;
}
int color = bitmap.getPixel(l, t);
Rect rect = new Rect(l, t, r, b);
paint.setColor(color);
canvas.drawRect(rect, paint);
}
}
canvas.save();
return mosaicBitmap;
}
}
|
package DOM_Difference;
import org.jsoup.nodes.Attribute;
public class AttributeInfo {
Attribute attr;
String differenceType;
int differenceCode;
public String getdifferenceType(int i)
{
String diffType="";
if(i == 12)
{
//System.out.println("***");
diffType="1.2.2 Index Changed";
return diffType;
}
if(i == 11)
{
//System.out.println("***");
diffType="1.2.1 Hierarchy Changed";
return diffType;
}
diffType="1.1.1";
//***********************Updated*****************
if(i == 1/* update*/)
{
if(this.getKey().equals("id"))
{
diffType=(new StringBuilder(diffType)).append(".1: ID not Found(Updated)").toString();
}
else if(this.getKey().equals("href"))
{
diffType=(new StringBuilder(diffType)).append(".3: Href Attribut not found(Updated)").toString();
}
else if(this.getKey().equals("alt"))
{
diffType=(new StringBuilder(diffType)).append(".4: Alternative text attribute not found(Updated)").toString();
}
else if(this.getKey().equals("name"))
{
diffType=(new StringBuilder(diffType)).append(".5: name attribute not found (Updated)").toString();
}
else if(this.getKey().equals("type"))
{
diffType=(new StringBuilder(diffType)).append(".6: type attribute not found (Updated)").toString();
}
else if(this.getKey().equals("class"))
{
diffType=(new StringBuilder(diffType)).append(".7: class attribute not found (Updated)").toString();
}
else if(this.getKey().equals("onclick"))
{
diffType=(new StringBuilder(diffType)).append(".8: onclick attribute not found (Updated)").toString();
}
else if(this.getKey().equals("maxlength"))
{
diffType="2.1: Invalid text field values input (Updated)";
}
else if(this.getKey().equals("value"))
{
diffType=(new StringBuilder(diffType)).append(".10: value attribute not found (Updated)").toString();
}
else if(this.getKey().equals("required"))
{
this.setDifferenceCode(14);
}
}
//***********************Added*******************************
if(i == 2 /* Added*/)
{
if(this.getKey().equals("id"))
{
diffType=(new StringBuilder(diffType)).append(".1: ID not Found (Added)").toString();
}
else if(this.getKey().equals("href"))
{
diffType=(new StringBuilder(diffType)).append(".3: Href Attribut not found (Added)").toString();
}
else if(this.getKey().equals("alt"))
{
diffType=(new StringBuilder(diffType)).append(".4: Alternative text attribute not found (Added)").toString();
}
else if(this.getKey().equals("name"))
{
diffType=(new StringBuilder(diffType)).append(".5: name attribute not found (Added)").toString();
}
else if(this.getKey().equals("type"))
{
diffType=(new StringBuilder(diffType)).append(".6: type attribute not found (Added)").toString();
}
else if(this.getKey().equals("class"))
{
diffType=(new StringBuilder(diffType)).append(".7: class attribute not found (Added)").toString();
}
else if(this.getKey().equals("onclick"))
{
diffType=(new StringBuilder(diffType)).append(".8: onclick attribute not found (Added)").toString();
}
else if(this.getKey().equals("maxlength"))
{
diffType="2.1: Invalid text field values input (Added)";
}
else if(this.getKey().equals("value"))
{
diffType=(new StringBuilder(diffType)).append(".10: value attribute not found (Added)").toString();
}
else if(this.getKey().equals("required"))
{
this.setDifferenceCode(14);
}
}
//**********************Deleted*****************
if(i == 3 /* Deleted*/)
{
if(this.getKey().equals("id"))
{
diffType=(new StringBuilder(diffType)).append(".1: ID not Found (Deleted)").toString();
}
else if(this.getKey().equals("href"))
{
diffType=(new StringBuilder(diffType)).append(".3: Href Attribut not found (Deleted)").toString();
}
else if(this.getKey().equals("alt"))
{
diffType=(new StringBuilder(diffType)).append(".4: Alternative text attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("name"))
{
diffType=(new StringBuilder(diffType)).append(".5: name attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("type"))
{
diffType=(new StringBuilder(diffType)).append(".6: type attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("class"))
{
diffType=(new StringBuilder(diffType)).append(".7: class attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("onclick"))
{
diffType=(new StringBuilder(diffType)).append(".8: onclick attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("maxlength"))
{
diffType="2.1: Invalid text field values input (Deleted)";
}
else if(this.getKey().equals("value"))
{
diffType=(new StringBuilder(diffType)).append(".10: value attribute not found (Deleted)").toString();
}
else if(this.getKey().equals("required"))
{
setDifferenceCode(14);;
}
}
if(i ==21)
{
return "5.1: onclick alert Added";
}
if(i ==22)
{
return "5.2: onclick alert deleted";
}
if(i ==14)
{
diffType="2.2 Missing Value";
return diffType;
}
if(i ==23)
{
diffType="6.1 Element Deleted from Html";
return diffType;
}
if(i ==24)
{
diffType="6.2 Element Added in Html";
return diffType;
}
if(i ==10)
{
diffType="1.1.2 Element Text not found Deleted";
return diffType;
}
if(i ==15)
{
diffType="2.3 value deleted from drop down";
return diffType;
}
return diffType;
}
public Attribute getAttr() {
return attr;
}
public AttributeInfo(Attribute attr, String diffType, int diffCode) {
this.attr = attr;
differenceCode = diffCode;
differenceType = getdifferenceType(differenceCode);
}
public void setAttr(Attribute attr, String diffType, int diffCode) {
this.attr = attr;
differenceCode = diffCode;
differenceType = getdifferenceType(differenceCode);
}
public String getDifferenceType() {
return differenceType;
}
public void setDifferenceType(String differenceType) {
this.differenceType = differenceType;
}
public int getDifferenceCode() {
return differenceCode;
}
public void setDifferenceCode(int differenceCode) {
this.differenceCode = differenceCode;
}
public AttributeInfo(Attribute arg_attr){
attr = arg_attr;
}
//getters
public String getKey(){
return attr.getKey();
}
public String getValue(){
return attr.getValue();
}
//setters
public void setKey(String key){
attr.setKey(key);
}
public void setValue(String val){
attr.setKey(val);
}
}
|
package com.revolut.moneytransfer.model;
public class AccountCreateRequest {
private String name;
public AccountCreateRequest() {
}
public AccountCreateRequest(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.example.student.laptrinhandroid_tuan02_bai01;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText et_SoA, et_SoB;
private TextView tv_KetQua;
private Button bt_TongHaiSo, bt_HieuHaiSo, bt_TichHaiSo, bt_ThuongHaiSo, bt_UocSoChungLonNhat, bt_Thoat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnhXa();
TongHaiSo();
HieuHaiSo();
TichHaiSo();
ThuongHaiSo();
Thoat();
}
public void AnhXa() {
et_SoA = (EditText) findViewById(R.id.et_SoA);
et_SoB = (EditText) findViewById(R.id.et_SoB);
tv_KetQua = (TextView) findViewById(R.id.tv_KetQua);
bt_TongHaiSo = (Button) findViewById(R.id.bt_TongHaiSo);
bt_HieuHaiSo = (Button) findViewById(R.id.bt_HieuHaiSo);
bt_TichHaiSo = (Button) findViewById(R.id.bt_TichHaiSo);
bt_ThuongHaiSo = (Button) findViewById(R.id.bt_ThuongHaiSo);
bt_UocSoChungLonNhat = (Button) findViewById(R.id.bt_UocSoChungLonNhat);
bt_Thoat = (Button) findViewById(R.id.bt_Thoat);
}
public void TongHaiSo() {
bt_TongHaiSo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = Integer.parseInt(et_SoA.getText().toString());
int b = Integer.parseInt(et_SoB.getText().toString());
tv_KetQua.setText("Kết quả: " + (a+b));
}
});
}
public void HieuHaiSo() {
bt_HieuHaiSo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = Integer.parseInt(et_SoA.getText().toString());
int b = Integer.parseInt(et_SoB.getText().toString());
tv_KetQua.setText("Kết quả: " + (a-b));
}
});
}
public void TichHaiSo() {
bt_TichHaiSo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = Integer.parseInt(et_SoA.getText().toString());
int b = Integer.parseInt(et_SoB.getText().toString());
tv_KetQua.setText("Kết quả: " + (a*b));
}
});
}
public void ThuongHaiSo() {
bt_ThuongHaiSo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int a = Integer.parseInt(et_SoA.getText().toString());
int b = Integer.parseInt(et_SoB.getText().toString());
tv_KetQua.setText("Kết quả: " + (a/b));
}
});
}
public void Thoat() {
bt_Thoat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
}
|
/*
* 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 jc.fog.presentation.commands;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jc.fog.data.DataFacade;
import jc.fog.data.DataFacadeImpl;
import jc.fog.data.DbConnector;
import jc.fog.exceptions.FogException;
import jc.fog.logic.dto.UsersDTO;
import jc.fog.presentation.Pages;
/**
*
* @author Jespe
*/
public class ShowUserHomeCommand extends Command
{
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws FogException
{
try
{
//sikker sig at man har den rigtigt rank for at kun se det her område.
HttpSession session = request.getSession();
UsersDTO user = (UsersDTO)session.getAttribute("user");
// Har vi en user i session, er denne logget ind, gå til index side.
if(user == null)
{
return Pages.INDEX;
}
request.setAttribute("getUserName", user.getName());//bruger session med ens navn.
return Pages.USER_HOME;
}
catch(Exception e)
{
throw new FogException("Den ikke vise forsiden til bruger - ", e.getMessage(), e);
}
}
}
|
package com.java.springboot.service.impl;
import com.java.springboot.entity.Dept;
import com.java.springboot.mapper.DeptMapper;
import com.java.springboot.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @program: springBoot_emp
* @description: 部门信息业务层
* @author: Mr.Yu
* @create: 2020-07-29 15:26
**/
@Service
@Transactional(readOnly = false)
public class DeptServiceImpl implements DeptService {
//注入部门Mapper
@Autowired
private DeptMapper deptMapper;
/**
* @Description: 查询所有部门信息
* @Param: []
* @return:
* @Author: Mr.Yu
* @Date:
*/
@Override
public List<Dept> findAllDept() throws Exception {
return deptMapper.selectAllDept();
}
}
|
package com.tyland.musicbox.data;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.ArtistColumns;
import com.tyland.musicbox.model.Artist;
import java.util.ArrayList;
import java.util.List;
public class ArtistDataAccess {
private Context mContext;
public ArtistDataAccess(Context context) {
mContext = context;
}
/**
* 读取本地媒体库中的所有艺人信息列表
*
* @return
*/
public List<Artist> getArtistList() {
ContentResolver cr = mContext.getContentResolver();
String[] projection = new String[] { BaseColumns._ID,
ArtistColumns.ARTIST_KEY,
ArtistColumns.ARTIST,
ArtistColumns.NUMBER_OF_ALBUMS,
ArtistColumns.NUMBER_OF_TRACKS };
Cursor cursor = cr.query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.Audio.Artists.DEFAULT_SORT_ORDER);
List<Artist> artistList = new ArrayList<Artist>();
while (cursor.moveToNext()) {
Artist artist = new Artist();
artist.setId(cursor.getLong(cursor
.getColumnIndexOrThrow(BaseColumns._ID)));
artist.setArtistKey(cursor.getString(cursor
.getColumnIndexOrThrow(ArtistColumns.ARTIST_KEY)));
artist.setArtist(cursor.getString(cursor
.getColumnIndexOrThrow(ArtistColumns.ARTIST)));
artist.setNumberOfAlbums(cursor.getInt(cursor
.getColumnIndexOrThrow(ArtistColumns.NUMBER_OF_ALBUMS)));
artist.setNumberOfTracks(cursor.getInt(cursor
.getColumnIndexOrThrow(ArtistColumns.NUMBER_OF_TRACKS)));
artistList.add(artist);
}
cursor.close();
return artistList;
}
}
|
/**
* Copyright 2005 Sean J. Barbeau
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.barbeau.networks.astar;
import java.util.*;
/**
* This object is used to hold nodes and sort them by the estimated cost to get to the goal, estimated by a heuristic
* @author Sean J. Barbeau
*/
public class PriorityQueue extends LinkedList {
/** Creates a new instance of PriorityQueue */
public PriorityQueue() {
super();
}
/**
* This method finds the appropriate location to store the new node that is being added to the queue, and adds it to the queue
* NOTE: uses the "Comparable" extention to the Node class and function "compare_To" to find where it should be inserted into the queue.
* @param newNode node to be added to the queue
*/
public void add(Comparable newNode) {
//*****************************************************************************************************
//*
try
{
for (int i = 0 ; i < this.size() ; i++) {
if (newNode.compareTo(get(i)) <= 0) {
add(i, newNode); //Add this new node to the list
return;
}
}
//If execution reaches this point then add it as the last node in the list
addLast(newNode);
}
catch (Exception e)
{
System.out.println("Error in adding element in PriorityQueue object:" + e) ;
}
}
/* public void sort() {
//This function sorts the Priority Queue in case any elements comparable features have changed
try {
for (int i = 0 ; i < this.size() ; i++) {
for (int j = 0 ; j < this.size() ; j++) {
if (((Comparable)get(j)).compareTo(get(i)) >= 0) {
if(i == 0) {
this.addFirst(this.remove(j)); //Move to beginning
}
else {
if(i == this.size()) {
this.addLast(this.remove(j)); //Move to end
}
else {
this.add(i, this.remove(j)); //Move to current position
}
}
}
}
}
}
catch (Exception e) {
System.out.println("Error sorting PriorityQueue object:" + e) ;
}
} */
/**
* This is a test method to print the current contents of the Priority Queue in order from lowest (first) to highest (last)
*/
public void printContents() {
try
{
System.out.println("------------------------");
System.out.println("PriorityQueue Contents:");
System.out.println(this.size() + " elements.");
while (!this.isEmpty()) {
HeuristicsNode test = (HeuristicsNode)removeFirst();
System.out.println(test.label + " at cost of " + test.get_total_heuristic_cost());
}
}
catch (Exception e)
{
System.out.println("Error in printing PriorityQueue contents:" + e) ;
}
}
}
|
package com.grebnev.game.actors;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
/**
* Created by Grebnev on 23.04.2017.
*/
public class GameSquare extends Actor {
private final char alphabet[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
private final Texture bgTable = new Texture(Gdx.files.internal("bg_table.jpg"));
private final Texture lightSquare = new Texture(Gdx.files.internal("light_internal.png"));
private final Vector2 indexPosition, pixelPosition;
private final PieceColor color;
private GamePiece piece;
public Vector2 getIndexPosition() {
return indexPosition;
}
public Vector2 getPixelPosition() {
return pixelPosition;
}
public GamePiece getPiece() {
return piece;
}
public void setPiece(GamePiece piece) {
this.piece = piece;
}
public GameSquare(Vector2 indexPosition, Vector2 pixelPosition, int size, PieceColor color) {
this.indexPosition = indexPosition;
this.pixelPosition = pixelPosition;
this.color = color;
setBounds(pixelPosition.x + 110, pixelPosition.y + 150, size, size);
//setName(alphabet[(int)indexPosition.x] + String.valueOf((int)indexPosition.y + 1));
addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
GameSquare squareTouched = (GameSquare) event.getListenerActor();
Vector2 stageCoords = squareTouched.localToStageCoordinates(new Vector2(x, y));
Gdx.app.debug("Input",
String.format("%s %s %s at position (Relative - X:%.2f, Y:%.2f) (Absolute - X:%.2f, Y:%.2f)",
event.getListenerActor().getClass().getSimpleName(), event.getListenerActor(), event.getType().name(), x, y, stageCoords.x, stageCoords.y));
return true;
}
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
GameSquare squareTouched = (GameSquare) event.getListenerActor();
Vector2 stageCoords = squareTouched.localToStageCoordinates(new Vector2(x, y));
Gdx.app.debug("Input",
String.format("%s %s %s at position (Relative - X:%.2f, Y:%.2f) (Absolute - X:%.2f, Y:%.2f)",
event.getListenerActor().getClass().getSimpleName(), event.getListenerActor(), event.getType().name(), x, y, stageCoords.x, stageCoords.y));
super.touchUp(event, x, y, pointer, button);
}
});
}
@Override
public void draw(Batch batch, float parentAlpha) {
batch.setColor(getColor());
if (color == PieceColor.BG_TABLE) {
batch.draw(bgTable, 0, 0);
}
if (color == PieceColor.DARK) {
batch.draw(lightSquare, getX(), getY(), getWidth(), getHeight());
}
else if (color == PieceColor.LIGHT)
batch.draw(lightSquare, getX(), getY(), getWidth(), getHeight());
batch.setColor(Color.WHITE);
super.draw(batch, parentAlpha);
}
}
|
package com.mobdeve.s11.g32.tindergree.Models;
import java.util.ArrayList;
public class Matches {
public String uid;
public ArrayList<String> uidMatches;
public ArrayList<String> uidMatchRequests;
public Matches(String uid) {
this.uid = uid;
}
public Matches(String uid, ArrayList<String> uidMatches, ArrayList<String> uidMatchRequests) {
this.uid = uid;
this.uidMatches = uidMatches;
this.uidMatchRequests = uidMatchRequests;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
/**
* For newly registered accounts, this initializes the Matches in the database, which is empty for now.
*/
public void initializeMatches() {
this.uidMatches = new ArrayList<>();
this.uidMatchRequests = new ArrayList<>();
}
public void addMatchRequest(String matchRequestUid) {
uidMatchRequests.add(matchRequestUid);
}
public void addMatches(String matchUid) {
uidMatches.add(matchUid);
}
public void removeMatchRequests(String matchRequestUid) {
uidMatchRequests.remove(matchRequestUid);
}
public void removeMatch(String matchId) {
uidMatches.remove(matchId);
}
}
|
/*
* Name: Luis Gustavo Grubert Valensuela Z#:23351882 lvalensuela2015@fau.edu
* Course: JavaProgramming
* Professor: Dr. Mehrdad Nojoumian
* Due Date:04/12/2018 Due Time: 11:30PM
* Assignment Number: lab 08
* Last Changed: 03/29/2018
*
* Description:
* Program to show inheritanse throught out classes
*/
package lab10.q1;
/**
* Main Class
* @author Luis Gustavo Grubert Valensuela
*/
public class Q1 {
public static void main(String[] args) {
Animal [] pet = new Animal[2];
pet[0] = new Dog("Buddy", 41);
pet[1] = new Cat("Whiskers",4);
for(Animal i : pet)
{
System.out.println("The pet name is " + i.getName() +
" and it weights "+ i.getWeifhtPounds() + " pounds and says "
+ i.Speak());
}
}
}
|
package com.myvodafone.android.front.payment;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.myvodafone.android.R;
import com.myvodafone.android.business.managers.MemoryCacheManager;
import com.myvodafone.android.business.managers.PaymentsManager;
import com.myvodafone.android.front.VFGRFragment;
import com.myvodafone.android.front.helpers.Dialogs;
import com.myvodafone.android.front.helpers.WrapContentListView;
import com.myvodafone.android.front.soasta.OmnitureHelper;
import com.myvodafone.android.model.business.VFAccount;
import com.myvodafone.android.model.business.VFMobileAccount;
import com.myvodafone.android.model.service.Account;
import com.myvodafone.android.model.service.AssetMsisdn;
import com.myvodafone.android.model.service.BillingInfo;
import com.myvodafone.android.model.service.GetMSISDNs;
import com.myvodafone.android.model.service.GetMsisdnInfo;
import com.myvodafone.android.model.service.Login;
import com.myvodafone.android.model.service.MsisdnBillDetails;
import com.myvodafone.android.model.service.MyAccount;
import com.myvodafone.android.utils.PermissionsController;
import com.myvodafone.android.utils.PermissionsHelper;
import com.myvodafone.android.utils.StaticTools;
import com.myvodafone.android.utils.VFPreferences;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/**
* Created by kakaso on 2/16/2016.
*/
public class FragmentPostPayBilling extends VFGRFragment implements PaymentsManager.GetPdfListener,
PaymentsManager.PaymentsListener,
PaymentsManager.MsisdnsListener,
PaymentsManager.MsisdnDetailsListener,
PermissionsController
{
WrapContentListView listAccounts;
TextView txtUsagePeriod, txtFullname, txtAccountId, txtCurrentAmount, txtOverdueAmount, txtLastpayment;
ImageView txtPostPayAccountIcon;
Button btnPayment;
ArrayList<String> errorMessages;
int tasksCounter;
public static FragmentPostPayBilling newInstance() {
FragmentPostPayBilling fragment = new FragmentPostPayBilling();
return fragment;
}
@Override
public BackFragment getPreviousFragment() {
return BackFragment.FragmentHome;
}
@Override
public String getFragmentTitle() {
return activity.getString(R.string.my_bill_top_label);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_postpay_mybill, container, false);
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
VFMobileAccount vfMobileAccount = (VFMobileAccount) vfAccount;
if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_ADMINISTRATOR)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackView("My bill business admin hybrid");
} else {
OmnitureHelper.trackView("My bill business admin");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_CHILD)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackView("My bill consumer child hybrid");
} else {
OmnitureHelper.trackView("My bill consumer child");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_PARENT)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackView("My bill consumer parent hybrid");
} else {
OmnitureHelper.trackView("My bill consumer parent");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_SIMPLE_USER)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackView("My bill business employee hybrid");
} else {
OmnitureHelper.trackView("My bill business employee");
}
}
}
initViews(v);
return v;
}
private void initViews(View v) {
txtUsagePeriod = (TextView) v.findViewById(R.id.txtPostPayUsagePeriod);
txtFullname = (TextView) v.findViewById(R.id.txtPostPayFullname);
txtAccountId = (TextView) v.findViewById(R.id.txtPostPayCustomerId);
txtCurrentAmount = (TextView) v.findViewById(R.id.txtPostPayCurrentTotal);
txtOverdueAmount = (TextView) v.findViewById(R.id.txtPostPayOverdue);
txtLastpayment = (TextView) v.findViewById(R.id.txtLastpayment);
txtPostPayAccountIcon = (ImageView) v.findViewById(R.id.txtPostPayAccountIcon);
btnPayment = (Button) v.findViewById(R.id.btnPayBill);
header = (TextView) v.findViewById(R.id.headerTitle);
listAccounts = (WrapContentListView) v.findViewById(R.id.listPostPayAccount);
listAccounts.setFocusable(false);
ArrayList<ListAccountItem> items = getAccountItems();
ListAccountAdapter adapter = new ListAccountAdapter(items);
listAccounts.setAdapter(adapter);
listAccounts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListAccountItem item = (ListAccountItem) parent.getItemAtPosition(position);
activity.replaceFragment(FragmentPostPayBillInfo.newInstance(item.getMsisdn(), item.getTarif()));
}
});
v.findViewById(R.id.btnPostPayPdf).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
VFMobileAccount vfMobileAccount = (VFMobileAccount) vfAccount;
if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_ADMINISTRATOR)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill business admin hybrid pdf");
} else {
OmnitureHelper.trackEvent("My bill business admin pdf");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_CHILD)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill consumer child hybrid pdf");
} else {
OmnitureHelper.trackEvent("My bill consumer child pdf");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_PARENT)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill consumer parent hybrid pdf");
} else {
OmnitureHelper.trackEvent("My bill consumer parent pdf");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_SIMPLE_USER)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill business employee hybrid pdf");
} else {
OmnitureHelper.trackEvent("My bill business employee pdf");
}
}
}
PermissionsHelper.checkPermissions(activity, FragmentPostPayBilling.this, FragmentPostPayBilling.this, PermissionsHelper.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
}
});
btnPayment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
VFMobileAccount vfMobileAccount = (VFMobileAccount) vfAccount;
if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_ADMINISTRATOR)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill business admin hybrid pay");
} else {
OmnitureHelper.trackEvent("My bill business admin pay");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_CHILD)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill consumer child hybrid pay");
} else {
OmnitureHelper.trackEvent("My bill consumer child pay");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_POSTPAY_CONSUMER_PARENT)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill consumer parent hybrid pay");
} else {
OmnitureHelper.trackEvent("My bill consumer parent pay");
}
} else if (vfMobileAccount.getMobileAccount().getVopUserType().equalsIgnoreCase(PaymentsManager.VUT_SIMPLE_USER)) {
if (vfAccount.isHybrid()) {
OmnitureHelper.trackEvent("My bill business employee hybrid pay");
} else {
OmnitureHelper.trackEvent("My bill business employee pay");
}
}
}
activity.replaceFragment(FragmentPostPayPayment.newInstance());
}
});
txtUsagePeriod.setText("");
txtLastpayment.setText("");
}
private ArrayList<ListAccountItem> getAccountItems() {
ArrayList<ListAccountItem> list = new ArrayList<>();
if(!StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())) {
ArrayList<Account> accounts = MemoryCacheManager.getMyAccount() != null ?
MemoryCacheManager.getMyAccount().getCustomer().getAccounts() : null;
if (accounts != null) {
String selectedBa = MemoryCacheManager.getMyAccount().getCustomer().getAccountNumber(
MemoryCacheManager.getSelectedAccount().getSelectedAccountNumber() );
for (Account account : accounts) {
if(account.getAccount_number().equals(selectedBa)) {
for (AssetMsisdn msisdn : account.getMsisdns()) {
ListAccountItem item = new ListAccountItem();
item.setMsisdn(msisdn.getNumber());
item.setTarif(msisdn.getTariff_plan().getName());
list.add(item);
}
}
}
}
}
else{
ListAccountItem item = new ListAccountItem();
item.setMsisdn(MemoryCacheManager.getSelectedBizMsisdn());
if (MemoryCacheManager.getMapMsisdnInfo().containsKey(MemoryCacheManager.getSelectedBizMsisdn())) {
GetMsisdnInfo msisdnInfo = MemoryCacheManager.getMapMsisdnInfo().get(MemoryCacheManager.getSelectedBizMsisdn());
if (msisdnInfo != null) {
ArrayList<Account> accounts = msisdnInfo.getCustomer().getAccounts();
if (accounts != null) {
for (Account account : accounts) {
boolean found = false;
for (AssetMsisdn msisdn : account.getMsisdns()) {
if (msisdn.getTariff_plan() != null && MemoryCacheManager.getSelectedBizMsisdn().equals(msisdn.getNumber())) {
item.setTarif(msisdn.getTariff_plan().getName());
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
list.add(item);
}
return list;
}
@Override
public void onResume() {
super.onResume();
activity.sideMenuHelper.setToggle(getView().findViewById(R.id.toggleDrawer));
activity.sideMenuHelper.setBackButton(getView().findViewById(R.id.back), activity);
setFragmentTitle();
//loadData();
if (errorMessages == null) {
errorMessages = new ArrayList<>();
} else {
errorMessages.clear();
}
Dialogs.showProgress(activity);
if(StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())) {
PaymentsManager.getBizMsidns(MemoryCacheManager.getSelectedBizBA().getBillingAccountIdShow(), true, false, activity, new WeakReference<PaymentsManager.MsisdnsListener>(this));
tasksCounter++;
}
else{
PaymentsManager.getMobileBillingInformation(activity, null, new WeakReference<PaymentsManager.PaymentsListener>(this));
tasksCounter++;
}
getMsisdnDetails();
loadName();
//BG
StaticTools.setAppBackground(getContext(),StaticTools.BACKGROUND_TYPE_INSIDE,(ImageView)getView().findViewById(R.id.insideBG),null);
}
private void getMsisdnDetails(){
String msisdn;
if(StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())){
msisdn = MemoryCacheManager.getSelectedBizMsisdn();
}
else{
msisdn = MemoryCacheManager.getSelectedAccount().getSelectedAccountNumber();
}
tasksCounter++;
PaymentsManager.getMsisdnDetails(activity, msisdn, new WeakReference<PaymentsManager.MsisdnDetailsListener>(this));
}
private void loadName(){
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
String fullName = "";
String selectedMsisdn = StaticTools.isBizAdmin(vfAccount)
&& MemoryCacheManager.getSelectedBizMsisdn() != null
? MemoryCacheManager.getSelectedBizMsisdn()
: MemoryCacheManager.getSelectedAccount().getSelectedAccountNumber();
if (selectedMsisdn != null && MemoryCacheManager.getMapMsisdnInfo().containsKey(selectedMsisdn)) {
fullName = MemoryCacheManager.getMapMsisdnInfo().get(selectedMsisdn).getCustomer().getCustomer_name();
} else if (MemoryCacheManager.getMyAccount() != null
&& MemoryCacheManager.getMyAccount().getCustomer() != null
&& MemoryCacheManager.getMyAccount().getCustomer().getAccounts() != null) {
for (Account account : MemoryCacheManager.getMyAccount().getCustomer().getAccounts()) {
AssetMsisdn assetMsisdn = account.getAssetMsisdn(selectedMsisdn);
if (assetMsisdn != null) {
fullName = assetMsisdn.getName();
break;
}
}
}
txtFullname.setText(fullName);
if (StaticTools.isBizAdmin(vfAccount) && MemoryCacheManager.getSelectedBizMsisdn() != null) {
//StaticTools.loadFriendlyName(txtFullname, vfAccount.getUsername(), MemoryCacheManager.getSelectedBizMsisdn(), fullName);
StaticTools.loadProfileImage(txtPostPayAccountIcon, R.drawable.profile_icon, MemoryCacheManager.getSelectedBizMsisdn(), activity);
} else {
//StaticTools.loadFriendlyName(txtFullname, vfAccount.getUsername(), vfAccount.getSelectedAccountNumber(), fullName);
StaticTools.loadProfileImage(txtPostPayAccountIcon, R.drawable.profile_icon, vfAccount.getSelectedAccountNumber(), activity);
}
}
}
private void loadData(String totalAmount) {
btnPayment.setEnabled(true);
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
MyAccount myAccount = MemoryCacheManager.getMyAccount();
if(!StaticTools.isBizAdmin(vfAccount) && myAccount != null) {
if (myAccount.getCustomer() != null) {
txtAccountId.setText(getString(R.string.my_bill_ba) + " " + myAccount.getCustomer().getAccountNumber(MemoryCacheManager.getSelectedAccount().getSelectedAccountNumber()));
}
}
else {
txtAccountId.setText(getString(R.string.my_bill_ba) + " " + MemoryCacheManager.getSelectedBizBA());
}
if (!StaticTools.isNullOrEmpty(totalAmount)) {
txtCurrentAmount.setText(StaticTools.formatNumber(totalAmount, 2) + "€");
}
else {
txtCurrentAmount.setText("");
}
}
if (StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())) {
GetMSISDNs msisdNs = MemoryCacheManager.getMsisdnsMap().get(MemoryCacheManager.getSelectedBizBA().getBillingAccountIdShow());
if (msisdNs != null) {
if (!StaticTools.isNullOrEmpty(msisdNs.getBillingDueDate())) {
//2016-04-10T21:00:00.000Z //UTC
// To TimeZone Athens
SimpleDateFormat sdfGreece = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
try {
sdfGreece.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateUtc = sdfGreece.parse(msisdNs.billingDueDate);
TimeZone tzInGreece = TimeZone.getTimeZone("Europe/Athens");
sdfGreece.setTimeZone(tzInGreece);
String sDateInGreece = sdfGreece.format(dateUtc);
txtOverdueAmount.setText(String.format(getString(R.string.bill_info_overdue_pay_until), StaticTools.tryFormatDate(StaticTools.tryParseDate(sDateInGreece,"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",0), "dd/MM/yyyy", "")));
}
catch (Exception e){
StaticTools.Log(e);
}
} else {
txtOverdueAmount.setText("");
}
if (!StaticTools.isNullOrEmpty(msisdNs.getOverdue())) {
txtLastpayment.setText(buildOverdueSpannable(getContext(), StaticTools.formatNumber(msisdNs.getOverdue(), 2), ""));
} else {
txtLastpayment.setText("");
}
} else {
txtOverdueAmount.setText("");
txtLastpayment.setText("");
}
} else {
BillingInfo billingInfo = MemoryCacheManager.getCurrentBillingInfo();
if (billingInfo != null) {
if (!StaticTools.isNullOrEmpty(billingInfo.billingDueDate.toString())) {
txtOverdueAmount.setText(String.format(getString(R.string.bill_info_overdue_pay_until),
StaticTools.tryFormatDate(StaticTools.tryParseDate(billingInfo.billingDueDate.toString() ,"dd/MM/yy", 0) ,"dd/MM/yyyy", "")));
} else {
txtOverdueAmount.setText("");
}
if (!StaticTools.isNullOrEmpty(billingInfo.getOverdueAmount())) {
txtLastpayment.setText(buildOverdueSpannable(getContext(), StaticTools.formatNumber(billingInfo.getOverdueAmount(), 2),""));
} else {
txtLastpayment.setText("");
}
} else {
txtOverdueAmount.setText("");
txtLastpayment.setText("");
}
}
}
@Override
public void onSuccessPdf(String result) {
Dialogs.closeProgress();
Intent intent = new Intent(Intent.ACTION_VIEW);
File pdfLocal = new File(result);
intent.setDataAndType(Uri.fromFile(pdfLocal), "application/pdf");
//intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(intent);
} catch (Exception e) {
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
}
@Override
public void onErrorPdf(String result) {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
@Override
public void onGenericErrorPdf() {
Dialogs.closeProgress();
Dialogs.showErrorDialog(activity, getString(R.string.vf_generic_error));
}
@Override
public void onDownloadManagerError(String result) {
Dialogs.closeProgress();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setType(PaymentsManager.MIME_TYPE_PDF);
i.setData(Uri.parse(result));
startActivity(i);
}
@Override
public void onBillingInfoReceived(double overdueBalance, double currentBalance) {
checkTasks("");
loadData(currentBalance!=-PaymentsManager.PAYMENT_MAX?String.valueOf(currentBalance):"");
}
@Override
public void onErrorBilling(String message) {
String msg = StaticTools.isNullOrEmpty(message) ? getString(R.string.vf_generic_error) : message;
checkTasks(msg);
btnPayment.setEnabled(false);
}
@Override
public void onGenericErrorBilling(int errorCode) {
checkTasks(getString(R.string.vf_generic_error));
btnPayment.setEnabled(false);
}
@Override
public void onSuccessMsisdns(GetMSISDNs response, boolean getBillingInfo, String ba) {
checkTasks("");
loadData(response.getBalance());
}
@Override
public void onGotMsisdnsError(String message, String ba, boolean getBillingInfo) {
String msg = StaticTools.isNullOrEmpty(message) ? getString(R.string.vf_generic_error) : message;
checkTasks(msg);
// Dialogs.showErrorDialog(activity, msg);
btnPayment.setEnabled(false);
}
@Override
public void onSuccessMsisdnInfo(String ba, String msisdn) {
checkTasks("");
loadName();
txtUsagePeriod.setText(String.format(getString(R.string.my_bill_billing_period),
StaticTools.getDateRange(
MemoryCacheManager.getMapMsisdnInfo().get(msisdn).getFromDate(),
MemoryCacheManager.getMapMsisdnInfo().get(msisdn).getToDate(), "-", false)));
}
@Override
public void onErrorMsisdnInfo(String message, String ba, String baShow, String msisdn) {
String msg = StaticTools.isNullOrEmpty(message) ? getString(R.string.vf_generic_error) : message;
checkTasks(msg);
// Dialogs.showErrorDialog(activity, msg);
}
@Override
public void onNotMatchingMsisdn(String message, String ba, String baShow, String msisdn) {
onErrorMsisdnInfo(message, ba, baShow, msisdn);
}
@Override
public void onSuccessMsisdnDetails(MsisdnBillDetails response) {
checkTasks("");
loadName();
txtUsagePeriod.setText(String.format(getString(R.string.my_bill_billing_period),
StaticTools.getDateRange(
StaticTools.tryFormatDate(StaticTools.tryParseDate(response.getFromDate(), "dd/MM/yy HH:mm",0), "dd/MM/yyyy", ""),
StaticTools.tryFormatDate(StaticTools.tryParseDate(response.getToDate(), "dd/MM/yy HH:mm",0), "dd/MM/yyyy", ""), "-", false)));
}
@Override
public void onErrorMsisdnDetails(String message) {
String msg = StaticTools.isNullOrEmpty(message) ? getString(R.string.vf_generic_error) : message;
checkTasks(msg);
}
@Override
public void onGenericErrorMsisdnDetails() {
String msg = getString(R.string.vf_generic_error);
checkTasks(msg);
}
class ListAccountItem {
String msisdn, tarif;
public String getMsisdn() {
return msisdn;
}
public void setMsisdn(String msisdn) {
this.msisdn = msisdn;
}
public String getTarif() {
return tarif;
}
public void setTarif(String tarif) {
this.tarif = tarif;
}
}
class ListAccountViewHolder {
TextView txtMsisdn, txtTarifName;
ImageView imgProfile;
}
class ListAccountAdapter extends BaseAdapter {
List<ListAccountItem> items = new ArrayList<>();
public ListAccountAdapter(List<ListAccountItem> items) {
this.items = items;
}
@Override
public int getCount() {
return items.size();
}
@Override
public ListAccountItem getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = activity.getLayoutInflater().inflate(R.layout.item_postpay_account, parent, false);
ListAccountViewHolder vh = new ListAccountViewHolder();
vh.txtMsisdn = (TextView) convertView.findViewById(R.id.txtItemPostPayMsisdn);
vh.txtTarifName = (TextView) convertView.findViewById(R.id.txtItemPostPayTarif);
vh.imgProfile = (ImageView) convertView.findViewById(R.id.imgMobile);
convertView.setTag(vh);
}
ListAccountViewHolder viewHolder = (ListAccountViewHolder) convertView.getTag();
viewHolder.txtMsisdn.setText(getItem(position).getMsisdn());
viewHolder.txtTarifName.setText(getItem(position).getTarif());
Picasso.with(activity).cancelRequest(viewHolder.imgProfile);
StaticTools.loadProfileImage(viewHolder.imgProfile, R.drawable.profile_mobile_icon, getItem(position).getMsisdn(), activity);
return convertView;
}
}
private void checkTasks(String error){
if (!StaticTools.isNullOrEmpty(error) && errorMessages != null) {
errorMessages.add(error);
}
tasksCounter--;
if(tasksCounter==0) {
Dialogs.closeProgress();
if (errorMessages != null && errorMessages.size() > 0) {
for (int i = errorMessages.size() - 1; i >= 0; i--) {
String errorMessage = errorMessages.get(i);
if (!StaticTools.isNullOrEmpty(errorMessage)) {
Dialogs.showErrorDialog(activity, errorMessage);
break;
}
}
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
boolean permissionGranted = (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);
boolean permissionRevoked = false;
switch (requestCode) {
case PermissionsHelper.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (!permissionGranted) {
if (!shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
permissionRevoked = true;
}
}
}
}
if(permissionGranted) {
this.Result(permissionGranted, PermissionsHelper.permissioncode);
}
else if(permissionRevoked){
//store permission revoked forever
VFPreferences.setBoolVal(permissions[0], true);
}
}
@Override
public void Result(boolean permissionGranted, int code) {
switch (code) {
case PermissionsHelper.MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE:
if(permissionGranted)
{
VFAccount vfAccount = MemoryCacheManager.getSelectedAccount();
if (vfAccount instanceof VFMobileAccount) {
Login login = ((VFMobileAccount) vfAccount).getMobileAccount();
if (login != null) {
Dialogs.showProgress(activity);
String ba;
if(StaticTools.isBizAdmin(MemoryCacheManager.getSelectedAccount())){
ba = MemoryCacheManager.getSelectedBizBA().getBillingAccountIdShow();
}
else {
ba = StaticTools.getAccountBA((VFMobileAccount) MemoryCacheManager.getSelectedAccount());
}
PaymentsManager.getPdf(activity, ba, "",
new WeakReference<PaymentsManager.GetPdfListener>(FragmentPostPayBilling.this));
}
}
}
break;
}
}
}
|
package hw9.task3;
public class Circle {
private static final double PI = 3.14;
private double radiuse;
public Circle(double radiuse) {
this.radiuse = radiuse;
}
public double getRadiuse() {
return radiuse;
}
public void setRadiuse(double radiuse) {
this.radiuse = radiuse;
}
public double squareCircle() {
return PI * radiuse * radiuse;
}
public double lengthCircle() {
return 2 * PI * radiuse;
}
@Override
public String toString() {
return "Circle{" +
"radiuse=" + radiuse +
'}';
}
}
|
package com.dh.comunicacao.comunicaocombundle;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import com.dh.comunicacao.R;
public class MainActivity extends AppCompatActivity {
FragmentManager fgm = getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_bundle);
FragmentTransaction ft = fgm.beginTransaction();
//Instanciando os fragments
FragmentoNumero1 frag1 = new FragmentoNumero1();
ft.add(R.id.frame1, frag1);
ft.commit();
}
} |
package fr.cea.nabla.interpreter;
import java.io.File;
import java.io.IOException;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
class TestMeshWrapper {
public static void main(String[] args) throws IOException {
Context polyglot = Context.newBuilder("llvm")
.allowAllAccess(true)
// .option("inspect", "9229") //Uncomment to debug C++ in chrome
.build();
File file = new File("libcppnabla.so");
Source source = Source.newBuilder("llvm", file).build();
Value library = polyglot.eval(source);
Value wrapper = library.getMember("jsonInit").execute("{\n" +
" \"mesh\":\n" +
" {\n" +
" \"nbXQuads\":40,\n" +
" \"nbYQuads\":40,\n" +
" \"xSize\":0.05,\n" +
" \"ySize\":0.05\n" +
" }\n" +
"}" + "\0");
Value v1 = library.getMember("getNodes").execute(wrapper);
Value v2 = library.getMember("getNbNodes").execute(wrapper);
Value v3 = library.getMember("getNodesOfCell").execute(wrapper, 0);
System.out.println("v1 = " + v1 + " ; v2 = " + v2);
library.getMember("free_wrapper").execute(wrapper);
}
}
|
package sort;
import java.util.ArrayList;
import java.util.List;
/*
문제 설명
0 또는 양의 정수가 주어졌을 때, 정수를 이어 붙여 만들 수 있는 가장 큰 수를 알아내 주세요.
예를 들어, 주어진 정수가 [6, 10, 2]라면 [6102, 6210, 1062, 1026, 2610, 2106]를 만들 수 있고, 이중 가장 큰 수는 6210입니다.
0 또는 양의 정수가 담긴 배열 numbers가 매개변수로 주어질 때, 순서를 재배치하여 만들 수 있는 가장 큰 수를 문자열로 바꾸어 return 하도록 solution 함수를 작성해주세요.
제한 사항
numbers의 길이는 1 이상 100,000 이하입니다.
numbers의 원소는 0 이상 1,000 이하입니다.
정답이 너무 클 수 있으니 문자열로 바꾸어 return 합니다
*/
public class BigNumber {
public static void main(String[] args) {
System.out.println(new BigNumber().solution(new int[]{6, 10, 2})); // 6210
System.out.println(new BigNumber().solution(new int[]{3, 30, 34, 5, 9})); //9534330
System.out.println(new BigNumber().solution(new int[]{661000, 38000, 7000, 63000, 339000})); //76616338339
System.out.println(new BigNumber().solution(new int[]{00, 000, 0000, 00000, 0000000})); //0
}
public String solution(int[] numbers) {
List<String> stringList = new ArrayList<>();
for (int number : numbers) {
stringList.add(String.valueOf(number));
}
stringList.sort((o1, o2) -> (o2 + o1).compareTo(o1 + o2));
StringBuilder sb = new StringBuilder();
for (String string : stringList) {
sb.append(string);
}
String answer = sb.toString();
if (answer.startsWith("0")) {
return "0";
} else {
return answer;
}
}
}
|
package com.miyatu.tianshixiaobai.activities.search;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import com.miyatu.tianshixiaobai.R;
import com.miyatu.tianshixiaobai.activities.BaseActivity;
import com.miyatu.tianshixiaobai.activities.mine.ShoppingCartActivity;
import com.miyatu.tianshixiaobai.activities.mine.ViewMessageDetailsActivity;
import com.miyatu.tianshixiaobai.adapter.ViewPagerAdapter;
import com.flyco.tablayout.SlidingTabLayout;
import java.util.ArrayList;
import java.util.List;
public class GoodsDetailsActivity extends BaseActivity {
private String serviceID;
private ViewPagerAdapter viewPagerAdapter;
private SlidingTabLayout tabLayout;
private ViewPager viewPager;
private List<Fragment> fragments = new ArrayList<>();
private LinearLayout titleBack;
private RelativeLayout titleShare;
private Button buyNow; //立即购买
private LinearLayout contactXiaoBai; //联系小白
// private LinearLayout shoppingCart; //购物车
public static void startActivity(Activity activity, String serviceID){
Intent intent = new Intent(activity, GoodsDetailsActivity.class);
intent.putExtra("serviceID", serviceID);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_goods_details;
}
@Override
protected void initView() {
buyNow = findViewById(R.id.buyNow);
titleBack = findViewById(R.id.titleBack);
titleShare = findViewById(R.id.titleShare);
tabLayout = findViewById(R.id.tabLayout);
viewPager = findViewById(R.id.viewPager);
contactXiaoBai = findViewById(R.id.contactXiaoBai);
// shoppingCart = findViewById(R.id.shoppingCart);
}
@Override
protected void initData() {
serviceID = getIntent().getStringExtra("serviceID");
initFragments();
}
@Override
protected void initEvent() {
titleBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
}
});
buyNow.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
ConfirmOrderActivity.startActivity(GoodsDetailsActivity.this);
}
});
contactXiaoBai.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewMessageDetailsActivity.startActivity(GoodsDetailsActivity.this, ViewMessageDetailsActivity.TYPE_USER);
}
});
// shoppingCart.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// ShoppingCartActivity.startActivity(GoodsDetailsActivity.this);
// }
// });
}
@Override
protected void updateView() {
}
private void initFragments() {
fragments.add(new GoodsDetailsProjectFragment(serviceID));
fragments.add(new GoodsDetailsDetailsFragment(serviceID));
fragments.add(new GoodsDetailsCommentFragment(serviceID));
String[] title = new String[]{"项目","详情", "评论"};
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(),fragments,title);
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setViewPager(viewPager);
}
}
|
package ro.microservices.store.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
@Column(unique=true)
private String code;
@ManyToOne
private Category category;
}
|
package codePlus.AGBasic1.dp;
import java.util.Scanner;
/*
* 2021.01.12
* 11053번 - 가장 긴 증가하는 부분 수열
*/
public class DP_11053 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int numbers[] = new int[n];
for(int i=0; i<numbers.length; i++) {
numbers[i]= scn.nextInt();
}
System.out.println();
int[] dp = new int [n];
for(int i=0; i<n; i++) {
dp[i]=1;
for(int j=0; j<i; j++) {
if(numbers[j]<numbers[i] && dp[i]<dp[j]+1) {
// 마지막 수보다 앞에 위치한 수 < 마지막 수보다 작은 경우 && dp[마지막 수] < dp[마지막수보다 앞에 위치한 수]+1
dp[i] = dp[j]+1; //dp[j] = 마지막 수보다 작은 수들의 LIS 중 크기가 가장 큰 것
}
}
System.out.print(dp[i]+" ");
}
System.out.println();
int answer = dp[0];
for(int i=0; i<n; i++) {
if(answer<dp[i]) { //dp배열 안에 삽입된 수가 answer보다 큰 경우를 만나면
answer = dp[i]; //해당 수로 answer를 변경해줌
}
}
System.out.println("answer= "+answer);
}
}
|
package com.sirma.itt.javacourse.threads.task4.synchronizedthreads;
import com.sirma.itt.javacourse.InputUtils;
/**
* Runner class for synchronized counting.
*
* @author Simeon Iliev
*/
public class RunSyncThreads {
/**
* Main method.
*
* @param args
* arguments for the main method.
*/
public static void main(String[] args) {
CounterSynchronizedThread threadOne = new CounterSynchronizedThread();
CounterSynchronizedThread threadTwo = new CounterSynchronizedThread();
InputUtils.printConsoleMessage("Input number for the threads to count to.");
int temp = InputUtils.readInt();
threadOne.setUpThread(temp);
threadTwo.setUpThread(temp);
threadOne.start();
threadTwo.start();
}
}
|
package modul.systemu.asi.frontend.Controllers;
import modul.systemu.asi.backend.dao.CommentRepository;
import modul.systemu.asi.backend.dao.UserRepository;
import modul.systemu.asi.backend.services.NotificationService;
import modul.systemu.asi.backend.services.TaskService;
import modul.systemu.asi.frontend.model.Notification;
import modul.systemu.asi.frontend.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
@Controller
public class NotificationController {
@Autowired
private UserRepository userRepository;
@Autowired
private NotificationService notificationService;
@Autowired
private TaskService taskService;
@Autowired
private CommentRepository commentRepository;
@RequestMapping("/notifications/notification-list")
public String notificationList(WebRequest request, Model model) {
User user = userRepository.findByEmail(request.getRemoteUser());
model.addAttribute("notifications", notificationService.getAllActiveNotifications());
model.addAttribute("notificationsForLayout", notificationService.getAllActiveNotifications().size());
model.addAttribute("tasksForLayout", taskService.getAllTasksOfUser(user).size());
return "notification/notification-list";
}
@RequestMapping("/notifications/add-notification")
public String addNotifications(WebRequest request, Model model) {
User user = userRepository.findByEmail(request.getRemoteUser());
Notification notification = new Notification();
model.addAttribute("notificationsForLayout", notificationService.getAllActiveNotifications().size());
model.addAttribute("tasksForLayout", taskService.getAllTasksOfUser(user).size());
return "notification/add-notification";
}
@RequestMapping("/notifications/archived-notifications")
public String archivedNotifications(WebRequest request, Model model) {
User user = userRepository.findByEmail(request.getRemoteUser());
model.addAttribute("notifications", notificationService.getAllArchivedNotifications());
model.addAttribute("notificationsForLayout", notificationService.getAllActiveNotifications().size());
model.addAttribute("tasksForLayout", taskService.getAllTasksOfUser(user).size());
return "notification/notification-list";
}
@RequestMapping("/notifications/notification-details")
public String notificationDetails(WebRequest request, Model model, @RequestParam long notificationId) {
Notification notification = notificationService.getNotificationById(notificationId);
model.addAttribute("notification", notification);
model.addAttribute("comments", commentRepository.findAllByNotificationOrderByDateAsc(notification));
return "notification/notification-details";
}
@RequestMapping("/notifications/notification-history")
public String notificationHistory(WebRequest request, Model model, @RequestParam long notificationId) {
model.addAttribute("notification", notificationService.getNotificationById(notificationId));
model.addAttribute("notificationHistory", notificationService.getHistoryOfNotification(notificationId));
return "notification/notification-history";
}
@RequestMapping("/notifications/update-notification")
public String updateNotification(WebRequest request, Model model, @RequestParam long notificationId) {
model.addAttribute("notification", notificationService.getNotificationById(notificationId));
return "notification/update-notification";
}
@RequestMapping("/notifications/add-comment")
public String addCommentToNotification(WebRequest request, Model model, @RequestParam long notificationId) {
model.addAttribute("notification", notificationService.getNotificationById(notificationId));
return "notification/add-comment";
}
}
|
package com.wxt.designpattern.command.test02.example3;
/*********************************
* @author weixiaotao1992@163.com
* @date 2018/12/1 22:40
* QQ:1021061446
* 命令接口,声明执行的操作
*********************************/
public interface Command {
/**
* 执行命令对应的操作
*/
void execute();
/**
* 设置命令的接收者
* @param cookApi 命令的接收者
*/
void setCookApi(CookApi cookApi);
/**
* 返回发起请求的桌号,就是点菜的桌号
* @return 发起请求的桌号
*/
int getTableNum();
} |
package com.health.system.feign.factory;
import com.health.system.domain.SysRole;
import com.health.system.feign.RemoteRoleService;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @author zq
*/
@Slf4j
@Component
public class RemoteRoleFallbackFactory implements FallbackFactory<RemoteRoleService> {
@Override
public RemoteRoleService create(Throwable throwable) {
log.error(throwable.getMessage());
return new RemoteRoleService() {
@Override
public SysRole selectSysRoleByRoleId(long roleId) {
return null;
}
};
}
}
|
package org.jaxws.stub2html.service;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.jaxws.stub2html.model.StubTypeTree;
/**
*
* @author chenjianjx
*
*/
public class StubTypeTreeRepository {
private Map<Class<?>, StubTypeTree> repository = new HashMap<Class<?>, StubTypeTree>();
public StubTypeTree getStubTypeTree(Class<?> type) {
StubTypeTree tree = repository.get(type);
if (tree == null) {
tree = new StubTypeTree();
tree.setType(type);
repository.put(type, tree);
}
return tree;
}
public Collection<StubTypeTree> getAllTrees() {
return repository.values();
}
public boolean isEmpty() {
return repository.isEmpty();
}
}
|
package org.dimigo.vaiohazard.Object;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.MoveByAction;
import com.badlogic.gdx.scenes.scene2d.actions.RepeatAction;
import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction;
import org.dimigo.vaiohazard.CustomActions;
/**
* Created by YuTack on 2015-11-11.
* in this game actors moves to vertical of horizontal line,
* define several game animations
*/
public class VaioActor extends Actor {
public enum MovingState {
walking,
walkingOver,
wating
}
private Animation walkAnimation;
private Texture walkSheet;
private TextureRegion[] walkFrame;
private SpriteBatch spriteBatch;
private TextureRegion currentFrame;
protected int FRAME_COLS, FRAME_ROWS;
protected String image;
private float stateTime;
//dot per second
protected int walkSpeed = 80; //default
protected MovingState moveState = MovingState.wating;
public VaioActor() {
super();
this.setOrigin(getWidth()/2, getHeight()/2);
}
public VaioActor(int walkSpeed) {
super();
this.walkSpeed = walkSpeed;
this.setOrigin(getWidth()/2, getHeight()/2);
}
public VaioActor(int walkSpeed, String imgPath) {
}
//
protected void setAnimation(String image, int cols, int rows) {
setBounds(0,0,100,100);
this.image = image;
this.FRAME_COLS = cols;
this.FRAME_ROWS = rows;
walkSheet = new Texture(Gdx.files.internal("resources/Actor/" + image));
TextureRegion[][] temp = TextureRegion.split(walkSheet, walkSheet.getWidth()/FRAME_COLS, walkSheet.getHeight()/FRAME_ROWS);
walkFrame = new TextureRegion[FRAME_COLS*FRAME_ROWS-1];
int p = 0;
for(int i=0; i<FRAME_ROWS; i++) {
for(int j=0; j<FRAME_COLS; j++) {
if(i==0 && j ==0) continue;
walkFrame[p++] = temp[i][j];
}
}
walkAnimation = new Animation(0.4f, walkFrame);
spriteBatch = new SpriteBatch();
stateTime = 0f;
}
public void notifyWalkingOver() {
moveState = MovingState.walkingOver;
}
@Override
public void act(float delta){
super.act(delta);
}
@Override
public void draw(Batch batch, float parentAlpha){
super.draw(batch, parentAlpha);
stateTime += Gdx.graphics.getDeltaTime();
currentFrame = walkAnimation.getKeyFrame(stateTime, true);
batch.draw(currentFrame, getX(), getY(), getOriginX(), getOriginY(),
getWidth(), getHeight(), getScaleX(), getScaleY(), getRotation());
}
//걸어가는 함수임. 방향 지정해 주면 알아서 갑니다
public void walkTo(int dotX, int dotY, boolean goXFirst) {
assert((moveState == MovingState.wating));
MoveByAction toX = new MoveByAction();
toX.setAmount(dotX - getX(), 0);
toX.setDuration(Math.abs(dotX - getX()) / walkSpeed);
MoveByAction toY = new MoveByAction();
toY.setAmount(0, dotY - getY());
toY.setDuration(Math.abs(dotY - getY()) / walkSpeed);
SequenceAction seq = null;
if(goXFirst)
seq = new SequenceAction(toX, toY);
else
seq = new SequenceAction(toY, toX);
seq.addAction(new Action() {
@Override
public boolean act(float delta) {
notifyWalkingOver();
return true;
}
});
moveState = MovingState.walking;
this.addAction(seq);
}
public static int FOREVER = -1;
//흔들흔들~
public void twitch(int count) {
this.setOrigin(getWidth()/2, getHeight()/2);
RepeatAction repeat = new RepeatAction();
repeat.setAction(CustomActions.twinkle());
if(count > 0)
repeat.setCount(count);
else if(count == -1)
repeat.setCount(RepeatAction.FOREVER);
else
assert true : "wtf";
this.addAction(repeat);
}
/*public void walkAround(int x1, int y1, int x2, int y2) {
}*/
}
|
package com.yufei.sys.query;
import com.yufei.base.BaseQuery;
import com.yufei.sys.model.SysUser;
import java.util.Calendar;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.format.annotation.DateTimeFormat;
public class SysUserQuery extends BaseQuery<SysUser> {
private static final long serialVersionUID = 1L;
/** 主键 */
private String id;
/** 用户名 */
private String userName;
/** 显示名 */
private String showName;
/** 密码 */
private String password;
/** 手机号 */
private String mobile;
/** 状态:0停用;1启用 */
private Integer status;
/** 最后登录ip */
private String lastLoginIp;
/** 最后登录时间 */
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date lastLoginTimeBegin;
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date lastLoginTimeEnd;
/** 备注 */
private String remark;
/** 创建人 */
private String creator;
/** 创建时间 */
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date createTimeBegin;
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date createTimeEnd;
/** 最后修改人 */
private String lastModifier;
/** 最后修改时间 */
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date lastModifyTimeBegin;
@DateTimeFormat(pattern = DATE_FORMAT)
private java.util.Date lastModifyTimeEnd;
/** 删除标记:0删除;1正常 */
private Integer deleted;
public String getId() {
return this.id;
}
public void setId(String value) {
this.id = value;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String value) {
this.userName = value;
}
public String getShowName() {
return this.showName;
}
public void setShowName(String value) {
this.showName = value;
}
public String getPassword() {
return this.password;
}
public void setPassword(String value) {
this.password = value;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String value) {
this.mobile = value;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer value) {
this.status = value;
}
public String getLastLoginIp() {
return this.lastLoginIp;
}
public void setLastLoginIp(String value) {
this.lastLoginIp = value;
}
public java.util.Date getLastLoginTimeBegin() {
return this.lastLoginTimeBegin;
}
public void setLastLoginTimeBegin(java.util.Date value) {
this.lastLoginTimeBegin = value;
}
public java.util.Date getLastLoginTimeEnd() {
return this.lastLoginTimeEnd;
}
public void setLastLoginTimeEnd(java.util.Date value) {
if(value != null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.add(Calendar.DAY_OF_MONTH, 1);
this.lastLoginTimeEnd = calendar.getTime();
}else {
this.lastLoginTimeEnd = value;
}
}
public String getRemark() {
return this.remark;
}
public void setRemark(String value) {
this.remark = value;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String value) {
this.creator = value;
}
public java.util.Date getCreateTimeBegin() {
return this.createTimeBegin;
}
public void setCreateTimeBegin(java.util.Date value) {
this.createTimeBegin = value;
}
public java.util.Date getCreateTimeEnd() {
return this.createTimeEnd;
}
public void setCreateTimeEnd(java.util.Date value) {
if(value != null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.add(Calendar.DAY_OF_MONTH, 1);
this.createTimeEnd = calendar.getTime();
}else {
this.createTimeEnd = value;
}
}
public String getLastModifier() {
return this.lastModifier;
}
public void setLastModifier(String value) {
this.lastModifier = value;
}
public java.util.Date getLastModifyTimeBegin() {
return this.lastModifyTimeBegin;
}
public void setLastModifyTimeBegin(java.util.Date value) {
this.lastModifyTimeBegin = value;
}
public java.util.Date getLastModifyTimeEnd() {
return this.lastModifyTimeEnd;
}
public void setLastModifyTimeEnd(java.util.Date value) {
if(value != null){
Calendar calendar = Calendar.getInstance();
calendar.setTime(value);
calendar.add(Calendar.DAY_OF_MONTH, 1);
this.lastModifyTimeEnd = calendar.getTime();
}else {
this.lastModifyTimeEnd = value;
}
}
public Integer getDeleted() {
return this.deleted;
}
public void setDeleted(Integer value) {
this.deleted = value;
}
public String toString() {
return ToStringBuilder.reflectionToString(this,ToStringStyle.MULTI_LINE_STYLE);
}
}
|
package ru.job4j.array;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* re-sorting program
* @author Aliaksandr Kuzura (vorota-24@bk.ru)
* @version $Id$
* @since 0.1
*/
public class BubbleSortTest {
/**
* compares an array with a sorted array
*/
@Test
public void whenSortArrayWithTenElementsThenSortedArray() {
//напишите здесь тест, проверяющий сортировку массива из 10 элементов методом пузырька, например {1, 5, 4, 2, 3, 1, 7, 8, 0, 5}.
BubbleSort bubbleSort = new BubbleSort();
int[] input = new int[] {5, 1, 2, 7, 3, 6, 4, 10, 8, 9};
int[] result = bubbleSort.sort(input);
int[] expected = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
assertThat(result, is(expected));
}
} |
package com.example.hante.newprojectsum.tablelayout.fragment;
import android.os.Bundle;
import com.example.hante.newprojectsum.R;
import com.example.hante.newprojectsum.tablelayout.LazyFragment;
/**
* Created by handan on 2016/10/25.
*/
public class EFragment extends LazyFragment {
public static final String INTENT_INT_INDEX="index";
public static EFragment newInstance(int tabIndex,boolean isLazyLoad) {
Bundle args = new Bundle();
args.putInt(INTENT_INT_INDEX, tabIndex);
args.putBoolean(LazyFragment.INTENT_BOOLEAN_LAZYLOAD, isLazyLoad);
EFragment fragment = new EFragment();
fragment.setArguments(args);
return fragment;
}
@Override
protected void onCreateViewLazy(Bundle savedInstanceState) {
super.onCreateViewLazy(savedInstanceState);
setContentView(R.layout.fragment_e);
}
}
|
package com.mycontacts.localstorage;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.mycontacts.model.M_Contact1;
import java.util.ArrayList;
public class LocalStorageHandler extends SQLiteOpenHelper {
//Table Fields
public static final String ID = "id";
public static final String CONTACT_ID = "contact_id";
public static final String CONTACT_NAME = "contact_name";
public static final String CONTACT_NUMBER = "contact_number";
public static final String CONTACT_IMAGE = "contact_image";
public static final String CONTACT_STATUS = "contact_status";
private static final String TAG = LocalStorageHandler.class.getSimpleName();
private static final String DATABASE_NAME = "contact.db";
private static final int DATABASE_VERSION = 1;
private static final String DB_TABLE_NAME_CONTACT = "contact_details";
// create table
String CREATE_TABLE_CONTACT = "CREATE TABLE " + DB_TABLE_NAME_CONTACT + "( "
+ ID + " INTEGER PRIMARY KEY,"
+ CONTACT_ID + " TEXT,"
+ CONTACT_NAME + " TEXT,"
+ CONTACT_NUMBER + " TEXT,"
+ CONTACT_IMAGE + " TEXT,"
+ CONTACT_STATUS + " TEXT )";
public LocalStorageHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_CONTACT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade DB " + oldVersion + " older version:" + newVersion
+ "; new version");
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME_CONTACT);
onCreate(db);
}
//add data
public void addContacts(M_Contact1 mContact) {
try {
long rows = 0;
SQLiteDatabase conDB = this.getWritableDatabase();
ContentValues expValues = new ContentValues();
expValues.put(CONTACT_ID, mContact.getContact_ID());
expValues.put(CONTACT_NAME, mContact.getContact_Name());
expValues.put(CONTACT_NUMBER, mContact.getContact_Number());
expValues.put(CONTACT_IMAGE, mContact.getContact_Image_uri());
expValues.put(CONTACT_STATUS, mContact.getContact_Status());
conDB.insert(DB_TABLE_NAME_CONTACT, null, expValues);
conDB.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//get all data
public ArrayList<M_Contact1> getAllContacts() {
SQLiteDatabase conDB = this.getReadableDatabase();
ArrayList<M_Contact1> contactList = null;
try {
contactList = new ArrayList<>();
String QUERY = "SELECT * FROM " + DB_TABLE_NAME_CONTACT;
Cursor cursor = conDB.rawQuery(QUERY, null);
if (!cursor.isLast()) {
while (cursor.moveToNext()) {
M_Contact1 mContact = new M_Contact1();
mContact.setID(cursor.getInt(0));
mContact.setContact_ID(cursor.getString(1));
mContact.setContact_Name(cursor.getString(2));
mContact.setContact_Number(cursor.getString(3));
mContact.setContact_Image_uri(cursor.getString(4));
mContact.setContact_Status(cursor.getString(5));
contactList.add(mContact);
}
}
conDB.close();
} catch (Exception e) {
Log.e("error", e + "");
}
return contactList;
}
// update table data
public boolean updateData(String contact_Id, String contact_name, String contactNumber, String imagePath, String status) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(CONTACT_ID, contact_Id);
contentValues.put(CONTACT_NAME, contact_name);
contentValues.put(CONTACT_NUMBER, contactNumber);
contentValues.put(CONTACT_IMAGE, imagePath);
contentValues.put(CONTACT_STATUS, status);
db.insert(DB_TABLE_NAME_CONTACT, null, contentValues);
return true;
}
// Re-Create table
public void createContact() {
try {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(CREATE_TABLE_CONTACT);
db.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
// delete table
public void deleteContact() {
try {
SQLiteDatabase db = this.getWritableDatabase();
//delete all rows in a table
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE_NAME_CONTACT);
db.close();
createContact();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
import static org.junit.Assert.*;
import java.util.Iterator;
import org.junit.Before;
import org.junit.Test;
public class StackImplTest {
private StackImpl<Student> studentRecords;
@Before
public void setUp() throws Exception {
studentRecords = new StackImpl<Student>();
}
/**
* Should be able push into the empty stack
*/
@Test
public void shouldBeAbleToPushIntoTheEmptyStack() {
studentRecords.push(new Student("leela", "thati"));
studentRecords.push(new Student("sahiti", "thati"));
studentRecords.push(new Student("virat", "k"));
}
/**
* if the stack is empty , pop should throw exception
*/
@Test
public void popShouldThrowExceptionWhenStackIsEmpty()
{
try
{
studentRecords.pop();
}
catch(StackOrQueueException e)
{
return;
}
assertFalse(true);
}
/**
* when stack is not empty should return the newly inserted element
*/
@Test
public void popShouldReturnNewlyInsertedElement()
{
studentRecords.push(new Student("leela", "thati"));
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
assertEquals(virat, studentRecords.pop());
assertEquals(sahiti, studentRecords.pop());
}
/**
* pop Should ThrowException Only After Stack Has Become Empty
*/
@Test
public void popShouldThrowExceptionOnlyAfterStackHasBecomeEmpty()
{
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
assertEquals(virat, studentRecords.pop());
assertEquals(sahiti, studentRecords.pop());
try
{
studentRecords.pop();
}
catch(StackOrQueueException e)
{
return;
}
assertFalse(true);
}
/**
* Insert elements into a stack after pop
*/
@Test
public void shouldBeAbleToInsertElementsIntoTheStack()
{
studentRecords.push(new Student("leela", "thati"));
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
assertEquals(virat, studentRecords.pop());
assertEquals(sahiti, studentRecords.pop());
studentRecords.push(virat);
assertEquals(virat, studentRecords.pop());
}
/**
* If the stack is empty top should return exception
*/
@Test
public void topShouldThrowExceptionWhenStackIsEmpty()
{
try
{
studentRecords.top();
}
catch(StackOrQueueException e)
{
return;
}
assertFalse(true);
}
/**
* if the stack is not empty should return the top element but shouldn't remove it
*/
@Test
public void topShouldReturnTheTopElementInTheStack()
{
studentRecords.push(new Student("leela", "thati"));
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
assertEquals(virat, studentRecords.top());
assertEquals(virat, studentRecords.top());
}
/**
* If the stack is empty isEmpty Should Return true
*/
@Test
public void shouldReturnTrueIfStackIsEmpty()
{
assertTrue(studentRecords.isEmpty());
}
/**
* If the stack is not empty isEmpty Should Return false
*/
@Test
public void shouldReturnFalseIfStackIsNotEmpty()
{
studentRecords.push(new Student("leela", "thati"));
assertFalse(studentRecords.isEmpty());
}
/**
* Should be able to iterate through the stack
*/
@Test
public void shouldBeAbleToIterateThroughTheStack() {
Student leela = new Student("leela", "thati");
studentRecords.push(leela);
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
Iterator<Student> studentItr = studentRecords.iterator();
if(studentItr.hasNext()) {
Student element = studentItr.next();
assertEquals(virat, element);
}
if(studentItr.hasNext()) {
Student element = studentItr.next();
assertEquals(sahiti, element);
}
if(studentItr.hasNext()) {
Student element = studentItr.next();
assertEquals(leela, element);
}
if(studentItr.hasNext())
{
assertFalse(true);
}
}
/**
* Should be able to iterate through the stack after pop
*/
@Test
public void shouldBeAbleToIterateThroughTheStackAfterPop() {
Student leela = new Student("leela", "thati");
studentRecords.push(leela);
Student sahiti = new Student("sahiti", "thati");
studentRecords.push(sahiti);
Student virat = new Student("virat", "k");
studentRecords.push(virat);
Iterator<Student> studentItrInitial = studentRecords.iterator();
studentRecords.pop();
if(studentItrInitial.hasNext()) {
Student element = studentItrInitial.next();
assertEquals(virat, element);
}
if(studentItrInitial.hasNext()) {
Student element = studentItrInitial.next();
assertEquals(sahiti, element);
}
if(studentItrInitial.hasNext()) {
Student element = studentItrInitial.next();
assertEquals(leela, element);
}
if(studentItrInitial.hasNext())
{
assertFalse(true);
}
Iterator<Student> studentItr = studentRecords.iterator();
if(studentItr.hasNext()) {
Student element = studentItr.next();
assertEquals(sahiti, element);
}
if(studentItr.hasNext()) {
Student element = studentItr.next();
assertEquals(leela, element);
}
if(studentItr.hasNext())
{
assertFalse(true);
}
try
{
studentItr.remove();
}
catch(Exception UnsupportedOperationException)
{
return;
}
assertFalse(true);
}
}
|
package com.heyskill.element_core.net.callback;
public interface IRequest {
void onRequestStart();
void onRequestEnd();
}
|
/**
* @Title: MergeWithBrandsService.java
* @Package com.beike.service.brand
* @Description: 品牌聚合业务逻辑接口
* @author Qingcun Guo guoqingcun@qianpin.com
* @date Aug 29, 2012 10:59:26 AM
* @version V1.0
*/
package com.beike.service.brand;
import com.beike.entity.brand.MergeWithBrands;
/**
* @ClassName: MergeWithBrandsService
* @Description: 品牌聚合业务逻辑接口
* @author Qingcun Guo guoqingcun@qianpin.com
* @date Aug 29, 2012 10:59:26 AM
*
*/
public interface MergeWithBrandsService {
/**
*
* @Title: getMergeWithBrands
* @Description: 根据商品标识获取品牌聚合数据
* @param @param goodsid 商品标识
* @param @return 设定文件
* @return MergeWithBrands 返回类型
* @throws
*/
public MergeWithBrands getMergeWithBrands(Long goodsid)throws Exception;
public MergeWithBrands getMergeWithBrands(Long gsid, Long serialnum,String tpbbk, String zbqgg)throws Exception;
}
|
package com.ykl.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ykl.entity.EasybuyProduct;
import com.ykl.pojo.RespBean;
import com.ykl.service.EasybuyProductCategoryService;
import com.ykl.service.EasybuyProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Api(tags = "EasybuyProductController")
@RequestMapping(value = "EasybuyProduct")
@RestController
/*跨域*/
@CrossOrigin
public class EasybuyProductController {
@Autowired
private EasybuyProductService easybuyProductService;
private EasybuyProductCategoryService easybuyProductCategoryService;
@ApiOperation(value = "查询全部方法")
@GetMapping(value = "/findByid")
public RespBean findByid(@RequestParam(value = "id")Integer id){
EasybuyProduct findByid = easybuyProductService.findByid(id);
return RespBean.success("查询成功",findByid);
}
@ApiOperation(value = "搜索")
@GetMapping(value = "/secrchname")
public RespBean secrchname(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "name")String name){
PageHelper.startPage(pageNum,5);
List<EasybuyProduct> secrchname = easybuyProductService.secrchname(name);
PageInfo<EasybuyProduct> searchList = new PageInfo<EasybuyProduct>(secrchname);
return RespBean.success("查询成功",searchList);
}
@ApiOperation(value = "搜索")
@GetMapping(value = "/findall")
public RespBean findall(@RequestParam(value = "pageNum",defaultValue = "1") int pageNum){
PageHelper.startPage(pageNum,5);
List<EasybuyProduct> findall = easybuyProductService.findall();
PageInfo<EasybuyProduct> findalllist = new PageInfo<EasybuyProduct>(findall);
return RespBean.success("查询成功",findalllist);
}
}
|
package com.mountblue.kbrshoppingsite.service;
import com.mountblue.kbrshoppingsite.model.Product;
import com.mountblue.kbrshoppingsite.model.ProductImage;
import com.mountblue.kbrshoppingsite.repository.ProductImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.IOException;
@Service
public class ProductImageService {
@Autowired
private ProductImageRepository productImageRepository;
public ProductImage storeFile(MultipartFile file) throws Exception {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if (fileName.contains("..")) {
throw new FileNotFoundException("Sorry! Filename contains invalid path sequence " + fileName);
}
ProductImage dbFile = new ProductImage(file.getName(), file.getBytes());
return productImageRepository.save(dbFile);
} catch (IOException ex) {
throw new Exception("Could not store file " + fileName + ". Please try again!", ex);
}
}
public ProductImage getFile(int fileId) throws FileNotFoundException {
return productImageRepository.findById(fileId)
.orElseThrow(() -> new FileNotFoundException("File not found with id " + fileId));
}
} |
package com.example.elearning.entities;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
@Getter @Setter @NoArgsConstructor
@Entity
@DiscriminatorValue("A")
public class Apprenant extends Profile {
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Apprenant_has_formation",
joinColumns = { @JoinColumn(name = "idapprenant",referencedColumnName = "id")},
inverseJoinColumns = { @JoinColumn(name = "idformation",referencedColumnName = "idformation") }
)
private List<Formation> formations;
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(
name = "Apprenant_has_module",
joinColumns = { @JoinColumn(name = "idapprenant",referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "idmodule",referencedColumnName = "id") }
)
private List<Module> modules;
public Apprenant(String identifiant, String motdepasse, String nom, String email) {
super(identifiant, motdepasse, nom, email);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.