text stringlengths 10 2.72M |
|---|
/*
* Sonar Timeline plugin
* Copyright (C) 2009 SonarSource
* dev@sonar.codehaus.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.timeline.client;
import org.sonar.wsclient.gwt.AbstractCallback;
import org.sonar.wsclient.gwt.AbstractListCallback;
import org.sonar.wsclient.gwt.Sonar;
import org.sonar.wsclient.services.Event;
import org.sonar.wsclient.services.EventQuery;
import org.sonar.wsclient.services.TimeMachine;
import org.sonar.wsclient.services.TimeMachineQuery;
import java.util.List;
public abstract class TimelineLoader {
private String resourceKey;
private String[] metricsToLoad;
private List<Event> events;
public TimelineLoader(String resourceKey, String[] metrics) {
this.resourceKey = resourceKey;
this.metricsToLoad = metrics;
loadEventsData();
}
private void loadEventsData() {
EventQuery eventQuery = new EventQuery(resourceKey);
Sonar.getInstance().findAll(eventQuery, new AbstractListCallback<Event>() {
@Override
protected void doOnResponse(List<Event> result) {
events = result;
loadTimemachine();
}
@Override
protected void doOnError(int errorCode, String errorMessage) {
noData();
}
@Override
protected void doOnTimeout() {
noData();
}
});
}
private void loadTimemachine() {
TimeMachineQuery query = TimeMachineQuery.createForMetrics(resourceKey, metricsToLoad);
Sonar.getInstance().find(query, new AbstractCallback<TimeMachine>() {
@Override
protected void doOnResponse(TimeMachine timeMachine) {
data(metricsToLoad, timeMachine, events);
}
@Override
protected void doOnError(int errorCode, String errorMessage) {
noData();
}
@Override
protected void doOnTimeout() {
noData();
}
});
}
abstract void data(String[] metrics, TimeMachine timemachine, List<Event> events);
abstract void noData();
}
|
package ru.mse.dataserver;
import java.time.LocalDate;
public class TimetableChangeRequest {
public LocalDate date;
public TimetableChange change;
}
|
import commands.Command;
import commands.CommandParser;
import role.Commander;
import ui.UI;
import java.util.List;
public class App {
public static void main(String[] args) {
UI ui = new UI();
String commandsInString = ui.getCommandsInString();
Commander commander = new Commander();
List<Command> commands = CommandParser.parse(commandsInString);
String positionAndOrientation = commander.send(commands);
ui.print(positionAndOrientation);
}
}
|
package com.tencent.mm.plugin.wallet_ecard.b;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.wallet_ecard.a.a;
import com.tencent.mm.plugin.wallet_ecard.a.b;
import com.tencent.mm.plugin.wallet_ecard.a.c;
import com.tencent.mm.plugin.wallet_ecard.a.d;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.wallet_core.d.g;
import com.tencent.mm.wallet_core.d.i;
import com.tencent.mm.wallet_core.ui.WalletBaseUI;
class b$g extends g {
final /* synthetic */ b pCf;
public b$g(b bVar, MMActivity mMActivity, i iVar) {
this.pCf = bVar;
super(mMActivity, iVar);
}
public final CharSequence ui(int i) {
return this.fEY.getIntent().getStringExtra(a.pBM);
}
public final boolean s(Object... objArr) {
l dVar;
int i = b.s(this.pCf).getInt(a.pBC);
String e = b.e(this.pCf);
x.i("MicroMsg.OpenECardProcess", "bind action: %s", new Object[]{Integer.valueOf(i)});
if (i == a.pBS) {
dVar = new d(b.b(this.pCf), e, b.t(this.pCf).getString(a.pBF), b.u(this.pCf).getString(a.pBG), b.v(this.pCf).getString(a.pBH), b.m(this.pCf), true, true);
} else {
dVar = new d(b.b(this.pCf), e, b.w(this.pCf).getString(a.pBI), b.x(this.pCf).getString(a.pBJ), b.y(this.pCf).getString(a.pBK), b.m(this.pCf), false, true);
}
this.uXK.jr(1985);
this.uXK.a(dVar, true);
return true;
}
public final boolean m(Object... objArr) {
b.z(this.pCf).getString("key_pwd1");
String string = b.A(this.pCf).getString("key_verify_code");
String e = b.e(this.pCf);
int i = b.B(this.pCf).getInt(a.pBy);
c cVar = new c(b.b(this.pCf), e, string, this.fEY.getIntent().getStringExtra(a.pBL), i);
this.uXK.jr(1986);
this.uXK.a(cVar, true, 3);
return true;
}
public final boolean d(int i, int i2, String str, l lVar) {
if (lVar instanceof c) {
this.uXK.js(1986);
c cVar = (c) lVar;
if (i == 0 && i2 == 0) {
if (cVar.pBX.hwV == 0) {
Bundle bundle = new Bundle();
if (!(cVar.pBX.rhf == null || bi.oW(cVar.pBX.rhf.title))) {
x.i("MicroMsg.OpenECardProcess", "succ title: %s", new Object[]{cVar.pBX.rhf.title});
b.C(this.pCf).putString(a.pBR, cVar.pBX.rhf.title);
}
this.pCf.a(this.fEY, 0, bundle);
} else if (!b.a((WalletBaseUI) this.fEY, cVar.pBX.rhe)) {
h.b(this.fEY, b.d(this.fEY, new String[]{cVar.pBX.hwW, str}), "", false);
}
}
return true;
} else if (!(lVar instanceof d)) {
return false;
} else {
this.uXK.js(1985);
d dVar = (d) lVar;
if (i != 0 || i2 != 0) {
x.w("MicroMsg.OpenECardProcess", "net error: %s", new Object[]{dVar});
h.b(this.fEY, b.d(this.fEY, new String[]{str}), "", false);
} else if (dVar.pBY.hwV == 0) {
this.fEY.getIntent().putExtra(a.pBL, dVar.pBY.rhd);
} else if (!(b.a((WalletBaseUI) this.fEY, dVar.pBY.rhe) || b.a((WalletBaseUI) this.fEY, dVar, dVar.hUm, dVar.hUn, dVar.pBY.hwV, dVar.pBY.hwW))) {
h.b(this.fEY, b.d(this.fEY, new String[]{dVar.pBY.hwW, dVar.hUn, str}), "", false);
}
return true;
}
}
public final void onActivityResult(int i, int i2, Intent intent) {
x.i("MicroMsg.OpenECardProcess", "reqCode: %s, resCode: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
this.pCf.b(this.fEY, new Bundle());
super.onActivityResult(i, i2, intent);
}
}
|
package edu.wayne.cs.severe.redress2.entity.refactoring.json;
import java.util.List;
public class OBSERVRefactorings {
private List<OBSERVRefactoring> refactorings;
public List<OBSERVRefactoring> getRefactorings() {
return refactorings;
}
public void setRefactorings(List<OBSERVRefactoring> refactorings) {
this.refactorings = refactorings;
}
@Override
public String toString() {
return "OBSERVRefactorings [refactorings=" + refactorings + "]";
}
}
|
package com.example.manyamadan.medlib;
import android.content.Context;
import android.widget.Toast;
/**
* Created by manyamadan on 03/07/16.
*/
public class MedLib {
private static MedLib ourInstance = new MedLib();
public static MedLib getInstance() {
return ourInstance;
}
private MedLib() {
}
public void showToast(Context context,String data)
{
Toast.makeText(context,"yayyyyy",Toast.LENGTH_LONG).show();
}
}
|
package divideAndconquer;
// https://discuss.leetcode.com/topic/20064/my-concise-o-m-n-java-solution
// https://leetcode.com/problems/search-a-2d-matrix-ii/
public class Search2D {
// start from top right corner
// if target > current_num, then move to next row;
// if target < curretn_num, then move to next column;
// 51.81%
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int r = 0;
int c = matrix[0].length - 1;
while(r < matrix.length && c >= 0) {
if(matrix[r][c]==target) return true;
if(matrix[r][c] > target)
c--;
else r++;
}
return false;
}
public static void main(String[] args) {
int[][] matrix = {{-1, 3}};
Search2D s2d = new Search2D();
System.out.println(s2d.searchMatrix(matrix, 1));
}
}
|
package queue.operations;
public interface QueueOperations {
String enqueue(String arg);
String dequeue();
Boolean isEmpty();
int length();
void listAllElements();
}
|
package com.cristovantamayo.ubsvoce.repositories;
/**
* Repositório para Geocode implementando JpaRepository<Score>.
*/
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.cristovantamayo.ubsvoce.entities.Score;
@Repository
public interface ScoreRepository extends JpaRepository<Score, Long> {
}
|
package org.tec.salsas.CarpoolingREST.services;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import database.Database;
import org.tec.salsas.CarpoolingREST.model.Student;
/**
* Clase encargada de la conexion del servidor con el cliente
* @author Kevin Zeledon
* */
@Path("/signup")
public class signUp {
/**
* Verifica si el correo ya esta registrado
* */
@PUT
@Path("/student")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public HashMap<String,String> isRegistered(HashMap<String,String> dataList) throws Exception {
File prueba = Database.findFile("student", dataList.get("mail"));
HashMap<String,String> result = new HashMap<>();
if(prueba==null) {
result.put("result", "true");
}else {
result.put("result","false");
}
return result;
}
/**
* Registra un nuevo usuario en la base de datos
* @throws Exception
* */
@POST
@Path("/student")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public HashMap<String,String> register(Student newStudent) throws Exception {
System.out.println(newStudent.toString());
newStudent.setRate(5.0);
Database.WriteXML("student", newStudent);
HashMap<String,String> result = new HashMap<>();
result.put("result","true");
return result;
}
} |
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class BOJ_1719_택배 {
private static StringBuilder sb = new StringBuilder();
private static int INF = Integer.MAX_VALUE;
private static int[] parents;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
List<Edge>[] list = new ArrayList[N+1];
for (int i = 1; i <= N; i++) {
list[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int s = Integer.parseInt(st.nextToken());
int e = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
list[s].add(new Edge(e, v));
list[e].add(new Edge(s, v));
}
// 다익스트라를 각 시작위치로부터 N번 돌려야 겟죠?
for (int s = 1; s <= N; s++) {
PriorityQueue<Edge> pq = new PriorityQueue<>();
Edge[] D = new Edge[N+1];
// 시작위치는 0, 나머지는 가중치 최고로
for (int i = 1; i <= N; i++) {
if(i == s) {
D[i] = new Edge(i, 0);
}else {
D[i] = new Edge(i, INF);
}
}
pq.add(D[s]);
// 부모(직전)의 위치를 저장한다
parents = new int[N+1];
// makeSet
for (int i = 0; i <= N; i++) {
makeSet(i);
}
while(!pq.isEmpty()) {
Edge edge = pq.poll();
// 방문 처리
if(D[edge.v].weight != edge.weight) continue;
// 흔한 다익스트라
for (Edge next : list[edge.v]) {
if(D[next.v].weight > D[edge.v].weight + next.weight) {
// 경로 처리, 현재위치의 부모를 저장한다(s가 부모인곳은 그냥 자신이 일단 자기 자신이 부모일 것이다)
if(edge.v!=s) {
parents[next.v] = edge.v;
}
D[next.v].weight = D[edge.v].weight + next.weight;
pq.remove(D[next.v]);
pq.add(D[next.v]);
}
}
}
// 부모의 부모의 부모를 찾는다(root, 정확히는 root 직전값)
for (int i = 1; i <= N; i++) {
if(i==s) {
sb.append("- ");
continue;
}
findSet(i);
sb.append(parents[i] +" ");
}
sb.append("\n");
}
System.out.println(sb);
}
static class Edge implements Comparable<Edge>{
int v, weight;
public Edge(int v, int weight) {
this.v = v;
this.weight = weight;
}
@Override
public int compareTo(Edge o) {
return Integer.compare(this.weight, o.weight);
}
@Override
public String toString() {
return "Edge [" + weight + "]";
}
}
// 세팅
static void makeSet(int x) {
parents[x] =x;
}
static int findSet(int x) {
if(x == parents[x]) // 자기 자신이 부모라면 --> 본인이 팀의 식별자!
return x;
else { // 그게 아니면 다시 탐색한다
parents[x] = findSet(parents[x]);
return parents[x];
}
}
}
|
import java.util.Scanner;
/**
* author : sangeun lee
*/
public class p3 {
public static void main(String[] args) {
System.out.println("What is the quote? ");
String quote = new Scanner(System.in).nextLine();
System.out.println("Who said it? ");
String name = new Scanner(System.in).nextLine();
System.out.println(name + " says," + " \"" + quote + "\"");
}
} |
package com.tencent.mm.pluginsdk.ui;
import android.view.KeyEvent;
import com.tencent.mm.sdk.platformtools.x;
class VoiceInputFooter$5 implements ChatFooterPanel$a {
final /* synthetic */ VoiceInputFooter qHn;
VoiceInputFooter$5(VoiceInputFooter voiceInputFooter) {
this.qHn = voiceInputFooter;
}
public final void bbF() {
}
public final void gp(boolean z) {
}
public final void apK() {
VoiceInputFooter.e(this.qHn).getInputConnection().sendKeyEvent(new KeyEvent(0, 67));
VoiceInputFooter.e(this.qHn).getInputConnection().sendKeyEvent(new KeyEvent(1, 67));
}
public final void append(String str) {
try {
VoiceInputFooter.e(this.qHn).abr(str);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.VoiceInputFooter", e, "", new Object[0]);
}
}
}
|
package com.xuecheng.pojo;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.Date;
@Data
@Document(indexName = "xc_course",type = "doc",shards = 1)
public class Course {
@Id
private Long id;
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
private String name;
@Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_smart")
private String description;
@Field(type = FieldType.Keyword)
private String studymodel;
@Field(type = FieldType.Text,index = false)
private String pic;
@Field(type = FieldType.Float)
private Float price;
@Field(type = FieldType.Date,format = DateFormat.year_month_day)
private Date timestamp;
}
|
package net.minecraft.block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyDirection;
public abstract class BlockDirectional extends Block {
public static final PropertyDirection FACING = PropertyDirection.create("facing");
protected BlockDirectional(Material materialIn) {
super(materialIn);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\BlockDirectional.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ |
// 6번
public class Multiple {
static int MultipleNum(int num1, int num2) {
int result = (int) Math.pow(num1, num2);
System.out.println(result);
return result;
}
public static void main(String[] args) {
MultipleNum(2, 5);
}
}
|
package com.facebook.react.bridge;
public class NativeArgumentsParseException extends JSApplicationCausedNativeException {
public NativeArgumentsParseException(String paramString) {
super(paramString);
}
public NativeArgumentsParseException(String paramString, Throwable paramThrowable) {
super(paramString, paramThrowable);
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\bridge\NativeArgumentsParseException.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.zhy.dagger2.multibindings;
public class MyClassKey {
}
|
package Ex1.SymbolTables;
import ast.AstType;
import ast.VariableIntroduction;
public class VarEntry {
AstType type;
boolean isFormal;
public boolean isFormal() {
return isFormal;
}
public boolean isVarDecl() {
return isVarDecl;
}
public boolean isField() {
return isField;
}
boolean isVarDecl;
boolean isField;
public VarEntry(VariableIntroduction var, String varType){
this.type = var.type();
this.isFormal = varType.equals("formal");
this.isVarDecl = varType.equals("varDecl");
this.isField = varType.equals("field");
}
public AstType type(){
return this.type;
}
}
|
package samples;
import tss.Helpers;
import tss.Tpm;
import tss.TpmFactory;
import tss.Tss;
import tss.tpm.*;
import java.io.Serializable;
public class sample implements Serializable {
private boolean usesTbs;
private Tpm tpm;
private TPMT_PUBLIC aesTemplate;
private byte[] iv;
public static byte[] nullVec = new byte[0];
public sample()
{
usesTbs = CmdLine.isOptionPresent("tbs", "t");
System.out.println("Connecting to " + (usesTbs ? "OS TPM" : "TPM Simulator"));
tpm = usesTbs ? TpmFactory.platformTpm() : TpmFactory.localTpmSimulator();
aesTemplate = new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
new TPMA_OBJECT(TPMA_OBJECT.decrypt, TPMA_OBJECT.sign, TPMA_OBJECT.fixedParent, TPMA_OBJECT.fixedTPM,
TPMA_OBJECT.userWithAuth),
new byte[0],
new TPMS_SYMCIPHER_PARMS(new TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 128, TPM_ALG_ID.CFB)),
new TPM2B_DIGEST_Symcipher());
}
public byte[] encrypt(byte[] toEncrypt, byte[] key){
// The key is passed in in the SENSITIVE_CREATE structure
TPMS_SENSITIVE_CREATE sensCreate = new TPMS_SENSITIVE_CREATE(nullVec, key);
// "Create" they key based on the externally provided keying data
CreatePrimaryResponse aesPrimary = tpm.CreatePrimary(tpm._OwnerHandle, sensCreate, aesTemplate, nullVec,
new TPMS_PCR_SELECTION[0]);
TPM_HANDLE aesHandle = aesPrimary.handle;
iv = new byte[16];
byte[] result = tpm.EncryptDecrypt(aesHandle, (byte) 0, TPM_ALG_ID.CFB, iv, toEncrypt).outData;
tpm.FlushContext(aesHandle);
return result;
}
public byte[] decrypt(byte[] encrypted, byte[] key){
System.out.println(Helpers.toHex(key));
TPMS_SENSITIVE_CREATE sensCreate = new TPMS_SENSITIVE_CREATE(nullVec, key);
CreatePrimaryResponse aesPrimary = tpm.CreatePrimary(tpm._OwnerHandle, sensCreate, aesTemplate, nullVec,
new TPMS_PCR_SELECTION[0]);
TPM_HANDLE aesHandle = aesPrimary.handle;
byte[] result = tpm.EncryptDecrypt(aesHandle, (byte) 1, TPM_ALG_ID.CFB, iv,
encrypted).outData;
tpm.FlushContext(aesHandle);
return result;
}
public byte[] getIV(){
return iv;
}
public void setIV(byte[] iv){
this.iv = iv;
}
public String hmac(TPM_ALG_ID hashAlg, byte[] toHash, byte[] key) {
// TPM HMAC needs a key loaded into the TPM.
// Key and data to be HMACd
TPMT_PUBLIC hmacTemplate = new TPMT_PUBLIC(hashAlg,
new TPMA_OBJECT(TPMA_OBJECT.sign, TPMA_OBJECT.fixedParent, TPMA_OBJECT.fixedTPM, TPMA_OBJECT.userWithAuth),
new byte[0], new TPMS_KEYEDHASH_PARMS(new TPMS_SCHEME_HMAC(hashAlg)),
new TPM2B_DIGEST_Keyedhash(new byte[0]));
// The key is passed in in the SENSITIVE_CREATE structure
TPMS_SENSITIVE_CREATE sensCreate = new TPMS_SENSITIVE_CREATE(nullVec, key);
// "Create" they key based on the externally provided keying data
CreatePrimaryResponse hmacPrimary = tpm.CreatePrimary(tpm._OwnerHandle, sensCreate, hmacTemplate, nullVec,
new TPMS_PCR_SELECTION[0]);
TPM_HANDLE keyHandle = hmacPrimary.handle;
// There are three ways for the TPM to HMAC. The HMAC command, an HMAC
// sequence, or TPM2_Sign()
byte[] hmac1 = tpm.HMAC(keyHandle, toHash, hashAlg);
tpm.FlushContext (keyHandle);
return toHex2(hmac1);
}
void write(String s) {
System.out.println(s);
}
public static String toHex2(byte[] x)
{
StringBuilder sb = new StringBuilder(x.length * 2);
for (byte b: x)
sb.append(String.format("%02x", b));
return sb.toString();
}
Tss.ActivationCredential bundle;
CreatePrimaryResponse rsaEk;
public void ek(byte[] activationData) {
// Note: this sample allows userWithAuth - a "standard" EK does not (see
// the other EK sample)
rsaEk = tpm.CreatePrimary(TPM_HANDLE.from(TPM_RH.OWNER),
new TPMS_SENSITIVE_CREATE(), new TPMT_PUBLIC(TPM_ALG_ID.SHA256,
new TPMA_OBJECT(TPMA_OBJECT.fixedTPM, TPMA_OBJECT.fixedParent, TPMA_OBJECT.sensitiveDataOrigin,
TPMA_OBJECT.userWithAuth,
/* TPMA_OBJECT.adminWithPolicy, */ TPMA_OBJECT.restricted, TPMA_OBJECT.decrypt),
new byte[] { (byte) 0x83, 0x71, (byte) 0x97, 0x67, 0x44, (byte) 0x84, (byte) 0xb3,
(byte) 0xf8, 0x1a, (byte) 0x90, (byte) 0xcc, (byte) 0x8d, 0x46, (byte) 0xa5, (byte) 0xd7, 0x24,
(byte) 0xfd, 0x52, (byte) 0xd7, 0x6e, 0x06, 0x52, 0x0b, 0x64, (byte) 0xf2, (byte) 0xa1, (byte) 0xda,
0x1b, 0x33, 0x14, 0x69, (byte) 0xaa },
new TPMS_RSA_PARMS(new TPMT_SYM_DEF_OBJECT(TPM_ALG_ID.AES, 128, TPM_ALG_ID.CFB),
new TPMS_NULL_ASYM_SCHEME(), 2048, 0),
new TPM2B_PUBLIC_KEY_RSA()), new byte[0], new TPMS_PCR_SELECTION[0]);
// Use tss.java to create an activation credential
bundle = Tss.createActivationCredential(rsaEk.outPublic,
rsaEk.name, activationData);
byte[] recoveredSecret = tpm.ActivateCredential(rsaEk.handle, rsaEk.handle, bundle.CredentialBlob, bundle.Secret);
byte[] recoveredSecret2 = tpm.ActivateCredential(rsaEk.handle, rsaEk.handle, bundle.CredentialBlob, bundle.Secret);
System.out.println("Activation in: " + Helpers.toHex(activationData));
System.out.println("Activation recovered: " + Helpers.toHex(recoveredSecret));
System.out.println("Activation recovered: " + Helpers.toHex(recoveredSecret2));
return;
}
public byte[] getKey(){
return tpm.ActivateCredential(rsaEk.handle, rsaEk.handle, bundle.CredentialBlob, bundle.Secret);
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.Facility;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.MedicalTransaction;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.TransactionType;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.Users;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_repository.FacilityRepository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_repository.MedicalTransactionRepository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_repository.TransactionTypeRepository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_repository.UserRepository;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service_interface.MedicalTransactionInterface;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service_interface.RunTrackerServiceInterface;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.exception.ResourceNotFoundException;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.logger.MedicalTrxLogger;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.message.LoggerMessage;
@Service
public class MedicalTransactionService implements MedicalTransactionInterface {
private static final Logger LOGGER = LoggerFactory.getLogger(RunTrackerServiceInterface.class);
@Autowired
private MedicalTransactionRepository medicalTransactionRepository;
@Autowired
private FacilityRepository facilityRepository;
@Autowired
private TransactionTypeRepository transactionTypeRepository;
@Autowired
private UserRepository usersRepository;
// returns the Medical transactions in a list
@Override
@Cacheable(value = "medicalTrasactionList")
public List<MedicalTransaction> findAllMedicalTransactionInformation() {
List<MedicalTransaction> medicalTrxList = medicalTransactionRepository.findAll();
if (medicalTrxList.isEmpty() || medicalTrxList.size() == 0) {
LOGGER.warn(LoggerMessage.GET_ALL_MEDICAL_TRX_ERROR_MESSAGE);
}
else {
LOGGER.info(LoggerMessage.GET_ALL_MEDICAL_TRX_INFO_MESSAGE);
}
return medicalTransactionRepository.findAll();
}
// based on the pathvariable thrown, this returns the Medical Transaction object that has the corresponding ID
@Override
@Cacheable(value = "medicaTrasactionById", key = "#medicalTransactionId")
public ResponseEntity<MedicalTransaction> findMedicalTransactionInformationById(@PathVariable Long medicalTransactionId) throws ResourceNotFoundException {
MedicalTransaction medicalTransaction = medicalTransactionRepository.findById(medicalTransactionId)
.orElseThrow(() -> new ResourceNotFoundException("Not Found"));
if (medicalTransactionId == null || medicalTransactionId == 0) {
LOGGER.error(LoggerMessage.GET_MEDICAL_TRX_BY_ID_ERROR_MESSAGE + ": " + medicalTransactionId);
}
else {
LOGGER.info(LoggerMessage.GET_MEDICAL_TRX_BY_ID_INFO_MESSAGE);
}
return ResponseEntity.ok().body(medicalTransaction);
}
// creates an MedicalTransaction object based off the fields that are filled.
@Override
@CachePut(value = "medicalTrasactionList")
public MedicalTransaction addMedicalTransactionInformation(@Valid @RequestBody MedicalTransaction medicalTransaction) throws ResourceNotFoundException {
if (medicalTransaction == null) {
LOGGER.warn(LoggerMessage.ADD_MEDICAL_TRX_ERROR_MESSAGE);
}
else {
LOGGER.info(LoggerMessage.ADD_MEDICAL_TRX_INFORMATION_INFO_MESSAGE + ": " + medicalTransaction.amount + " " + medicalTransaction.medical_transaction_date);
}
String medicalTRansactionDate = medicalTransaction.medical_transaction_date;
double amount = medicalTransaction.amount;
Facility facility = facilityRepository.findById((int) medicalTransaction.getUser().getUserid())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find"));
Users user = usersRepository.findById(medicalTransaction.getUser().getUserid())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find"));
TransactionType transactionType = transactionTypeRepository.findById(medicalTransaction.getTransactionType().getTransactionTypeId())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find"));
MedicalTransaction newMedicalTrx = new MedicalTransaction(medicalTRansactionDate,amount,facility,transactionType,user);
return medicalTransactionRepository.save(newMedicalTrx);
}
// updates the MedicalTransaction based on the id number entered. Once the fields are updated, then a new Auto
// Transaction object is created.
@Override
public ResponseEntity<MedicalTransaction> updateMedicalTransaction(@PathVariable Long medicalTransactionId,
@Valid @RequestBody MedicalTransaction medicalTransactionDetails) {
MedicalTransaction medicalTransaction = null;
try {
medicalTransaction = medicalTransactionRepository.findById(medicalTransactionId)
.orElseThrow(() -> new ResourceNotFoundException("Not Found"));
if (medicalTransactionId == null || medicalTransactionId == 0) {
LOGGER.warn(LoggerMessage.GET_MEDICAL_TRX_BY_ID_ERROR_MESSAGE);;
}
else {
LOGGER.info(LoggerMessage.GET_MEDICAL_TRX_BY_ID_INFO_MESSAGE + ": " + medicalTransactionId);
}
medicalTransaction.setAmount(medicalTransactionDetails.getAmount());
medicalTransaction.setMedicalTransactionDate(medicalTransactionDetails.getMedicalTransactionDate());
medicalTransaction.setFacility(facilityRepository.findById((int) medicalTransaction.getUser().getUserid())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find")));
medicalTransaction.setTransactionType(transactionTypeRepository.findById(medicalTransaction.getTransactionType().getTransactionTypeId())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find")));
medicalTransaction.setUser(usersRepository.findById(medicalTransaction.getUser().getUserid())
.orElseThrow(() -> new ResourceNotFoundException("Cannot find")));
MedicalTrxLogger.medicalTrxLogger.info("Currently updating medical transcation information for ID");
}
catch (ResourceNotFoundException e) {
e.printStackTrace();
}
final MedicalTransaction updatedMedicalTransaction = medicalTransactionRepository.save(medicalTransaction);
LOGGER.info(LoggerMessage.UPDATE_AUTO_TRX_INFO_MESSAGE + updatedMedicalTransaction.amount + updatedMedicalTransaction.medical_transaction_date);
return ResponseEntity.ok().body(updatedMedicalTransaction);
}
@Override
@CachePut(value = "medicalTrasactionList")
public Map<String,Boolean> deleteMedicalTraansactionInformation(@PathVariable Long medicalTransactionId) {
medicalTransactionRepository.deleteById(medicalTransactionId);
if (medicalTransactionId == null || medicalTransactionId == 0) {
LOGGER.warn(LoggerMessage.DELETE_MEDICAL_TRX_ERROR_MESSAGE);
}
else {
LOGGER.info(LoggerMessage.DELETE_MEDICAL_TRX_INFORMATION_INFO_MESSAGE + ": " + medicalTransactionId);
}
Map<String,Boolean> response = new HashMap<>();
response.put("Medical Transaction deleted", Boolean.TRUE);
return response;
}
@Override
public long getCountOfMedicalTransactions() {
return medicalTransactionRepository.count();
}
}
|
/*
* Copyright (C) 2020-2023 Hedera Hashgraph, LLC
*
* 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.hedera.mirror.monitor.publish.transaction.token;
import com.hedera.hashgraph.sdk.AccountId;
import com.hedera.hashgraph.sdk.Hbar;
import com.hedera.hashgraph.sdk.PublicKey;
import com.hedera.hashgraph.sdk.TokenId;
import com.hedera.hashgraph.sdk.TokenUpdateTransaction;
import com.hedera.mirror.monitor.publish.transaction.AdminKeyable;
import com.hedera.mirror.monitor.publish.transaction.TransactionSupplier;
import com.hedera.mirror.monitor.util.Utility;
import jakarta.validation.constraints.Future;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.time.Instant;
import lombok.Data;
import org.hibernate.validator.constraints.time.DurationMin;
@Data
public class TokenUpdateTransactionSupplier implements TransactionSupplier<TokenUpdateTransaction>, AdminKeyable {
private String adminKey;
@NotNull
@DurationMin(seconds = 1)
private Duration autoRenewPeriod = Duration.ofSeconds(8000000);
@Future
private Instant expirationTime;
@Min(1)
private long maxTransactionFee = 1_000_000_000;
@NotBlank()
private String symbol = "HMNT";
@NotBlank
private String tokenId;
private String treasuryAccountId;
@Override
public TokenUpdateTransaction get() {
TokenUpdateTransaction tokenUpdateTransaction = new TokenUpdateTransaction()
.setMaxTransactionFee(Hbar.fromTinybars(maxTransactionFee))
.setTokenMemo(Utility.getMemo("Mirror node updated test token"))
.setTokenName(symbol + "_name")
.setTokenSymbol(symbol)
.setTokenId(TokenId.fromString(tokenId));
if (adminKey != null) {
PublicKey key = PublicKey.fromString(adminKey);
tokenUpdateTransaction
.setAdminKey(key)
.setFeeScheduleKey(key)
.setFreezeKey(key)
.setKycKey(key)
.setSupplyKey(key)
.setWipeKey(key);
}
if (treasuryAccountId != null) {
AccountId treastury = AccountId.fromString(treasuryAccountId);
tokenUpdateTransaction.setAutoRenewAccountId(treastury).setTreasuryAccountId(treastury);
}
if (expirationTime != null) {
tokenUpdateTransaction.setExpirationTime(expirationTime);
} else {
tokenUpdateTransaction.setAutoRenewPeriod(autoRenewPeriod);
}
return tokenUpdateTransaction;
}
}
|
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class ControllerDate1
{
@FXML TextField date1, date2;
@FXML ListView<String> lv = new ListView();
public void showw(ActionEvent event)
{
try
{
Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
DateFormat format = new SimpleDateFormat("yyyy-mm-dd", Locale.ENGLISH);
Date datee = format.parse(date1.getText());
Date dateee = format.parse(date2.getText());
Query qry = session.createQuery("SELECT e.date, p.fname, p.mname, p.lname FROM Deliveries e inner join Providers p on e.providerid=p.id where e.date between :datee and :dateee");
qry.setParameter("datee", datee);
qry.setParameter("dateee", dateee);
List<Object[]> r = qry.getResultList();
ObservableList l = FXCollections.observableArrayList();
for(Object[] elements: r)
{
String a,b,c;
Timestamp d= (Timestamp) elements[0];
Date d1=format.parse(String.valueOf(d)); l.add("Date: "+d1);
a= (String) elements[1]; l.add("First name: "+a);
b= (String) elements[2]; l.add("Middle name: "+b);
c= (String) elements[3]; l.add("Last name: "+c);
String str=" "; l.add(str);
}
lv.setItems(l);
}
catch (Exception e) { e.printStackTrace(); }
}
}
|
/**
* ====================================================================
* Codificacion {@code application-www-www-form-urlencoded}.
* Los valores son codificados en tuplas de valores llaves separados
* por '&', con un '=' entre la llave y el valor.
* ====================================================================
*/
package restlight;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import restlight.io.IOUtils;
public class FormBody extends RequestBody {
protected final List<String> keys = new ArrayList<String>();
protected final List<Object> values = new ArrayList<Object>();
public FormBody() {
}
public FormBody(Map<String, Object> map) {
addMap(map);
}
/**
* @param charset
* @return el tipo de contenido para POST o PUT.
*/
@Override public String contentType(Charset charset) {
return "application/x-www-form-urlencoded; charset=" + charset.name();
}
@Override public long contentLength(Charset charset) throws IOException {
ByteArrayOutputStream baos = null;
try {
baos = IOUtils.arrayOutputStream();
writeTo(baos, charset);
return baos.size();
} finally {
IOUtils.closeQuietly(baos);
}
}
@Override public void writeTo(OutputStream out, Charset chrst) throws IOException {
for (int i = 0, size = size(); i < size; i++) {
if (i > 0) out.write('&');
out.write(URLEncoder.encode(key(i), chrst.name()).getBytes());
out.write('=');
out.write(URLEncoder.encode(valueStr(i), chrst.name()).getBytes());
}
}
public String encodedUrlParams(Charset chrst) throws IOException {
ByteArrayOutputStream baos = null;
try {
baos = IOUtils.arrayOutputStream();
writeTo(baos, chrst);
return new String(baos.toByteArray(), chrst);
} finally {
IOUtils.closeQuietly(baos);
}
}
public int size() {
return keys.size();
}
public FormBody add(String key, Object value) {
keys.add(key);
values.add(value);
return this;
}
public FormBody addMap(Map<String, Object> map) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
add(entry.getKey(), entry.getValue());
}
return this;
}
public String key(int index) {
return keys.get(index);
}
public Object value(int index) {
return values.get(index);
}
public String valueStr(int index) {
Object value = value(index);
return value == null ? "" : value.toString();
}
@Override public String toString() {
try {
return encodedUrlParams(Request.DEFAULT_ENCODING);
} catch(Exception e) {
return "";
}
}
}
|
package ru.mirea.iis.chat.server.protocol;
/**
* Created by a4 on 2016-04-10.
* Класс сообщения.
*/
public class Message
{
public enum Type // какие типы сообщений будут
{
LOGIN("l"), CHAT("c"), SERVICE("s");
private final String code;
Type(String code)
{
this.code = code;
}
public String getCode()
{
return code;
}
public static Type findType(String code)
{
for (Type type : Type.values())
{
if (type.getCode().equals(code))
return type;
}
return null;
}
}
private final Type type;
private final String content;
// Конструктор класса
public Message(Type type, String content)
{
this.type = type;
this.content = content;
}
public Type getType()
{
return type;
}
public String getContent()
{
return content;
}
}
|
package jsExecutorExample;
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class GenerateReport implements ITestListener {
WebDriver driver=null;
String filepath = "C:\\Users\\Harry\\eclipse-workspace\\JavaPractice\\Screenshot";
@Override
public void onFinish(ITestContext arg0) {
System.out.println("onFinish");
}
@Override
public void onStart(ITestContext arg0) {
System.out.println("onStart"+arg0.getName());
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
System.out.println("onTestFailedButWithinSuccessPercentage");
}
@Override
public void onTestFailure(ITestResult arg0) {
System.out.println("onTestFailure"+arg0.getName());
}
@Override
public void onTestSkipped(ITestResult arg0) {
System.out.println("onTestSkipped");
}
@Override
public void onTestStart(ITestResult arg0) {
System.out.println("onTestStart");
}
@Override
public void onTestSuccess(ITestResult arg0) {
System.out.println("onTestSuccess");
}
}
|
package com.rc.portal.dao;
import java.sql.SQLException;
import java.util.List;
import com.rc.portal.vo.TOrder;
import com.rc.portal.vo.TOrderExample;
public interface TOrderDAO {
int countByExample(TOrderExample example) throws SQLException;
int deleteByExample(TOrderExample example) throws SQLException;
int deleteByPrimaryKey(Long id) throws SQLException;
Long insert(TOrder record) throws SQLException;
Long insertSelective(TOrder record) throws SQLException;
List selectByExample(TOrderExample example) throws SQLException;
TOrder selectByPrimaryKey(Long id) throws SQLException;
int updateByExampleSelective(TOrder record, TOrderExample example) throws SQLException;
int updateByExample(TOrder record, TOrderExample example) throws SQLException;
int updateByPrimaryKeySelective(TOrder record) throws SQLException;
int updateByPrimaryKey(TOrder record) throws SQLException;
}
|
package top.skyzc.juke.model;
import cn.bmob.v3.BmobObject;
public class Upgrade extends BmobObject {
private User nowUser;
private User upUser;
private User myNineUser;
public User getNowUser() {
return nowUser;
}
public void setNowUser(User nowUser) {
this.nowUser = nowUser;
}
public User getMyNineUser() {
return myNineUser;
}
public void setMyNineUser(User myNineUser) {
this.myNineUser = myNineUser;
}
public User getUpUser() {
return upUser;
}
public void setUpUser(User upUser) {
this.upUser = upUser;
}
}
|
/*
* 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 Dao;
import Entidades.entEvaluador;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author rosemary
*/
public class EvaluadorDAO {
public static List<entEvaluador> Listar(boolean activo) throws Exception
{
List<entEvaluador> lista = null;
Connection conn =null;
CallableStatement stmt = null;
ResultSet dr = null;
try {
String sql="select id_evaluador,nombre,apellido,codigo_erp,estado,usuario_responsable,fecha_modificacion"
+ " from evaluador ";
if(activo)
sql+=" where estado=1";
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
dr = stmt.executeQuery();
while(dr.next())
{
if(lista==null)
lista= new ArrayList<entEvaluador>();
entEvaluador entidad = new entEvaluador();
entidad.setId_evaluador(dr.getInt(1));
entidad.setNombre(dr.getString(2));
entidad.setApellido(dr.getString(3));
entidad.setCodigo_erp(dr.getString(4));
entidad.setEstado(dr.getBoolean(5));
entidad.setUsuario_responsable(dr.getString(6));
entidad.setFecha_modificacion(dr.getTimestamp(7));
lista.add(entidad);
}
} catch (Exception e) {
throw new Exception("Listar "+e.getMessage(), e);
}
finally{
try {
dr.close();
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return lista;
}
public static int insertar(entEvaluador entidad) throws Exception
{
int rpta = 0;
Connection conn =null;
PreparedStatement stmt = null;
try {
String sql="INSERT INTO evaluador(nombre,apellido,codigo_erp,estado,usuario_responsable,fecha_modificacion)"
+ " VALUES(?,?,?,?,?,GETDATE());";
conn = ConexionDAO.getConnection();
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, entidad.getNombre());
stmt.setString(2, entidad.getApellido());
stmt.setString(3, entidad.getCodigo_erp());
stmt.setBoolean(4, entidad.getEstado());
stmt.setString(5, entidad.getUsuario_responsable());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()){
rpta=rs.getInt(1);
}
rs.close();
} catch (Exception e) {
throw new Exception("Insertar"+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
public static boolean actualizar(entEvaluador entidad) throws Exception
{
boolean rpta = false;
Connection conn =null;
CallableStatement stmt = null;
try {
String sql="UPDATE evaluador SET nombre = ?,apellido= ?,codigo_erp=?,estado= ?,"
+ "usuario_responsable = ?,fecha_modificacion = GETDATE() WHERE id_evaluador = ?;";
conn = ConexionDAO.getConnection();
stmt = conn.prepareCall(sql);
stmt.setString(1, entidad.getNombre());
stmt.setString(2, entidad.getApellido());
stmt.setString(3, entidad.getCodigo_erp());
stmt.setBoolean(4, entidad.getEstado());
stmt.setString(5, entidad.getUsuario_responsable());
stmt.setInt(6,entidad.getId_evaluador());
rpta = stmt.executeUpdate() == 1;
} catch (Exception e) {
throw new Exception("Error Actualizar "+e.getMessage(), e);
}
finally{
try {
stmt.close();
conn.close();
} catch (SQLException e) {
}
}
return rpta;
}
}
|
package com.tencent.mm.console;
import android.content.Intent;
import com.tencent.mm.console.Shell.a;
import com.tencent.mm.g.a.ig;
import com.tencent.mm.sdk.platformtools.x;
class Shell$11 implements a {
Shell$11() {
}
public final void n(Intent intent) {
ig igVar = new ig();
igVar.bRH.bRM = intent.getExtras().getString("path", "/data/local/tmp/test.apk");
x.w("MicroMsg.Shell", "hotpatch test [%s]", new Object[]{igVar.bRH.bRM});
com.tencent.mm.sdk.b.a.sFg.m(igVar);
}
}
|
package com.smxknife.spring.ignoredependency.type;
/**
* @author smxknife
* 2020/2/5
*/
public class IgnoreTypeImpl implements IgnoreType {
}
|
class Solution {
public List<String> findMissingRanges(int[] nums, int lower, int upper) {
/*
1. compare the lower with the nums[0]
2. compare inside nums
3. compare the upper with the nums
**/
List<String> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
res.add(buildRange(lower, upper));
return res;
}
if (lower < nums[0]) {
res.add(buildRange(lower, nums[0] - 1));
}
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i + 1] != nums[i] && nums[i + 1] > nums[i] + 1)
res.add(buildRange(nums[i] + 1, nums[i + 1] - 1));
}
if (nums[nums.length - 1] < upper) {
res.add(buildRange(nums[nums.length - 1] + 1, upper));
}
return res;
}
private String buildRange(int low, int high) {
return low == high ? String.valueOf(low) : (low + "->" + high);
}
} |
/*
* Created on Mar 18, 2009
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package it.usi.xframe.xas.bfutil.data;
/**
* @author us01170
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class FileEmailAttachment extends AbstractEmailAttachment {
private String filePath;
public FileEmailAttachment() {
}
public FileEmailAttachment(
String fileDescription,
String mimeType,
String filePath) {
super(fileDescription, mimeType);
this.filePath = filePath;
}
/**
* @return
*/
public String getFilePath() {
return filePath;
}
/**
* @param string
*/
public void setFilePath(String string) {
filePath = string;
}
/**
* @see it.usi.xframe.jgh.bfutil.data.AbstractEmailAttachment#apply(it.usi.xframe.jgh.bfutil.data.EmailAttachmentVisitor)
*/
public void apply(EmailAttachmentVisitor visitor) {
visitor.visit(this);
}
}
|
package com.zhy.android_dagger;
import android.os.Bundle;
import android.util.Log;
import com.zhy.android_dagger.di.UserService;
import javax.inject.Inject;
import dagger.android.support.DaggerAppCompatActivity;
public class MainActivity extends DaggerAppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
@Inject
UserService userService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, userService.getUserName());
}
}
|
package net.chrisrichardson.eventstore.examples.customersandorders.orders.history.querysideservice.main;
import net.chrisrichardson.eventstore.examples.customersandorders.orders.history.querysideservice.OrderHistoryQuerySideServiceConfiguration;
import org.springframework.boot.SpringApplication;
public class OrderHistoryQuerySideService {
public static void main(String[] args) {
SpringApplication.run(OrderHistoryQuerySideServiceConfiguration.class, args);
}
}
|
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NameClass {
private static final String NAME_REGEX = "^[ACP]{1}[0-9]{4}[G, H, I, L, L, M]{1}$";
public NameClass() {
}
public boolean validate(String regex) {
Pattern pattern = Pattern.compile(NAME_REGEX);
Matcher matcher = pattern.matcher(regex);
return matcher.matches();
}
}
|
package Nomina;
/**
* @author Alejandro Erazo
*/
public class Empleado {
// Atributos
private String nombre;
private int cedula;
private String cargo;
private int salario;
// Constructor
public Empleado(String Nombre, int Cedula, String Cargo, int Salario) {
this.nombre = Nombre;
this.cedula = Cedula;
this.cargo = Cargo;
this.salario = Salario;
}
// Get & Set
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void setCedula(int cedula) {
this.cedula = cedula;
}
public void setCargo(String cargo) {
this.cargo = cargo;
}
public void setSalario(int salario) {
this.salario = salario;
}
public String getNombre() {
return nombre;
}
public int getCedula() {
return cedula;
}
public String getCargo() {
return cargo;
}
public int getSalario() {
return salario;
}
}
|
package com.sparknetworks.loveos.application.filtermatches;
import com.sparknetworks.loveos.application.filtermatches.filter.*;
import com.sparknetworks.loveos.domain.Range;
import com.sparknetworks.loveos.domain.UserMatchedFilter;
import java.util.ArrayList;
import java.util.List;
public class UserMatchedFilterBuilder {
private List<UserMatchedFilter> userMatchedFilters;
public UserMatchedFilterBuilder() {
this.userMatchedFilters = new ArrayList<>();
}
public Filters build() {
return new Filters(userMatchedFilters);
}
public UserMatchedFilterBuilder shouldHavePhoto(boolean value) {
if (value) this.userMatchedFilters.add(new HasPhotoFilter());
return this;
}
public UserMatchedFilterBuilder shouldBeFavorited(boolean value) {
if (value) this.userMatchedFilters.add(new FavoritedFilter());
return this;
}
public UserMatchedFilterBuilder shouldHaveExchangedContacts(boolean value) {
if (value) this.userMatchedFilters.add(new ContactsExchangedFilter());
return this;
}
public UserMatchedFilterBuilder shouldHaveCompatibilityScoreRange(Range<Double> compatibilityScoreRange) {
if (compatibilityScoreRange != null) this.userMatchedFilters.add(new CompatibilityScoreFilter(compatibilityScoreRange));
return this;
}
public UserMatchedFilterBuilder shouldBeAgedBetween(Range<Integer> ageRange) {
if (ageRange != null) this.userMatchedFilters.add(new AgeFilter(ageRange));
return this;
}
public UserMatchedFilterBuilder shouldHasAHeightBetween(Range<Integer> heightInCmRange) {
if (heightInCmRange != null) this.userMatchedFilters.add(new HeightFilter(heightInCmRange));
return this;
}
public UserMatchedFilterBuilder distanceInKmFromRelatedProfileCityShouldBeLessThan(Double distanceRadiusInKm) {
if (distanceRadiusInKm != null) this.userMatchedFilters.add(new DistanceRadiusFilter(distanceRadiusInKm));
return this;
}
}
|
package com.example.apoxeo;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
public interface ApiInterface {
@GET("place/nearbysearch/json?location=12.97,77.59&radius=5000&type=hindu_temple&key=AIzaSyAD90QUFl0kvHLyR98BmnivBEz79eGRisc")
Call<ResponseBody> getData();
}
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2016.05.11 um 01:33:35 PM CEST
//
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java-Klasse für IstAnalyseIdentType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="IstAnalyseIdentType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Id" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" minOccurs="0"/>
* <element name="ChargenNr" type="{http://www-fls.thyssen.com/xml/schema/qcs}ChargenNrType"/>
* <element name="Stahlwerk" type="{http://www-fls.thyssen.com/xml/schema/qcs}StahlwerkType"/>
* <element name="DatumAbguss" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "IstAnalyseIdentType", propOrder = {
"id",
"chargenNr",
"stahlwerk",
"datumAbguss"
})
public class IstAnalyseIdentType {
@XmlElement(name = "Id")
@XmlSchemaType(name = "unsignedLong")
protected BigInteger id;
@XmlElement(name = "ChargenNr", required = true)
protected String chargenNr;
@XmlElement(name = "Stahlwerk", required = true)
protected String stahlwerk;
@XmlElement(name = "DatumAbguss", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar datumAbguss;
/**
* Ruft den Wert der id-Eigenschaft ab.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getId() {
return id;
}
/**
* Legt den Wert der id-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setId(BigInteger value) {
this.id = value;
}
/**
* Ruft den Wert der chargenNr-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getChargenNr() {
return chargenNr;
}
/**
* Legt den Wert der chargenNr-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setChargenNr(String value) {
this.chargenNr = value;
}
/**
* Ruft den Wert der stahlwerk-Eigenschaft ab.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStahlwerk() {
return stahlwerk;
}
/**
* Legt den Wert der stahlwerk-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStahlwerk(String value) {
this.stahlwerk = value;
}
/**
* Ruft den Wert der datumAbguss-Eigenschaft ab.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDatumAbguss() {
return datumAbguss;
}
/**
* Legt den Wert der datumAbguss-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDatumAbguss(XMLGregorianCalendar value) {
this.datumAbguss = value;
}
}
|
package org.ms.iknow.persistence.repo.memory;
import org.ms.iknow.core.assertion.ElementValidator;
import org.ms.iknow.core.type.Neuron;
import org.ms.iknow.core.type.Synapse;
import org.ms.iknow.persistence.repo.Repository;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
public class MemoryRepository extends ElementValidator implements Repository {
private static MemoryRepository instance;
// <Name, id>
Map<String, List<IndexEntry>> indexes = new HashMap<String, List<IndexEntry>>();
public Map<String, NeuronEntry> neurons = new HashMap<String, NeuronEntry>();
Map<String, SynapseEntry> synapses = new HashMap<String, SynapseEntry>();
protected MemoryRepository() {
// Exists only to defeat instantiation.
}
public static MemoryRepository getInstance() {
if (instance == null) {
instance = new MemoryRepository();
}
return instance;
}
@Override
public Neuron persist(Neuron neuron) {
checkNotNull("Expected Neuron but was null.", neuron);
addToIndex(neuron.getName(), neuron.getId());
addToNeurons(neuron);
return neuron;
}
@Override
public Synapse persist(Synapse synapse) {
checkNotNull("Expected Synapse but was null.", synapse);
addToIndex(synapse.getParent());
addToIndex(synapse.getChild());
addToNeurons(synapse.getParent());
addToNeurons(synapse.getChild());
addToSynapses(synapse);
return synapse;
}
@Override
public List<Synapse> persist(List<Synapse> synapses) {
for (Synapse synapse : synapses) {
persist(synapse);
}
return synapses;
}
@Override
public List<Neuron> findByName(String name) {
List<Neuron> results = new ArrayList<Neuron>();
List<String> synapseIds = null;
List<Synapse> synapses = null;
List<String> neuronIds = findInIndexes(name);
Neuron child = null;
for (String neuronId : neuronIds) {
Neuron parent = findInNeurons(neuronId);
synapseIds = parent.getSynapseIds();
synapses = findInSynapses(synapseIds);
for (Synapse synapse : synapses) {
child = findInNeurons(synapse.getChildId());
synapse.setParent(parent);
synapse.setChild(child);
parent.addSynapse(synapse);
}
results.add(parent);
}
return results;
}
protected void addToIndex(Neuron neuron) {
addToIndex(neuron.getName(), neuron.getId());
}
protected void addToIndex(String key, String value) {
List<IndexEntry> entries = null;
IndexEntry entry = new IndexEntry();
entry.lock();
entry.setForeignKey(value);
// Key found: entry already existing.
if (indexes.containsKey(key)) {
entries = indexes.get(key);
if (!contains(value, entries)) {
entries.add(entry);
}
}
// Key not found: make a new entry.
else {
entries = new CopyOnWriteArrayList<IndexEntry>();
entries.add(entry);
indexes.put(key, entries);
}
entry.unlock();
}
protected void addToNeurons(Neuron neuron) {
addToNeurons(neuron.getName(), neuron);
}
protected void addToNeurons(String key, Neuron neuron) {
Neuron n = neuron.clone();
NeuronEntry entry = new NeuronEntry();
entry.setNeuron(n);
entry.lock();
this.neurons.put(n.getId(), entry);
entry.unlock();
}
protected void addToSynapses(Synapse synapse) {
Synapse s = synapse.clone();
SynapseEntry entry = new SynapseEntry();
entry.setSynapse(s);
entry.lock();
this.synapses.put(s.getId(), entry);
entry.unlock();
}
/**
* Returns the value (List<String>) of the entry matching key.
*/
protected List<String> findInIndexes(String key) {
List<IndexEntry> indexEntries = indexes.get(key);
List<String> foreignKeys = new ArrayList<String>();
for (IndexEntry indexEntry : indexEntries) {
foreignKeys.add(indexEntry.getForeignKey());
}
return foreignKeys;
}
protected Neuron findInNeurons(String key) {
return neurons.get(key).getNeuron();
}
protected List<Neuron> findInNeurons(List<String> keys) {
List<Neuron> results = new ArrayList<Neuron>();
Neuron clonedNeuron = null;
for (String key : keys) {
NeuronEntry neuronEntry = neurons.get(key);
clonedNeuron = neuronEntry.getNeuron().clone();
results.add(clonedNeuron);
}
return results;
}
protected List<Synapse> findInSynapses(List<String> keys) {
List<Synapse> results = new ArrayList<Synapse>();
Synapse clonedSynapse = null;
for (String key : keys) {
SynapseEntry synapseEntry = synapses.get(key);
clonedSynapse = synapseEntry.getSynapse().clone();
results.add(clonedSynapse);
}
return results;
}
protected Synapse findInSynapses(String key) {
SynapseEntry synapseEntry = synapses.get(key);
return synapseEntry.getSynapse().clone();
}
protected void removeFromIndexes(String key) {
if (indexes.containsKey(key)) {
indexes.remove(key);
}
}
protected void removeFromIndexes(String key, String foreignKey) {
List<IndexEntry> foreignKeys = indexes.get(key);
for (IndexEntry indexEntry : foreignKeys) {
if (indexEntry.getForeignKey().equals(foreignKey)) {
indexEntry.lock();
foreignKeys.remove(indexEntry);
indexEntry.unlock();
}
}
}
protected boolean contains(String value, List<IndexEntry> entries) {
for (IndexEntry indexEntry : entries) {
if (indexEntry.getForeignKey().equals(value)) {
return true;
}
}
return false;
}
@Override
public void deleteAll() {
neurons.clear();
synapses.clear();
indexes.clear();
}
public int getNumberOfNeurons() {
return neurons.size();
}
public int getNumberOfSynapses() {
return synapses.size();
}
public int getNumberOfIndexes() {
return indexes.size();
}
} |
package edu.cecar.controlador;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
* Clase que controla la validacion del email
* por medio de la API email-validator
*
*/
public class ValidarEmail {
public Long validarEmail(String email) {
HttpClient client = new DefaultHttpClient();
String apiKey = "ev-8aaec8ad2b255228dba5750ab63119da";
String apiUrl = "https://api.email-validator.net/api/verify";
try {
HttpPost request = new HttpPost(apiUrl);
List<NameValuePair> Input = new ArrayList<NameValuePair>();
Input.add(new BasicNameValuePair("EmailAddress", email));
Input.add(new BasicNameValuePair("APIKey", apiKey));
request.setEntity(new UrlEncodedFormEntity(Input));
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
String Output = EntityUtils.toString(entity, "UTF-8");
JSONParser parser = new JSONParser();
Object obj = parser.parse(Output);
JSONObject jsonObject = (JSONObject) obj;
Long result = (Long) jsonObject.get("status");
// result 200, 207, 215 - valid
// result 215 - can be retried to update catch-all status
// result 114 - greylisting, wait 5min and retry
// result 118 - api rate limit, wait 5min and retry
// result 3xx/4xx - bad
return result;
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
client.getConnectionManager().shutdown();
}
return null;
}
}
|
package com.tencent.mm.plugin.subapp.c;
import com.tencent.mm.ab.i$b;
import com.tencent.mm.compatible.b.f.a;
import com.tencent.mm.model.au;
import com.tencent.mm.model.q;
import com.tencent.mm.modelvoice.k;
import com.tencent.mm.sdk.f.e;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
public final class i implements com.tencent.mm.ab.i, a {
private static int bFx = 100;
private k bAY = null;
private String fileName = "";
private int hjR = 0;
private long iZe = 0;
private al orA = new al(new 1(this), true);
protected i$b oru;
protected com.tencent.mm.ab.i.a orv = null;
private boolean orw = false;
private a orx;
private long ory = 0;
private int orz = 0;
public final void ew(int i) {
x.d("MicroMsg.VoiceRemindRecorder", " Recorder onBluetoothHeadsetStateChange :" + i);
if (!this.orw) {
this.orw = true;
au.HV().b(this);
this.bAY = new k();
2 2 = new 2(this);
this.orx = new a(this);
e.post(this.orx, "VoiceRemindRecorder_record");
this.orz = 1;
this.orA.J(3000, 3000);
x.d("MicroMsg.VoiceRemindRecorder", "start end time:" + bi.bI(this.ory));
}
}
public final int getMaxAmplitude() {
if (this.bAY == null) {
return 0;
}
int maxAmplitude = this.bAY.getMaxAmplitude();
if (maxAmplitude > bFx) {
bFx = maxAmplitude;
}
x.d("getMaxAmplitude", " map: " + maxAmplitude + " max:" + bFx + " per:" + ((maxAmplitude * 100) / bFx));
return (maxAmplitude * 100) / bFx;
}
public final String getFileName() {
return this.fileName;
}
public final boolean isRecording() {
if (this.bAY != null && this.bAY.mStatus == 1) {
return true;
}
return false;
}
public final boolean dd(String str) {
String nJ = k.nJ(q.GF());
g gVar = new g();
gVar.field_filename = nJ;
gVar.field_user = str;
gVar.field_createtime = System.currentTimeMillis() / 1000;
gVar.field_clientid = nJ;
gVar.field_lastmodifytime = System.currentTimeMillis() / 1000;
gVar.field_status = 1;
gVar.field_human = q.GF();
gVar.bWA = -1;
k bGt = d.bGt();
x.d("MicroMsg.VoiceRemindStorage", "VoiceRemindStorage Insert");
int insert = (int) bGt.diF.insert("VoiceRemindInfo", "", gVar.wH());
x.d("MicroMsg.VoiceRemindStorage", "VoiceRemindStorage Insert result" + insert);
if (insert == -1) {
nJ = null;
}
this.fileName = nJ;
au.HV().a(this);
int yB = au.HV().yB();
this.orw = false;
if (yB != 0) {
ew(100);
} else {
new 3(this).sendEmptyMessageDelayed(0, 50);
}
return false;
}
public final boolean cancel() {
x.d("MicroMsg.VoiceRemindRecorder", "cancel Record :" + this.fileName);
synchronized (this) {
x.d("MicroMsg.VoiceRemindRecorder", "stop synchronized Record :" + this.fileName);
if (this.bAY != null) {
this.bAY.we();
}
}
String str = this.fileName;
if (str != null) {
x.d("MicroMsg.VoiceRemindLogic", "Mark Canceled fileName[" + str + "]");
g Ok = h.Ok(str);
if (Ok != null) {
Ok.field_status = 8;
Ok.field_totallen = c.nM(h.aY(str, false));
Ok.bWA = 64;
h.a(Ok);
}
}
d.bGu().run();
this.fileName = "";
return true;
}
public final boolean wk() {
boolean z = true;
boolean z2 = false;
au.HV().yC();
x.d("MicroMsg.VoiceRemindRecorder", "stop Record :" + this.fileName);
synchronized (this) {
x.d("MicroMsg.VoiceRemindRecorder", "stop synchronized Record :" + this.fileName);
if (this.bAY != null) {
this.bAY.we();
}
}
if (this.orz != 2) {
h.op(this.fileName);
this.fileName = null;
x.d("MicroMsg.VoiceRemindRecorder", "Stop " + this.fileName + " by not onPart: " + bi.bI(this.ory));
} else {
this.hjR = (int) wu();
if (((long) this.hjR) < 800 || ((long) this.hjR) < 1000) {
x.d("MicroMsg.VoiceRemindRecorder", "Stop " + this.fileName + " by voiceLen: " + this.hjR);
h.op(this.fileName);
this.fileName = "";
z = false;
} else {
String str = this.fileName;
int i = this.hjR;
if (str != null) {
x.d("MicroMsg.VoiceRemindLogic", "StopRecord fileName[" + str + "]");
g Ok = h.Ok(str);
if (Ok != null) {
if (!(Ok.field_status == 97 || Ok.field_status == 98)) {
Ok.field_status = 3;
}
Ok.field_totallen = c.nM(h.aY(str, false));
if (Ok.field_totallen <= 0) {
h.nP(str);
} else {
Ok.field_lastmodifytime = System.currentTimeMillis() / 1000;
Ok.field_voicelenght = i;
Ok.bWA = 3424;
bd bdVar = new bd();
bdVar.ep(Ok.field_user);
bdVar.setType(34);
bdVar.eX(1);
bdVar.eq(str);
if (Ok.field_status == 97) {
bdVar.setStatus(2);
bdVar.setContent(f.b(Ok.field_human, (long) Ok.field_voicelenght, false));
} else if (Ok.field_status == 98) {
bdVar.setStatus(5);
bdVar.setContent(f.b(Ok.field_human, -1, true));
} else {
bdVar.setStatus(1);
}
bdVar.ay(com.tencent.mm.model.bd.iD(Ok.field_user));
Ok.field_msglocalid = (int) com.tencent.mm.model.bd.i(bdVar);
h.a(Ok);
}
}
}
d.bGu().run();
x.d("MicroMsg.VoiceRemindRecorder", "Stop file success: " + this.fileName);
}
this.fileName = "";
z2 = z;
}
this.orz = -1;
return z2;
}
public final long wu() {
if (this.iZe <= 0) {
return 0;
}
return bi.bI(this.iZe);
}
public final void reset() {
if (this.bAY != null) {
this.bAY.we();
x.e("MicroMsg.VoiceRemindRecorder", "Reset recorder.stopReocrd");
}
this.fileName = "";
this.ory = 0;
this.orx = null;
this.orz = 0;
this.iZe = 0;
}
public final int wt() {
return this.hjR;
}
public final void a(com.tencent.mm.ab.i.a aVar) {
this.orv = aVar;
}
public final void a(i$b i_b) {
this.oru = i_b;
}
public final int ww() {
return 0;
}
}
|
package com.zhny.gr.wisdomcity.bean;
import java.util.List;
/**
* Created by tong on 2017/5/9.
*/
public class RecordRoot {
private String name;
private String id;
private List<Results> results;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setResults(List<Results> results) {
this.results = results;
}
public List<Results> getResults() {
return results;
}
}
|
package android.support.b;
import com.tencent.smtt.sdk.WebView;
import java.io.FilterOutputStream;
import java.io.OutputStream;
import java.nio.ByteOrder;
class a$b extends FilterOutputStream {
ByteOrder lO;
private final OutputStream lP;
public a$b(OutputStream outputStream, ByteOrder byteOrder) {
super(outputStream);
this.lP = outputStream;
this.lO = byteOrder;
}
public final void write(byte[] bArr) {
this.lP.write(bArr);
}
public final void write(byte[] bArr, int i, int i2) {
this.lP.write(bArr, i, i2);
}
public final void writeByte(int i) {
this.lP.write(i);
}
public final void writeShort(short s) {
if (this.lO == ByteOrder.LITTLE_ENDIAN) {
this.lP.write((s >>> 0) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((s >>> 8) & WebView.NORMAL_MODE_ALPHA);
} else if (this.lO == ByteOrder.BIG_ENDIAN) {
this.lP.write((s >>> 8) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((s >>> 0) & WebView.NORMAL_MODE_ALPHA);
}
}
public final void writeInt(int i) {
if (this.lO == ByteOrder.LITTLE_ENDIAN) {
this.lP.write((i >>> 0) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 8) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 16) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 24) & WebView.NORMAL_MODE_ALPHA);
} else if (this.lO == ByteOrder.BIG_ENDIAN) {
this.lP.write((i >>> 24) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 16) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 8) & WebView.NORMAL_MODE_ALPHA);
this.lP.write((i >>> 0) & WebView.NORMAL_MODE_ALPHA);
}
}
}
|
package v1;
public class AnimalHabitat implements Sqaure {
private String animalName;
private Player owner;
private int numZoos;
private int numNationalParks;
private String biomeColour;
private int investmentCost;
private int fee_normal;
private int fee_monopoly;
private int fee_onehouse;
private int fee_twohouse;
private int fee_threehouse;
private int fee_fourhouse;
private int fee_NationalPark;
private int Zoo_cost;
public AnimalHabitat(String animalName, String biomeColour, int investCost, int f_n, int f_biome, int f_1z, int f_2z, int f_3z, int f_4z, int f_np, int zooCost)
{
this.animalName = animalName;
this.biomeColour = biomeColour;
this.investmentCost = investCost;
this.fee_normal = f_n;
this.fee_monopoly = f_biome;
this.fee_onehouse = f_1z;
this.fee_twohouse = f_2z;
this.fee_threehouse = f_3z;
this.fee_fourhouse = f_4z;
this.fee_NationalPark = f_np;
this.Zoo_cost = zooCost;
}
public String getName()
{
return animalName;
}
public Player getOwner()
{
return owner;
}
@Override
public String getColor() {
// TODO Auto-generated method stub
return biomeColour;
}
@Override
public void addHouse() {
// TODO Auto-generated method stub
}
@Override
public void removeHouse() {
// TODO Auto-generated method stub
}
}
|
package cn.com.zjol.userhome.activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import cn.com.zjol.biz.core.DailyActivity;
import cn.com.zjol.biz.core.nav.Nav;
import cn.com.zjol.userhome.R;
import cn.com.zjol.userhome.bean.UserVideoResponse;
import cn.com.zjol.userhome.callback.OnUserInfoCallback;
import cn.com.zjol.userhome.callback.OnUserNavCallback;
import cn.com.zjol.userhome.fragment.UserHomeFragment;
/**
* 用户主页
* Created by wangzhen on 2019-09-05.
*/
public class UserHomeActivity extends DailyActivity implements OnUserNavCallback, OnUserInfoCallback {
private static final String TAG_USER_HOME = UserHomeFragment.class.getSimpleName();
private Fragment mFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_home);
String account_id = null;
if (getIntent().getData() != null) {
account_id = getIntent().getData().getQueryParameter("id");
}
if (TextUtils.isEmpty(account_id)) {
account_id = getIntent().getStringExtra("id");
}
FragmentManager manager = getSupportFragmentManager();
mFragment = manager.findFragmentByTag(TAG_USER_HOME);
if (mFragment != null) {
manager.beginTransaction().show(mFragment).commit();
} else {
mFragment = new UserHomeFragment();
Bundle bundle = new Bundle();
bundle.putString("account_id", account_id);
mFragment.setArguments(bundle);
manager.beginTransaction().add(R.id.container, mFragment, TAG_USER_HOME).commit();
}
}
@Override
public boolean isShowTopBar() {
return false;
}
@Override
public void onNavBack() {
finish();
}
@Override
public void finish() {
if (getIntent() != null) {
String from = getIntent().getStringExtra("from");
if (TextUtils.equals(from, "PublishActivity")) {
Nav.with(this).toPath("/native/homepage/me");
}
}
super.finish();
}
@Override
public void updateUserInfo(UserVideoResponse.DataBean data) {
if (mFragment instanceof UserHomeFragment) {
((UserHomeFragment) mFragment).updateInfo(data);
}
}
}
|
package servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;
import bean.NoteBean;
import bean.UserBean;
import dao.CollectDao;
import dao.CommentDao;
import dao.LikesDao;
import dao.NoteDao;
import dao.UserDao;
/**
* Servlet implementation class NoteServlet
*/
@WebServlet("/SportNoteServlet")
public class ScienceNoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ScienceNoteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
NoteDao noteDao = new NoteDao();
LikesDao like = new LikesDao();
CollectDao collect = new CollectDao();
CommentDao comment = new CommentDao();
response.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
String userid = request.getParameter("userId");
String noteid = request.getParameter("noteId");
UserDao userDao = new UserDao();
UserBean user = new UserBean();
List<NoteBean> noteLike = new ArrayList<NoteBean>();
if(userid!=null) {
int userId = Integer.parseInt(userid);
user=userDao.getUserById(userId);
noteLike=like.getLikeNoteList(user.getUserId());
System.out.println("notelike"+noteLike.size());
}
if(userid!=null&¬eid!=null) {
int userId = Integer.parseInt(userid);
int noteId = Integer.parseInt(noteid);
String islike = request.getParameter("islike");
System.out.println("userID"+userId+"noteid:"+noteId);
if(islike.equals("false")) {
like.addLike(userId, noteId);
}else {
like.deleteLike(userId, noteId);
}
}
//UserBean user = (UserBean) session.getAttribute("user");
List<NoteBean> noteList=null;
if(session.getAttribute("noteList")==null) {
noteList = noteDao.getNoteBytypeId(6);
session.setAttribute("noteList", noteList);
}else {
noteList = noteDao.getNoteBytypeId(6);
noteList=(List<NoteBean>) session.getAttribute("noteList");
}
for(NoteBean note:noteList) {
int a = note.getNoteId();
int b = like.selectLike(a);
int c = comment.getCommentCount(a);
int d = collect.selectCollectCount(a);
int ilike = 0;
note.setNoteLikeCount(b);
note.setNoteCollectionCount(d);
note.setNoteCommentCount(c);
for(NoteBean nlike:noteLike) {
//System.out.println(note.getNoteId()+"点赞"+nlike.getNoteId());
if(note.getNoteId()==nlike.getNoteId()) {
ilike=1;
break;
}else {
ilike=0;
}
}
note.setLike(ilike);
System.out.println(note.getNoteId()+"islike"+note.isLike());
}
request.setAttribute("noteList", noteList);
String jsonString="";
jsonString = JsonTools.createJsonString("note",noteList);
response.getWriter().append(jsonString).append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.codegym.controller;
import com.codegym.entity.User;
import com.codegym.repository.RoleRepository;
import com.codegym.repository.UserRepository;
import com.codegym.service.RoleService;
import com.codegym.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class UserController {
@Autowired
UserService userService;
@Autowired
RoleService roleService;
@GetMapping("/register")
public String goRegister(Model model) {
model.addAttribute("user", new User());
model.addAttribute("roleList", roleService.findAll());
return "register";
}
@PostMapping("/register")
public String registerUser(@ModelAttribute User user, RedirectAttributes redirectAttributes) {
userService.save(user);
redirectAttributes.addFlashAttribute("message", "Register successfully!");
return "redirect:/";
}
}
|
package xdpm.nhom11.angrybirdsproject.entities;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.ParserConfigurationException;
import org.andengine.engine.camera.SmoothCamera;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.JumpModifier;
import org.andengine.entity.modifier.RotationModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.PinchZoomDetector;
import org.andengine.input.touch.detector.ScrollDetector;
import org.andengine.input.touch.detector.PinchZoomDetector.IPinchZoomDetectorListener;
import org.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.andengine.input.touch.detector.SurfaceScrollDetector;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.util.adt.color.Color;
import org.xml.sax.SAXException;
import android.content.Context;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import xdpm.nhom11.angrybirdsproject.bird.BlackBird;
import xdpm.nhom11.angrybirdsproject.bird.BlueBird;
import xdpm.nhom11.angrybirdsproject.bird.RedBird;
import xdpm.nhom11.angrybirdsproject.bird.WhiteBird;
import xdpm.nhom11.angrybirdsproject.bird.YellowBird;
import xdpm.nhom11.angrybirdsproject.entities.GameEntity.ObjectType;
import xdpm.nhom11.angrybirdsproject.manager.DataManager;
import xdpm.nhom11.angrybirdsproject.manager.EffectManager;
import xdpm.nhom11.angrybirdsproject.manager.Game;
import xdpm.nhom11.angrybirdsproject.manager.SceneManager;
import xdpm.nhom11.angrybirdsproject.resourcemanager.SoundHelper;
import xdpm.nhom11.angrybirdsproject.resourcemanager.TexturePackerHelper;
import xdpm.nhom11.angrybirdsproject.xmlbird.DAOWorld;
import xdpm.nhom11.angrybirdsproject.xmlbird.DTOWorld;
public class Map implements IOnSceneTouchListener, IUpdateHandler,
IScrollDetectorListener, IPinchZoomDetectorListener {
// PhysicsWorld của một map
public static PhysicsWorld mPhysicsWorld;
// biến tạm tạo fixturedef cho toàn bộ object;
static boolean isPause = false;
static boolean isResume = false;
FixtureDef fx;
float maxWidth = 3000;
float maxHeight = 4000;
// danh sách chim
ArrayList<Bird> ListBird;
// danh sách vật cản
ArrayList<Block> ListObject;
ArrayList<Pig> ListPig;
// cây ná
Slingshot mSlingshot;
MapBackground background;
Earth mEarth;
// mặt đất tạm
Rectangle staticRect;
SmoothCamera camera;
boolean startDelay = false;
// camera
float mPinchZoomStartedCameraZoomFactor = 0;
static PinchZoomDetector mPinchZoomDetector;
static SurfaceScrollDetector mScrollDetector;
static int BirdIndex = -1;
ArrayList<Sprite> earth;
ArrayList<Sprite> sky;
ArrayList<Sprite> earthsurface1;
ArrayList<Sprite> earthsurface2;
public Map(Context context, VertexBufferObjectManager vbo) {
Map.mPhysicsWorld = new PhysicsWorld(new Vector2(0, -10), false);
fx = PhysicsFactory.createFixtureDef(50, 0.2f, 0.3f);
Map.mPhysicsWorld.setContactListener(createContactListener());
ListBird = new ArrayList<Bird>();
ListObject = new ArrayList<Block>();
ListPig = new ArrayList<Pig>();
}
public void Load() {
SceneManager.getInstance().getCurrentScene()
.registerUpdateHandler(this);
SceneManager.getInstance().getCurrentScene()
.setOnSceneTouchListener(this);
SceneManager.getInstance().getCurrentScene()
.registerUpdateHandler(Map.mPhysicsWorld);
CreateMapScene();
CreateMapFromData();
CreateBackground();
CreateEarthSurface();
startDelay = true;
}
public void CreateMapFromData() {
ArrayList<DTOWorld> world = DataManager.getInstance().DTOListWorld;
ListObject = world.get(DataManager.getInstance().currentWorldChoosed).chapters
.get(DataManager.getInstance().currentChapterChoosed).levels
.get(DataManager.getInstance().currentLevelChoosed)
.getListBlock();
ListBird = world.get(DataManager.getInstance().currentWorldChoosed).chapters
.get(DataManager.getInstance().currentChapterChoosed).levels
.get(DataManager.getInstance().currentLevelChoosed)
.getListBird();
ListPig = world.get(DataManager.getInstance().currentWorldChoosed).chapters
.get(DataManager.getInstance().currentChapterChoosed).levels
.get(DataManager.getInstance().currentLevelChoosed)
.getListPig();
mSlingshot = world.get(DataManager.getInstance().currentWorldChoosed).chapters
.get(DataManager.getInstance().currentChapterChoosed).levels
.get(DataManager.getInstance().currentLevelChoosed)
.getSlingshot();
background = new MapBackground(
world.get(DataManager.getInstance().currentWorldChoosed).backgroundID);
}
private void CreateMapScene() {
//
Game.getInstance().camera.setBounds(0, -100, maxWidth, maxHeight - 100);
Game.getInstance().camera.setBoundsEnabled(true);
Game.getInstance().camera.setCenterDirect(0, 0);
Game.getInstance().camera.setChaseEntity(null);
Game.getInstance().camera.setMaxVelocity(1000, 1000);
mPinchZoomDetector = new PinchZoomDetector(this);
mScrollDetector = new SurfaceScrollDetector(this);
}
private void CreateBackground() {
SceneManager.getInstance().getCurrentScene()
.setBackground(new Background(background.getColor()));
// EARTH
earth = new ArrayList<Sprite>();
int n = (int) (maxWidth / background.getEarthBackground().getWidth() + 1);
float widthTexture = background.getEarthBackground().getWidth();
float heightTexture = background.getEarthBackground().getHeight();
for (int i = 0; i < n; i++) {
final Sprite sp1 = new Sprite(widthTexture / 2 + i * widthTexture,
-(heightTexture / 2), background.getEarthBackground(),
Game.getInstance().vbom);
sp1.setZIndex(-2);
earth.add(sp1);
}
// EARTHSURFACE1
n = (int) (maxWidth
/ background.getEarthSurface1Background().getWidth() + 1);
widthTexture = background.getEarthSurface1Background().getWidth();
heightTexture = background.getEarthSurface1Background().getHeight();
earthsurface1 = new ArrayList<Sprite>();
for (int i = 0; i < n; i++) {
final Sprite sp1 = new Sprite(0, 0,
background.getEarthSurface1Background(),
Game.getInstance().vbom);
sp1.setAnchorCenter(0, 0);
sp1.setScale(1);
sp1.setPosition(i * widthTexture * sp1.getScaleX(), -7);
sp1.setZIndex(2);
earthsurface1.add(sp1);
}
// EARTHSURFACE2
n = (int) (maxWidth
/ background.getEarthSurface2Background().getWidth() + 1);
widthTexture = background.getEarthSurface2Background().getWidth();
heightTexture = background.getEarthSurface2Background().getHeight();
earthsurface2 = new ArrayList<Sprite>();
for (int i = 0; i < n; i++) {
final Sprite sp1 = new Sprite(0, 0,
background.getEarthSurface2Background(),
Game.getInstance().vbom);
sp1.setAnchorCenter(0, 0);
sp1.setScale(2.5f);
sp1.setPosition(i * widthTexture * sp1.getScaleX(), -10);
sp1.setZIndex(-3);
earthsurface2.add(sp1);
}
// SKY
n = (int) (maxWidth / background.getSkyBackground().getWidth() + 1);
widthTexture = background.getSkyBackground().getWidth();
heightTexture = background.getSkyBackground().getHeight();
sky = new ArrayList<Sprite>();
for (int i = 0; i < n; i++) {
final Sprite sp1 = new Sprite(0, 0, background.getSkyBackground(),
Game.getInstance().vbom);
sp1.setScale(2);
sp1.setPosition(
(sp1.getWidth() * sp1.getScaleX()) / 2 + i * sp1.getWidth()
* sp1.getScaleX(),
sp1.getHeight() / 2 * sp1.getScaleY() - 23);
sp1.setZIndex(-5);
sky.add(sp1);
}
}
public void CreateEarthSurface() {
mEarth = new Earth(0);
}
public void Attached(Scene scene) {
// attach cho chim
for (Bird bird : ListBird) {
bird.onAttached(scene);
}
for (Block bird : ListObject) {
bird.onAttached(scene);
}
for (Pig pig : ListPig) {
pig.onAttached(scene);
}
if (mSlingshot != null)
mSlingshot.onAttached(scene);
for (Sprite spr : earth) {
scene.attachChild(spr);
}
for (Sprite spr : sky) {
scene.attachChild(spr);
}
for (Sprite spr : earthsurface1) {
scene.attachChild(spr);
}
for (Sprite spr : earthsurface2) {
scene.attachChild(spr);
}
scene.sortChildren();
}
private void ChangeBird() {
if (BirdIndex < ListBird.size() - 1) {
BirdIndex++;
if (mSlingshot != null) {
RotationModifier rota = new RotationModifier(2, 0, 1800);
rota.setAutoUnregisterWhenFinished(true);
JumpModifier jump = new JumpModifier(2, ListBird.get(BirdIndex)
.getSprite().getX(), mSlingshot.getPosition().x,
ListBird.get(BirdIndex).getSprite().getY(),
mSlingshot.getPosition().y,
-(mSlingshot.getPosition().y + 20)) {
@Override
protected void onModifierFinished(IEntity pItem) {
// TODO Auto-generated method stub
mSlingshot.ReadyShoot(ListBird.get(BirdIndex));
}
};
jump.setAutoUnregisterWhenFinished(true);
ListBird.get(BirdIndex).getSprite()
.registerEntityModifier(rota);
ListBird.get(BirdIndex).getSprite()
.registerEntityModifier(jump);
}
}
}
@Override
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
// TODO Auto-generated method stub
if (!isPause) {
if (isStarted) {
// Runaway.Remove_line();
// UnloadResource();
// gán indexmove con chim đang ở trên ná và đưa camera v�? lại
// vị
// trí
// ban
// đầu
// camera2D.mSmoothCamera.set(0,0,800,480);
// đảm bảo lúc này con chim ko bay
// isMove = false;
//
// //nếu con chim ko bay cho phép scroll và zoom
// if(!isMove)
// {
// camera2D.mPinchZoomDetector.onSceneTouchEvent(pScene,
// pSceneTouchEvent);
// if (camera2D.mPinchZoomDetector.isZooming())
// {
// camera2D.mScrollDetector.setEnabled(false);
// } else
// {
// camera2D.mScrollDetector.onSceneTouchEvent(pScene,
// pSceneTouchEvent);
// }
// }
if (ListBird != null)
if (ListBird.size() > 0)
ListBird.get(BirdIndex).UseSkill();
Map.mPinchZoomDetector.onSceneTouchEvent(pScene,
pSceneTouchEvent);
if (Map.mPinchZoomDetector.isZooming()) {
Map.mScrollDetector.setEnabled(false);
} else {
if (pSceneTouchEvent.isActionDown())
Map.mScrollDetector.setEnabled(true);
Map.mScrollDetector.onTouchEvent(pSceneTouchEvent);
}
//
if (mSlingshot != null) {
mSlingshot.onSceneTouchEvent(pScene, pSceneTouchEvent);
if (mSlingshot.isBirdTouch == true) {
Map.mScrollDetector.setEnabled(false);
}
}
if (mSlingshot != null)
mSlingshot.onSceneTouchEvent(pScene, pSceneTouchEvent);
// this.mScrollDetector
// .onSceneTouchEvent(pScene, pSceneTouchEvent);
}
}
return false;
}
public boolean isStarted = false;
public void Start() {
isStarted = true;
for (Block ob : ListObject) {
ob.mBody.setActive(true);
}
for (Pig opig : ListPig) {
opig.mBody.setActive(true);
}
if (mSlingshot != null)
ChangeBird();
SoundHelper.level_start_military.play();
}
int count = 0;
@Override
public void onUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
//
if (startDelay == true) {
count++;
if (count > 100) {
Start();
count = 0;
startDelay = false;
}
}
if (BirdIndex >= 0)
if (ListBird.get(BirdIndex).isDead == true) {
ChangeBird();
}
//
// }
// t++;
// if (t % 3 == 0)
// Runaway.Add_line(ListBird.get(BirdIndex).getSprite().getX(),
// ListBird.get(BirdIndex).getSprite().getY());
// if (ListBird.get(BirdIndex).getSprite().getY() > camera
// .getBoundsHeight() && zoomed == false) {
// camera.setZoomFactor(0.68f);
// zoomed = true;
//
// } else if (ListBird.get(BirdIndex).getSprite().getY() <= camera
// .getBoundsHeight() && zoomed == true) {
// camera.setZoomFactor(1f);
// zoomed = false;
// }
// for (int i = 0; i < ListObject.size(); i++) {
// ListObject.get(i).onUpdate(pSecondsElapsed);
//
// }
// for (int i = 0; i < ListPig.size(); i++) {
// ListPig.get(i).onUpdate(pSecondsElapsed);
//
// }
// for (int i = 0; i < ListBird.size(); i++) {
// ListBird.get(i).onUpdate(pSecondsElapsed);
//
// }
// if(isMove)
// {
// //đặt con chim tiếp theo vào vị trí bắn
// if( mSlingshot.birdShooted == null &&
// ListBird.get(indexmove).getSprite().getY() +
// ListBird.get(indexmove).getSprite().getHeight()*2 >
// mSlingshot.mPosition.y)
// {
// mSlingshot.ReadyShoot(ListBird.get(index));
// }
//
}
@Override
public void reset() {
// TODO Auto-generated method stub
}
public void UnloadResource() {
SoundHelper.StopAll();
SceneManager.getInstance().getCurrentScene()
.unregisterUpdateHandler(this);
SceneManager.getInstance().getCurrentScene()
.setOnSceneTouchListener(null);
SceneManager.getInstance().getCurrentScene()
.unregisterUpdateHandler(Map.mPhysicsWorld);
for (Bird bird : ListBird)
bird.unload();
for (Block object : ListObject)
object.unload();
for (Pig pig : ListPig)
pig.unload();
if (mSlingshot != null)
mSlingshot.unload();
if (mEarth != null)
mEarth.unload();
for (Sprite spr : earth) {
SceneManager.getInstance().getCurrentScene().detachChild(spr);
}
for (Sprite spr : sky) {
SceneManager.getInstance().getCurrentScene().detachChild(spr);
}
ListBird.clear();
ListObject.clear();
ListPig.clear();
startDelay = true;
isStarted = false;
count = 0;
isPause = false;
BirdIndex = -1;
Game.getInstance().camera.setZoomFactorDirect(1);
Game.getInstance().camera.setCenterDirect(0, 0);
Game.getInstance().camera.setBounds(0, 0,
Game.getInstance().camera.getWidth(),
Game.getInstance().camera.getHeight());
Game.getInstance().camera.setBoundsEnabled(false);
//
}
float maxImpulse;
Vector2 birdForce;
float aguForce;
private ContactListener createContactListener() {
ContactListener contactListener = new ContactListener() {
@Override
public void preSolve(Contact contact, Manifold oldManifold) {
// TODO Auto-generated method stub
final Body x1 = contact.getFixtureA().getBody();
final Body x2 = contact.getFixtureB().getBody();
if (x1.getUserData() != null && x2.getUserData() != null) {
if (((GameEntity) x1.getUserData()).getType() == ObjectType.BIRD
&& ((GameEntity) x2.getUserData()).getType() != ObjectType.BIRD) {
birdForce = x1.getLinearVelocity();
aguForce = x1.getAngularVelocity();
}
if (((GameEntity) x2.getUserData()).getType() == ObjectType.BIRD
&& ((GameEntity) x1.getUserData()).getType() != ObjectType.BIRD) {
birdForce = x2.getLinearVelocity();
aguForce = x2.getAngularVelocity();
}
}
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse) {
maxImpulse = impulse.getNormalImpulses()[0];
// for (int i = 1; i < impulse.getNormalImpulses().length; i++)
// maxImpulse = Math.max(impulse.getNormalImpulses()[i],
// maxImpulse);
final Body x1 = contact.getFixtureA().getBody();
final Body x2 = contact.getFixtureB().getBody();
if (x1.getUserData() != null && x2.getUserData() != null) {
if (maxImpulse >= ((GameEntity) x1.getUserData())
.getCurrentLifeValue()) {
if (((GameEntity) x1.getUserData()).getType() != ObjectType.BIRD
&& ((GameEntity) x2.getUserData()).getType() == ObjectType.BIRD) {
((GameEntity) x1.getUserData()).destroy();
x2.setLinearVelocity(birdForce.mul(0.6f));
x2.setAngularVelocity(aguForce / 6);
}
} else if (maxImpulse >= ((GameEntity) x2.getUserData())
.getCurrentLifeValue()) {
if (((GameEntity) x2.getUserData()).getType() != ObjectType.BIRD
&& ((GameEntity) x1.getUserData()).getType() == ObjectType.BIRD) {
((GameEntity) x1.getUserData()).destroy();
x1.setLinearVelocity(birdForce.mul(0.6f));
x1.setAngularVelocity(aguForce / 6);
}
}
}
if (x1.getUserData() != null) {
((GameEntity) x1.getUserData()).collide(maxImpulse);
}
if (x2.getUserData() != null) {
((GameEntity) x2.getUserData()).collide(maxImpulse);
}
}
@Override
public void endContact(Contact contact) {
// TODO Auto-generated method stub
}
@Override
public void beginContact(Contact contact) {
// TODO Auto-generated method stub
}
};
return contactListener;
}
// xác định 1 body va chạm đầu tiên
public void Reset() {
SoundHelper.StopAll();
startDelay = true;
isStarted = false;
count = 0;
isPause = false;
BirdIndex = -1;
for (Bird bird : ListBird) {
bird.resetSeft();
bird.onAttached(SceneManager.getInstance().getCurrentScene());
}
for (Pig pig : ListPig) {
pig.resetSeft();
pig.onAttached(SceneManager.getInstance().getCurrentScene());
}
for (Block object : ListObject) {
object.resetSeft();
object.onAttached(SceneManager.getInstance().getCurrentScene());
}
mSlingshot.birdShooted = null;
SceneManager.getInstance().getCurrentScene().sortChildren();
// UnloadResource();
// Load();
// Attached(SceneManager.getInstance().getCurrentScene());
}
public void Pause() {
if (!isPause) {
for (int i = 0; i < ListBird.size(); i++) {
ListBird.get(i).mBody.setActive(false);
}
for (int i = 0; i < ListObject.size(); i++)
ListObject.get(i).mBody.setActive(false);
for (int i = 0; i < ListPig.size(); i++)
ListPig.get(i).mBody.setActive(false);
isPause = true;
}
}
public void Resume() {
if (isPause) {
for (int i = BirdIndex; i >= 0; i--)
if (ListBird.get(i).isFlying == true)
ListBird.get(i).mBody.setActive(true);
for (int i = 0; i < ListObject.size(); i++)
ListObject.get(i).mBody.setActive(true);
for (int i = 0; i < ListPig.size(); i++)
ListPig.get(i).mBody.setActive(true);
isPause = false;
}
}
public int Check_win() {
int isDead = 1;
for (int i = 0; i < ListPig.size(); i++) {
if (ListPig.get(i).isDead == false) {
isDead = -1;
break;
}
}
if (isDead == -1) {
for (int i = 0; i < ListBird.size(); i++) {
if (ListBird.get(i).isDead == false) {
return 0;
}
}
return isDead;
}
return isDead;
}
// SCROLL
float tscoll = 0;
@Override
public void onScroll(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
// TODO Auto-generated method stub
final float zoomFactor = Game.getInstance().camera.getZoomFactor();
Game.getInstance().camera.setCenterDirect(
(int) (-pDistanceX / zoomFactor)
+ Game.getInstance().camera.getCenterX(),
Game.getInstance().camera.getCenterY());
tscoll = (int) (-pDistanceX / zoomFactor);
}
@Override
public void onScrollFinished(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
// TODO Auto-generated method stub
final float zoomFactor = Game.getInstance().camera.getZoomFactor();
Game.getInstance().camera.setChaseEntity(null);
if (!isPause) {
if ((int) (-pDistanceX / zoomFactor) > tscoll) {
Game.getInstance().camera.setCenter(mSlingshot.getPosition().x,
mSlingshot.getPosition().y);
} else {
// Vector2 temp = getPigPosition();
Game.getInstance().camera.setCenter(1500,
mSlingshot.getPosition().y);
}
}
}
// ZOOM
@Override
public void onPinchZoomStarted(PinchZoomDetector pPinchZoomDetector,
TouchEvent pSceneTouchEvent) {
// TODO Auto-generated method stub
mPinchZoomStartedCameraZoomFactor = Game.getInstance().camera
.getZoomFactor();
}
float tzoom = 0;
@Override
public void onPinchZoomFinished(PinchZoomDetector pPinchZoomDetector,
TouchEvent pTouchEvent, float pZoomFactor) {
// TODO Auto-generated method stub
float temp = pZoomFactor;
if (tzoom <= temp)
Game.getInstance().camera.setCenter(mSlingshot.getPosition().x,
mSlingshot.getPosition().y);
if (tzoom > temp)
Game.getInstance().camera.setCenter(1500,
mSlingshot.getPosition().y);
// Game.getInstance().camera.setCenter(Game.getInstance().camera.getCenterX(),mSlingshot.getPosition().y);
}
@Override
public void onPinchZoom(PinchZoomDetector pPinchZoomDetector,
TouchEvent pTouchEvent, float pZoomFactor) {
// TODO Auto-generated method stub
float temp = mPinchZoomStartedCameraZoomFactor * pZoomFactor;
float scalex = 800 / maxWidth;
float scaley = 480 / maxHeight;
float maxzoom = 1;
if (scalex < scaley)
maxzoom = scaley;
else
maxzoom = scalex;
if (temp <= 1 && temp >= maxzoom) {
Game.getInstance().camera.setZoomFactor(temp);
}
tzoom = Game.getInstance().camera.getZoomFactor();
// } else if (temp >= 1) {
// Game.getInstance().camera.setZoomFactor(1);
// } else {
// Game.getInstance().camera.setZoomFactor(maxzoom);
// }
}
@Override
public void onScrollStarted(ScrollDetector pScollDetector, int pPointerID,
float pDistanceX, float pDistanceY) {
// TODO Auto-generated method stub
}
}
|
package com.hanxx.shiro.service;
import com.hanxx.shiro.model.User;
/**
* @Author hanxx
* @Date 2018/4/1716:00
*/
public interface UserService {
User findByUsername(String username);
}
|
import javax.swing.*;
import java.awt.*;
import java.util.List;
public class AfficherReservation extends JPanel {
private final int MAX_LIST = 5;
private JLabel[][] grilleJLabel = new JLabel[MAX_LIST-1][5];
private MonBouton[] tabBouton = new MonBouton[MAX_LIST-1];
private List<Reservation> listReservation;
private int reservationSelectionner;
private ControleurSelectionner controleur;
public AfficherReservation() {
this.reservationSelectionner = -1;
this.listReservation = null;
this.setLayout(new GridBagLayout());
JLabel reservation = new JLabel("Réservation");
JPanel tableau = new JPanel();
GridBagConstraints c = new GridBagConstraints();
Font font = new Font("Arial",Font.BOLD,20);
reservation.setFont(font);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.CENTER;
c.anchor = GridBagConstraints.SOUTH;
c.insets = new Insets(5,5,5,5);
c.weightx=1.0f;
c.weighty=1.0f;
this.add(reservation, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.CENTER;
c.anchor = GridBagConstraints.SOUTH;
c.insets = new Insets(0,0,0,0);
c.weightx=1.0f;
c.weighty=1.0f;
this.add(tableau, c);
tableau.setLayout(new GridLayout(MAX_LIST,6));
tableau.add(new JLabel("Référence"));
tableau.add(new JLabel("Début du séjour"));
tableau.add(new JLabel("nombre de nuits"));
tableau.add(new JLabel("Type de chambre"));
tableau.add(new JLabel("<html>Description<br>du type</html>"));
tableau.add(new JLabel(" ")); // colonne bouton
for(int i=0; i<MAX_LIST-1; i++) {
for(int j=0; j<5; j++) {
grilleJLabel[i][j] = new JLabel("");
grilleJLabel[i][j].setOpaque(true);
tableau.add(grilleJLabel[i][j]);
}
tabBouton[i] = new MonBouton("Selectionner");
tabBouton[i].setVisible(false);
tableau.add(tabBouton[i]);
}
}
public void setValeur(List<Reservation> listRes) {
this.listReservation = listRes;
int i=0;
if(listRes == null) {
this.reservationSelectionner = -1;
} else {
this.reservationSelectionner = -2;
for(i=0; i<listRes.size() && i < MAX_LIST-1; i++) {
Reservation res = listRes.get(i);
this.grilleJLabel[i][0].setText(res.getReference());
this.grilleJLabel[i][1].setText(res.getDebut().toString());
this.grilleJLabel[i][2].setText(""+res.getNuit());
this.grilleJLabel[i][3].setText(res.getSigle());
this.grilleJLabel[i][4].setText(res.getTexte());
this.tabBouton[i].setValeur(i);
this.tabBouton[i].setVisible(true);
}
if(listRes.size()==1) { // il y a qu'une ligne donc elle est séléctionnée de base
this.tabBouton[0].setVisible(false);
this.reservationSelectionner = 0;
for(int j=0; j<grilleJLabel[0].length; j++) {
grilleJLabel[0][j].setBackground(Color.GRAY);
}
controleur.selectionner(0); //utilise la fonction du controleur
}
}
//efface les autres
while(i<MAX_LIST-1) {
this.grilleJLabel[i][0].setText(" ");
this.grilleJLabel[i][1].setText(" ");
this.grilleJLabel[i][2].setText(" ");
this.grilleJLabel[i][3].setText(" ");
this.grilleJLabel[i][4].setText(" ");
this.tabBouton[i].setVisible(false);
for(int j=0; j<grilleJLabel[i].length; j++) {
grilleJLabel[i][j].setBackground(this.getBackground());
}
i++;
}
}
public void setReservationSelectionner(int a) {
for(int i=0; i<grilleJLabel.length; i++) {
for(int j=0; j<grilleJLabel[i].length; j++) {
grilleJLabel[i][j].setBackground(this.getBackground());
}
}
for(int i=0; i<grilleJLabel[0].length; i++) {
grilleJLabel[a][i].setBackground(Color.GRAY);
}
this.reservationSelectionner = a;
}
public int getReservationSelectionner() {
return this.reservationSelectionner;
}
public List<Reservation> getListReservation() {
return this.listReservation;
}
public void setControleur(ControleurSelectionner cont) {
for(int i=0; i<tabBouton.length-1; i++) {
tabBouton[i].addActionListener(cont);
}
this.controleur = cont;
}
}
|
package com.zs.web.shopadmin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Created by IDEA
* @author:LiuYiBo(小博)
* @Date:2018/7/27
* @Time:15:42
*/
@Controller
@RequestMapping(value = "shopadmin",method ={RequestMethod.GET})
public class ShopAdminController {
@RequestMapping(value = "/shopoperation")
public String shopOperation(){
return "shop/shopoperation";
}
}
|
package jp.co.logacy.validator.search;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ArtistNameValidator {
public Map<String, String> validator(final String artistName, Map<String, String> errorMap) {
if (StringUtils.isEmpty(artistName)) {
errorMap.put("empty", "search.msg.empty");
return errorMap;
}
return errorMap;
}
}
|
package sample;
public interface CommerceInterface {
public abstract void buy(Good good);
}
|
package edu.pdx.cs.cs554.gomoku;
import android.content.Context;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.TextView;
public class TimerView extends TextView {
private static final int PLAYER_TIME_LIMIT_IN_MILLISECONDS = 10 * 60 * 1000; // 10 minutes
private String prefix;
private PlayerTimer playerTimer;
private long remainingMilliseconds = PLAYER_TIME_LIMIT_IN_MILLISECONDS + 1;
public TimerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void start() {
if (playerTimer == null) {
playerTimer = new PlayerTimer(remainingMilliseconds, 1000);
}
playerTimer.start();
}
public void pause() {
if (playerTimer != null) {
playerTimer.stop();
}
playerTimer = null;
}
public String getPrefix() {
return prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
class PlayerTimer extends CountDownTimer {
private boolean shouldStop = false;
public PlayerTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
if (shouldStop) {
TimerView.this.remainingMilliseconds = millisUntilFinished;
cancel();
}
long minutes = millisUntilFinished / 1000 / 60;
long seconds = millisUntilFinished / 1000 % 60;
TimerView.this.setText(TimerView.this.getPrefix() + String.format("%02d:%02d", minutes, seconds));
}
@Override
public void onFinish() {
TimerView.this.setText(TimerView.this.getPrefix() + "00:00");
}
public void stop() {
shouldStop = true;
}
}
}
|
package 两个栈模拟一个队列;
import java.util.Scanner;
import java.util.Stack;
public class TwoStacks {
Stack<Integer> stack = new Stack<>();
Stack<Integer> cache = new Stack<>();
public void push(int node){
while (!cache.isEmpty()){
stack.push(cache.pop());
}
stack.push(node);
}
public int pop(){
while (!stack.isEmpty()){
cache.push(stack.pop());
}
return cache.pop();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
for (int i = 0; i < count; i++) {
}
}
}
|
package com.smartcity.commonbase.widget.pagestatus;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.support.annotation.IntDef;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Author: YuJunKui
* Time:2017/12/8 9:24
* Tips: 页面状态类
*/
public class PageStatusHelper {
private View bindView;
private Builder builder;
private ViewStatusController controller;
private OnErrorClickListener onErrorClickListener;
private OnNoLoginClickListener onNoLoginClickListener;
private OnEmptyClickListener onEmptyClickListener;
public static final int ERROR = 0, NO_LOGIN = 1, LOADING = 2, NET_WORK = 3, EMPTY = 4, CONTENT = 5;
private static final String TAG = "PageStatusHelper";
@PageStatusValue
private int currentPageStatusValue = CONTENT;
private String bindViewBgColor;
/**
* @param context 用于构建view
*/
public PageStatusHelper(Context context) {
this(context, new Builder(context));
}
/**
* @param context 用于构建view
*/
public PageStatusHelper(Context context, Builder builder) {
setBuilder(builder);
controller = new ViewStatusController();
}
@Deprecated
public PageStatusHelper setLayoutParams(LayoutParams params) {
builder.setLayoutParams(params);
return this;
}
public PageStatusHelper bindView(View bindView) {
checkBindView();
if (this.bindView != null) {
return this;// song 没抛运行时异常
}
builder.setBindView(bindView);
this.bindView = bindView;
this.bindViewBgColor = ColorUtils.obtainBgColor(bindView);
return this;
}
//检测
private void checkBindView() {
}
@Deprecated
public void bindActivity(Activity bindActivity) {
this.bindView = bindActivity.getWindow().getDecorView();
}
public PageStatusHelper setBuilder(Builder builder) {
this.builder = builder;
return this;
}
public Builder getBuilder() {
return builder;
}
/**
* 此方法会将在GONE状态下的bindView改为INVISIBLE
*
* @param pageStatusValue
*/
public PageStatusHelper refreshPageStatus(@PageStatusValue final int pageStatusValue) {
//状态一样不做处理
if (currentPageStatusValue == pageStatusValue) {
return this;
}
Log.i(TAG,"call refreshPageStatus currentPageStatusValue="+pageStatusValue);
currentPageStatusValue = pageStatusValue;
if (bindView.getVisibility() == View.GONE) {
bindView.setVisibility(View.INVISIBLE);
}
//没有绘制完成的
if (bindView.getWidth() == 0) {
bindView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
refreshStatus(pageStatusValue);
bindView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
} else {
refreshStatus(pageStatusValue);
}
return this;
}
private void refreshStatus(@PageStatusValue final int pageStatusValue) {
builder.setBindViewBgColor(bindViewBgColor);
if (pageStatusValue == CONTENT) {
controller.showContent();
return;
}
View statusView;
if (pageStatusValue == ERROR) {
statusView = builder.buildErrorView(onErrorClickListener != null);
} else if (pageStatusValue == EMPTY) {
statusView = builder.buildEmptyView();
} else if (pageStatusValue == LOADING) {
statusView = builder.buildLoadingView();
} else if (pageStatusValue == NET_WORK) {
statusView = builder.buildNetWorkView(onErrorClickListener != null);
} else if (pageStatusValue == NO_LOGIN) {
statusView = builder.buildNoLoginView();
} else {
return;
}
//绑定事件
statusView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if ((pageStatusValue == ERROR || pageStatusValue == NET_WORK) && onErrorClickListener != null) {
//改变状态
refreshPageStatus(LOADING);
onErrorClickListener.onErrorClick(v);
} else if (pageStatusValue == NO_LOGIN && onNoLoginClickListener != null) {
onNoLoginClickListener.OnNoLoginClick(v);
} else if (pageStatusValue == EMPTY && onEmptyClickListener != null) {
onEmptyClickListener.onEmptyClick(v);
}
}
});
controller.showViewStatus(bindView, statusView, builder.getLayoutParams());
}
public PageStatusHelper setOnNoLoginClickListener(OnNoLoginClickListener onNoLoginClickListener) {
this.onNoLoginClickListener = onNoLoginClickListener;
return this;
}
@Deprecated
public void showContent() {
refreshPageStatus(CONTENT);
}
@IntDef({ERROR, NO_LOGIN, LOADING, NET_WORK, EMPTY, CONTENT})
@Retention(RetentionPolicy.SOURCE)
public @interface PageStatusValue {
}
public void setOnErrorClickListener(OnErrorClickListener onErrorClickListener) {
this.onErrorClickListener = onErrorClickListener;
}
public void setOnEmptyClickListener(OnEmptyClickListener onEmptyClickListener) {
this.onEmptyClickListener = onEmptyClickListener;
}
public int getCurrentPageStatusValue() {
return currentPageStatusValue;
}
}
|
package com.example.cral_gates.xmenu2;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import com.example.cral_gates.base.BaseActivity;
import com.example.cral_gates.base.Constants;
import com.example.cral_gates.fragment.ContentFragment;
import com.example.cral_gates.fragment.MenuFragment;
import com.example.cral_gates.widget.xmenu.XMenu;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends BaseActivity implements MenuFragment.OnFragmentInteractionListener{
private XMenu xMenu;
private MenuFragment mMenuFragment;
private ContentFragment mContentFragment;
private String[] test = {"t1","t2","t3","t4","t5","t6","test7"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
xMenu = new XMenu(this);
setContentView(xMenu);
configContent();
configMenu();
}
private void configMenu() {
mMenuFragment = new MenuFragment(test);
getSupportFragmentManager().beginTransaction()
.replace(R.id.menu_frame, mMenuFragment).commit();
xMenu.setMenu(R.layout.menu_container);
int width = Math.min(Constants.sWidth, Constants.sHeight);
xMenu.setMenuWidth(3 * width / 4);
}
/*
* #0001 外部传入title
* leobert
* 2015-8-28 15:03:47
* */
private void configContent() {
List<View> mViewList = new ArrayList<View>();
for(int i=0;i<test.length;i++){
mViewList.add(LayoutInflater.from(getApplicationContext()).inflate(R.layout.page_item, null));
}
mContentFragment = new ContentFragment(test,mViewList);//new ContentFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mContentFragment).commit();
xMenu.setContent(R.layout.activity_main);
}
@Override
public void onFragmentInteraction(String id){
//at here we can get the list item id we touch
Log.i("leobert:", "Interaction" + id);
}
public void toggle() {
xMenu.toggle();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
toggle();
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package de.jmda.app.xstaffr.common.service.jpa;
import de.jmda.jpa.jse.AbstractPersistenceContextAccess;
public class TestXStaffrService_JPA_SE_Environment
{
private static class PersistenceContextAccess extends AbstractPersistenceContextAccess
{
@Override public String getPersistenceUnitName() { return "invalid persistence unit name"; }
}
public static void main(String[] args)
{
// creates new anonymous class
AbstractPersistenceContextAccess abstractPersistenceContextAccess = new PersistenceContextAccess() { };
// expected to fail with runtime exception because anonymous class does not provide a valid name for a jpa persistence unit
XStaffrServiceJPASE xStaffrService = new XStaffrServiceJPASE(abstractPersistenceContextAccess);
System.out.println(xStaffrService.ping("pong"));
}
} |
package com.dbs.spring.capstoneproject.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.dbs.spring.capstoneproject.model.Buy;
import com.dbs.spring.capstoneproject.service.BuyService;
@CrossOrigin
@RestController
@RequestMapping("/buy")
public class BuyController {
public BuyController()
{
}
@Autowired
private BuyService service;
@GetMapping("/{id}")
public List<Buy> getStocks(@PathVariable String id){
return this.service.findsalebuysbyid(id);
}
@GetMapping("/all")
public List<Buy> findallstocks(){
return this.service.findallbid();
}
@PostMapping
public ResponseEntity<Object> insertbuy(@RequestBody Buy buy) {
String cid=buy.getClient().getClientid();
String iid=buy.getInstrument().getInstrumentid();
int p=buy.getPrice();
int q=buy.getQuantity();
int bid=this.service.insertBuy(cid, iid, p, q);
if(bid>=1)
{
return ResponseEntity.status(HttpStatus.OK).body(service.findbyid(bid));
}
else
{
return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body("This bid does not exist");
}
}
}
|
package modul5.ae10.paket.paket2;
import modul5.ae10.paket.paket1.KlasseA;
class KlasseAC extends KlasseA {
}
|
package com.tencent.mm.plugin.webview.model;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.model.au;
import com.tencent.mm.modelcdntran.g;
import com.tencent.mm.modelcdntran.i;
import com.tencent.mm.modelcdntran.i.a;
import com.tencent.mm.plugin.webview.model.d.b;
import com.tencent.mm.protocal.c.arw;
import com.tencent.mm.protocal.c.ary;
import com.tencent.mm.protocal.c.asc;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;
public final class ad implements e {
private a dVu = new 1(this);
private CopyOnWriteArraySet<b> pRK = new CopyOnWriteArraySet();
private CopyOnWriteArraySet<d.a> pRL = new CopyOnWriteArraySet();
public final void a(d.a aVar) {
if (this.pRL != null && aVar != null && !this.pRL.contains(aVar)) {
this.pRL.add(aVar);
}
}
public final void a(b bVar) {
if (this.pRK != null && bVar != null) {
this.pRK.remove(bVar);
}
}
public final void b(d.a aVar) {
if (this.pRL != null && aVar != null) {
this.pRL.remove(aVar);
}
}
private void b(boolean z, String str, String str2, String str3) {
if (this.pRK != null && this.pRK.size() > 0) {
Iterator it = this.pRK.iterator();
while (it.hasNext()) {
((b) it.next()).a(z, str, str2, str3);
}
}
}
final void b(boolean z, int i, int i2, String str, String str2) {
x.i("MicroMsg.WebviewFileChooserCdnService", "notifyProgressCallback, upload : %b, mediaType : %d, percent : %d, localId : %s, mediaId : %s", new Object[]{Boolean.valueOf(z), Integer.valueOf(i), Integer.valueOf(i2), str, str2});
if (this.pRL != null && this.pRL.size() > 0) {
Iterator it = this.pRL.iterator();
while (it.hasNext()) {
((d.a) it.next()).a(z, i, i2, str, str2);
}
}
}
public final boolean a(String str, String str2, b bVar) {
ae bUX = com.tencent.mm.plugin.webview.modeltools.e.bUX();
if (!bi.oW(str2)) {
for (WebViewJSSDKFileItem webViewJSSDKFileItem : bUX.pRP.values()) {
if (bi.oV(webViewJSSDKFileItem.fnN).equals(str2)) {
break;
}
}
}
x.e("MicroMsg.WebViewJSSDKFileItemManager", "getItemByServerId error, media id is null or nil");
WebViewJSSDKFileItem webViewJSSDKFileItem2 = null;
if (webViewJSSDKFileItem2 != null) {
webViewJSSDKFileItem2.appId = str;
x.i("MicroMsg.WebviewFileChooserCdnService", "the file item has alreay in local : appid : %s, serverId : %s, localId : %s", new Object[]{str, str2, webViewJSSDKFileItem2.bNH});
bVar.a(true, webViewJSSDKFileItem2.bNH, webViewJSSDKFileItem2.fnN, null);
} else {
au.DF().a(1035, this);
au.DF().a(new g(str, str2), 0);
this.pRK.add(bVar);
}
return true;
}
private void a(WebViewJSSDKFileItem webViewJSSDKFileItem) {
i iVar = new i();
iVar.dPV = this.dVu;
iVar.ceW = false;
iVar.field_mediaId = webViewJSSDKFileItem.mediaId;
iVar.field_fullpath = webViewJSSDKFileItem.fnM;
iVar.field_totalLen = webViewJSSDKFileItem.pRN.field_fileLength;
iVar.field_fileType = com.tencent.mm.modelcdntran.b.MediaType_FILE;
iVar.field_fileId = webViewJSSDKFileItem.pRN.field_fileId;
iVar.field_aesKey = webViewJSSDKFileItem.pRN.field_aesKey;
iVar.field_priority = com.tencent.mm.modelcdntran.b.dOk;
iVar.field_needStorage = false;
iVar.field_isStreamMedia = false;
x.i("MicroMsg.WebviewFileChooserCdnService", "add download cdn task : %b, localid : %s", new Object[]{Boolean.valueOf(g.ND().b(iVar, -1)), webViewJSSDKFileItem.fnN});
if (!g.ND().b(iVar, -1)) {
b(false, null, null, null);
}
}
public final boolean a(String str, String str2, int i, int i2, int i3, b bVar) {
WebViewJSSDKFileItem Qq = com.tencent.mm.plugin.webview.modeltools.e.bUX().Qq(str2);
if (Qq == null) {
x.e("MicroMsg.WebviewFileChooserCdnService", "addUploadTask get webview file chooser item by local id failed : %s", new Object[]{str2});
return false;
}
Qq.appId = str;
if (bVar != null) {
this.pRK.add(bVar);
}
if (i2 == 202) {
Qq.fnR = false;
}
Qq.fnP = true;
i iVar = new i();
iVar.dPV = this.dVu;
iVar.ceW = true;
iVar.field_mediaId = Qq.mediaId;
iVar.field_fullpath = Qq.fnM;
iVar.field_fileType = i;
iVar.field_talker = "weixin";
iVar.field_priority = com.tencent.mm.modelcdntran.b.dOk;
if (i == com.tencent.mm.modelcdntran.b.dOo) {
iVar.field_needStorage = true;
} else {
iVar.field_needStorage = false;
}
iVar.field_isStreamMedia = false;
iVar.field_appType = i2;
iVar.field_bzScene = i3;
iVar.field_force_aeskeycdn = true;
iVar.field_trysafecdn = false;
x.i("MicroMsg.WebviewFileChooserCdnService", "summersafecdn add upload cdn task : %b, force_aeskeycdn: %b, trysafecdn: %b, localid : %s ", new Object[]{Boolean.valueOf(g.ND().c(iVar)), Boolean.valueOf(iVar.field_force_aeskeycdn), Boolean.valueOf(iVar.field_trysafecdn), str2});
return g.ND().c(iVar);
}
public final boolean b(String str, String str2, b bVar) {
return a(str, str2, com.tencent.mm.modelcdntran.b.MediaType_FILE, 0, 0, bVar);
}
public static boolean rq(String str) {
WebViewJSSDKFileItem Qq = com.tencent.mm.plugin.webview.modeltools.e.bUX().Qq(str);
if (Qq != null) {
return g.ND().lw(Qq.mediaId);
}
x.e("MicroMsg.WebviewFileChooserCdnService", "cancelUploadTask get webview file chooser item by local id failed : %s", new Object[]{str});
return false;
}
public static boolean Qm(String str) {
x.i("MicroMsg.WebviewFileChooserCdnService", "cancelDownloadTask get webview file chooser item by local id : %s", new Object[]{str});
return g.ND().lx(str);
}
public final void a(int i, int i2, String str, l lVar) {
x.i("MicroMsg.WebviewFileChooserCdnService", "onSceneEnd, errType = %d, errCode = %d, funcType = %d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(lVar.getType())});
String str2;
String str3;
String str4;
String str5;
switch (lVar.getType()) {
case 1034:
au.DF().b(1034, this);
x xVar = (x) lVar;
str2 = ((asc) xVar.diG.dIE.dIL).rUv;
str3 = xVar.appId;
str4 = xVar.bNH;
WebViewJSSDKFileItem Qq = com.tencent.mm.plugin.webview.modeltools.e.bUX().Qq(str4);
String str6 = "MicroMsg.WebviewFileChooserCdnService";
str5 = "get server server id : %s from server for appid : %s, localId = %s, item == null ? %b";
Object[] objArr = new Object[4];
objArr[0] = str2;
objArr[1] = str3;
objArr[2] = str4;
objArr[3] = Boolean.valueOf(Qq == null);
x.i(str6, str5, objArr);
if (i != 0 || i2 != 0) {
x.e("MicroMsg.WebviewFileChooserCdnService", "upload cdn info failed");
if (Qq != null) {
b(false, Qq.bNH, Qq.mediaId, null);
return;
}
return;
} else if (!bi.oW(str3) && !bi.oW(str2) && Qq != null) {
Qq.fnN = str2;
b(true, Qq.bMT, 100, Qq.bNH, Qq.fnN);
b(true, Qq.bNH, Qq.fnN, Qq.pRN.field_fileUrl);
return;
} else {
return;
}
case 1035:
au.DF().b(1035, this);
if (i == 0 && i2 == 0) {
g gVar = (g) lVar;
str2 = gVar.appId;
str3 = gVar.fnN;
arw arw = ((ary) gVar.diG.dIE.dIL).rUw;
str5 = "MicroMsg.WebviewFileChooserCdnService";
String str7 = "appid = %s, serverId = %s, cdninfo == null ? %b";
Object[] objArr2 = new Object[3];
objArr2[0] = str2;
objArr2[1] = str3;
objArr2[2] = Boolean.valueOf(arw == null);
x.i(str5, str7, objArr2);
if (!bi.oW(str2) && !bi.oW(str3) && arw != null) {
str4 = arw.type;
x.i("MicroMsg.WebviewFileChooserCdnService", "cdn info type = %s", new Object[]{str4});
if (!bi.oW(str4)) {
WebViewJSSDKFileItem Qo;
if (str4.toLowerCase().equals("voice")) {
Qo = WebViewJSSDKFileItem.Qo(aj.Qx(str2));
} else if (str4.toLowerCase().equals("video")) {
Qo = WebViewJSSDKFileItem.Qp(aj.Qr(bi.VF()));
} else {
Qo = WebViewJSSDKFileItem.Qn(aj.Qr(bi.VF()));
}
Qo.fnP = false;
Qo.appId = str2;
Qo.fnN = str3;
if (Qo.pRN == null) {
Qo.pRN = new WebViewJSSDKFileItem.a();
}
if (arw == null) {
x.e("MicroMsg.WebViewJSSDKFileItem", "jsapidcdn info is null");
} else {
Qo.pRN.field_aesKey = arw.rUt;
Qo.pRN.field_fileId = arw.rUs;
Qo.pRN.field_fileLength = arw.rqN;
}
com.tencent.mm.plugin.webview.modeltools.e.bUX().b(Qo);
a(Qo);
return;
}
return;
}
return;
}
x.e("MicroMsg.WebviewFileChooserCdnService", "download cdn info failed");
b(false, null, null, null);
return;
default:
return;
}
}
}
|
package recetas;
import inventario.Naranjas;
public class ZumoNaranja {
public int comprobarItem(){
Naranjas naranjas = new Naranjas();
int n=naranjas.verNaranjas();
return n;
}
public void cocinar(){
if(comprobarItem()>=4){
if(Math.random()<=0.5){
System.out.print("Zumo naranja conseguido \n");
Naranjas naranjas = new Naranjas();
naranjas.zumoConseguido();
}else{
System.out.print("Zumo naranja no conseguido \n");
Naranjas naranjas = new Naranjas();
naranjas.zumoFallido();
}
}else{
System.out.print("No tienes suficientes naranjas \n");
}
}
}
|
package com.tencent.xweb.xwalk.a;
import com.tencent.xweb.c.a.b;
public class a$c {
public boolean bUseCdn;
b vCo = new b();
public String vFk;
public String vFp;
public boolean vFq;
public int vFr;
public int vFs;
public a.b[] vFt;
public a$d vFu = new a$d();
}
|
package Logic;
import Entities.*;
/**
* This class is for calling movements of all entities.
* We've separated this logic with consideration for future improvements
* e.g. configurable, customizable movement logic
*
* @author Cowteriyaki
* @author K
*/
public class MovementLogic {
private EntitiesContainer entityData; // calling data class
public MovementLogic(EntitiesContainer entityData){
this.entityData = entityData;
}
/**
* For now, it only calls each entity to move by units relative to delta.
* Not much to see here.
* @param delta
*/
public void movement(double delta){
for(Virus virus : entityData.getVirusList())
virus.move(delta);
for(Bacteria bacteria : entityData.getBacteriaList())
bacteria.move(delta);
for(Macrophage macrophage : entityData.getMacroList())
macrophage.move(delta);
for(Neutrophil neutrophil : entityData.getNeutroList())
neutrophil.move(delta);
for(NKCell nkcell : entityData.getNKList())
nkcell.move(delta);
for(Soma soma : entityData.getSomaList())
soma.move(delta);
for(LFS lfs : entityData.getLFSList())
lfs.move(delta);
for(IFN ifn : entityData.getIFNList())
ifn.move(delta);
for(TNF tnf : entityData.getTNFList())
tnf.move(delta);
}
}
|
package com.brainmentors.apps.controllers;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.brainmentors.apps.models.User;
@Controller
public class WelcomeController {
@RequestMapping("/hello")
public String sayWelcome(Model model) {
model.addAttribute("msg", "Hello User");
model.addAttribute("userModel", new User());
//model.addAttribute("userModel",new User("anil","1234"));
return "welcome";
}
@RequestMapping(path = "/login3",method = RequestMethod.POST)
public String doLogin(@ModelAttribute("userModel") User user , Model model) {
if(user.getUserid().equals(user.getPwd())) {
model.addAttribute("msg", "Hello "+user.getUserid());
}
else {
model.addAttribute("msg", "Invalid Userid or Password");
}
return "dashboard";
}
@RequestMapping(path = "/login2",method = RequestMethod.POST)
public String doLogin(@RequestParam("userid") String uid, @RequestParam("pwd") String password, Model model) {
if(uid.equals(password)) {
model.addAttribute("msg", "Hello "+uid);
}
else {
model.addAttribute("msg", "Invalid Userid or Password");
}
return "dashboard";
}
@RequestMapping("/login")
public String doLogin(HttpServletRequest request, Model model) {
String userid = request.getParameter("userid");
String password = request.getParameter("pwd");
if(userid.equals(password)) {
model.addAttribute("msg", "Hello "+userid);
}
else {
model.addAttribute("msg", "Invalid Userid or Password");
}
return "dashboard";
}
}
|
// Copyright (c) 2013-2014 MediaMiser Ltd. All rights reserved.
package com.mediamiser.test;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
/**
* A log4j1 extension that will throw an {@code java.lang.AssertionError} if a
* {@code Level.ERROR} logging statement is propagated to an slf4j logger.
*
* <br>
* <br>
* This is used to detect whether an error condition is met during the course of
* unit tests. If a test causes production code to log an error, it will fail
* the test by throwing an {@code java.lang.AssertionError}. For code coverage
* reasons, tests still need to ensure that when an error condition occurs that
* a {@code Level.ERROR} logging statement is propagated to an slf4j logger;
* this can be accomplished using {@link com.mediamiser.test.LogTester}.
*
* <br>
* <br>
* To use this appender in your test suite, add it to the root logger before any
* tests run, e.g., before your test suite is run:
*
* <br>
* <br>
*
* <pre>
* public class MyTestSuite {
*
* @BeforeClass
* public static void failTestWhenItLogsAnError() {
* Logger.getRootLogger().addAppender(new Log4j1ErrorAppender());
* }
*
* }
* </pre>
*
* @author Chris Fournier {@literal <chris.fournier@mediamiser.com>}
*/
public class Log4j1ErrorAppender extends AppenderSkeleton {
@Override
public void close() {
// Do nothing
}
@Override
public boolean requiresLayout() {
return false;
}
@Override
protected void append(final LoggingEvent event) {
// If an error was logged, throw an assertion so that the test that
// caused the error will fail
if (event.getLevel() == Level.ERROR) {
throw new AssertionError("Test logged at the error level: " + event.getMessage());
}
}
}
|
package com.tencent.mm.plugin.luckymoney.appbrand.ui.receive;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import com.tencent.mm.sdk.platformtools.x;
class c$4 implements OnClickListener {
final /* synthetic */ c kMQ;
c$4(c cVar) {
this.kMQ = cVar;
}
public final void onClick(DialogInterface dialogInterface, int i) {
x.i("MicroMsg.WxaReceiveLuckyMoneyLogic", "RealnameGuideHelper dialog click cancel");
this.kMQ.Q(new Intent().putExtra("result_error_code", -1).putExtra("result_error_msg", "fail:system error {{user cancel realname}}"));
}
}
|
package tankas;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
public class Tankas {
int x = 0, y = 0, suviai = 0, suviaiS = 0, suviaiR = 0, suviaiV = 0, suviaiP = 0;
String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
String kryptis;
Random random = new Random();
int priesasX = (random.nextInt(20))-10;
int priesasY = (random.nextInt(20))-10;
int c;
static boolean runProgram = true;
public void iSiaure() {
y++;
kryptis="Siaure";
System.out.println("Tankas pajuda į Šiaurę\n"+time+" "+ x+";"+ y);
System.out.println("Kita komanda:");
// pajuda i siaure x0 y+1
//laikas + kordinates esamos x y
}
public void iPietus() {
y--;
kryptis="Pietus";
System.out.println("Tankas pajuda į Pietus\n"+time+" "+ x+";"+ y);
System.out.println("Kita komanda:");
// pajuda i pietus x0 y-1
//laikas + kordinates esamos x y
}
public void iVakarus() {
x--;
kryptis = "Vakarus";
System.out.println("Tankas pajuda į Rytus\n"+time+" "+ x+";"+ y);
System.out.println("Kita komanda:");
// pajuda i vakarus x-1 y0
//laikas + kordinates esamos x y
}
public void iRytus() {
x++;
kryptis = "Rytus";
System.out.println("Tankas pajuda į Vakarus\n"+time+" "+ x+";"+ y);
System.out.println("Kita komanda:");
// pajuda i rytus x+1 y0
//laikas + kordinates esamos x y
}
public void suvis() {
suviai++;
if(kryptis=="Siaure") {
suviaiS++;
} else if (kryptis=="Pietus") {
suviaiP++;
} else if (kryptis=="Vakarus") {
suviaiV++;
} else if (kryptis=="Rytus") {
suviaiR++;
}
System.out.println("Šuvis į "+kryptis);
System.out.println(time+" "+ x+";"+ y);
//suviai i priesa
if (kryptis=="Siaure"&&x==priesasX) {
for (c=y;c<=priesasY;c++) {
infoX();
runProgram = false;
break;
}
} else if (kryptis=="Pietus"&&x==priesasX) {
for (c=y;y>=priesasY;c-- ) {
runProgram = false;
infoX();
break;
}
} else if (kryptis=="Siaure"&&y==priesasY) {
for (c=x;x<=priesasX;c++ ) {
runProgram = false;
infoX();
break;
}
} else if (kryptis=="Siaure"&&y==priesasY) {
for (c=x;x>=priesasX;c-- ) {
runProgram = false;
infoX();
break;
}
}
else {
System.out.println("Kita komanda:");
}
//suvis i pasisukusia krypti
}
public void info() {
System.out.println("INFO: tanko koordinatės: "+x+":"+y);
System.out.println("INFO: Tanko šūviai: "+suviaiS+" į Šiaurę, "+suviaiR+" į Rytus,"+ suviaiP
+" į Pietus, "+suviaiV +" į Vakarus. Iš viso šūvių: "+suviai);
System.out.println(priesasX+" "+ priesasY);
System.out.println("Kita komanda:");
//kryptis
//kordinates x/y esamos
//kiek atliko suviu
//kiek atliko suviu i kiekviena puse
}
public void infoX() {
System.out.println("INFO: tanko koordinatės: "+x+":"+y);
System.out.println("INFO: Tanko šūviai: "+suviaiS+" į Šiaurę, "+suviaiR+" į Rytus,"+ suviaiP
+" į Pietus, "+suviaiV +" į Vakarus. Iš viso šūvių: "+suviai);
System.out.println("Pataikei! Priešas buvo: "+priesasX+";"+priesasY);
System.out.println("G.G.");
}
}
|
package com.podarbetweenus.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.podarbetweenus.Entity.ResourceList;
import com.podarbetweenus.R;
import java.util.ArrayList;
/**
* Created by Administrator on 11/26/2015.
*/
public class ResourceAdapter extends BaseAdapter{
private Context context;
LayoutInflater layoutInflater;
Context con;
ArrayList<ResourceList> resource_list;
public ResourceAdapter(Context context,ArrayList<ResourceList> resource_list) {
this.context = context;
this.resource_list = resource_list;
this.layoutInflater = layoutInflater.from(this.context);
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return resource_list.size();
}
@Override
public Object getItem(int position) {
return resource_list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
View showLeaveStatus = convertView;
if (showLeaveStatus == null) {
holder = new ViewHolder();
showLeaveStatus = layoutInflater.inflate(R.layout.template_child_resource, null);
holder.tv_resource = (TextView) showLeaveStatus.findViewById(R.id.tv_resource);
holder.img_resource_icon = (ImageView) showLeaveStatus.findViewById(R.id.img_resource_icon);
} else {
holder = (ViewHolder) showLeaveStatus.getTag();
}
showLeaveStatus.setTag(holder);
try {
if (resource_list.get(position).crl_descp.equalsIgnoreCase("Audio/Video")) {
holder.img_resource_icon.setImageResource(R.drawable.audio);
} else if (resource_list.get(position).crl_descp.equalsIgnoreCase("Presentation")) {
holder.img_resource_icon.setImageResource(R.drawable.ppt1_32);
} else if (resource_list.get(position).crl_descp.equalsIgnoreCase("Video")) {
holder.img_resource_icon.setImageResource(R.drawable.videos);
} else if (resource_list.get(position).crl_descp.equalsIgnoreCase("Worksheet")) {
holder.img_resource_icon.setImageResource(R.drawable.pdf_file_format_symbol);
} else {
holder.img_resource_icon.setImageResource(R.drawable.pdf_file_format_symbol);
}
}
catch (Exception e)
{
e.printStackTrace();
}
holder.tv_resource.setText(resource_list.get(position).crl_discription);
return showLeaveStatus;
}
public static class ViewHolder
{
TextView tv_resource;
//ImageView
ImageView img_resource_icon;
}
}
|
package com.pay.payo.viewmodels;
import android.app.Application;
import android.util.Log;
import com.pay.payo.application.PayOApplication;
import com.pay.payo.model.NetworksResponseModel;
import com.pay.payo.network.APIService;
import com.pay.payo.repository.Repository;
import com.pay.payo.utils.AppExecutors;
import com.pay.payo.utils.Resource;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
public class NetworksViewModel extends AndroidViewModel {
private static final String TAG = NetworksViewModel.class.getSimpleName();
public static final String QUERY_EXHAUSTED = "No more results.";
public enum ViewState {NETWORKS}
private MutableLiveData<ViewState> viewState;
private MediatorLiveData<Resource<NetworksResponseModel>> networkData = new MediatorLiveData<>();
private Repository repository;
private boolean cancelRequest;
public NetworksViewModel(@NonNull Application application) {
super(application);
repository = ((PayOApplication) application).getApplicationComponent().getRepository();
init();
}
private void init() {
if (viewState == null) {
viewState = new MutableLiveData<>();
viewState.setValue(ViewState.NETWORKS);
}
}
public LiveData<Resource<NetworksResponseModel>> getNetworkData() {
return networkData;
}
public void getNetworkInfoFromNetwork(APIService apiService,
AppExecutors executors) {
cancelRequest = false;
viewState.setValue(ViewState.NETWORKS);
final LiveData<Resource<NetworksResponseModel>> repositorySource = repository
.getNetworks(apiService, executors);
networkData.addSource(repositorySource, listResource -> {
if (!cancelRequest) {
if (listResource != null) {
if (listResource.status == Resource.Status.SUCCESS) {
Log.d(TAG, "onChanged: " + listResource.data);
if (listResource.data != null) {
if (listResource.data.getNetworks().getApplicable().size() == 0) {
Log.d(TAG, "onChanged: query is exhausted...");
networkData.setValue(
new Resource<>(
Resource.Status.ERROR,
listResource.data,
QUERY_EXHAUSTED
)
);
}
}
networkData.removeSource(repositorySource);
} else if (listResource.status == Resource.Status.ERROR) {
networkData.removeSource(repositorySource);
}
networkData.setValue(listResource);
} else {
networkData.removeSource(repositorySource);
}
} else {
networkData.removeSource(repositorySource);
}
});
}
}
|
package com.pz.Dto;
import lombok.*;
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class SLTypyPokoiDto {
private long id;
private String nazwa;
}
|
package com.sinata.rwxchina.component_home.adapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.amap.api.services.core.PoiItem;
import com.sinata.rwxchina.basiclib.base.BaseActivity;
import com.sinata.rwxchina.basiclib.utils.amaputils.NativeUtils;
import com.sinata.rwxchina.basiclib.utils.appUtils.CallPhoneUtils;
import com.sinata.rwxchina.basiclib.view.ActionSheetDialog;
import com.sinata.rwxchina.component_home.R;
import java.util.List;
/**
* @author:zy
* @detetime:2018/1/5
* @describe:类描述
* @modifyRecord:修改记录
*/
public class NearbyServiceAdapter extends BaseAdapter {
List<PoiItem> list;
private BaseActivity baseActivity;
public NearbyServiceAdapter(List<PoiItem> list, BaseActivity baseActivity) {
this.list = list;
this.baseActivity = baseActivity;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(baseActivity).inflate(R.layout.item_civilianservice, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.mItemCivilianserviceName.setText(list.get(position).getTitle());
viewHolder.mItemCivilianserviceAddress.setText(list.get(position).getSnippet());
if (list.get(position).getDistance() != -1) {
float f = list.get(position).getDistance() / 1000.0f;
viewHolder.mItemCivilianserviceMiles.setText(f + "km");
}
viewHolder.mItemCivilianserviceSubtitle.setText(list.get(position).getTypeDes());
if (TextUtils.isEmpty(list.get(position).getTel())){
viewHolder.mItemCivilianservicePhone.setVisibility(View.GONE);
}else {
viewHolder.mItemCivilianservicePhone.setVisibility(View.VISIBLE);
}
viewHolder.mItemCivilianservicePhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CallPhoneUtils.call(baseActivity,list.get(position).getTel());
}
});
viewHolder.mItemCivilianserviceRoute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new ActionSheetDialog(baseActivity)
.builder()
.setCancelable(false)
.setCanceledOnTouchOutside(false)
.addSheetItem("百度地图", ActionSheetDialog.SheetItemColor.Blue,
new ActionSheetDialog.OnSheetItemClickListener() {
@Override
public void onClick(int which) {
NativeUtils.invokingBD(baseActivity,list.get(position).getTitle(),list.get(position).getCityName());
}
})
.addSheetItem("高德地图", ActionSheetDialog.SheetItemColor.Blue,
new ActionSheetDialog.OnSheetItemClickListener() {
@Override
public void onClick(int which) {
NativeUtils.invokingGD(baseActivity,list.get(position).getTitle());
}
}).show();
}
});
return convertView;
}
public List<PoiItem> getList() {
return list;
}
public void setList(List<PoiItem> list) {
this.list = list;
}
class ViewHolder {
private TextView mItemCivilianserviceName;
private TextView mItemCivilianserviceSubtitle;
private TextView mItemCivilianserviceMiles;
private TextView mItemCivilianserviceAddress;
private LinearLayout mItemCivilianservicePhone;
private LinearLayout mItemCivilianserviceRoute;
public ViewHolder(View view) {
mItemCivilianserviceName = view.findViewById(R.id.item_civilianservice_name);
mItemCivilianserviceSubtitle = view.findViewById(R.id.item_civilianservice_subtitle);
mItemCivilianserviceMiles = view.findViewById(R.id.item_civilianservice_miles);
mItemCivilianserviceAddress = view.findViewById(R.id.item_civilianservice_address);
mItemCivilianservicePhone = view.findViewById(R.id.item_civilianservice_phone);
mItemCivilianserviceRoute = view.findViewById(R.id.item_civilianservice_route);
}
}
}
|
package com.jlgproject.activity;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jlgproject.MainActivity;
import com.jlgproject.R;
import com.jlgproject.base.BaseActivity;
import com.jlgproject.http.AddHeaders;
import com.jlgproject.http.BaseUrl;
import com.jlgproject.http.GetParmars;
import com.jlgproject.http.HttpMessageInfo;
import com.jlgproject.http.OkHttpUtils;
import com.jlgproject.model.Login_zud;
import com.jlgproject.model.Yzm;
import com.jlgproject.util.ActivityCollector;
import com.jlgproject.util.ConstUtils;
import com.jlgproject.util.CountdownTimer_utils;
import com.jlgproject.util.SharedUtil;
import com.jlgproject.util.ToastUtil;
import org.greenrobot.eventbus.EventBus;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.RequestBody;
/**
* Created by sunbeibei on 2017/5/19.
* 更改手机号
*/
public class ChangePhone extends BaseActivity implements View.OnClickListener, HttpMessageInfo.IMessage {
private ImageView title_left;
private TextView title;
private Button button, btn_save;
private int indext = 60;
private Handler handler = new Handler();
private EditText phone_number, et_yzm;
private String phone;//手机号
private String yzm;//验证码
private LinearLayout change;
@Override
public int loadWindowLayout() {
return R.layout.change_phone;
}
@Override
public void initDatas() {
super.initDatas();
}
@Override
public void initViews() {
super.initViews();
change = (LinearLayout) findViewById(R.id.prgress_change_phone);
title_left = (ImageView) findViewById(R.id.iv_title_left);
title = (TextView) findViewById(R.id.tv_title_name);
title.setText("更换手机号");
title_left.setImageResource(R.mipmap.back);
title_left.setVisibility(View.VISIBLE);
title_left.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
phone_number = (EditText) findViewById(R.id.phone_number);//手机号
et_yzm = (EditText) findViewById(R.id.et_yzm);
button = (Button) findViewById(R.id.btn);
button.setOnClickListener(this);
btn_save = (Button) findViewById(R.id.btn_save);
btn_save.setOnClickListener(this);
}
private void timerUtils() {
new Thread(new CountdownTimer_utils(60, handler, button,getResources().getDrawable(R.drawable.countimer),getResources().getDrawable(R.drawable.delete))).start();
HttpMessageInfo<Yzm> info = new HttpMessageInfo<>(BaseUrl.YZM, new Yzm());
info.setiMessage(this);
GetParmars parmars = new GetParmars();
parmars.add("mobile", phone_number.getText().toString().trim());
OkHttpUtils.getInstance().getServiceMassage(OkHttpUtils.TYPE_GET, info, parmars, null, 1);
}
@Override
public void onClick(View v) {
if (button == v) {
if (!TextUtils.isEmpty(phone_number.getText().toString().trim())) {
phone = phone_number.getText().toString().trim();
if(phone.length()==11){
timerUtils();
} else {
ToastUtil.showShort(this, "请输入正确的手机号");
}
} else {
ToastUtil.showShort(this, "请输入手机号");
}
} else if (btn_save == v) {
change.setVisibility(View.VISIBLE);
if (et_yzm.getText().toString().trim() != null) {
Login_zud login = (Login_zud) SharedUtil.getSharedUtil().getObject(this, ConstUtils.IOGIN_INFO, null);
HttpMessageInfo<Yzm> info = new HttpMessageInfo<Yzm>(BaseUrl.MY_PHONE, new Yzm());
info.setiMessage(this);
RequestBody requestBody = new FormBody.Builder()
.add("mobile", phone)
.add("validcode", et_yzm.getText().toString().trim())
.build();
info.setFormBody(requestBody);
if (login != null) {
AddHeaders headers = new AddHeaders();
headers.add("Authorization", login.getData().getToken());
OkHttpUtils.getInstance().getServiceMassage(OkHttpUtils.TYPE_POST, info, null, headers, 1);
}
} else {
ToastUtil.showShort(this, "请输入验证码");
}
}
}
@Override
public void getServiceData(Object o) {
if (o instanceof Yzm) {
Yzm yzm = (Yzm) o;
if (yzm.getState().equals("ok")) {
change.setVisibility(View.GONE);
if (yzm.getMessage().equals("短信发送成功!")) {
ToastUtil.showShort(this, yzm.getMessage());
} else {
ToastUtil.showShort(this,yzm.getMessage());
EventBus.getDefault().postSticky("1");
ActivityCollector.startA(this, MainActivity.class, "currMenu", 3);
finish();
}
} else if (yzm.getState().equals("warn")) {
change.setVisibility(View.GONE);
ToastUtil.showShort(this, yzm.getMessage().toString());
}
}
}
@Override
public void getErrorData(Call call, IOException e) {
}
}
|
package lombok_test;
import java.util.HashSet;
import java.util.Set;
/**
* Description:
* 1、必须勾选Preferences-Build,Execution,Deployment-Compiler-Annotation Processors-Enable annotation processing,
* 否则无法通过编译
* 2、参考:
* <a href="https://mp.weixin.qq.com/s?__biz=Mzg2OTA0Njk0OA==&mid=2247485385&idx=2&sn=a7c3fb4485ffd8c019e5541e9b1580cd&chksm=cea24802f9d5c1144eee0da52cfc0cc5e8ee3590990de3bb642df4d4b2a8cd07f12dd54947b9&token=1381785723&lang=zh_CN#rd"></a>
*
* @author Baltan
* @date 2019-12-01 17:00
*/
public class Test1 {
public static void main(String[] args) {
/**
* @AllArgsConstructor
*/
Person zhangsan = new Person(1, "Zhang San", 33, "male", "Teacher");
Person anotherZhangsan = new Person(1, "Zhang San", 33, "male", "Teacher");
Person lisi = new Person(2, "Li Si", 34, "male", "Doctor");
/**
* @RequiredArgsConstructor(staticName = "getInstance")
*/
Person wangwu = Person.getInstance(3, "Wang Wu", "male", "Worker");
/**
* @ToString(exclude = {"id"}, includeFieldNames = false)
*/
System.out.println(zhangsan);
System.out.println(lisi);
System.out.println(wangwu);
zhangsan.say("I am Zhang San!");
/**
* @NonNull
* NullPointerException: sentence is marked non-null but is null
*/
// zhangsan.say(null);
/**
* @EqualsAndHashCode
*/
Set<Person> persons = new HashSet<>();
persons.add(zhangsan);
persons.add(anotherZhangsan);
persons.add(lisi);
persons.add(wangwu);
System.out.println(persons);
/**
* @Data:注解在类上,相当于同时使用了@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor
*/
Book cynh = new Book("草样年华", "孙睿");
System.out.println(cynh.getName());
System.out.println(cynh.getAuthor());
System.out.println(cynh);
/**
* @Value:注解在类上,是@Data的不可变形式,相当于为属性添加final声明,只提供getter方法,而不提供setter方法
*/
Computer mbp = new Computer("Apple", "MacBook Pro(13-inch)", 9999.99f);
System.out.println(mbp.getBrand());
System.out.println(mbp.getModel());
System.out.println(mbp.getPrice());
System.out.println(mbp);
/**
* @Builder:用在类、构造器、方法上,为你提供复杂的builder APIs
*/
Desk desk = Desk.builder().length(2f).width(1.2f).height(1.1f).color("white").build();
System.out.println(desk);
}
}
|
package com.cleo.ringto;
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by terrin on 4/5/15.
*/
public class RingToAPI extends Fragment
{
private String token = "";
private String access_token = "";
private String jb_token = "";
private GetMessages messages = null;
private JSONArray jobj_message = null;
// protected RingToChatScreen activity = null;
private boolean isTaskRunning = false;
private ProgressDialog progressDialog = null;
ActionBarActivity mActivity = null;
ChatListThreadAdapter list = null;
public void setToken(String token)
{
this.token = token;
}
public void setAccessToken(String access_token)
{
this.access_token = token;
}
public void setList(ChatListThreadAdapter list)
{
this.list = list;
}
void attach(ActionBarActivity activity)
{
mActivity = activity;
}
void detach()
{
mActivity = null;
}
// @Override
// public void onActivityCreated(Bundle savedInstanceState)
// {
// super.onActivityCreated(savedInstanceState);
// // If we are returning here from a screen orientation
// // and the AsyncTask is still working, re-create and display the
// // progress dialog.
//
// if (isTaskRunning)
// {
// progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
// }
// }
// public RingToAPI(String token)
// {
// this.token = token;
// this.messages = new GetMessages();
// }
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public String getToken()
{
return token;
}
public String getAccessToken()
{
return access_token;
}
public void setActivity(ActionBarActivity activity)
{
this.mActivity = activity;
}
public void setAPI(ActionBarActivity activity, String token, ChatListThreadAdapter list)
{
this.mActivity = activity;
this.token = token;
new GetMessages(mActivity,token).execute();
this.list = list;
}
public void setAPI(ActionBarActivity activity, String token)
{
this.mActivity = activity;
this.token = token;
new GetMessages(mActivity,token).execute();
}
public void setAPI(ActionBarActivity activity, String token, String access_token)
{
this.mActivity = activity;
this.token = token;
this.access_token = access_token;
new GetMessages(mActivity,token).execute();
}
public void setAPI(ActionBarActivity activity, String token, String access_token, String jb_token)
{
this.mActivity = activity;
this.token = token;
this.access_token = access_token;
this.jb_token = jb_token;
new GetMessages(mActivity,token).execute();
new GetNumbers(mActivity, token, jb_token).execute();
}
public void setAPI(ActionBarActivity activity, String token, String access_token, String current_number, ArrayList<String> media, String text, ArrayList<String> sent_number)
{
this.mActivity = activity;
this.token = token;
this.access_token = access_token;
new SendMessage(mActivity, token, current_number, media, text, sent_number).execute();
}
public void onTaskStarted()
{
isTaskRunning = true;
// progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
}
public void onTaskFinished(String result)
{
if (progressDialog != null)
{
// progressDialog.dismiss();
}
isTaskRunning = false;
}
@Override
public void onDetach()
{
// All dialogs should be closed before leaving the activity in order to avoid
// the: Activity has leaked window com.android.internal.policy... exception
if (progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
super.onDetach();
}
public void pullMessages(ActionBarActivity activity, String token)
{
// this.activity = activity;
// messages.execute();
messages = new GetMessages(activity, token);
onTaskStarted();
messages.execute();
}
// public JSONArray storeMessages(ActionBarActivity activity)
// {
// Log.d("Message Size", Integer.toString(jobj_message.length()));
//
// for(int i = jobj_message.length()-1; i > -1; i--)
// {
// long server_id;
// String from_number;
// String to_number;
// String direction;
// String date;
// String date_raw;
// String text;
// String incoming;
// String status;
// String read;
// boolean left;
//
// try
// {
// server_id = jobj_message.getJSONObject(i).getLong("id");
// from_number = jobj_message.getJSONObject(i).getString("from");
// to_number = jobj_message.getJSONObject(i).getString("to");
// direction = jobj_message.getJSONObject(i).getString("direction");
// date = jobj_message.getJSONObject(i).getString("date");
// date_raw = jobj_message.getJSONObject(i).getString("date_raw");
// text = jobj_message.getJSONObject(i).getString("text");
// incoming = jobj_message.getJSONObject(i).getString("status_id");
// status = jobj_message.getJSONObject(i).getString("status");
// read = jobj_message.getJSONObject(i).getString("read");
//
// if(direction.equals("Incoming"))
// {
// left = true;
// }
//
// else
// {
// left = false;
// }
//
// ((RingToMainContainer) activity).storeChatMessage(left, server_id, from_number, to_number, direction,
// date, date_raw, text, incoming, status, read);
// }
//
// catch (JSONException e)
// {
// e.printStackTrace();
// }
// }
//
// return jobj_message;
// }
private class SendMessage extends AsyncTask<Void, Void, Void>
{
String token = "";
String current_number = "";
ArrayList<String> media = new ArrayList<String>();
String text = "";
ArrayList<String> sent_number = new ArrayList<String>();
int[] message_ids;
String[] status;
JSONObject obj;
boolean completion = false;
public SendMessage(ActionBarActivity activity, String token, String current_number, ArrayList<String> media, String text, ArrayList<String> sent_number)
{
attach(activity);
this.token = token;
this.current_number = current_number;
this.media = media;
this.text = text;
this.sent_number = sent_number;
}
@Override
protected Void doInBackground(Void... params)
{
Log.d("Starting", "AsyncTask starting.");
JSONObject jObj = null;
JSONArray jObj_returned = null;
String retSrc = "";
// String URL = "https://ring.to/api/messages?";
RingToApplication application = new RingToApplication();
String URL = "https://partners.ring.to/api/users/" + token + "/messages?access_token="
+ access_token;
// String URL = "https://ring.to/api/users/" + getToken();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try
{
// RingTo API to obtain token
obj = new JSONObject();
JSONArray m = new JSONArray();
for(int i = 0; i < media.size(); i++)
{
m.put(media.get(i));
}
JSONArray sn = new JSONArray();
for(int i = 0; i < sent_number.size(); i++)
{
sn.put("+" + sent_number.get(i));
}
obj.put("from", "+" + current_number);
obj.put("media", m);
obj.put("text", text);
obj.put("to", sn);
// List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
// nameValuePairs.add(new BasicNameValuePair("from", "+" + current_number));
// nameValuePairs.add(new BasicNameValuePair("media", "5523parabal"));
// nameValuePairs.add(new BasicNameValuePair("text", text));
// nameValuePairs.add(new BasicNameValuePair("to", "terrincelestin@gmail.com"));
// httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpPost.setEntity(new ByteArrayEntity(obj.toString().getBytes("UTF8")));
httpPost.setHeader("Content-Type", "application/json");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null)
{
retSrc = EntityUtils.toString(httpEntity);
jObj_returned = new JSONArray(retSrc);
Log.d("String url", URL);
Log.d("JSON Send Message", jObj_returned.toString());
Log.d("JSON Object", obj.toString());
message_ids = new int[jObj_returned.length()];
status = new String[jObj_returned.length()];
for(int i = 0; i < jObj_returned.length(); i++)
{
message_ids[i] = (int) ((JSONObject) jObj_returned.get(i)).get("message_id");
status[i] = (String) ((JSONObject) jObj_returned.get(i)).get("status");
Log.d("status", Integer.toString(message_ids[i]));
Log.d("status", status[i]);
}
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d("Error", "Cannot Estabilish Connection");
completion = false;
}
completion = true;
return null;
}
@Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
if(completion)
{
try
{
((RingToChatScreen) mActivity).storeChatMessage(false, message_ids[0], obj.getString("from"), obj.getString("to"), "out", Message.getDateAndTime(), text, status[0], "true");
}
catch(JSONException e)
{
Log.e("RingToAPI", "JSON object did not have the correct attributes");
Log.d("RingToAPI Object Attrib", obj.toString());
}
}
else
{
Log.e("RingToAPI", "GetMessages did not complete the getMessage HTTPConnection.");
}
}
}
private class GetNumbers extends AsyncTask<Void, Integer, Void>
{
boolean login = false;
String token = "";
String jb_token = "";
ArrayList<Message> temp = null;
ProgressDialog progressDialog;
public GetNumbers(ActionBarActivity activity, String token, String jb_token)
{
attach(activity);
this.token = token;
this.jb_token = jb_token;
// progressDialog = ProgressDialog.show(activity, "Downloading Messages",
// "dialog message", true);
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}
@Override
// protected Void doInBackground(Void... params)
protected Void doInBackground(Void... params)
{
Log.d("Starting", "AsyncTask starting.");
JSONObject jObj_returned = null;
String URL = "https://ring.to/api/numbers";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
Log.d("jb token thing", jb_token);
httpPost.setHeader("JB-Token", jb_token);
ArrayList<String> numbers = new ArrayList<String>();
try
{
Log.d("RingTo jb-token", jb_token);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String retSrc = "";
if (httpEntity != null)
{
retSrc = EntityUtils.toString(httpEntity);
jObj_returned = new JSONObject(retSrc);
JSONArray number = (JSONArray) jObj_returned.get("numbers");
for(int i=0; i < number.length(); i++)
{
numbers.add(number.getJSONObject(i).getString("number"));
}
Log.d("Numbers", numbers.get(0));
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d("Error", "Cannot Estabilish Connection");
}
return null;
}
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values)
{
if(values[0].longValue() < 20)
{
progressDialog.setMessage("Parsing Through Messages");
}
else if(values[0].longValue() > 20)
{
progressDialog.setMessage("Storing Messages In Local Database");
}
// getMessages(mActivity);
}
@Override
protected void onPostExecute(Void params)
{
super.onPostExecute(params);
if (mActivity != null)
{
// storeMessages(mActivity);
ArrayList<Message> temp = new ArrayList<Message>();
temp.addAll(((RingToMainContainer) mActivity).getDataSource().getRecentChatThreads());
if(list != null)
{
list.addMessageThreads(temp);
list.notifyDataSetChanged();
}
progressDialog.cancel();
((RingToMainContainer) mActivity).printStuff(temp);
Toast.makeText(mActivity, "AsyncTask finished", Toast.LENGTH_LONG).show();
Log.d("Done", "AsyncTask finished while Activity was attached.");
RingToApplication singleton = (RingToApplication) mActivity.getApplicationContext();
singleton.setInitialPullMessage(true);
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
detach();
}
else
{
Log.d("Done", "AsyncTask finished while no Activity was attached.");
}
}
}
private class GetMessages extends AsyncTask<Void, Integer, Void>
{
boolean login = false;
String token = "";
ArrayList<Message> temp = null;
ProgressDialog progressDialog;
public GetMessages(ActionBarActivity activity, String token)
{
attach(activity);
this.token = token;
// progressDialog = ProgressDialog.show(activity, "Downloading Messages",
// "dialog message", true);
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
progressDialog = new ProgressDialog(activity);
progressDialog.setTitle("Downloading All Messages");
progressDialog.setMessage("Pulling Messages From Server");
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.show();
}
@Override
// protected Void doInBackground(Void... params)
protected Void doInBackground(Void... params)
{
Log.d("Starting", "AsyncTask starting.");
JSONObject jObj = null;
JSONObject jObj_returned = null;
String retSrc = "";
// String URL = "https://ring.to/api/messages?";
RingToApplication application = new RingToApplication();
String URL = "https://partners.ring.to/api/users/" + token + "/messages/conversations?access_token="
+ access_token + "&messages=10&page=1&page_size=30";
DefaultHttpClient httpClient = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
try
{
Log.d("RingTo uuid", token);
Log.d("RingTo uuid", application.getAccessToken());
HttpGet httpGet = new HttpGet(URL);
// httpGet.setHeader("JB-Token", token);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
JSONObject obj = new JSONObject(builder.toString());
Log.d("Output", obj.toString());
List<String> list = new ArrayList<String>();
JSONArray array1 = null;
try
{
array1 = obj.getJSONArray("data");
}
catch (JSONException e)
{
e.printStackTrace();
}
int array_count = 0;
int prev_array_length = 0;
for(int message_count = 0; message_count < array1.length(); message_count++)
{
JSONObject obj2 = array1.getJSONObject(message_count);
JSONArray array = obj2.getJSONArray("messages");
array_count = array_count + array.length();
Log.d("Length of Array1", Integer.toString(array_count));
}
int myProgress = 0;
for(int index = 0; index < array1.length(); index++)
{
JSONObject obj2 = array1.getJSONObject(index);
JSONArray array = obj2.getJSONArray("messages");
jobj_message = array;
progressDialog.setProgress(myProgress);
publishProgress(myProgress);
for (int i = 0; i < array.length(); i++)
{
list.add(array.getJSONObject(i).getString("text"));
prev_array_length = prev_array_length + 1;
myProgress = ((prev_array_length * 100) / (2 * array_count)); //jobj_message.length()));
progressDialog.setProgress(myProgress);
publishProgress(myProgress);
Log.d("array length", Integer.toString(prev_array_length));
Log.d("20 my progress", Integer.toString(myProgress));
}
// for (int j = 0; j < list.size(); j++) {
// Log.d("Text", list.get(j));
// }
if (mActivity != null)
{
Log.d("Message Size", Integer.toString(jobj_message.length()));
for (int i = jobj_message.length() - 1; i > -1; i--)
{
long message_id;
String direction;
String from_number;
String to_number;
String text;
String time;
// String date_raw;
// String incoming;
String read;
String status;
boolean left;
try
{
message_id = jobj_message.getJSONObject(i).getLong("message_id");
from_number = jobj_message.getJSONObject(i).getString("from");
to_number = jobj_message.getJSONObject(i).getString("to");
direction = jobj_message.getJSONObject(i).getString("direction");
time = jobj_message.getJSONObject(i).getString("time");
//date_raw = jobj_message.getJSONObject(i).getString("date_raw");
text = jobj_message.getJSONObject(i).getString("text");
// incoming = jobj_message.getJSONObject(i).getString("status");
status = jobj_message.getJSONObject(i).getString("status");
read = jobj_message.getJSONObject(i).getString("read");
// if(direction.equals("Incoming"))
if (direction.equals("in"))
{
left = true;
}
else
{
left = false;
}
((RingToMainContainer) mActivity).storeChatMessage(left, message_id, from_number, to_number, direction,
time, text, status, read);
}
catch (JSONException e)
{
e.printStackTrace();
}
prev_array_length = prev_array_length + 1; //(jobj_message.length() - i);
myProgress = ((prev_array_length * 100)/ (2 * array_count));
publishProgress(myProgress);
progressDialog.setProgress(myProgress);
Log.d("array length", Integer.toString(prev_array_length));
Log.d("20 my progress", Integer.toString(myProgress));
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
Log.d("Error", "Cannot Estabilish Connection");
}
return null;
}
@Override
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values)
{
if(values[0].longValue() < 20)
{
progressDialog.setMessage("Parsing Through Messages");
}
else if(values[0].longValue() > 20)
{
progressDialog.setMessage("Storing Messages In Local Database");
}
// getMessages(mActivity);
}
@Override
protected void onPostExecute(Void params)
{
super.onPostExecute(params);
if (mActivity != null)
{
// storeMessages(mActivity);
ArrayList<Message> temp = new ArrayList<Message>();
temp.addAll(((RingToMainContainer) mActivity).getDataSource().getRecentChatThreads());
if(list != null)
{
list.addMessageThreads(temp);
list.notifyDataSetChanged();
}
progressDialog.cancel();
((RingToMainContainer) mActivity).printStuff(temp);
Toast.makeText(mActivity, "AsyncTask finished", Toast.LENGTH_LONG).show();
Log.d("Done", "AsyncTask finished while Activity was attached.");
RingToApplication singleton = (RingToApplication) mActivity.getApplicationContext();
singleton.setInitialPullMessage(true);
mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
detach();
}
else
{
Log.d("Done", "AsyncTask finished while no Activity was attached.");
}
}
}
}
|
package com.example.sam.cs_125_final_project;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "FinalProject";
/** Request queue for our network requests. */
private static RequestQueue requestQueue;
private static String code = "CNY";
private static double rates = 0;
@SuppressWarnings("CheckStyle")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up a queue for our Volley requests
requestQueue = Volley.newRequestQueue(this);
setContentView(R.layout.activity_main);
final TextView output = (TextView) findViewById(R.id.output);
final EditText input = findViewById(R.id.input);
final Button bt_1 = findViewById(R.id.bt_1);
bt_1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for HKD");
code = "HKD";
startAPICall(code);
if (input.getText() == null) {
Log.d(TAG,"NUll");
}
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_2 = findViewById(R.id.bt_2);
bt_2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for KRW");
code = "KRW";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_3 = findViewById(R.id.bt_3);
bt_3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for RUB");
code = "RUB";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_4 = findViewById(R.id.bt_4);
bt_4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for JPY");
code = "JPY";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_5 = findViewById(R.id.bt_5);
bt_5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for CAD");
code = "CAD";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_6 = findViewById(R.id.bt_6);
bt_6.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for NZD");
code = "NZD";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_7 = findViewById(R.id.bt_7);
bt_7.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for CNY");
code = "CNY";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_8 = findViewById(R.id.bt_8);
bt_8.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for EUR");
code = "EUR";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
final Button bt_9 = findViewById(R.id.bt_9);
bt_9.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d(TAG,"button for GBP");
code = "GBP";
startAPICall(code);
double num = Double.parseDouble(input.getText().toString());
output.setText(String.valueOf(rates * num));
}
});
}
void startAPICall(final String str) {
try {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.GET,
"https://api.exchangeratesapi.io/latest?base=USD",
null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(final JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONObject rate = response.getJSONObject("rates");
Log.d(TAG, rate.get(str).toString());
rates = Double.parseDouble(rate.get(str).toString());
Log.d(TAG,String.valueOf(rates));
} catch (JSONException e) {
Log.e(TAG, "i dont know what happened");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(final VolleyError error) {
Log.w(TAG, error.toString());
}
});
requestQueue.add(jsonObjectRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package model.Eagle;
import model.Tile;
import model.interfaces.Piece;
import resources.Sprites;
public class NormDummyEagleDecorator extends EagleDecorator {
public NormDummyEagleDecorator(Piece decoratedEagle) {
super(decoratedEagle);
super.setSprite(Sprites.Eagle);
}
// Used for debugging only - returns ANSI_RED D
@Override
public String toString() {
return "\u001B[31m D \u001B[0m";
}
@Override
public Piece transform() {
Piece newForm = new AltDummyEagleDecorator(this.decoratedEagle);
super.getTile().setPiece(newForm);
return newForm;
}
} |
package com.example.demo.config;
import com.couchbase.mock.BucketConfiguration;
import com.couchbase.mock.CouchbaseMock;
import java.util.ArrayList;
public class CouchbaseStartConfig {
private static CouchbaseMock couchbaseMock;
public static void couchbaseStart() {
BucketConfiguration bucketConfiguration = new BucketConfiguration();
bucketConfiguration.numNodes = 1;
bucketConfiguration.numReplicas = 1;
bucketConfiguration.numVBuckets = 1024;
bucketConfiguration.type = com.couchbase.mock.Bucket.BucketType.COUCHBASE;
bucketConfiguration.name = "test";
bucketConfiguration.password = "password";
ArrayList<BucketConfiguration> configList = new ArrayList<BucketConfiguration>();
configList.add(bucketConfiguration);
try {
couchbaseMock = new CouchbaseMock(8091, configList);
couchbaseMock.start();
couchbaseMock.waitForStartup();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void couchbaseStop() {
couchbaseMock.stop();
}
}
|
package swt6.timer.factories;
import swt6.timer.interfaces.TimerServiceFactory;
import swt6.timer.services.TimerServiceImpl;
import swt6.timer.interfaces.TimerService;
public class TimerServiceFactoryImpl implements TimerServiceFactory {
public TimerService getTimerService() {
return new TimerServiceImpl();
}
public boolean providesFeature(String feature) {
return feature.equals("TimerServiceImpl");
}
}
|
package ict376.murdoch.edu.au.jobtaskrapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
public class SignUpActivity extends AppCompatActivity {
private View V;
protected boolean flag = false;
Client_SignUp myFg = null;
Tech_SignUp newTechSignupFg = null;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener;
{
mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.client_Nav:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Fragment currentFragment = getApplicationContext().getFragmentManager().findFragmentById(R.id.fragment_container);
if (newTechSignupFg != null) {
ft.remove(newTechSignupFg);
// ft.commit();
}
myFg = new Client_SignUp();
ft.replace(R.id.areaFragment, myFg);
ft.commit();
flag = true;
break;
case R.id.tech_Nav:
FragmentTransaction fx = getSupportFragmentManager().beginTransaction();
newTechSignupFg = new Tech_SignUp();
fx.replace(R.id.areaFragment, newTechSignupFg);
fx.commit();
flag = true;
break;
}
return flag;
}
};
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
public static Intent newIntent(Context packageContext){
Intent i = new Intent(packageContext, SignUpActivity.class);
return i;
}
}
|
package com.nxtlife.mgs.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.nxtlife.mgs.service.ActivityService;
import com.nxtlife.mgs.service.TeacherService;
import com.nxtlife.mgs.view.ActivityRequestResponse;
import com.nxtlife.mgs.view.ClubMembershipResponse;
import com.nxtlife.mgs.view.SuccessResponse;
import com.nxtlife.mgs.view.TeacherRequest;
import com.nxtlife.mgs.view.TeacherResponse;
@RestController
@RequestMapping("/")
public class TeacherController {
@Autowired
private TeacherService teacherService;
@Autowired
private ActivityService activityService;
@PostMapping(value = { "api/teacher/", "teacher/signUp" })
public TeacherResponse saveTeacher(@RequestBody TeacherRequest teacherRequest) {
return teacherService.save(teacherRequest);
}
// @PostMapping("teacher/signUp")
// public TeacherResponse signUp(@RequestBody TeacherRequest teacherRequest) {
// if (teacherRequest.getIsCoach())
// return teacherService.saveCoach(teacherRequest);
// return teacherService.saveClassTeacher(teacherRequest);
// }
@PutMapping("api/teacher/update/{cid}")
public TeacherResponse update(@RequestBody TeacherRequest request,
@PathVariable(value = "cid", required = false) String cid) {
return teacherService.update(request, cid);
}
@PutMapping("api/teacher/profilePic")
public TeacherResponse setProfilePic(@RequestParam("profilePic") MultipartFile file,
@RequestParam(value = "cid", required = false) String cid) {
return teacherService.setProfilePic(file, cid);
}
@DeleteMapping("api/teacher/{cid}")
public SuccessResponse delete(@PathVariable(value = "cid", required = false) String cid) {
return teacherService.delete(cid);
}
@GetMapping("api/teachers")
public List<TeacherResponse> getAllTeachers(@RequestParam(defaultValue = "0") Integer pageNo,
@RequestParam(defaultValue = "20") Integer pageSize) {
return teacherService.getAllTeachers(pageNo, pageSize);
}
@GetMapping(value = "api/teachers/{schoolId}")
public List<TeacherResponse> getAllTeachersBySchool(
@PathVariable(value = "schoolId", required = false) String schoolId) {
return teacherService.getAllTeachersOfSchool(schoolId);
}
// @GetMapping(value = "q" +
// "" +
// "classTeachers")
// public List<TeacherResponse> getAllClassTeachers() {
// return teacherService.getAllClassTeachers();
// }
@GetMapping(value = "api/teacher/{cId}")
public TeacherResponse getTeacherByCId(@PathVariable(value = "cId", required = false) String cId) {
return teacherService.findByCId(cId);
}
// @GetMapping(value = "api/teacher/classTeacher/{cId}")
// public TeacherResponse getClassTeacherByCId(@PathVariable("cId") String cId) {
// return teacherService.findClassTeacherByCId(cId);
// }
// @GetMapping(value = "api/managment/{schoolCid}")
// public List<TeacherResponse> getAllManagmentBySchool(@PathVariable("schoolCid") String schoolCid) {
// return teacherService.getAllManagmentBySchool(schoolCid);
// }
@GetMapping(value = "api/teacher/club/members") // doneGrade //toSend
public List<ClubMembershipResponse> getMembershipDetails(
@RequestParam(value = "teacherId", required = false) String teacherId,
@RequestParam(value = "schoolId", required = false) String schoolCid) {
return teacherService.getMembershipDetails(teacherId, schoolCid);
}
@GetMapping(value = "api/teacher/club/{clubId}/members") // doneGrade //toSend
public List<ClubMembershipResponse> getMembershipDetailsbyClub(@PathVariable("clubId") String clubId,
@RequestParam(value = "teacherId", required = false) String teacherId,
@RequestParam(value = "schoolId", required = false) String schoolCid) {
return teacherService.getMembershipDetailsbyClub(clubId, teacherId, schoolCid);
}
@GetMapping(value = "api/teacher/clubs") // doneGrade
public List<ActivityRequestResponse> getAllClubsOfTeacher(
@RequestParam(value = "teacherId", required = false) String teacherId,
@RequestParam(value = "schoolId", required = false) String schoolId) {
return activityService.getAllClubsOfTeacher(teacherId, schoolId);
}
@PutMapping(value = "api/teacher/club") // doneGrade //toSend
public ClubMembershipResponse updateStatus(@RequestParam(name = "studentId") String studentId,
@RequestParam(name = "activityId") String activityId,
@RequestParam(name = "verified", defaultValue = "true") Boolean verified,
@RequestParam(value = "teacherId", required = false) String teacherId) {
return teacherService.updateStatus(studentId, activityId, verified, teacherId);
}
}
|
/*
* 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 initarray;
import java.util.Scanner;
public class InitArray {
public static void main(String[] args) {
int[] vetor = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int nota = 0;
Scanner entrada = new Scanner(System.in);
System.out.println("Informe as notas: (-1 para sair)");
while(nota != -1){
nota = entrada.nextInt();
vetor[nota/10]++;
}
System.out.println("Distribuição de notas:");
for (int contador = 0; contador < vetor.length; contador++) {
// gera saída do código de barras ( "00-09: ", ...., "90-99: ", "100: ")
if (contador == 10)
System.out.printf("%5d: ", 100);
else
System.out.printf("%02d-%02d: ", contador * 10, contador * 10 + 9);
// imprime a barra de asteriscos
for (int estrelas = 0; estrelas < vetor[contador]; estrelas++) {
System.out.print("*");
}
System.out.println();
}
}
}
|
package utils;
import java.util.concurrent.TimeUnit;
import play.libs.Akka;
import akka.util.Duration;
import com.typesafe.plugin.MailerAPI;
import com.typesafe.plugin.MailerPlugin;
public class AssyncEmailSender{
private Runnable sender = null;
public AssyncEmailSender(String subject, String body, String from, String replyTo, String to) {
sender = new EmailSender(subject, body, from, replyTo, to);
}
public void send() {
Akka.system().scheduler().scheduleOnce(
Duration.create(0, TimeUnit.SECONDS),
sender
);
}
private class EmailSender implements Runnable {
private String subject,
body,
from,
replyTo,
to;
public EmailSender(String subject, String body, String from, String replyTo, String to) {
this.subject = subject;
this.body = body;
this.from = from;
this.replyTo = replyTo;
this.to = to;
}
public void run() {
MailerAPI mail = play.Play.application().plugin(MailerPlugin.class).email();
mail.setSubject( subject );
mail.addRecipient(to);
mail.addFrom(from);
mail.setReplyTo(replyTo);
mail.send( body );
}
}
}
|
package com.designpattern.createpattern.factory;
public class FactroyB implements AbstractFactory {
@Override
public Object getInstance() {
return new FactroyB();
}
}
|
package com.tencent.mm.plugin.product.ui;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.widget.TextView.BufferType;
import com.tencent.mm.sdk.platformtools.ah.a;
class HtmlTextView$1 implements a {
private volatile Spanned lSa;
final /* synthetic */ String lSb;
final /* synthetic */ HtmlTextView lSc;
HtmlTextView$1(HtmlTextView htmlTextView, String str) {
this.lSc = htmlTextView;
this.lSb = str;
}
public final boolean Kr() {
this.lSa = HtmlTextView.a(this.lSc, this.lSb);
return true;
}
public final boolean Ks() {
HtmlTextView.a(this.lSc, this.lSa, BufferType.SPANNABLE);
this.lSc.setMovementMethod(LinkMovementMethod.getInstance());
return true;
}
public final String toString() {
return super.toString() + "|setText";
}
}
|
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector<String> v1 = new Vector<String>();
v1.add("James");
v1.add("John");
v1.add("Smith");
System.out.println(v1.size() + ":" + v1.capacity());
v1.add("James");
v1.add("John");
v1.add("Smith");
v1.add("James");
v1.add("John");
v1.add("Smith");
v1.add("James");
v1.add("John");
v1.add("Smith");
System.out.println(v1.size() + ":" + v1.capacity());
}
}
|
package com.moon.netty.server;
import com.alibaba.fastjson.JSONObject;
import com.moon.base.utils.Constant;
import com.moon.netty.dto.BaseMsg;
import com.moon.netty.dto.Msg_Type;
import com.moon.netty.thread.servertask.Thread01;
import com.moon.netty.thread.servertask.Thread02;
import io.netty.channel.ChannelHandlerAdapter;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
/**
* Created by mgq on 2016/3/1.
*/
public class NettyServerHandler extends ChannelHandlerAdapter {
private static ExecutorService executorService = Executors.newCachedThreadPool();
//服务端读取客户端请求
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
ByteBuf buf = (ByteBuf) msg;
String rev = getMessage(buf);
BaseMsg baseMsg=JSONObject.parseObject(rev, BaseMsg.class);
/*
* 1、assert <boolean表达式>
如果<boolean表达式>为true,则程序继续执行。
如果为false,则程序抛出AssertionError,并终止执行。
2、assert <boolean表达式> : <错误信息表达式>
如果<boolean表达式>为true,则程序继续执行。
如果为false,则程序抛出java.lang.AssertionError,并输入<错误信息表达式>。
*
* */
assert baseMsg != null:"客户端请求数据为空!";
Msg_Type type=baseMsg.getMsgType();
//System.out.println("客户端的请求:" + baseMsg);
switch (type){
case TYPE_TEST01:{
NettyHandlerMap.add("001",ctx);
Thread t01=new Thread(new Thread01());
t01.start();
}
break;
case TYPE_TEST02:{
NettyHandlerMap.add("001",ctx);
Thread t02=new Thread(new Thread02());
t02.start();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
//服务端发送请求道客户端(客户端需要启动才可以发送)
@Override
public void channelActive(ChannelHandlerContext ctx) {
try {
System.out.println("server 发送请求 start....");
// Thread thread=new Thread(new Thread02());
// thread.start();
}catch (Exception e){
}
}
/*
* 从ByteBuf中获取信息 使用UTF-8编码返回
*/
private String getMessage(ByteBuf buf) {
byte[] con = new byte[buf.readableBytes()];
buf.readBytes(con);
try {
return new String(con,Constant.UTF8);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private ByteBuf getSendByteBuf(String message)
throws UnsupportedEncodingException {
byte[] req = message.getBytes("UTF-8");
ByteBuf pingMessage = Unpooled.buffer();
pingMessage.writeBytes(req);
return pingMessage;
}
}
|
package com.spbsu.flamestream.runtime.master.acker;
import com.spbsu.flamestream.core.FlameStreamSuite;
import com.spbsu.flamestream.runtime.master.acker.table.AckTable;
import com.spbsu.flamestream.runtime.master.acker.table.ArrayAckTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* User: Artem
* Date: 30.08.2017
*/
public class AckTableTest extends FlameStreamSuite {
private static final Logger LOG = LoggerFactory.getLogger(AckTableTest.class);
@Test
public void emptyTableTest() {
final AckTable table = new ArrayAckTable(0, 10, 10, true);
Assert.assertEquals(table.tryPromote(0), 0);
}
@Test
public void singleHeartbeatTest() {
final long heartbeat = (long) 1e7;
final AckTable table = new ArrayAckTable(0, 10, 10, true);
Assert.assertEquals(table.tryPromote(heartbeat), heartbeat);
}
@Test
public void singleAckTest() {
final long ack = 70;
final AckTable table = new ArrayAckTable(0, 14, 10, true);
table.ack(ack, 1);
Assert.assertEquals(table.tryPromote(Long.MAX_VALUE), ack);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void overflowTest() {
final AckTable table = new ArrayAckTable(0, 10, 10, true);
table.ack((long) 1e9, 1);
}
@Test
public void logicTest() {
final Random rd = new Random(1);
final long head = 0;
final int capacity = 100;
final int window = 10;
final long width = capacity * window;
final AckTable table = new ArrayAckTable(head, capacity, window, true);
for (long epoch = 0; epoch < 10000; ++epoch) {
final long epochFloor = head + epoch * width / 2;
final long epochCeil = epochFloor + width / 2;
final Map<Long, Long> xors = rd
.longs(epochFloor, epochCeil)
.limit(width)
.distinct()
.boxed()
.collect(Collectors.toMap(Function.identity(), e -> rd.nextLong()));
xors.forEach(table::ack);
table.tryPromote(epochCeil);
xors.forEach(table::ack);
Assert.assertEquals(table.tryPromote(epochCeil), epochCeil);
}
}
}
|
// Given 3 int values, a b c, return their sum. However,
// if any of the values is a teen -- in the range 13..19 inclusive -- then that value counts as 0,
// except 15 and 16 do not count as a teens.
public class NoTeenSum {
static int noTeenSum(int a, int b, int c) {
return fixTeen(a) + fixTeen(b) + fixTeen(c);
}
static int fixTeen(int n) {
if(n >= 13 && n <= 19 && n != 15 && n != 16) {
n = 0;
}
return n;
}
}
|
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Configuration {
public static void main(String[] args) {
try {
if (args.length > 1) {
boolean error = false;
boolean maps, redundancy, ports, fragment;
maps = redundancy = ports = fragment = false;
int numberArguments = 2;
int count = 0;
if (args[count].startsWith("-")) {
String options = args[count];
numberArguments += options.length();
if (options.length() <= 4)
for (int i = 1; i < numberArguments - 2; i++) {
switch (options.charAt(i)) {
case 'm':
maps = true;
break;
case 'r':
redundancy = true;
break;
case 'p':
ports = true;
break;
case 'f':
fragment = true;
break;
default:
error = true;
}
}
else
error = true;
count++;
}
if (!error && args.length == numberArguments) {
String path = args[count];
String javaPath = path.replace("\\", "\\\\");
count++;
String[] hosts = args[count].trim().replaceAll("\\s+", " ").split(" ");
count++;
int numberPorts, numberMaps, numberRedundancy, fragmentLength;
numberPorts = numberMaps = numberRedundancy = fragmentLength = 0;
if (ports) {
numberPorts = Integer.parseInt(args[count]);
count++;
}
if (maps) {
numberMaps = Integer.parseInt(args[count]);
count++;
}
if (redundancy) {
numberRedundancy = Integer.parseInt(args[count]);
count++;
}
if (fragment)
fragmentLength = Integer.parseInt(args[count]);
if (!error) {
Path filePath = Paths.get("config" + File.separator + "ClusterConfig.java");
List<String> fileContent = new ArrayList<>(Files.readAllLines(filePath, StandardCharsets.ISO_8859_1));
for (int i = 0; i < fileContent.size(); i++) {
String line = fileContent.get(i);
if (line.contains("public final static String PATH"))
fileContent.set(i, " public final static String PATH = \"" + javaPath + "\";");
else if (line.contains("public final static String[] hosts")) {
StringBuilder newLine = new StringBuilder();
newLine.append(" public final static String[] hosts = {");
for (int j = 0; j < hosts.length - 1; j++)
newLine.append("\"" + hosts[j] + "\", ");
newLine.append("\"" + hosts[hosts.length - 1] + "\"};");
fileContent.set(i, newLine.toString());
} else if (line.contains("public final static int numberDaemons"))
fileContent.set(i, " public final static int numberDaemons = " + hosts.length + ";");
else if (line.contains("public final static int[][] ports")) {
StringBuilder newLine = new StringBuilder();
newLine.append(" public final static int[][] ports = {{");
int currentPort = 0;
if (ports)
currentPort = numberPorts;
else
currentPort = 4001;
for (int j = 0; j < 2; j++) {
for (int k = 0; k < hosts.length - 1; k++)
newLine.append(currentPort++ + ", ");
newLine.append("" + currentPort++ + "}, {");
}
for (int k = 0; k < hosts.length - 1; k++)
newLine.append(currentPort++ + ", ");
newLine.append("" + currentPort++ + "}};");
fileContent.set(i, newLine.toString());
}
else if (maps && line.contains("public final static int numberMaps")) {
fileContent.set(i, " public final static int numberMaps = " + numberMaps + ";");
}
else if (redundancy && line.contains("public final static int redundancy")) {
fileContent.set(i, " public final static int redundancy = " + numberRedundancy + ";");
}
}
Files.write(filePath, fileContent, StandardCharsets.ISO_8859_1);
if (fragment) {
filePath = Paths.get("config" + File.separator + "ClientConfig.java");
fileContent = new ArrayList<>(Files.readAllLines(filePath, StandardCharsets.ISO_8859_1));
for (int i = 0; i < fileContent.size(); i++) {
String line = fileContent.get(i);
if (line.contains("public static final int fragmentLength"))
fileContent.set(i, " public static final int fragmentLength = " + fragmentLength + ";");
}
Files.write(filePath, fileContent, StandardCharsets.ISO_8859_1);
}
/*filePath = Paths.get("lancer-hidoop.sh");
fileContent = new ArrayList<>();
fileContent.add("javac -encoding ISO-8859-1 .java");
fileContent.add("mate-terminal --window -e \"/bin/bash -c \\\"java hdfs.server.ServerHDFS; exec /bin/bash\\\"\" \\");
for (int i = 0; i < hosts.length - 1; i++)
fileContent.add("--tab -e \"/bin/bash -c \\\"ssh $USER@" + hosts[i] + " 'cd " + path + " && java hdfs.daemon.DaemonHDFS " + i + "'; exec /bin/bash\\\"\" \\");
fileContent.add("--tab -e \"/bin/bash -c \\\"ssh $USER@" + hosts[hosts.length - 1] + " 'cd " + path + " && java hdfs.daemon.DaemonHDFS " + (hosts.length - 1) + "'; exec /bin/bash\\\"\"");
if (hosts.length > 1) {
fileContent.add("mate-terminal --window -e \"/bin/bash -c \\\"ssh $USER@" + hosts[0] + " 'cd " + path + " && java ordo.DaemonImpl " + 0 + "'; exec /bin/bash\\\"\" \\");
for (int i = 1; i < hosts.length - 1; i++)
fileContent.add("--tab -e \"/bin/bash -c \\\"ssh $USER@" + hosts[i] + " 'cd " + path + " && java ordo.DaemonImpl " + i + "'; exec /bin/bash\\\"\" \\");
fileContent.add("--tab -e \"/bin/bash -c \\\"ssh $USER@" + hosts[hosts.length - 1] + " 'cd " + path + " && java ordo.DaemonImpl " + (hosts.length - 1) + "'; exec /bin/bash\\\"\"");
} else
fileContent.add("mate-terminal --window -e \"/bin/bash -c \\\"ssh $USER@" + hosts[0] + " 'cd " + path + " && java ordo.DaemonImpl " + 0 + "'; exec /bin/bash\\\"\"");
Files.write(filePath, fileContent, StandardCharsets.ISO_8859_1);*/
filePath = Paths.get("lancer-hidoop.sh");
fileContent = new ArrayList<>();
fileContent.add("javac -encoding ISO-8859-1 */*.java */*/*.java");
fileContent.add("mate-terminal --window -e \"/bin/bash -c \\\"java hdfs.server.ServerHDFS; exec /bin/bash\\\"\" \\");
for (int i = 0; i < hosts.length - 1; i++) {
fileContent.add("ssh $USER@" + hosts[hosts.length - 1] + " 'cd " + path + " && java hdfs.daemon.DaemonHDFS " + (hosts.length - 1) + "' &");
fileContent.add("ssh $USER@" + hosts[hosts.length - 1] + " 'cd " + path + " && java ordo.DaemonImpl " + (hosts.length - 1) + "' &");
}
filePath = Paths.get("clean.sh");
fileContent = new ArrayList<>();
fileContent.add("pkill -f java.*ServerHDFS");
for (int i = 0; i < hosts.length; i++)
fileContent.add("ssh $USER@" + hosts[i] + " 'pkill -f java.*DaemonHDFS* && pkill -f java.*DaemonImpl*'");
Files.write(filePath, fileContent, StandardCharsets.ISO_8859_1);
filePath = Paths.get("preparation-ssh.sh");
fileContent = new ArrayList<>();
fileContent.add("ssh-keygen -t rsa");
for (int i = 0; i < hosts.length; i++)
fileContent.add("ssh-copy-id $USER@" + hosts[i]);
Files.write(filePath, fileContent, StandardCharsets.ISO_8859_1);
}
}
}
} catch (Exception e) {e.printStackTrace();}
}
}
|
package dev.borowiecki.home.after_week_1.solutions;
import java.util.Arrays;
public class Ex7 {
public static void main(String[] args) {
char[] someArray = "My lstirng".toCharArray();
for(int i = 0; i < someArray.length / 2;i++) {
char temp = someArray[i];
someArray[i] = someArray[someArray.length - i - 1];
someArray[someArray.length -i - 1 ] = temp;
}
System.out.println(Arrays.toString(someArray));
}
}
|
package Alpha;
public class demolog {
static java.util.logging.Logger log = java.util.logging.Logger.getLogger(demolog.class.getName());
public static void main(String[] args) {
System.out.println("Logger");
}
}
|
// ______________________________________________________
// Generated by sql2java - http://sql2java.sourceforge.net/
// jdbc driver used at code generation time: com.mysql.jdbc.Driver
//
// Please help us improve this tool by reporting:
// - problems and suggestions to
// http://sourceforge.net/tracker/?group_id=54687
// - feedbacks and ideas on
// http://sourceforge.net/forum/forum.php?forum_id=182208
// ______________________________________________________
package legaltime.model;
import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;
import legaltime.model.GeneratedBean;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* ExpenseInvoiceItemBean is a mapping of expense_invoice_item Table.
* @author sql2java
*/
public class ExpenseInvoiceItemBean
implements Serializable, GeneratedBean
{
private static final long serialVersionUID = 6038475096495975809L;
private java.util.Date lastUpdate;
private boolean lastUpdateIsModified = false;
private boolean lastUpdateIsInitialized = false;
private Integer invoiceId;
private boolean invoiceIdIsModified = false;
private boolean invoiceIdIsInitialized = false;
private Double amount;
private boolean amountIsModified = false;
private boolean amountIsInitialized = false;
private String expenseDescription;
private boolean expenseDescriptionIsModified = false;
private boolean expenseDescriptionIsInitialized = false;
private java.util.Date expenseDate;
private boolean expenseDateIsModified = false;
private boolean expenseDateIsInitialized = false;
private Integer expenseInvoiceItemId;
private boolean expenseInvoiceItemIdIsModified = false;
private boolean expenseInvoiceItemIdIsInitialized = false;
private boolean _isNew = true;
/**
* Prefered methods to create a ExpenseInvoiceItemBean is via the createExpenseInvoiceItemBean method in ExpenseInvoiceItemManager or
* via the factory class ExpenseInvoiceItemFactory create method
*/
protected ExpenseInvoiceItemBean()
{
}
/**
* Getter method for lastUpdate.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.last_update</li>
* <li>column size: 19</li>
* <li>jdbc type returned by the driver: Types.TIMESTAMP</li>
* </ul>
*
* @return the value of lastUpdate
*/
public java.util.Date getLastUpdate()
{
return lastUpdate;
}
/**
* Setter method for lastUpdate.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to lastUpdate
*/
public void setLastUpdate(java.util.Date newVal)
{
if ((newVal != null && lastUpdate != null && (newVal.compareTo(lastUpdate) == 0)) ||
(newVal == null && lastUpdate == null && lastUpdateIsInitialized)) {
return;
}
lastUpdate = newVal;
lastUpdateIsModified = true;
lastUpdateIsInitialized = true;
}
/**
* Setter method for lastUpdate.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to lastUpdate
*/
public void setLastUpdate(long newVal)
{
setLastUpdate(new java.util.Date(newVal));
}
/**
* Determines if the lastUpdate has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isLastUpdateModified()
{
return lastUpdateIsModified;
}
/**
* Determines if the lastUpdate has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isLastUpdateInitialized()
{
return lastUpdateIsInitialized;
}
/**
* Getter method for invoiceId.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.invoice_id</li>
* <li>column size: 10</li>
* <li>jdbc type returned by the driver: Types.INTEGER</li>
* </ul>
*
* @return the value of invoiceId
*/
public Integer getInvoiceId()
{
return invoiceId;
}
/**
* Setter method for invoiceId.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to invoiceId
*/
public void setInvoiceId(Integer newVal)
{
if ((newVal != null && invoiceId != null && (newVal.compareTo(invoiceId) == 0)) ||
(newVal == null && invoiceId == null && invoiceIdIsInitialized)) {
return;
}
invoiceId = newVal;
invoiceIdIsModified = true;
invoiceIdIsInitialized = true;
}
/**
* Setter method for invoiceId.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to invoiceId
*/
public void setInvoiceId(int newVal)
{
setInvoiceId(new Integer(newVal));
}
/**
* Determines if the invoiceId has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isInvoiceIdModified()
{
return invoiceIdIsModified;
}
/**
* Determines if the invoiceId has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isInvoiceIdInitialized()
{
return invoiceIdIsInitialized;
}
/**
* Getter method for amount.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.amount</li>
* <li>column size: 22</li>
* <li>jdbc type returned by the driver: Types.DOUBLE</li>
* </ul>
*
* @return the value of amount
*/
public Double getAmount()
{
return amount;
}
/**
* Setter method for amount.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to amount
*/
public void setAmount(Double newVal)
{
if ((newVal != null && amount != null && (newVal.compareTo(amount) == 0)) ||
(newVal == null && amount == null && amountIsInitialized)) {
return;
}
amount = newVal;
amountIsModified = true;
amountIsInitialized = true;
}
/**
* Setter method for amount.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to amount
*/
public void setAmount(double newVal)
{
setAmount(new Double(newVal));
}
/**
* Determines if the amount has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isAmountModified()
{
return amountIsModified;
}
/**
* Determines if the amount has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isAmountInitialized()
{
return amountIsInitialized;
}
/**
* Getter method for expenseDescription.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.expense_description</li>
* <li>column size: 255</li>
* <li>jdbc type returned by the driver: Types.VARCHAR</li>
* </ul>
*
* @return the value of expenseDescription
*/
public String getExpenseDescription()
{
return expenseDescription;
}
/**
* Setter method for expenseDescription.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to expenseDescription
*/
public void setExpenseDescription(String newVal)
{
if ((newVal != null && expenseDescription != null && (newVal.compareTo(expenseDescription) == 0)) ||
(newVal == null && expenseDescription == null && expenseDescriptionIsInitialized)) {
return;
}
expenseDescription = newVal;
expenseDescriptionIsModified = true;
expenseDescriptionIsInitialized = true;
}
/**
* Determines if the expenseDescription has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isExpenseDescriptionModified()
{
return expenseDescriptionIsModified;
}
/**
* Determines if the expenseDescription has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isExpenseDescriptionInitialized()
{
return expenseDescriptionIsInitialized;
}
/**
* Getter method for expenseDate.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.expense_date</li>
* <li>column size: 10</li>
* <li>jdbc type returned by the driver: Types.DATE</li>
* </ul>
*
* @return the value of expenseDate
*/
public java.util.Date getExpenseDate()
{
return expenseDate;
}
/**
* Setter method for expenseDate.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to expenseDate
*/
public void setExpenseDate(java.util.Date newVal)
{
if ((newVal != null && expenseDate != null && (newVal.compareTo(expenseDate) == 0)) ||
(newVal == null && expenseDate == null && expenseDateIsInitialized)) {
return;
}
expenseDate = newVal;
expenseDateIsModified = true;
expenseDateIsInitialized = true;
}
/**
* Setter method for expenseDate.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to expenseDate
*/
public void setExpenseDate(long newVal)
{
setExpenseDate(new java.util.Date(newVal));
}
/**
* Determines if the expenseDate has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isExpenseDateModified()
{
return expenseDateIsModified;
}
/**
* Determines if the expenseDate has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isExpenseDateInitialized()
{
return expenseDateIsInitialized;
}
/**
* Getter method for expenseInvoiceItemId.
* <br>
* PRIMARY KEY.<br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: expense_invoice_item.expense_invoice_item_id</li>
* <li>column size: 10</li>
* <li>jdbc type returned by the driver: Types.INTEGER</li>
* </ul>
*
* @return the value of expenseInvoiceItemId
*/
public Integer getExpenseInvoiceItemId()
{
return expenseInvoiceItemId;
}
/**
* Setter method for expenseInvoiceItemId.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to expenseInvoiceItemId
*/
public void setExpenseInvoiceItemId(Integer newVal)
{
if ((newVal != null && expenseInvoiceItemId != null && (newVal.compareTo(expenseInvoiceItemId) == 0)) ||
(newVal == null && expenseInvoiceItemId == null && expenseInvoiceItemIdIsInitialized)) {
return;
}
expenseInvoiceItemId = newVal;
expenseInvoiceItemIdIsModified = true;
expenseInvoiceItemIdIsInitialized = true;
}
/**
* Setter method for expenseInvoiceItemId.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to expenseInvoiceItemId
*/
public void setExpenseInvoiceItemId(int newVal)
{
setExpenseInvoiceItemId(new Integer(newVal));
}
/**
* Determines if the expenseInvoiceItemId has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isExpenseInvoiceItemIdModified()
{
return expenseInvoiceItemIdIsModified;
}
/**
* Determines if the expenseInvoiceItemId has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isExpenseInvoiceItemIdInitialized()
{
return expenseInvoiceItemIdIsInitialized;
}
/**
* Determines if the current object is new.
*
* @return true if the current object is new, false if the object is not new
*/
public boolean isNew()
{
return _isNew;
}
/**
* Specifies to the object if it has been set as new.
*
* @param isNew the boolean value to be assigned to the isNew field
*/
public void isNew(boolean isNew)
{
this._isNew = isNew;
}
/**
* Determines if the object has been modified since the last time this method was called.
* <br>
* We can also determine if this object has ever been modified since its creation.
*
* @return true if the object has been modified, false if the object has not been modified
*/
public boolean isModified()
{
return lastUpdateIsModified || invoiceIdIsModified || amountIsModified || expenseDescriptionIsModified || expenseDateIsModified || expenseInvoiceItemIdIsModified ;
}
/**
* Resets the object modification status to 'not modified'.
*/
public void resetIsModified()
{
lastUpdateIsModified = false;
invoiceIdIsModified = false;
amountIsModified = false;
expenseDescriptionIsModified = false;
expenseDateIsModified = false;
expenseInvoiceItemIdIsModified = false;
}
/**
* Copies the passed bean into the current bean.
*
* @param bean the bean to copy into the current bean
*/
public void copy(ExpenseInvoiceItemBean bean)
{
setLastUpdate(bean.getLastUpdate());
setInvoiceId(bean.getInvoiceId());
setAmount(bean.getAmount());
setExpenseDescription(bean.getExpenseDescription());
setExpenseDate(bean.getExpenseDate());
setExpenseInvoiceItemId(bean.getExpenseInvoiceItemId());
}
/**
* return a dictionnary of the object
*/
public Map getDictionnary()
{
Map dictionnary = new HashMap();
dictionnary.put("last_update", getLastUpdate() == null ? "" : getLastUpdate().toString());
dictionnary.put("invoice_id", getInvoiceId() == null ? "" : getInvoiceId().toString());
dictionnary.put("amount", getAmount() == null ? "" : getAmount().toString());
dictionnary.put("expense_description", getExpenseDescription() == null ? "" : getExpenseDescription().toString());
dictionnary.put("expense_date", getExpenseDate() == null ? "" : getExpenseDate().toString());
dictionnary.put("expense_invoice_item_id", getExpenseInvoiceItemId() == null ? "" : getExpenseInvoiceItemId().toString());
return dictionnary;
}
/**
* return a dictionnary of the pk columns
*/
public Map getPkDictionnary()
{
Map dictionnary = new HashMap();
dictionnary.put("expense_invoice_item_id", getExpenseInvoiceItemId() == null ? "" : getExpenseInvoiceItemId().toString());
return dictionnary;
}
/**
* return a the value string representation of the given field
*/
public String getValue(String column)
{
if (null == column || "".equals(column)) {
return "";
} else if ("last_update".equalsIgnoreCase(column) || "lastUpdate".equalsIgnoreCase(column)) {
return getLastUpdate() == null ? "" : getLastUpdate().toString();
} else if ("invoice_id".equalsIgnoreCase(column) || "invoiceId".equalsIgnoreCase(column)) {
return getInvoiceId() == null ? "" : getInvoiceId().toString();
} else if ("amount".equalsIgnoreCase(column) || "amount".equalsIgnoreCase(column)) {
return getAmount() == null ? "" : getAmount().toString();
} else if ("expense_description".equalsIgnoreCase(column) || "expenseDescription".equalsIgnoreCase(column)) {
return getExpenseDescription() == null ? "" : getExpenseDescription().toString();
} else if ("expense_date".equalsIgnoreCase(column) || "expenseDate".equalsIgnoreCase(column)) {
return getExpenseDate() == null ? "" : getExpenseDate().toString();
} else if ("expense_invoice_item_id".equalsIgnoreCase(column) || "expenseInvoiceItemId".equalsIgnoreCase(column)) {
return getExpenseInvoiceItemId() == null ? "" : getExpenseInvoiceItemId().toString();
}
return "";
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object)
{
if (!(object instanceof ExpenseInvoiceItemBean)) {
return false;
}
ExpenseInvoiceItemBean obj = (ExpenseInvoiceItemBean) object;
return new EqualsBuilder()
.append(getLastUpdate(), obj.getLastUpdate())
.append(getInvoiceId(), obj.getInvoiceId())
.append(getAmount(), obj.getAmount())
.append(getExpenseDescription(), obj.getExpenseDescription())
.append(getExpenseDate(), obj.getExpenseDate())
.append(getExpenseInvoiceItemId(), obj.getExpenseInvoiceItemId())
.isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
return new HashCodeBuilder(-82280557, -700257973)
.append(getLastUpdate())
.append(getInvoiceId())
.append(getAmount())
.append(getExpenseDescription())
.append(getExpenseDate())
.append(getExpenseInvoiceItemId())
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return toString(ToStringStyle.MULTI_LINE_STYLE);
}
/**
* you can use the following styles:
* <li>ToStringStyle.DEFAULT_STYLE</li>
* <li>ToStringStyle.MULTI_LINE_STYLE</li>
* <li>ToStringStyle.NO_FIELD_NAMES_STYLE</li>
* <li>ToStringStyle.SHORT_PREFIX_STYLE</li>
* <li>ToStringStyle.SIMPLE_STYLE</li>
*/
public String toString(ToStringStyle style) {
return new ToStringBuilder(this, style)
.append("last_update", getLastUpdate())
.append("invoice_id", getInvoiceId())
.append("amount", getAmount())
.append("expense_description", getExpenseDescription())
.append("expense_date", getExpenseDate())
.append("expense_invoice_item_id", getExpenseInvoiceItemId())
.toString();
}
public int compareTo(Object object)
{
ExpenseInvoiceItemBean obj = (ExpenseInvoiceItemBean) object;
return new CompareToBuilder()
.append(getLastUpdate(), obj.getLastUpdate())
.append(getInvoiceId(), obj.getInvoiceId())
.append(getAmount(), obj.getAmount())
.append(getExpenseDescription(), obj.getExpenseDescription())
.append(getExpenseDate(), obj.getExpenseDate())
.append(getExpenseInvoiceItemId(), obj.getExpenseInvoiceItemId())
.toComparison();
}
}
|
package com.xvr.serviceBook.controller.restapi.assemblers;
import com.xvr.serviceBook.controller.restapi.dtorepresentation.TicketModelRepresentation;
import com.xvr.serviceBook.entity.Ticket;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.server.RepresentationModelAssembler;
import org.springframework.stereotype.Component;
@Component
public class TicketPaginationModelAssembler implements RepresentationModelAssembler<Ticket, TicketModelRepresentation> {
@Override
public TicketModelRepresentation toModel(Ticket entity) {
TicketModelRepresentation ticketModelRepresentation = TicketModelRepresentation.builder()
.id(entity.getId())
.startDateTicket(entity.getStartDateTicket())
.endDateTicket(entity.getEndDateTicket())
.statusTicket(entity.getStatusTicket().getStatusName())
.ticketDescription(entity.getTicketDescription())
.clientDepartmentRepresentation(entity.getClientDepartment().getName())
.build();
return ticketModelRepresentation;
}
@Override
public CollectionModel<TicketModelRepresentation> toCollectionModel(Iterable<? extends Ticket> entities) {
return RepresentationModelAssembler.super.toCollectionModel(entities);
}
}
|
package duke.exception;
public class InvalidIndexException extends DukeException {
@Override
public String toString() {
return "You have entered an invalid index. Please try again.";
}
}
|
package com.jiw.dudu.structure.linklist;
/**
* @Description LeetCode328奇偶链表
* @Author pangh
* @Date 2023年04月10日
* @Version v1.0.0
* <p>
* 力扣算法题:https://leetcode.cn/problems/odd-even-linked-list/
*/
public class LeetCode328 {
private class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null){
return head;
}
// 初始化各种节点和头指针
ListNode oddHead = head;
ListNode oddCurrent = head;
ListNode evenHead = head.next;
ListNode evenCurrent = head.next;
// 遍历
while (evenCurrent != null && evenCurrent.next != null){
oddCurrent.next = oddCurrent.next.next;
evenCurrent.next = evenCurrent.next.next;
oddCurrent = oddCurrent.next;
evenCurrent = evenCurrent.next;
}
oddCurrent.next = evenHead;
return oddHead;
}
}
|
package com.zimmermusic.kenobi;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import org.deeplearning4j.datasets.iterator.DataSetIterator;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.dataset.api.DataSetPreProcessor;
import org.nd4j.linalg.factory.Nd4j;
/** A very simple DataSetIterator for use in the GravesLSTMCharModellingExample.
* Given a text file and a few options, generate feature vectors and labels for training,
* where we want to predict the next character in the sequence.<br>
* This is done by randomly choosing a position in the text file to start the sequence and
* (optionally) scanning backwards to a new line (to ensure we don't start half way through a word
* for example).<br>
* Feature vectors and labels are both one-hot vectors of same length
* @author Alex Black
*/
public class NoteIterator implements DataSetIterator {
private static final long serialVersionUID = -7287833919126626356L;
private static final int MAX_SCAN_LENGTH = 200;
private char[] validCharacters;
private Map<Character,Integer> charToIdxMap;
private char[] fileCharacters;
private int exampleLength = 100;
private int miniBatchSize = 10;
private int numExamplesToFetch = 400;
private int examplesSoFar = 0;
private Random rng;
private final int numNotes = 12; //the total available pitches to choose from
public NoteIterator() throws IOException {
this(new Random());
}
/**
* of no new line characters, to avoid scanning entire file)
* @throws IOException If text file cannot be loaded
*/
public NoteIterator(Random rng) throws IOException {
this.rng = rng;
}
/** A minimal character set, with a-z, A-Z, 0-9 and common punctuation etc */
// public static char[] getMinimalCharacterSet(){
// List<Character> validChars = new LinkedList<>();
// for(char c='a'; c<='z'; c++) validChars.add(c);
// for(char c='A'; c<='Z'; c++) validChars.add(c);
// for(char c='0'; c<='9'; c++) validChars.add(c);
// char[] temp = {'!', '&', '(', ')', '?', '-', '\'', '"', ',', '.', ':', ';', ' ', '\n', '\t'};
// for( char c : temp ) validChars.add(c);
// char[] out = new char[validChars.size()];
// int i=0;
// for( Character c : validChars ) out[i++] = c;
// return out;
// }
// /** As per getMinimalCharacterSet(), but with a few extra characters */
// public static char[] getDefaultCharacterSet(){
// List<Character> validChars = new LinkedList<>();
// for(char c : getMinimalCharacterSet() ) validChars.add(c);
// char[] additionalChars = {'@', '#', '$', '%', '^', '*', '{', '}', '[', ']', '/', '+', '_',
// '\\', '|', '<', '>'};
// for( char c : additionalChars ) validChars.add(c);
// char[] out = new char[validChars.size()];
// int i=0;
// for( Character c : validChars ) out[i++] = c;
// return out;
// }
public char convertIndexToCharacter( int idx ){
return validCharacters[idx];
}
public int convertCharacterToIndex( char c ){
return charToIdxMap.get(c);
}
public int getRandomNote(){
return 3;
}
public boolean hasNext() {
return examplesSoFar <= numExamplesToFetch; //true; //examplesSoFar + miniBatchSize <= numExamplesToFetch;
}
public DataSet next() {
return next(miniBatchSize);
}
public DataSet next(int num) {
// if( examplesSoFar+num > numExamplesToFetch ) throw new NoSuchElementException();
//Allocate space:
INDArray input = Nd4j.zeros(new int[]{num,numNotes,exampleLength});
INDArray labels = Nd4j.zeros(new int[]{num,numNotes,exampleLength});
// int maxStartIdx = fileCharacters.length - exampleLength;
//Randomly select a subset of the file. No attempt is made to avoid overlapping subsets
// of the file in the same minibatch
//eventually I can create a dictionary of possble events - c4 quarter note, c4 half note, c4 eightnote, etc
//and then feed into the machine the index of the note, lets me predict two variables
for( int i=0; i<num; i++ ){
int startIdx = 0;//(int) (rng.nextDouble()*maxStartIdx);
int endIdx = startIdx + 100; //exampleLength;
int scanLength = 0;
int currCharIdx = 1;// charToIdxMap.get(fileCharacters[startIdx]); //Current input
int c=0;
for( int j=startIdx+1; j<=endIdx; j++, c++ ){
int nextCharIdx = (currCharIdx + 1) % 10; // charToIdxMap.get(fileCharacters[j]); //Next character to predict
// System.out.println("Training with value " + currCharIdx);
input.putScalar(new int[]{i,currCharIdx,c}, 1.0);
labels.putScalar(new int[]{i,nextCharIdx,c}, 1.0);
currCharIdx = nextCharIdx;
}
}
examplesSoFar += num;
return new DataSet(input,labels);
}
public int totalExamples() {
return numExamplesToFetch;
}
public int inputColumns() {
return numNotes;
}
public int totalOutcomes() {
return numNotes;
}
public void reset() {
examplesSoFar = 0;
}
public int batch() {
return miniBatchSize;
}
public int cursor() {
return examplesSoFar;
}
public int numExamples() {
return numExamplesToFetch;
}
public void setPreProcessor(DataSetPreProcessor preProcessor) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public List<String> getLabels() {
throw new UnsupportedOperationException("Not implemented");
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
|
public class FactMethod {
static int fact(int a)
{
int f=1;
for(int i=1;i<a;i++)
{
f=f*i;
}
return f;
}
public static void main(String[] args)
{
int res=fact(7);
System.out.println("result is"+res);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.