blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
919c800c3695a7039ce496a08804ef336211a44b
60d2946d7c1c8c41c6938ce268da3bd092d58de6
/app/src/main/java/meuestudo/wave/br/meuestudo/BancoController.java
c971575b97b6dc1bc25fcec0fd3ccec1df112b5f
[]
no_license
Amancio302/Meu_estudo
8da821abe30d3dc450c3794730f67395cc4782ea
508f64f7aeccc8bee841753becbb029d4b30ad28
refs/heads/master
2020-03-27T11:31:02.850954
2018-08-29T00:03:45
2018-08-29T00:03:45
146,491,685
0
0
null
null
null
null
UTF-8
Java
false
false
11,731
java
package meuestudo.wave.br.meuestudo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class BancoController { private SQLiteDatabase db; private CriaBanco banco; public BancoController(Context context) { banco = new CriaBanco(context); } public boolean insereMateria(String nome, int meta) { ContentValues valores; long resultado; db = banco.getWritableDatabase(); valores = new ContentValues(); valores.put(CriaBanco.nomeMateria, nome); valores.put(CriaBanco.meta, meta); resultado = db.insert(CriaBanco.Materia, null, valores); db.close(); if (resultado ==-1) { return false; } else { return true; } } public boolean insereNota(int nota, int materia) { ContentValues valores; long resultado; db = banco.getWritableDatabase(); valores = new ContentValues(); valores.put(CriaBanco.nota, nota); valores.put(CriaBanco.Materia_idMateria, materia); resultado = db.insert(CriaBanco.Nota, null, valores); db.close(); if (resultado ==-1) { return false; } else { return true; } } public boolean insereEvento(String titulo, String descricao, String data, boolean concluido, String cor, int notaTotal, int materia) { ContentValues valores; long resultado; db = banco.getWritableDatabase(); valores = new ContentValues(); valores.put(CriaBanco.titulo, titulo); valores.put(CriaBanco.descricao, descricao); valores.put(CriaBanco.date, data); valores.put(CriaBanco.concluido, concluido); valores.put(CriaBanco.cor, cor); valores.put(CriaBanco.notaTotal, notaTotal); valores.put(CriaBanco.Materia_idMateria, materia); resultado = db.insert(CriaBanco.Evento, null, valores); db.close(); if (resultado ==-1) { return false; } else { return true; } } public boolean insereAlarme(String data, String toque, int evento) { ContentValues valores; long resultado; db = banco.getWritableDatabase(); valores = new ContentValues(); valores.put(CriaBanco.dataAlarme, data); valores.put(CriaBanco.toque, toque); valores.put(CriaBanco.Evento_idEvento, evento); resultado = db.insert(CriaBanco.Materia, null, valores); db.close(); if (resultado ==-1) { return false; } else { return true; } } public Cursor carregaMateria() { Cursor cursor; String[] campos = {banco.idMateria, banco.nomeMateria, banco.meta}; db = banco.getReadableDatabase(); cursor = db.query(banco.Materia, campos, null, null, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } db.close(); return cursor; } public Cursor carregaNota() { Cursor cursor; String[] campos = {banco.idNota, banco.nota, banco.Materia_idMateria}; db = banco.getReadableDatabase(); cursor = db.query(banco.Nota, campos, null, null, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } db.close(); return cursor; } public Cursor carregaEvento() { Cursor cursor; String[] campos = {banco.idEvento, banco.titulo, banco.descricao, banco.date, banco.concluido, banco.cor, banco.notaTotal, banco.Materia_idMateria}; db = banco.getReadableDatabase(); cursor = db.query(banco.Evento, campos, null, null, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } db.close(); return cursor; } public Cursor carregaAlarme() { Cursor cursor; String[] campos = {banco.idAlarme, banco.dataAlarme, banco.toque, banco.Evento_idEvento}; db = banco.getReadableDatabase(); cursor = db.query(banco.Alarme, campos, null, null, null, null, null, null); if (cursor != null) { cursor.moveToFirst(); } db.close(); return cursor; } public void apagaMateria (int id) { String where = CriaBanco.idMateria + "=" + id; db = banco.getReadableDatabase(); Cursor cursor = carregaEventoByMateria(id); for(int i = 0; i < cursor.getCount(); i++){ //Move para a posição i; cursor.moveToPosition(i); //Pega o index da coluna int iIdEvento = cursor.getColumnIndex("idEvento"); int iTitulo = cursor.getColumnIndex("titulo"); int iDescricao = cursor.getColumnIndex("descricao"); int iDate = cursor.getColumnIndex("date"); int iConcluido = cursor.getColumnIndex("concluido"); int iCor = cursor.getColumnIndex("cor"); int iNotaTotal = cursor.getColumnIndex("notaTotal"); //Resgata o valor da coluna int idEvento = cursor.getInt(iIdEvento); String titulo = cursor.getString(iTitulo); String descricao = cursor.getString(iDescricao); String date = cursor.getString(iDate); int conc = cursor.getInt(iConcluido); boolean concluido = (conc != 0); String cor = cursor.getString(iCor); int notaTotal = cursor.getInt(iNotaTotal); //Altera materia para 0 alteraEvento(idEvento, titulo, descricao, date, concluido, cor, notaTotal, 0); } db.delete(CriaBanco.Materia, where, null); } public void apagaNota (int id) { String where = CriaBanco.idNota + "=" + id; db = banco.getReadableDatabase(); db.delete(CriaBanco.Nota, where, null); } public void apagaEvento (int id) { String where = CriaBanco.idEvento + "=" + id; db = banco.getReadableDatabase(); db.delete(CriaBanco.Evento, where, null); } public void apagaAlarme (int id) { String where = CriaBanco.idAlarme + "=" + id; db = banco.getReadableDatabase(); db.delete(CriaBanco.Alarme, where, null); } public Cursor carregaMateriaById(int id){ Cursor cursor; String[] campos = {banco.idMateria, banco.nomeMateria, banco.meta}; String where = CriaBanco.idMateria + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Materia, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; } public Cursor carregaNotaById(int id){ Cursor cursor; String[] campos = {banco.idNota, banco.nota, banco.Materia_idMateria}; String where = CriaBanco.idNota + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Nota, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; } public Cursor carregaEventoById(int id){ Cursor cursor; String[] campos = {banco.idEvento, banco.titulo, banco.descricao, banco.date, banco.concluido, banco.cor, banco.notaTotal, banco.Materia_idMateria}; String where = CriaBanco.idEvento + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Evento, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; } public Cursor carregaAlarmeById(int id){ Cursor cursor; String[] campos = {banco.idAlarme, banco.dataAlarme, banco.toque, banco.Evento_idEvento}; String where = CriaBanco.idAlarme + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Alarme, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; } public void alteraMateria(int id, String nome, int meta){ ContentValues valores; String where; db = banco.getWritableDatabase(); where = CriaBanco.idMateria + "=" + id; valores = new ContentValues(); valores.put(CriaBanco.nomeMateria, nome); valores.put(CriaBanco.meta, meta); db.update(CriaBanco.Materia, valores, where, null); } public void alteraNota(int id, int nota, int materia){ ContentValues valores; String where; db = banco.getWritableDatabase(); where = CriaBanco.idNota + "=" + id; valores = new ContentValues(); valores.put(CriaBanco.nota, nota); valores.put(CriaBanco.Materia_idMateria, materia); db.update(CriaBanco.Nota, valores, where, null); } public void alteraEvento(int id, String titulo, String descricao, String data, boolean concluido, String cor, int notaTotal, int materia){ ContentValues valores; String where; db = banco.getWritableDatabase(); where = CriaBanco.idEvento + "=" + id; valores = new ContentValues(); valores.put(CriaBanco.titulo, titulo); valores.put(CriaBanco.descricao, descricao); valores.put(CriaBanco.date, data); valores.put(CriaBanco.concluido, concluido); valores.put(CriaBanco.cor, cor); valores.put(CriaBanco.notaTotal, notaTotal); valores.put(CriaBanco.Materia_idMateria, materia); db.update(CriaBanco.Evento, valores, where, null); } public void alteraAlarme(int id, String data, String toque, int evento){ ContentValues valores; String where; db = banco.getWritableDatabase(); where = CriaBanco.idAlarme + "=" + id; valores = new ContentValues(); valores.put(CriaBanco.dataAlarme, data); valores.put(CriaBanco.toque, toque); valores.put(CriaBanco.Evento_idEvento, evento); db.update(CriaBanco.Nota, valores, where, null); } public Cursor carregaNotaByMateria(int id){ Cursor cursor; String[] campos = {banco.idNota, banco.nota}; String where = CriaBanco.idMateria + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Nota, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; }; public Cursor carregaEventoByMateria(int id){ Cursor cursor; String[] campos = {banco.idEvento, banco.titulo, banco.descricao, banco.date, banco.concluido, banco.cor, banco.notaTotal, banco.Materia_idMateria}; String where = CriaBanco.idMateria + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Evento, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; }; public Cursor carregaAlarmeByEvento(int id){ Cursor cursor; String[] campos = {banco.idAlarme, banco.dataAlarme, banco.toque, banco.Evento_idEvento}; String where = CriaBanco.idEvento + "=" + id; db = banco.getReadableDatabase(); cursor = db.query(CriaBanco.Alarme, campos, where, null, null, null, null, null); if(cursor != null) cursor.moveToFirst(); db.close(); return cursor; }; }
cee9c6eda15a90fd2690d968ebdb3f1eddce2f51
c15be76f89d9d600c95e9f7535969f222e2943b0
/src/main/java/ContratAuto.java
d2864f006ca5d36e41eb8496e7d82201d2a5f9c0
[]
no_license
AntoineColin/TP_NOTE
8244be40d9f2209cc9491f3499cb11254391f00c
1897623838c0c55ad70513d5f51c1c224cd2f51f
refs/heads/master
2021-08-28T08:18:22.985124
2017-12-11T17:20:49
2017-12-11T17:20:49
113,868,685
0
0
null
null
null
null
ISO-8859-1
Java
false
false
573
java
import java.util.List; public class ContratAuto extends Contrat{ public ContratAuto() { cotisation = 150.0; Contrat.instances.add(this); } public List<String> determinerGaranties(){ System.out.println("Souhaitez vous la garantie Accident? Y/N"); //demande de sélection à faire garanties.add("Accidents"); garanties.add("Bris de glace"); garanties.add("Responsabilité civile"); return garanties; } public static Contrat creationContrat() { ContratAuto contrat = new ContratAuto(); contrat.determinerGaranties(); return contrat; } }
21e35e67df1fed81d7634faeee7553757569b406
1ed05a47ad9e368d7de6a1b0c0b54aaf5d3dab1b
/Bharti-Class-Code/TestNgDec2015/src/com/test/StringOperationsNegTest.java
5f468a80d0a97119bc33b126fd649e2abdfeefa5
[]
no_license
sangameshwar2804/Framework
4b874c8fbc3e92fe77cc0b9c9239825625635dc9
970efe9fd37b98450160ebc873c2e212523c325e
refs/heads/master
2020-04-30T11:03:33.982098
2019-03-20T20:09:51
2019-03-20T20:09:51
176,792,355
0
0
null
null
null
null
UTF-8
Java
false
false
449
java
package com.test; import static org.testng.AssertJUnit.assertEquals; import org.testng.annotations.Test; import com.main.StringOperations; public class StringOperationsNegTest extends GetTestData { @Test(expectedExceptions=NullPointerException.class) public void method7() { String str = null; StringOperations op = new StringOperations(); int expected = 0; int actual = op.countVowels(str); assertEquals(expected,actual); } }
[ "Aryav" ]
Aryav
60e2d831e5e74d6046a7208387a0de93ff1e950a
711b1eb036f4f939ac231ae5ca6ec12033a92444
/TJWspringCloud-consumer-feign/src/main/java/com/tianjunwei/consumer/ConsumerFeignApplication.java
515ca565ab2597c9a141c7985a60764eeb261263
[ "Apache-2.0" ]
permissive
tian-junwei/TJWspringCloud
96fe02ffa689c20cc9937197553d7e846765bb59
fd9b2781cffa56fef1ea80a9d13492deef73b903
refs/heads/master
2021-10-11T00:01:14.656750
2019-01-19T13:32:03
2019-01-19T13:32:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
524
java
package com.tianjunwei.consumer; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @EnableFeignClients @SpringBootApplication @EnableDiscoveryClient public class ConsumerFeignApplication { public static void main(String[] args) { SpringApplication.run(ConsumerFeignApplication.class, args); } }
73b062a8e0cc7d589b8585445bb386f0ccfebdf2
bd44432a74ebbfc83d60974247d6d92d460766e8
/avalon-common/src/main/java/com/avalon/common/util/CookieUtil.java
e8571190f3d7f4e9beb9a2beff9375365bbb25ac
[]
no_license
Suppercell/avalon-master
a52d83d0c6575566f7a3e2458bd1d4fbc24122cb
ddabe18629e6de8f944f69c683b07e9f43aa3f25
refs/heads/master
2020-03-29T18:41:22.934533
2018-09-25T08:24:02
2018-09-25T08:24:02
150,226,577
0
0
null
null
null
null
UTF-8
Java
false
false
2,681
java
package com.avalon.common.util; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieUtil { public static void addCookie(HttpServletResponse response, String domain, String name, String value, int age) { Cookie cookies = new Cookie(name, value); cookies.setPath("/"); //设置cookie经过多长秒后被删除。如果0,就说明立即删除。如果是负数就表明当浏览器关闭时自动删除。 cookies.setMaxAge(age); cookies.setDomain(domain); response.addCookie(cookies); } public static String getCookieValue(HttpServletRequest request, String domain, String cookieName) { if (cookieName != null) { Cookie cookie = getCookie(request, cookieName); if (cookie != null) { return cookie.getValue(); } } return ""; } public static Cookie getCookie(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); Cookie cookie = null; try { if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().equals(cookieName)) { return cookie; } } } } catch (Exception e) { throw new RuntimeException(e); } return null; } public static Map<String, String> getCookies(HttpServletRequest request) { Map<String, String> result = new HashMap<String, String>(); Cookie[] cookies = request.getCookies(); Cookie cookie = null; if (cookies != null && cookies.length > 0) { for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; result.put(cookie.getName(), cookie.getValue()); } } return result; } public static boolean deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { if (cookieName != null) { Cookie cookie = getCookie(request, cookieName); if (cookie != null) { cookie.setMaxAge(0);//如果0,就说明立即删除 cookie.setPath("/");//不要漏掉 response.addCookie(cookie); return true; } } return false; } }
c602d871bbb7a20f04e75464d23d0f4580d72184
8e39c0f99ae814daa38c01e58eb5458b209daa21
/app/src/main/java/br/edu/ifsp/scl/sdm/pedrapapeltesoura/CondicaoPedra.java
03e6329bc2f9517a455eee6c9ced2a53c61310f9
[]
no_license
JosePicharillo/PedraPapelTesoura
d29be22ea8da2e6ea1b15f98f4e1b3437a4b9b6e
af97f361da25e1caf914a826c8874c131c9630d0
refs/heads/master
2023-08-14T04:43:54.606517
2021-09-17T00:23:10
2021-09-17T00:23:10
402,577,762
0
0
null
null
null
null
UTF-8
Java
false
false
2,255
java
package br.edu.ifsp.scl.sdm.pedrapapeltesoura; public class CondicaoPedra { /** * Calcula se a condição do jogador for PEDRA */ public String calculoCondicaoPedra(Opcoes jogadaComputador01, Opcoes jogadaComputador02) { String resposta = ""; if (jogadaComputador01 == Opcoes.PEDRA && jogadaComputador02 == Opcoes.PEDRA) { resposta = "EMPATE - TODOS OS JOGADORES ESCOLHERAM PEDRA"; } if (jogadaComputador01 == Opcoes.PEDRA && jogadaComputador02 == Opcoes.PAPEL) { resposta = "VOCÊ PERDEU - COMPUTADOR 02 VENCEU"; } if (jogadaComputador01 == Opcoes.PEDRA && jogadaComputador02 == Opcoes.TESOURA) { resposta = "EMPATE - VOCÊ E COMPUTADOR 01 EMPATARAM"; } if (jogadaComputador01 == Opcoes.PAPEL && jogadaComputador02 == Opcoes.PEDRA) { resposta = "VOCÊ PERDEU - COMPUTADOR 01 VENCEU"; } if (jogadaComputador01 == Opcoes.PAPEL && jogadaComputador02 == Opcoes.PAPEL) { resposta = "VOCÊ PERDEU - COMPUTADOR 01 E COMPUTADOR 02 EMPATARAM"; } if (jogadaComputador01 == Opcoes.PAPEL && jogadaComputador02 == Opcoes.TESOURA) { resposta = "EMPATE"; } if (jogadaComputador01 == Opcoes.TESOURA && jogadaComputador02 == Opcoes.PEDRA) { resposta = "EMPATE - VOCÊ E COMPUTADOR 02 EMPATARAM"; } if (jogadaComputador01 == Opcoes.TESOURA && jogadaComputador02 == Opcoes.PAPEL) { resposta = "EMPATE"; } if (jogadaComputador01 == Opcoes.TESOURA && jogadaComputador02 == Opcoes.TESOURA) { resposta = "VOCÊ VENCEU"; } return resposta; } /** * Calcula se a condição do jogador for PEDRA (Jogo com 2 Jogadores) */ public String calculoCondicaoPedraDoisJogadores(Opcoes jogadaComputador01) { String resposta = ""; if (jogadaComputador01 == Opcoes.PEDRA) { resposta = "EMPATE"; } if (jogadaComputador01 == Opcoes.PAPEL) { resposta = "VOCÊ PERDEU"; } if (jogadaComputador01 == Opcoes.TESOURA) { resposta = "VOCÊ VENCEU"; } return resposta; } }
fafdf165e38f7c6fc435d275f7ac4ecf5073f1da
9e9a76feb62fd0e6e39d6eabc8f3aa057e93f3fe
/rear-end/guli-framework-parent/guli-microservice-edu/src/main/java/com/guli/edu/entity/query/QueryTeacher.java
b30cf3506c092c9b429dc36885db15f3b0972a55
[]
no_license
Xuxuehua1229/Project01-edu
1c7ee4b3168ec8ff83dea0e2c5b7e0729c2bdb01
663a725cf3e02dda01284550570c1294d611c10b
refs/heads/master
2023-03-19T08:11:44.085572
2021-03-14T14:09:34
2021-03-14T14:09:34
347,643,527
0
0
null
null
null
null
UTF-8
Java
false
false
203
java
package com.guli.edu.entity.query; import lombok.Data; @Data public class QueryTeacher { private String name; private String level; private String beginDate; private String endDate; }
685dbc0f3810d187fb5b9f54a3e8c8254846b4a7
b08f92afb8168783d2fb1c74e821eebbba343eb5
/src/main/java/com/train/collection/comparison/javolution/MultisetTest.java
92a2da18077db13d6ccd1c1a0191fbd6b9a9af66
[]
no_license
lemon-jh/test
2f73eee03e0c428a778fd379cb6aa55acfc37a84
7c08cd02afe6c6bf76ab7fc1b7bb60913e6a72ca
refs/heads/master
2021-05-31T13:20:35.084886
2016-02-29T15:02:55
2016-02-29T15:02:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
497
java
package com.train.collection.comparison.javolution; import java.util.Arrays; import java.util.List; import com.google.common.collect.HashMultiset; public class MultisetTest { private static final String [] temp = new String[]{"1","2","1"}; public static void main(String[] args) { HashMultiset<String> multiSet = HashMultiset.create(); List<String> s = Arrays.asList(temp); multiSet.addAll(s); System.out.println(multiSet.count("1")); } }
3a4acf0b26a2fd32d31a6a1b26ad5ad4d65e333e
662789816652f0b915ec373a48e2dc3b241d87e9
/xflow-designer/src/main/java/net/ms/designer/editors/componentdetail/commands/ReorderPartCommand.java
015dc6cba6a5c2090706c45b1534c1f664a51448
[]
no_license
fengweijp/xflow
4ff989b5411afed949ab4c50eada12e7ddb64591
808705586aa6eac99b9168f4bc1bf9d970d25024
refs/heads/master
2020-04-06T06:27:27.424150
2014-09-12T11:12:40
2014-09-12T11:12:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
924
java
package net.ms.designer.editors.componentdetail.commands; import net.ms.designer.editors.componentdetail.models.Container; import net.ms.designer.editors.componentdetail.models.Element; import net.ms.designer.editors.componentdetail.models.Messages; import org.eclipse.gef.commands.Command; public class ReorderPartCommand extends Command { private int oldIndex, newIndex; private Element child; private Container parent; public ReorderPartCommand(Element child, Container parent, int oldIndex, int newIndex) { super(Messages.getString("ReorderPartCommand.Label")); this.child = child; this.parent = parent; this.oldIndex = oldIndex; this.newIndex = newIndex; } public void execute() { parent.removeChild(child); parent.addChild(child, newIndex); } public void undo() { parent.removeChild(child); parent.addChild(child, oldIndex); } }
5c924950911ade4e9ed3046677a0f02a6995e23d
5fbeaa2d0b1f4c13b812ab53af645657eb295fcf
/bundles/org.eclipse.ecf.salvo.ui/src/org/eclipse/ecf/salvo/ui/internal/resources/ISalvoResource.java
58e485a18e93fdc4f0f875dfc2d5c4d1b1e0539a
[]
no_license
ECF/Newsreader
3f0b2db62d9db9e2283ac990b05f87c9fad35b89
309cf81049a8315c6417e67581c297b4d5e19a7c
refs/heads/master
2016-09-02T01:15:25.597593
2015-05-11T11:30:58
2015-05-11T11:30:58
764,856
3
4
null
null
null
null
UTF-8
Java
false
false
1,555
java
/******************************************************************************* * Copyright (c) 2010 Weltevree Beheer BV, Remain Software & Industrial-TSI * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wim Jongman - initial API and implementation *******************************************************************************/ package org.eclipse.ecf.salvo.ui.internal.resources; import java.util.Collection; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.ecf.salvo.ui.internal.provider.IChildProvider; public interface ISalvoResource extends IAdaptable { public abstract Collection<ISalvoResource> getChildren(); public abstract void addChild(ISalvoResource child); public abstract void setName(String name); public abstract String getName(); public abstract Object getObject(); public abstract void setChildProvider(IChildProvider childProvider); public abstract IChildProvider getChildProvider(); public abstract ISalvoResource getParent(); public abstract void setParent(ISalvoResource parent); public abstract boolean hasChildren(); }
eba0a3a038b54ac28cf78d9a0737d9246c1c3dec
e18bcaf6953432c77730c1f39925a378cd55c5a9
/samuel.catalano.external/src/main/java/com/oodlefinance/samuel/catalano/external/handler/ErrorResponse.java
4676506dd710b4d65abb578e286b73d57916ed20
[]
no_license
samuelcatalano/oodle-finance-technical-challenge
e990a242d94c35d179cbc9029a9106d900ab0c1d
6f01cf5a267d0d4fc250c95008e204a2bc896565
refs/heads/main
2023-03-19T01:01:48.856982
2023-02-11T23:25:58
2023-02-11T23:25:58
555,071,736
0
0
null
null
null
null
UTF-8
Java
false
false
136
java
package com.oodlefinance.samuel.catalano.external.handler; public record ErrorResponse(String status, String message, Integer code) { }
eba72342474e541b4ce01e2c664ba22d228190b7
e60068ba8e8c1b77eac7f863928873ed8c1c6040
/src/com/sumit/noticeP/StarPrintPyramid.java
2728896956a99f61a8b49251b77280698d5216d6
[]
no_license
sumitkamboj/algopractice
77836a8d487940694a7a62e9e7258ca0e6316fc2
1e0add09f8fffe8a30cbd08a0eb33726e6946a05
refs/heads/master
2023-01-04T12:11:00.717877
2020-11-04T10:44:16
2020-11-04T10:44:16
292,478,321
0
0
null
null
null
null
UTF-8
Java
false
false
577
java
package com.sumit.noticeP; import java.io.IOException; import java.util.Scanner; public class StarPrintPyramid { public static void main(String args[]) { System.out.println("please enter number of rows"); int n = 0; try { Scanner in = new Scanner(System.in); n = in.nextInt(); }catch(Exception e) { System.out.println("wrong input"+e); } for(int i = 0; i<n; i++) { for(int j =n-i; j>1 ; j--) { System.out.print(" "); } for(int k = 0 ; k<=i; k++) { System.out.print("* "); } System.out.println(); } } }
02b0bd897d401b07164341bee7259b9dc8d3182f
dc7534f5b290382463748d192e06fab2b2c7bbbb
/src/main/java/web/services/UserService.java
b7c080bbf94d29e82bbe5b3dffc1638c726d8b59
[]
no_license
pavel203/2.3.1.App
3409c567454b95a39aa790e6656dc8aafe1bdb8c
39694c9953f58fb765bcf4fa16f529e84bca8125
refs/heads/master
2023-08-08T09:57:35.970216
2021-08-17T22:03:16
2021-08-17T22:03:16
396,938,989
0
0
null
null
null
null
UTF-8
Java
false
false
312
java
package web.services; import org.springframework.stereotype.Service; import web.models.User; import java.util.List; @Service public interface UserService { List<User> getAllUsers(); void addUser(User user); void deleteUser(long id); void updateUser(User user); User getUserById(long id); }
61701564279aeba3ad232623f4e04a7447289249
c470af36975194670cfb88e8aca992547a28e7b1
/src/main/java/fxc/rest/Vehicle/VehicleRestController.java
47072947476f9961b0e4e6bd24554d15da6d5267
[]
no_license
qeqewewr/Logistics-Website
573b1269215ac943f70cea729fa0741e08be4a04
5ea851d971a0ad09ed7e4dbcda0b7ac9f741982a
refs/heads/master
2016-09-13T15:46:56.216124
2016-04-27T06:48:30
2016-04-27T06:48:30
57,190,565
0
0
null
null
null
null
UTF-8
Java
false
false
2,278
java
package fxc.rest.Vehicle; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import fxc.entity.Owner; import fxc.entity.Vehicle; import fxc.service.Vehicle.VehicleService; import fxc.service.account.AccountService; @Controller @RequestMapping(value = "/api/Vehicle") public class VehicleRestController { @Autowired private VehicleService vehicleService; @Autowired private AccountService accountService; @RequestMapping(value = "get/{id}", method = RequestMethod.GET) @ResponseBody public List<String> getVehicleByname(@PathVariable("id") String username) { // User user=accountService.findUserByLoginName(username); Owner owner = accountService.findOwnerByUsername(username); List<Vehicle> vehicles = vehicleService.getVehicles(owner); List<String> list = new ArrayList<String>(); for (Vehicle ve : vehicles) { list.add(ve.getNumber()); } return list; } @RequestMapping(value = "getdetail/{id}", method = RequestMethod.GET) @ResponseBody public Map<String, Object> getDetail(@PathVariable("id") String number) { try { String decode_number = URLDecoder.decode(number, "utf-8"); Map<String, Object> maps = new HashMap<String, Object>(); Vehicle vehicle = vehicleService.getVehicleByNumber(decode_number); maps.put("type", vehicle.getType()); maps.put("volume", vehicle.getVolume()); return maps; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @RequestMapping(value = "edit", method = RequestMethod.POST) @ResponseBody public String edit(String number, float volume) { Vehicle vehicle = vehicleService.getVehicleByNumber(number); vehicle.setVolume(volume); vehicleService.addVehicle(vehicle); return "success"; } }
45a4ebce34c85402b666b792fef49278aa5e5b0b
f80f53a97e922d10d48ea44b0d2822dbb2e0d19d
/Tugas/4/Matic.java
a48b254eace2a22048b9609040625adce5c79c84
[]
no_license
canuesp/ProLan-11
151422122519c2564d8b0957b3ce33b9a13438da
f2c485e8c167f8f2ac151bc9dc646bb1724f7a57
refs/heads/master
2021-01-21T10:22:12.404559
2017-03-18T15:59:23
2017-03-18T15:59:23
83,414,847
0
0
null
null
null
null
UTF-8
Java
false
false
334
java
public class Matic { protected String merk, nama; protected Integer harga; public void informasi_matic() { System.out.print("Merk : " + merk + "\n"); System.out.print("Nama Motor : " + nama + " \n"); System.out.print("Harga Motor : " + harga + "\n"); System.out.print("\n"); } }
4bb5c06cb6d114199dcd5a64785f0e534338413b
8814f082e2f2e02192d47c0131d53925bbf8eae7
/Set-Theory/src/com/adil/set/AverageOfAllSubset.java
b54f9e55726f77c13e90a5647eb1cf6fe8212d4c
[]
no_license
adilazmi786/Mathematical-Programing
dd7970fa07916db740e3c3212e461b6ebda2fe62
9612c3d0adbfe9876e9e52dd65650b5496968331
refs/heads/master
2020-04-18T10:31:45.856782
2019-03-04T02:57:48
2019-03-04T02:57:48
167,469,982
0
0
null
null
null
null
UTF-8
Java
false
false
741
java
package com.adil.set; public class AverageOfAllSubset { public static void main(String[] args) { // TODO Auto-generated method stub int powSet[]= {1,2,3}; double avgSum=sumOfAverageOfSubset(powSet,powSet.length); System.out.println("Avg of power subset: "+avgSum); } private static double sumOfAverageOfSubset(int[] powSet, int n) { // TODO Auto-generated method stub int sum,counter; double avg=0,avgSum=0.0; for(int i=0;i<(1<<n);i++) { counter=0; sum=0; for(int j=0;j<n;j++) { if((i&(1<<j))>0) { sum=sum+powSet[j]; counter++; } } if(counter!=0) { avg=(double)sum/counter; avgSum+=avg; } } return avgSum; } }
[ "dell@DESKTOP-PF23KL2" ]
dell@DESKTOP-PF23KL2
1b7829b5637635d787ecebc73683cbaac3d59dd7
2c76426d8217b90102393b6b5ffef8e2f563e47d
/xmlcustomize/src/androidTest/java/com/example/xmlcustomize/ExampleInstrumentedTest.java
2feedf39f6eb9fcc39823883c59a60e11813d795
[]
no_license
yuheng0001/androidUI
bd9152b62ca3ba7b574b4421a18b12adc3f14cd5
80345351fc8963ba85f467839d53168a47702879
refs/heads/master
2023-01-04T17:22:10.832982
2020-10-27T03:41:05
2020-10-27T03:41:05
303,630,710
0
0
null
null
null
null
UTF-8
Java
false
false
764
java
package com.example.xmlcustomize; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.xmlcustomize", appContext.getPackageName()); } }
89eccdc9a4b060a01fb121c8bc79ad258f7b960c
cf54d771a2c209920a19af8b5dda8430e2b247c1
/src/SettingsDialog.java
9c1129a74e54e175a5d05a0c8201ecf52ee22e1c
[]
no_license
BauerJustin/TriangleClassifier
781c0a50714ea8b80388b934d7aa95675d218b4c
08e1ef8b8d62de21e29b0bf20f0e4502246bccd7
refs/heads/master
2022-09-17T17:28:12.926508
2020-06-04T03:27:34
2020-06-04T03:27:34
null
0
0
null
null
null
null
IBM852
Java
false
false
4,366
java
import java.awt.BorderLayout; import java.awt.FlowLayout; import java.util.Locale; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JRadioButton; import java.awt.Color; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class SettingsDialog extends JDialog { private final JPanel contentPanel = new JPanel(); private JRadioButton optEnglish; private JRadioButton optFrench; private JRadioButton optGerman; private ButtonGroup buttonGroup; private Locale locale = Locale.ENGLISH; private boolean ok = false; public boolean isOk() { return ok; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } /** * Launch the application. */ public static void main(String[] args) { try { SettingsDialog dialog = new SettingsDialog(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } /** * Create the dialog. */ public SettingsDialog() { addWindowListener(new WindowAdapter() { @Override public void windowOpened(WindowEvent arg0) { this_WindowOpened(arg0); } @Override public void windowClosed(WindowEvent e) { this_WindowClosed(e); } }); setBackground(Color.BLUE); setBounds(100, 100, 157, 172); getContentPane().setLayout(new BorderLayout()); contentPanel.setBackground(Color.BLUE); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); optEnglish = new JRadioButton("English"); optEnglish.setForeground(Color.WHITE); optEnglish.setBackground(Color.BLUE); optEnglish.setBounds(16, 7, 109, 23); contentPanel.add(optEnglish); optFrench = new JRadioButton("Franšais"); optFrench.setBackground(Color.BLUE); optFrench.setForeground(Color.WHITE); optFrench.setBounds(16, 33, 109, 23); contentPanel.add(optFrench); { optGerman = new JRadioButton("Deutsche"); optGerman.setForeground(Color.WHITE); optGerman.setBackground(Color.BLUE); optGerman.setBounds(16, 59, 109, 23); contentPanel.add(optGerman); } { JPanel buttonPane = new JPanel(); buttonPane.setBackground(Color.BLUE); buttonPane.setForeground(Color.BLUE); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { okButton_MouseClicked(arg0); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } { JButton cancelButton = new JButton("Cancel"); cancelButton.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { cancelButton_MouseClicked(e); } }); cancelButton.setActionCommand("Cancel"); buttonPane.add(cancelButton); } } buttonGroup = new ButtonGroup(); buttonGroup.add(this.optEnglish); buttonGroup.add(this.optFrench); buttonGroup.add(this.optGerman); } protected void this_WindowOpened(WindowEvent arg0) { if (this.locale == Locale.ENGLISH) { this.optEnglish.setSelected(true); }else if (this.locale == Locale.FRENCH) { this.optFrench.setSelected(true); }else{ this.optGerman.setSelected(true); } } protected void this_WindowClosed(WindowEvent e) { if (this.ok) { if (this.optEnglish.isSelected()) { this.locale = Locale.ENGLISH; }else if (this.optFrench.isSelected()) { this.locale = Locale.FRENCH; }else { this.locale = Locale.GERMAN; } }} protected void okButton_MouseClicked(MouseEvent arg0) { this.ok = true; this.setVisible(false); this_WindowClosed(null); } protected void cancelButton_MouseClicked(MouseEvent e) { this.ok = false; this.setVisible(false); this_WindowClosed(null); } }
9692049a5cbf765bd91db90e64ae51ed8937d6dc
fa93c9be2923e697fb8a2066f8fb65c7718cdec7
/sources/com/avito/android/component/timer/Counter.java
d6acd327eee0be23730a1baac6523a9e1a59e95f
[]
no_license
Auch-Auch/avito_source
b6c9f4b0e5c977b36d5fbc88c52f23ff908b7f8b
76fdcc5b7e036c57ecc193e790b0582481768cdc
refs/heads/master
2023-05-06T01:32:43.014668
2021-05-25T10:19:22
2021-05-25T10:19:22
370,650,685
0
0
null
null
null
null
UTF-8
Java
false
false
4,486
java
package com.avito.android.component.timer; import android.os.CountDownTimer; import com.avito.android.remote.auth.AuthSource; import com.yandex.mobile.ads.video.tracking.Tracker; import java.util.Arrays; import java.util.Date; import java.util.Objects; import java.util.concurrent.TimeUnit; import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000&\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\u0002\n\u0002\b\u0006\n\u0002\u0010\t\n\u0002\b\u0003\n\u0002\u0018\u0002\n\u0002\b\u0006\u0018\u00002\u00020\u0001B\u000f\u0012\u0006\u0010\u000e\u001a\u00020\u000b¢\u0006\u0004\b\u0013\u0010\u0014J\u0015\u0010\u0005\u001a\u00020\u00042\u0006\u0010\u0003\u001a\u00020\u0002¢\u0006\u0004\b\u0005\u0010\u0006J\r\u0010\u0007\u001a\u00020\u0004¢\u0006\u0004\b\u0007\u0010\bR\u0018\u0010\u0003\u001a\u0004\u0018\u00010\u00028\u0002@\u0002X‚\u000e¢\u0006\u0006\n\u0004\b\t\u0010\nR\u0016\u0010\u000e\u001a\u00020\u000b8\u0002@\u0002X‚\u0004¢\u0006\u0006\n\u0004\b\f\u0010\rR\u0018\u0010\u0012\u001a\u0004\u0018\u00010\u000f8\u0002@\u0002X‚\u000e¢\u0006\u0006\n\u0004\b\u0010\u0010\u0011¨\u0006\u0015"}, d2 = {"Lcom/avito/android/component/timer/Counter;", "", "Lcom/avito/android/component/timer/TimeWidget;", "widget", "", Tracker.Events.CREATIVE_START, "(Lcom/avito/android/component/timer/TimeWidget;)V", "stop", "()V", AuthSource.SEND_ABUSE, "Lcom/avito/android/component/timer/TimeWidget;", "", "c", "J", "endDate", "Landroid/os/CountDownTimer;", AuthSource.BOOKING_ORDER, "Landroid/os/CountDownTimer;", "timer", "<init>", "(J)V", "ui-components_release"}, k = 1, mv = {1, 4, 2}) public final class Counter { public TimeWidget a; public CountDownTimer b; public final long c; public Counter(long j) { this.c = j; } public static final void access$showCurrentTime(Counter counter, long j, TimeWidget timeWidget) { Objects.requireNonNull(counter); TimeUnit timeUnit = TimeUnit.MILLISECONDS; long hours = timeUnit.toHours(j); long millis = j - TimeUnit.HOURS.toMillis(hours); long minutes = timeUnit.toMinutes(millis); long seconds = timeUnit.toSeconds(millis - TimeUnit.MINUTES.toMillis(minutes)); String format = String.format("%02d", Arrays.copyOf(new Object[]{Long.valueOf(hours)}, 1)); Intrinsics.checkNotNullExpressionValue(format, "java.lang.String.format(this, *args)"); timeWidget.setHours(format); String format2 = String.format("%02d", Arrays.copyOf(new Object[]{Long.valueOf(minutes)}, 1)); Intrinsics.checkNotNullExpressionValue(format2, "java.lang.String.format(this, *args)"); timeWidget.setMinutes(format2); String format3 = String.format("%02d", Arrays.copyOf(new Object[]{Long.valueOf(seconds)}, 1)); Intrinsics.checkNotNullExpressionValue(format3, "java.lang.String.format(this, *args)"); timeWidget.setSeconds(format3); } public final void start(@NotNull TimeWidget timeWidget) { Intrinsics.checkNotNullParameter(timeWidget, "widget"); this.a = timeWidget; if (this.b == null) { long time = this.c - new Date().getTime(); Counter$createTimer$1 counter$createTimer$1 = new CountDownTimer(time, time, 1000) { // from class: com.avito.android.component.timer.Counter$createTimer$1 @Override // android.os.CountDownTimer public void onFinish() { TimeWidget timeWidget2 = Counter.this.a; if (timeWidget2 != null) { Counter.access$showCurrentTime(Counter.this, 0, timeWidget2); timeWidget2.onFinish(); } } @Override // android.os.CountDownTimer public void onTick(long j) { TimeWidget timeWidget2 = Counter.this.a; if (timeWidget2 != null) { Counter.access$showCurrentTime(Counter.this, j, timeWidget2); } } }; counter$createTimer$1.start(); this.b = counter$createTimer$1; } } public final void stop() { CountDownTimer countDownTimer = this.b; if (countDownTimer != null) { countDownTimer.cancel(); } this.b = null; this.a = null; } }
b2dac09be3865f0564b72ae450d0b037800ba5fd
49d9d8dc18b3524afa7ed3d9ab63e0d446d67f31
/T5/scope/of/variable/PrivateModifier.java
ed07dcb354180e8e2e820ca52661eb1902037440
[]
no_license
angadisharan/mathrusoft_java_tutorial
89d767d310969b8a570c79b857763bd53dd3609e
8453eeaabf25c68e86b3a372f9bc526f5f1173f8
refs/heads/master
2021-01-17T17:09:52.479998
2016-10-20T06:37:10
2016-10-20T06:37:10
69,086,009
0
0
null
null
null
null
UTF-8
Java
false
false
330
java
package scope.of.variable; public class PrivateModifier { public static void main(String[] args) { Data data = new Data(); data.dataInteger = 3; System.out.println(data.getDataInteger()); } class SubClass { public void subClassMethod() { Data data = new Data(); data.dataInteger = 23; } } }
c4fb4fc9ca053d27eee9e82dc3b7682369edb03a
14da20b02d3d2d2a8b6aca3db841b08166388027
/src/clock_v2/Clock.java
e74c62e35b3c39191b9a758445f1d115416bb5f6
[ "MIT" ]
permissive
AlbertHambardzumyan/clock
c73437b2a9ad532b547a044712f869465df0970a
5e6dff4c592fee85e2d4e79a0daf31ea8c6e00d5
refs/heads/master
2021-07-14T18:38:12.568707
2017-10-14T10:09:53
2017-10-14T10:09:53
106,915,670
9
0
null
null
null
null
UTF-8
Java
false
false
2,396
java
package clock_v2; import java.awt.*; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Clock extends Animator { private Point center; private Arm h, m, s; public void init() { Date time = new Date(System.currentTimeMillis()); String temp = time.toString(); int h_time = Integer.parseInt("" + temp.charAt(11) + temp.charAt(12)); int m_time = Integer.parseInt("" + temp.charAt(14) + temp.charAt(15)); int s_time = Integer.parseInt("" + temp.charAt(17) + temp.charAt(18)); center = new Point(100, 100); s = new Arm(center.x - 10, 60, 1000, s_time); h = new Arm(center.x - 40, 12, 3600000, h_time); m = new Arm(center.x - 20, 60, 60000, m_time); setSize(2 * (center.x + 2), 2 * (center.y + 2)); ExecutorService threadExecutor = Executors.newCachedThreadPool(); threadExecutor.execute(s); // start seconds arm threadExecutor.execute(m); // start minutes arm threadExecutor.execute(h); // start hours arm threadExecutor.shutdown(); } public void snapshot(Graphics g) { g.drawString("Rado", 87, 70); g.drawOval(0, 0, 2 * center.x, 2 * center.y); int cycle = 24; int length = center.x - 85; for (double value = -1; value < 23; value++) { value = (value + 1); g.drawLine((int) (center.x + 6 * length * Math.sin(value * 2 * Math.PI / cycle)), (int) (center.y - 6 * length * Math.cos(value * 2 * Math.PI / cycle)), (int) (center.x + 6.5 * length * Math.sin(value * 2 * Math.PI / cycle)), (int) (center.y - 6.5 * length * Math.cos(value * 2 * Math.PI / cycle))); } cycle = 120; length = center.x - 5; for (double value = -1; value < 119; value++) { value = (value + 1); g.drawLine((int) (center.x + length * Math.sin(value * 2 * Math.PI / cycle)), (int) (center.y - length * Math.cos(value * 2 * Math.PI / cycle)), (int) (center.x + length * Math.sin(value * 2 * Math.PI / cycle)), (int) (center.y - length * Math.cos(value * 2 * Math.PI / cycle))); } s.draw(g, center); m.draw(g, center); h.draw(g, center); } }
6828fc2396dcca1d9df974437f6cc3b201e46a54
1b81ae13f689915a9484698006fbbfd420592daf
/Monitoreo/src/com/bancoazteca/monitoreo/consulta/ConsultaForm.java
1a06875aa750bc331d0e0c3395a1e65bd8444c77
[]
no_license
gvilchis23/eservice
079e3112ed3e7d7a340028d751d6b648741f2e12
7f6985cd46af1b305fd8e68e1fabf6d9eabacafe
refs/heads/master
2021-01-19T10:11:12.124456
2013-01-29T23:43:30
2013-01-29T23:43:30
7,904,272
1
0
null
null
null
null
UTF-8
Java
false
false
3,468
java
package com.bancoazteca.monitoreo.consulta; import java.text.DecimalFormat; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import com.bancoazteca.monitoreo.utileria.Validator; import com.bancoazteca.monitoreo.MonitoreoForm; public class ConsultaForm extends MonitoreoForm { private static final long serialVersionUID = 1L; private String consulta; private String diaInicial; private String mesInicial; private String anioInicial; private String diaFinal; private String mesFinal; private String anioFinal; private boolean conFechas; public String getConsulta() { return consulta; } public void setConsulta(String consulta) { this.consulta = consulta; } public String getDiaInicial() { return diaInicial; } public void setDiaInicial(String diaInicial) { this.diaInicial = diaInicial; } public String getMesInicial() { return mesInicial; } public void setMesInicial(String mesInicial) { this.mesInicial = mesInicial; } public String getAnioInicial() { return anioInicial; } public void setAnioInicial(String anioInicial) { this.anioInicial = anioInicial; } public String getDiaFinal() { return diaFinal; } public void setDiaFinal(String diaFinal) { this.diaFinal = diaFinal; } public String getMesFinal() { return mesFinal; } public void setMesFinal(String mesFinal) { this.mesFinal = mesFinal; } public String getAnioFinal() { return anioFinal; } public void setAnioFinal(String anioFinal) { this.anioFinal = anioFinal; } public boolean isConFechas() { return conFechas; } public void setConFechas(boolean conFechas) { this.conFechas = conFechas; } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); checkFields(); if(!isConFechas()){ DecimalFormat diaFormat = new DecimalFormat("00"); String dia = diaFormat.format(Integer.valueOf(getDiaInicial())); setDiaInicial(dia); String fechaInicial = getDiaInicial()+"/"+getMesInicial()+"/"+getAnioInicial(); dia = diaFormat.format(Integer.valueOf(getDiaFinal())); setDiaFinal(dia); String fechaFinal = getDiaFinal()+"/"+getMesFinal()+"/"+getAnioFinal(); if (!Validator.checkFecha(fechaInicial)) errors.add("errorFechaInicial", new ActionMessage("error.monitoreo.fechainicial")); if (!Validator.checkFecha(fechaFinal)) errors.add("errorFechaFinal", new ActionMessage("error.monitoreo.fechafinal")); } return errors; } public void checkFields(){ setConFechas(false); if ( ("".equals(getDiaInicial()))&&("Mes".equals(getMesInicial()))&&("".equals(getAnioInicial()))&&("".equals(getDiaFinal()))&&("Mes".equals(getMesFinal()))&&("".equals(getAnioFinal()))) setConFechas(true); else{ if("".equals( getDiaInicial() )) setDiaInicial("00"); if("".equals( getAnioInicial() )) setAnioInicial("0000"); if("".equals( getDiaFinal() )) setDiaFinal("00"); if("".equals( getAnioFinal() )) setAnioFinal("0000"); } } public void reset(ActionMapping mapping, HttpServletRequest request) { diaInicial = ""; mesInicial = "Mes"; anioInicial = ""; diaFinal = ""; mesFinal = "Mes"; anioFinal = ""; } }
025cf97513834ef2a0010c4a54be49e8fa2309f4
15135d47295da05435310e81a0595296f8033057
/src/main/java/ru/msm/framework/pages/ContributionsPage.java
6556f30e4302289578ee3954dde6f33feb8943fc
[]
no_license
msm1323/rencreditContributions
7ab78a2a497b959403a92755fddbae6ccc73abab
0540f1dcfacfd6c7d3476dd04cb0352d3b092168
refs/heads/master
2023-09-02T18:15:55.387928
2021-10-16T12:41:51
2021-10-16T12:41:51
417,811,917
0
0
null
null
null
null
UTF-8
Java
false
false
5,480
java
package ru.msm.framework.pages; import org.junit.jupiter.api.Assertions; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import java.util.List; public class ContributionsPage extends BasePage { @FindBy(xpath = "//input[contains(@name,'calc-currency')]") //пара protected List<WebElement> currencies; @FindBy(xpath = "//span[contains(@class,'calculator__currency-field-text')]") protected List<WebElement> spans; @FindBy(xpath = "//span[contains(@class,'check-block-text')]") //пара protected List<WebElement> checkBlockText; @FindBy(xpath = "//div[contains(@class,'jq-checkbox calculator__check')]") protected List<WebElement> checkBoxInput; @FindBy(xpath = "//input[contains(@class,'currency-input')]/../../..//label[contains(@class,'input-label')]") //пара protected List<WebElement> labels; @FindBy(xpath = "//input[contains(@class,'currency-input')]") protected List<WebElement> inputs; @FindBy(xpath = "//select[@name='period']") protected WebElement selectBox; @FindBy(xpath = "//tr[contains(@class,'result-table-row')]") protected List<WebElement> resTable; @FindBy(xpath = "//div[@class='calculator__dep-result']") protected WebElement depResult; private void selectElFromPair(String key, String msg) { for (int i = 0; i < checkBlockText.size(); i++) { if (checkBlockText.get(i).getText().contains(key)) { if (!checkBoxInput.get(i).getAttribute("class").contains("checked")) { try { waitUntilElementToBeClickable(checkBlockText.get(i)).click(); wait.until(ExpectedConditions.attributeContains(checkBoxInput.get(i), "class", "checked")); } catch (Exception ex) { System.out.println(ex.getMessage()); Assertions.fail(msg); } } break; } } } public void selectCurrency(String currency) { for (int i = 0; i < spans.size(); i++) { if (spans.get(i).getText().contains(currency)) { if (currencies.get(i).getAttribute("checked") == null) { //or false? try { waitUntilElementToBeClickable(spans.get(i)).click(); wait.until(ExpectedConditions.attributeToBe(currencies.get(i), "checked", "true")); } catch (Exception ex) { System.out.println(ex.getMessage()); Assertions.fail("Нужная валюта не выбрана!"); } } break; } } } public void selectOpeningDepositMode(String mode) { selectElFromPair(mode, "Нужный способ открытия банка не выбран!"); } private void selectAndFillField(String fieldName, String value) { for (int i = 0; i < labels.size(); i++) { if (labels.get(i).getText().contains(fieldName)) { inputs.get(i).clear(); inputs.get(i).sendKeys(value); Assertions.assertEquals(value, inputs.get(i).getAttribute("value"), "Поле \"" + fieldName + "\" не содержит заданное значение!"); break; } } } public void depositAmount(String fieldName, String depAmount) { selectAndFillField(fieldName, depAmount); } public void term(String term) { Select termSelect = new Select(selectBox); termSelect.selectByValue(term); try { wait.until(ExpectedConditions.attributeContains(selectBox, "value", term)); } catch (Exception ex) { System.out.println(ex.getMessage()); Assertions.fail("Требуемый срок не выбран!"); } } public void monthlyTopUp(String fieldName, String mTopUp) { selectAndFillField(fieldName, mTopUp); } public void selectMonthlyCapitalization(String mCap) { selectElFromPair(mCap, "\"" + mCap + "\" не выбрано!"); } public void checkSettlementsOnDeposit(List<List<String>> table) { for (List<String> arg : table) { if (depResult.getText().contains(arg.get(0))) { try { wait.until(ExpectedConditions.attributeContains(depResult, "outerText", arg.get(1))); } catch (Exception ex) { System.out.println(ex.getMessage()); Assertions.fail("Рассчет \"" + arg.get(0) + "\" не соответствует ожидаемому!"); } } for (WebElement element : resTable) { if (element.getText().contains(arg.get(0))) { try { wait.until(ExpectedConditions.attributeContains(element, "outerText", arg.get(1))); } catch (Exception ex) { System.out.println(ex.getMessage()); Assertions.fail("Рассчет \"" + arg.get(0) + "\" не соответствует ожидаемому!"); } } } } } }
a3e54b5092bb75be6e047376d76aa0f9d652b4fe
d6ceeb111b0009d821973ae94ad980ed251aba41
/subprojects/execution/src/main/java/org/gradle/internal/execution/SnapshotResult.java
8b37ab1e2755baa2e643f2709e92487d3f4947ef
[ "BSD-3-Clause", "LGPL-2.1-or-later", "LicenseRef-scancode-mit-old-style", "EPL-2.0", "CDDL-1.0", "MIT", "LGPL-2.1-only", "Apache-2.0", "MPL-2.0", "EPL-1.0" ]
permissive
johnuno11/gradle
dd42d125bbf182a2716b16b7012b359f9989ee1a
9223c47cb3b8f1f8232b55d474293b75580c529f
refs/heads/master
2023-01-11T14:24:49.993755
2020-11-21T04:00:51
2020-11-21T04:00:51
314,797,722
0
0
Apache-2.0
2021-03-22T19:33:05
2020-11-21T11:37:42
null
UTF-8
Java
false
false
1,207
java
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.execution; import com.google.common.collect.ImmutableSortedMap; import org.gradle.internal.snapshot.FileSystemSnapshot; public interface SnapshotResult extends Result { /** * Snapshots of the roots of output properties. * * In the presence of overlapping outputs this might be different from * {@link BeforeExecutionState#getOutputFileLocationSnapshots()}, * as this does not include overlapping outputs <em>not</em> produced by the work. */ ImmutableSortedMap<String, FileSystemSnapshot> getOutputFilesProduceByWork(); }
ac1af259dc1de0c804394bcab1a25ffc887880d9
a62a856158bf6dd7f79b55df088f399617fe0a12
/src/main/java/api/RaiderIoApi.java
0dbbe581939d7819f291b15ffe0cb2362e33194d
[]
no_license
Glis6/GuildProgressTracker
7abb5c81bc71d4a4ff925dba81ed5ce2cf8c54e0
d7de373f9aabdbd6d57c46748d0c7f37d0fb5025
refs/heads/master
2021-10-10T06:51:13.018613
2019-01-07T20:09:07
2019-01-07T20:09:07
164,487,409
0
0
null
null
null
null
UTF-8
Java
false
false
1,092
java
package api; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.NonNull; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import java.util.function.Function; /** * @author Glis */ public class RaiderIoApi { /** * The base url to access the Raider IO API. */ private final static Function<String, String> URL_CONSTRUCTOR = url -> "https://raider.io/api/v1/" + url; /** * The {@link JsonParser} */ private final static JsonParser JSON_PARSER = new JsonParser(); /** * @param uri The URI to attempt to reach. * @return The JSON object requested from the uri. */ protected final JsonObject attemptRequest(final @NonNull String uri) throws Exception { final Client client = ClientBuilder.newClient(); WebTarget target = client.target(URL_CONSTRUCTOR.apply(uri)); return JSON_PARSER.parse(target.request(MediaType.APPLICATION_JSON).get(String.class)).getAsJsonObject(); } }
5db9010091a3633072e079cbe09c998e8a625c30
6846119807c72186c6409081faaf7d516d666858
/src/Codiiiin/TestersObject.java
f38722e36b301c444839e66729f0c82e0bd59ed7
[]
no_license
Turkanbozdag/JavaSpringPractice2020
19c2272b9fd2f1a4e36f9764c902eca772ccde82
f9480346761f22668ce0001f8ec5fb5582e183b8
refs/heads/master
2022-12-17T00:03:33.499504
2020-09-20T12:43:45
2020-09-20T12:43:45
258,096,892
0
0
null
null
null
null
UTF-8
Java
false
false
513
java
package Codiiiin; public class TestersObject { public static void main(String[] args) { Tester tester1 =new Tester(); tester1.name=" turkan"; tester1.jobTitle="SDET"; tester1.salary=120000; tester1.employeeId=1234; System.out.println(tester1); Tester tester2=new Tester(); tester2.setInfo("sumbul","junior SDET",120000,123); System.out.println(tester2); tester1.smokeTesting(); tester2.smokeTesting(); tester2.creatingTicket(); } }
a49da3b04ba41e395b28b02fe92d3fb45fc75e6a
f17e0b3bfb4c32fddf4b7ca43bb13c7d782731b9
/wp-exam-master/wp-exam-master/wp-exam-master/src/main/java/mk/ukim/finki/wp/exam/example/model/exceptions/InvalidBookIdException.java
422c85539cd22397e80349e2d44f5f9086ed4d0b
[]
no_license
FINKI-ALST/Book
39b00f59a79259a47f995f5ba66bfc1a7a28136c
a37a3c2edbbee41d118a3775e27ba4f1e83c412d
refs/heads/master
2023-05-12T00:14:33.941134
2021-05-30T17:00:21
2021-05-30T17:00:21
372,231,437
0
0
null
null
null
null
UTF-8
Java
false
false
122
java
package mk.ukim.finki.wp.exam.example.model.exceptions; public class InvalidBookIdException extends RuntimeException { }
cf8d336fe6d2a50ef894e702b2a5aadedd22d64c
b9033f1009bdda0e8eda3c55e163008fd3d51158
/springboot-jasypt/src/main/java/org/dante/springboot/controller/PersonController.java
d7f4d0e97ccf009af91fcfd9c5bae1ca48a36ccf
[]
no_license
lcpsky1991/springboot
b351eca7afae6ef95d1deb61846eefd111f97b6e
6e9a197d4979a950b53d2b183f8a482d477d2762
refs/heads/master
2021-08-29T08:25:49.772650
2017-12-13T14:13:06
2017-12-13T14:13:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
699
java
package org.dante.springboot.controller; import java.util.List; import org.dante.springboot.dao.PersonDAO; import org.dante.springboot.po.PersonPO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; @Slf4j @RestController public class PersonController { @Autowired private PersonDAO personDAO; @Value("${spirit.pwd}") private String pwd; @GetMapping("/all") public List<PersonPO> findAll() { log.info("pwd -> {}", pwd); return personDAO.findAll(); } }
e790147f4892e6fd366f696cb20e8c3466efba7e
cc401926a86ae8e68106330bf658d658e2360efc
/1.16.3/src/main/java/com/congueror/clib/blocks/alloysmelter/AlloySmelterContainer.java
1ebcc85fec258ed499431ad30697c03b4f9c791c
[]
no_license
congueror/CLib
e3323fefd482fe687b89c792c4934195055b02d2
65f2da4fece1f62d6513f68cd7495f538b648d0a
refs/heads/master
2023-03-02T21:46:43.442494
2021-02-08T14:55:41
2021-02-08T14:55:41
272,241,626
2
1
null
2021-02-08T14:55:42
2020-06-14T16:34:37
Java
UTF-8
Java
false
false
2,894
java
package com.congueror.clib.blocks.alloysmelter; /*import java.util.Objects; import com.congueror.clib.init.BlockInit; import com.congueror.clib.init.ContainerTypes; import com.congueror.clib.util.FunctionalIntReferenceHolder; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.Slot; import net.minecraft.network.PacketBuffer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IWorldPosCallable; import net.minecraftforge.items.SlotItemHandler; public class AlloySmelterContainer extends Container { public AlloySmelterTileEntity tileEntity; private IWorldPosCallable canInteractWithCallable; public FunctionalIntReferenceHolder currentSmeltTime; //Server public AlloySmelterContainer(final int windowID, final PlayerInventory playerInv, final AlloySmelterTileEntity tile) { super(ContainerTypes.ALLOY_SMELTER_CONTAINER.get(), windowID); this.tileEntity = tile; this.canInteractWithCallable = IWorldPosCallable.of(tile.getWorld(), tile.getPos()); final int slotSizePlus2 = 18; final int startX = 8; // Hotbar int hotbarY = 142; for (int column = 0; column < 9; column++) { this.addSlot(new Slot(playerInv, column, startX + (column * slotSizePlus2), hotbarY)); } // Main Player Inventory final int startY = 84; for (int row = 0; row < 3; row++) { for (int column = 0; column < 9; column++) { this.addSlot(new Slot(playerInv, 9 + (row * 9) + column, startX + (column * slotSizePlus2), startY + (row * slotSizePlus2))); } } // Smelter Slots this.addSlot(new SlotItemHandler(tile.getInventory(), 0, 56, 17)); this.addSlot(new SlotItemHandler(tile.getInventory(), 1, 116, 35)); this.trackInt(currentSmeltTime = new FunctionalIntReferenceHolder(() -> this.tileEntity.currentSmeltTime, value -> this.tileEntity.currentSmeltTime = value)); } //Client public AlloySmelterContainer(final int windowID, final PlayerInventory playerInv, final PacketBuffer data) { this(windowID, playerInv, getTileEntity(playerInv, data)); } private static AlloySmelterTileEntity getTileEntity(final PlayerInventory playerInv, final PacketBuffer data) { Objects.requireNonNull(playerInv, "playerInv cannot be null"); Objects.requireNonNull(data, "data cannot be null"); final TileEntity tileAtPos = playerInv.player.world.getTileEntity(data.readBlockPos()); if (tileAtPos instanceof AlloySmelterTileEntity) { return (AlloySmelterTileEntity) tileAtPos; } throw new IllegalStateException("TileEntity is not correct " + tileAtPos); } @Override public boolean canInteractWith(PlayerEntity playerIn) { return isWithinUsableDistance(canInteractWithCallable, playerIn, BlockInit.ALLOY_SMELTER.get()); } }*/
9b1ce3bba4c71fdcfd79498f36a791f2dda5e1a2
6d98821adacfdf585d37e025364d43872636453c
/DUT Informatique 2/Java/BLOC1/src/Hierarchie_et_comportements/HumanTest.java
d0d1aa21ddb197686d0ebb373bcd2cbb439acca0
[]
no_license
Gratic/University
fd295c7a41b75a3cdf1be0b5e7e62ee10d7ccbab
2e5a89f0e12db0b3a9c90aa15c567ff556f5e534
refs/heads/master
2020-05-18T09:17:21.289388
2019-12-16T21:01:02
2019-12-16T21:01:02
184,320,294
1
0
null
null
null
null
UTF-8
Java
false
false
843
java
package Hierarchie_et_comportements; import static org.junit.Assert.*; public class HumanTest { @org.junit.Test public void TestStudent_work() { Student s = new Student("Alexis", "Strappazzon"); assertEquals("Dormir au fond de l'amphi.", s.work()); } @org.junit.Test public void TestTeacher_work() { Teacher t = new Teacher("Alexis", "Strappazzon"); assertEquals("Corrige des copies.", t.work()); } @org.junit.Test public void TestStudentGamer_play() { StudentGamer sg = new StudentGamer("Alexis", "Strappazzon"); assertEquals("rage quit", sg.play()); } @org.junit.Test public void TestTeacherGamer_play() { TeacherGamer tg = new TeacherGamer("Alexis", "Strappazzon"); assertEquals("prof OP", tg.play()); } }
513886a2c8b2382b33b2ffa05b76ad600a996122
3ce0de4358184427a543225b080d5fdc4252e305
/src/com/thingzdo/smartplug/udpserver/Function/ModuleUpgradeStartTask.java
e932e19b60e2b65327d9686587492b140f3d7c8e
[]
no_license
smli123/LSM-Server
979a9641796c7e8d908fc63438f7247714be2688
69d16ca993f7eac003c95bd92ade668a0a5ddcfd
refs/heads/master
2020-03-20T09:16:25.232991
2018-06-14T09:14:31
2018-06-14T09:14:31
137,332,897
0
0
null
null
null
null
UTF-8
Java
false
false
2,609
java
package com.thingzdo.smartplug.udpserver.Function; import java.io.IOException; import java.util.TimerTask; import com.thingzdo.platform.LogTool.LogWriter; import com.thingzdo.smartplug.udpserver.ModuleUpgradeOnLineMgr; import com.thingzdo.smartplug.udpserver.ServerWorkThread; import com.thingzdo.smartplug.udpserver.commdef.ICallFunction; public class ModuleUpgradeStartTask extends TimerTask implements ICallFunction{ ModuleUpgradeOnLineMgr m_upgradeMgr = null; private static int m_resend_count = 0; private static int RESEND_COUNT_UP_LIMIT = 10; public ModuleUpgradeStartTask(ModuleUpgradeOnLineMgr mgr) { m_upgradeMgr = mgr; } @Override public void run() { if (null == m_upgradeMgr) { //没有收到心跳包 LogWriter.WriteErrorLog(LogWriter.SELF, String.format("Upgrade Start: ModuleUpgradeOnLineMgr = null.")); return; } if (m_resend_count++ >= RESEND_COUNT_UP_LIMIT) { m_upgradeMgr.StopUpgradeStartTimer(); LogWriter.WriteDebugLog(LogWriter.SELF, String.format("Upgrade Failed. Start Timer is Closed. [%s] count:[%d]", m_upgradeMgr.getModuleID(), m_resend_count)); //m_resend_count = 0; //return; } String strModuleID = m_upgradeMgr.getModuleID(); // if(ServerWorkThread.getModuleConnectInfo(strModuleID).isAlive() == false) // { // //模块未登陆 // LogWriter.WriteErrorLog(LogWriter.SELF, // String.format("Upgrade Start: [%s]Module not login.", strModuleID)); // } // else { //定时器到,检测是否完成接收; 若未到终点,直接重新发送;若已经到达终点,cancel掉定时器即可; if (m_upgradeMgr.GetUpgradeStartTimerFlag() == true) { String strMsg = m_upgradeMgr.GetUpgradeStartCommand(); try { int iRet = ServerWorkThread.ServerMsgHandle(strMsg, strMsg.getBytes()); LogWriter.WriteDebugLog(LogWriter.SELF, String.format("Resend Upgrade_Start command. [%s] count:[%d] Msg:[%s] ", strModuleID, m_resend_count, strMsg)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { m_upgradeMgr.StopUpgradeStartTimer(); LogWriter.WriteDebugLog(LogWriter.SELF, String.format("Upgrade Start Timer is Close. [%s] count:[%d]", strModuleID, m_resend_count)); } } } @Override public int call(Runnable thread_base, String strMsg) { // TODO Auto-generated method stub return 0; } @Override public int resp(Runnable thread_base, String strMsg) { // TODO Auto-generated method stub return 0; } }
[ "smli123@a9a16a3e-c00a-4ab3-988f-67dfe284af05" ]
smli123@a9a16a3e-c00a-4ab3-988f-67dfe284af05
63684cc0b46e3a9e8e84ab91cb90479a120973ad
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/5/5_9730978d754e5658c32209238b1ba8b15a260c58/IntegrityTestRunnerView/5_9730978d754e5658c32209238b1ba8b15a260c58_IntegrityTestRunnerView_t.java
c7f0ba27e91385dde1aa84480bee288b4c391b10
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
63,846
java
package de.gebit.integrity.eclipse.views; import java.io.IOException; import java.io.Serializable; import java.net.UnknownHostException; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchParticipant; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.SearchRequestor; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.InputDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.TreeSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IActionBars; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.forms.HyperlinkGroup; import org.eclipse.ui.forms.IFormColors; import org.eclipse.ui.forms.events.HyperlinkAdapter; import org.eclipse.ui.forms.events.HyperlinkEvent; import org.eclipse.ui.forms.widgets.Form; import org.eclipse.ui.forms.widgets.FormToolkit; import org.eclipse.ui.forms.widgets.Hyperlink; import org.eclipse.ui.forms.widgets.ScrolledForm; import org.eclipse.ui.forms.widgets.Section; import org.eclipse.ui.part.ViewPart; import de.gebit.integrity.eclipse.Activator; import de.gebit.integrity.eclipse.actions.BreakpointAction; import de.gebit.integrity.eclipse.controls.ProgressBar; import de.gebit.integrity.eclipse.running.TestActionConfigurationDialog; import de.gebit.integrity.remoting.IntegrityRemotingConstants; import de.gebit.integrity.remoting.client.IntegrityRemotingClient; import de.gebit.integrity.remoting.client.IntegrityRemotingClientListener; import de.gebit.integrity.remoting.entities.setlist.SetList; import de.gebit.integrity.remoting.entities.setlist.SetListEntry; import de.gebit.integrity.remoting.entities.setlist.SetListEntryAttributeKeys; import de.gebit.integrity.remoting.entities.setlist.SetListEntryTypes; import de.gebit.integrity.remoting.transport.Endpoint; import de.gebit.integrity.remoting.transport.enums.ExecutionCommands; import de.gebit.integrity.remoting.transport.enums.ExecutionStates; import de.gebit.integrity.remoting.transport.enums.TestRunnerCallbackMethods; import de.gebit.integrity.remoting.transport.messages.ExecutionStateMessage; import de.gebit.integrity.remoting.transport.messages.IntegrityRemotingVersionMessage; import de.gebit.integrity.remoting.transport.messages.SetListBaselineMessage; /** * The Integrity Test Runner Eclipse Plugin main view. * * @author Rene Schneider */ public class IntegrityTestRunnerView extends ViewPart { /** * The ID of the view as specified by the extension. */ public static final String ID = "de.gebit.integrity.eclipse.views.IntegrityTestRunnerView"; /** * The sash form used to split the screen in one half for the tree, and another for the details view. */ private SashForm sashForm; /** * The container for the tree. */ private Form treeContainer; /** * The test execution tree viewer. */ private TreeViewer treeViewer; /** * Status flag which is used to signal whether the tree viewer is currently scrolled by the user (using the vertical * scrollbar). */ private boolean treeViewerIsScrolledManually; /** * The drawer to colorize the test execution tree. */ private TestTreeContentDrawer viewerContentDrawer; /** * The container for the detail information. */ private Composite detailsContainer; /** * The scrolling form for the details. */ private ScrolledForm details; /** * The hyperlink group for the fixture link. */ private HyperlinkGroup fixtureLinkGroup; /** * The link that allows to jump to a specific fixture method. */ private Hyperlink fixtureLink; /** * The label displaying whether a command is executed on a fork. */ private Label forkLabel; /** * The container for the detail information groups. */ private Composite detailGroups; /** * The variable section. */ private Section variableSection; /** * The composite for the variable table. */ private Composite variableComposite; /** * The table of defined variables. */ private TableViewer variableTable; /** * The section for parameters. */ private Section parameterSection; /** * The composite for the parameter table. */ private Composite parameterComposite; /** * The table with all defined parameters. */ private TableViewer parameterTable; /** * The section that gets the result info. */ private Section resultSection; /** * The composite containing result UI elements. */ private Composite resultComposite; /** * The label for the first (actual) result. */ private Label resultLine1Name; /** * The text field for the first (actual) result. */ private Text resultLine1Text; /** * The container for the first (actual) result text field, which adds a color border around it. */ private Composite resultLine1Border; /** * The label for the second (expected) result. */ private Label resultLine2Name; /** * The text field for the second (expected) result. */ private Text resultLine2Text; /** * The container for the second (expected) result text field, which adds a color border around it. */ private Composite resultLine2Border; /** * The container for the result table. */ private Composite resultTableComposite; /** * The result table (for multi-result tests). */ private TableViewer resultTable; /** * The container for the variable update table. */ private Composite varUpdateTableComposite; /** * The variable update table (for calls with multi-variable updates). */ private TableViewer varUpdateTable; /** * The color for results of successful tests. */ private Color resultSuccessColor; /** * The color for results of failed tests. */ private Color resultFailureColor; /** * The neutral color for results. */ private Color resultNeutralColor; /** * The color of exception results. */ private Color resultExceptionColor; /** * The image used to display successful test results. */ private Image resultSuccessIconImage; /** * The image used to display failed test results. */ private Image resultFailureIconImage; /** * The image used to display exception test results. */ private Image resultExceptionIconImage; /** * The container to display the success icon. */ private Label resultSuccessIcon; /** * The container to display the failure icon. */ private Label resultFailureIcon; /** * The container to display the exception icon. */ private Label resultExceptionIcon; /** * The success count. */ private Label resultSuccessCountLabel; /** * The failure count. */ private Label resultFailureCountLabel; /** * The exception count. */ private Label resultExceptionCountLabel; /** * The progress bar displaying the test execution progress. */ private ProgressBar executionProgress; /** * The background color for table test results (successful tests). */ private Color resultTableSuccessColor; /** * The background color for failed table test results (failed tests). */ private Color resultTableFailureColor; /** * The action that connects to a test runner. */ private Action connectToTestRunnerAction; /** * The action that allows test continuation. */ private Action playAction; /** * The action that allows to pause a running test execution. */ private Action pauseAction; /** * The action for single-stepping test execution steps. */ private Action stepIntoAction; /** * The action for stepping over suite calls. */ private Action stepOverAction; /** * The action that runs a predefined launch config and connects to the test runner automatically. */ private Action executeTestAction; /** * The action allowing to configure what is executed with {@link #executeTestAction}. */ private Action configureTestAction; /** * The action which expands all nodes one level further. */ private Action expandAllAction; /** * The action which collapses all nodes. */ private Action collapseAllAction; /** * The action which toggles the scroll lock function. */ private Action scrollLockAction; /** * Whether scroll lock is active. */ private boolean scrollLockActive; /** * The last level of node expansion. */ private int lastExpansionLevel; /** * The remoting client instance. */ private IntegrityRemotingClient client; /** * The currently used set list instance. */ private SetList setList; /** * The set of breakpoints currently in use. */ private Set<Integer> breakpointSet = Collections.synchronizedSet(new HashSet<Integer>()); /** * The launch configuration to run when the start button in the view is pressed. */ private ILaunchConfiguration launchConfiguration; /** * The constructor. */ public IntegrityTestRunnerView() { } /** * This is a callback that will allow us to create the viewer and initialize it. */ // SUPPRESS CHECKSTYLE MethodLength public void createPartControl(final Composite aParent) { aParent.setLayout(new FillLayout()); final FormToolkit tempToolkit = new FormToolkit(aParent.getDisplay()); resultSuccessColor = new Color(Display.getCurrent(), 0, 94, 13); resultFailureColor = new Color(Display.getCurrent(), 190, 0, 0); resultNeutralColor = new Color(Display.getCurrent(), 0, 0, 0); resultExceptionColor = new Color(Display.getCurrent(), 204, 163, 0); resultTableSuccessColor = new Color(Display.getCurrent(), 205, 255, 222); resultTableFailureColor = new Color(Display.getCurrent(), 255, 130, 130); resultSuccessIconImage = Activator.getImageDescriptor("icons/suite_success_big.png").createImage(); resultFailureIconImage = Activator.getImageDescriptor("icons/suite_failure_big.png").createImage(); resultExceptionIconImage = Activator.getImageDescriptor("icons/suite_exception_big.png").createImage(); sashForm = new SashForm(aParent, SWT.HORIZONTAL | SWT.SMOOTH); treeContainer = new Form(sashForm, SWT.NONE); treeContainer.setText("Not connected"); treeContainer.getBody().setLayout(new FormLayout()); treeContainer.setBackground(tempToolkit.getColors().getBackground()); treeContainer.setForeground(tempToolkit.getColors().getColor(IFormColors.TITLE)); treeContainer.setFont(JFaceResources.getHeaderFont()); tempToolkit.decorateFormHeading(treeContainer); executionProgress = new ProgressBar(treeContainer.getBody(), SWT.NONE); FormData tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 0); tempFormData.right = new FormAttachment(100, 0); tempFormData.top = new FormAttachment(0, 0); tempFormData.bottom = new FormAttachment(0, 16); executionProgress.setLayoutData(tempFormData); treeViewer = new TreeViewer(treeContainer.getBody(), SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL); treeViewer.setUseHashlookup(true); treeViewer.setContentProvider(new TestTreeContentProvider(treeViewer)); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 0); tempFormData.right = new FormAttachment(100, 0); tempFormData.top = new FormAttachment(executionProgress, 0); tempFormData.bottom = new FormAttachment(100, 0); treeViewer.getTree().setLayoutData(tempFormData); treeViewer.getTree().getVerticalBar().addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent anEvent) { // nothing to do } public void widgetSelected(SelectionEvent anEvent) { if (anEvent.detail == SWT.NONE) { treeViewerIsScrolledManually = false; } else if (anEvent.detail == SWT.DRAG) { treeViewerIsScrolledManually = true; } } }); detailsContainer = new Composite(sashForm, SWT.NONE); detailsContainer.setLayout(new FillLayout()); details = new ScrolledForm(detailsContainer, SWT.V_SCROLL | SWT.H_SCROLL); details.setExpandHorizontal(true); details.setExpandVertical(true); details.setBackground(tempToolkit.getColors().getBackground()); details.setForeground(tempToolkit.getColors().getColor(IFormColors.TITLE)); details.setFont(JFaceResources.getHeaderFont()); details.getBody().setLayout(new FormLayout()); tempToolkit.decorateFormHeading(details.getForm()); fixtureLinkGroup = new HyperlinkGroup(aParent.getDisplay()); fixtureLink = new Hyperlink(details.getBody(), SWT.NONE); fixtureLink.setBackground(details.getBackground()); fixtureLink.setText(""); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(0, 3); tempFormData.height = 10; fixtureLink.setLayoutData(tempFormData); fixtureLink.addHyperlinkListener(new HyperlinkAdapter() { public void linkActivated(HyperlinkEvent anEvent) { jumpToJavaMethod(anEvent.getLabel()); } }); fixtureLinkGroup.add(fixtureLink); forkLabel = new Label(details.getBody(), SWT.NONE); forkLabel.setText(""); forkLabel.setBackground(tempToolkit.getColors().getBackground()); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(fixtureLink, 3); tempFormData.height = 14; forkLabel.setLayoutData(tempFormData); detailGroups = new Composite(details.getBody(), SWT.NONE); detailGroups.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); detailGroups.setLayout(new FormLayout()); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(forkLabel, 3); tempFormData.bottom = new FormAttachment(100, 0); detailGroups.setLayoutData(tempFormData); resultSection = tempToolkit.createSection(detailGroups, Section.TITLE_BAR); resultSection.setText("Result"); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(0, 10); tempFormData.bottom = new FormAttachment(0, 202); resultSection.setLayoutData(tempFormData); resultSection.setLayout(new FillLayout()); resultComposite = tempToolkit.createComposite(resultSection); tempToolkit.paintBordersFor(resultComposite); resultSection.setClient(resultComposite); resultComposite.setLayout(new FormLayout()); parameterSection = tempToolkit.createSection(detailGroups, Section.TITLE_BAR); parameterSection.setText("Parameters"); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultSection, 10); tempFormData.bottom = new FormAttachment(resultSection, 140, SWT.BOTTOM); parameterSection.setLayoutData(tempFormData); parameterSection.setLayout(new FillLayout()); parameterComposite = tempToolkit.createComposite(parameterSection); tempToolkit.paintBordersFor(parameterComposite); parameterSection.setClient(parameterComposite); parameterComposite.setLayout(new FillLayout()); parameterTable = new TableViewer(parameterComposite); parameterTable.setContentProvider(new ArrayContentProvider()); configureTable(parameterTable); variableSection = tempToolkit.createSection(detailGroups, Section.TITLE_BAR); variableSection.setText("Variable definitions"); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(parameterSection, 10); tempFormData.bottom = new FormAttachment(parameterSection, 160, SWT.BOTTOM); variableSection.setLayoutData(tempFormData); variableSection.setLayout(new FillLayout()); variableComposite = tempToolkit.createComposite(variableSection); tempToolkit.paintBordersFor(variableComposite); variableSection.setClient(variableComposite); variableComposite.setLayout(new FillLayout()); variableTable = new TableViewer(variableComposite); variableTable.setContentProvider(new ArrayContentProvider()); configureTable(variableTable); resultComposite = tempToolkit.createComposite(resultSection); tempToolkit.paintBordersFor(resultComposite); resultSection.setClient(resultComposite); resultComposite.setLayout(new FormLayout()); resultTableComposite = tempToolkit.createComposite(resultComposite); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultComposite, 10); tempFormData.bottom = new FormAttachment(resultComposite, 160, SWT.BOTTOM); resultTableComposite.setLayoutData(tempFormData); resultTableComposite.setLayout(new FillLayout()); resultTable = new TableViewer(resultTableComposite); resultTable.setContentProvider(new ArrayContentProvider()); configureResultTable(resultTable); varUpdateTableComposite = tempToolkit.createComposite(resultComposite); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultComposite, 10); tempFormData.bottom = new FormAttachment(resultComposite, 160, SWT.BOTTOM); varUpdateTableComposite.setLayoutData(tempFormData); varUpdateTableComposite.setLayout(new FillLayout()); varUpdateTable = new TableViewer(varUpdateTableComposite); varUpdateTable.setContentProvider(new ArrayContentProvider()); configureVarUpdateTable(varUpdateTable); resultLine1Name = new Label(resultComposite, SWT.WRAP); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(0, 4); resultLine1Name.setLayoutData(tempFormData); resultLine1Border = new Composite(resultComposite, SWT.NONE); resultLine1Border.setForeground(resultNeutralColor); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultLine1Name, 2); tempFormData.bottom = new FormAttachment(resultLine1Name, 80); resultLine1Border.setLayoutData(tempFormData); FillLayout tempFill = new FillLayout(); tempFill.marginHeight = 1; tempFill.marginWidth = 1; resultLine1Border.setLayout(tempFill); configureTextFieldBorder(resultLine1Border); resultLine1Text = new Text(resultLine1Border, SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL); resultLine1Text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); resultLine2Name = new Label(resultComposite, SWT.WRAP); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultLine1Border, 6); resultLine2Name.setLayoutData(tempFormData); resultLine2Border = new Composite(resultComposite, SWT.NONE); resultLine2Border.setForeground(resultNeutralColor); tempFormData = new FormData(); tempFormData.left = new FormAttachment(0, 5); tempFormData.right = new FormAttachment(100, -5); tempFormData.top = new FormAttachment(resultLine2Name, 2); tempFormData.bottom = new FormAttachment(resultLine2Name, 80); resultLine2Border.setLayoutData(tempFormData); tempFill = new FillLayout(); tempFill.marginHeight = 1; tempFill.marginWidth = 1; resultLine2Border.setLayout(tempFill); configureTextFieldBorder(resultLine2Border); resultLine2Text = new Text(resultLine2Border, SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL); resultLine2Text.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE)); resultFailureIcon = new Label(resultComposite, SWT.NONE); resultFailureIcon.setImage(resultFailureIconImage); tempFormData = new FormData(); tempFormData.left = new FormAttachment(50, -24); tempFormData.top = new FormAttachment(0, 10); tempFormData.width = 48; tempFormData.height = 48; resultFailureIcon.setLayoutData(tempFormData); resultSuccessIcon = new Label(resultComposite, SWT.NONE); resultSuccessIcon.setImage(resultSuccessIconImage); tempFormData = new FormData(); tempFormData.right = new FormAttachment(resultFailureIcon, -16); tempFormData.top = new FormAttachment(0, 10); tempFormData.width = 48; tempFormData.height = 48; resultSuccessIcon.setLayoutData(tempFormData); resultExceptionIcon = new Label(resultComposite, SWT.NONE); resultExceptionIcon.setImage(resultExceptionIconImage); tempFormData = new FormData(); tempFormData.left = new FormAttachment(resultFailureIcon, 16); tempFormData.top = new FormAttachment(0, 10); tempFormData.width = 48; tempFormData.height = 48; resultExceptionIcon.setLayoutData(tempFormData); resultSuccessCountLabel = new Label(resultComposite, SWT.CENTER); resultSuccessCountLabel.setText("123"); resultSuccessCountLabel.setForeground(resultSuccessColor); FontData[] tempFontData = resultSuccessCountLabel.getFont().getFontData(); tempFontData[0].setHeight(16); tempFontData[0].setStyle(SWT.BOLD); resultSuccessCountLabel.setFont(new Font(Display.getCurrent(), tempFontData[0])); tempFormData = new FormData(); tempFormData.left = new FormAttachment(resultSuccessIcon, -32, SWT.CENTER); tempFormData.top = new FormAttachment(resultSuccessIcon, 4); tempFormData.width = 64; tempFormData.height = 24; resultSuccessCountLabel.setLayoutData(tempFormData); resultFailureCountLabel = new Label(resultComposite, SWT.CENTER); resultFailureCountLabel.setText("123"); resultFailureCountLabel.setForeground(resultFailureColor); tempFontData = resultFailureCountLabel.getFont().getFontData(); tempFontData[0].setHeight(16); tempFontData[0].setStyle(SWT.BOLD); resultFailureCountLabel.setFont(new Font(Display.getCurrent(), tempFontData[0])); tempFormData = new FormData(); tempFormData.left = new FormAttachment(resultFailureIcon, -32, SWT.CENTER); tempFormData.top = new FormAttachment(resultFailureIcon, 4); tempFormData.width = 64; tempFormData.height = 24; resultFailureCountLabel.setLayoutData(tempFormData); resultExceptionCountLabel = new Label(resultComposite, SWT.CENTER); resultExceptionCountLabel.setText("123"); resultExceptionCountLabel.setForeground(resultExceptionColor); tempFontData = resultExceptionCountLabel.getFont().getFontData(); tempFontData[0].setHeight(16); tempFontData[0].setStyle(SWT.BOLD); resultExceptionCountLabel.setFont(new Font(Display.getCurrent(), tempFontData[0])); tempFormData = new FormData(); tempFormData.left = new FormAttachment(resultExceptionIcon, -32, SWT.CENTER); tempFormData.top = new FormAttachment(resultExceptionIcon, 4); tempFormData.width = 64; tempFormData.height = 24; resultExceptionCountLabel.setLayoutData(tempFormData); PlatformUI.getWorkbench().getHelpSystem().setHelp(treeViewer.getControl(), "de.gebit.integrity.eclipse.viewer"); attachTreeInteractionListeners(); makeActions(); hookContextMenu(); contributeToActionBars(); updateDetailPanel(null, null); } private void configureTable(final TableViewer aTable) { aTable.getTable().setHeaderVisible(true); aTable.getTable().setLinesVisible(true); TableViewerColumn tempColumn = new TableViewerColumn(aTable, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); tempColumn.getColumn().setText("Name"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.NAME); } }); tempColumn = new TableViewerColumn(aTable, SWT.NONE); tempColumn.getColumn().setText("Value"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.VALUE); } }); } private void configureResultTable(final TableViewer aTable) { aTable.getTable().setHeaderVisible(true); aTable.getTable().setLinesVisible(true); TableViewerColumn tempColumn = new TableViewerColumn(aTable, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); tempColumn.getColumn().setText("Name"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.NAME); } @Override public Color getBackground(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; Boolean tempSuccess = (Boolean) tempEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG); if (tempSuccess == null) { return super.getBackground(anElement); } else if (tempSuccess) { return resultTableSuccessColor; } else { return resultTableFailureColor; } } }); tempColumn = new TableViewerColumn(aTable, SWT.NONE); tempColumn.getColumn().setText("Result"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.VALUE); } @Override public Color getBackground(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; Boolean tempSuccess = (Boolean) tempEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG); if (tempSuccess == null) { return super.getBackground(anElement); } else if (tempSuccess) { return resultTableSuccessColor; } else { return resultTableFailureColor; } } }); tempColumn = new TableViewerColumn(aTable, SWT.NONE); tempColumn.getColumn().setText("Expected"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.EXPECTED_RESULT); } @Override public Color getBackground(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; Boolean tempSuccess = (Boolean) tempEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG); if (tempSuccess == null) { return super.getBackground(anElement); } else if (tempSuccess) { return resultTableSuccessColor; } else { return resultTableFailureColor; } } }); } private void configureVarUpdateTable(final TableViewer aTable) { aTable.getTable().setHeaderVisible(true); aTable.getTable().setLinesVisible(true); TableViewerColumn tempColumn = new TableViewerColumn(aTable, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); tempColumn.getColumn().setText("Result"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.PARAMETER_NAME); } }); tempColumn = new TableViewerColumn(aTable, SWT.NONE); tempColumn.getColumn().setText("Variable"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.VARIABLE_NAME); } }); tempColumn = new TableViewerColumn(aTable, SWT.NONE); tempColumn.getColumn().setText("Value"); tempColumn.getColumn().setWidth(150); tempColumn.getColumn().setResizable(true); tempColumn.getColumn().setMoveable(false); tempColumn.setLabelProvider(new ColumnLabelProvider() { @Override public String getText(Object anElement) { SetListEntry tempEntry = (SetListEntry) anElement; return (String) tempEntry.getAttribute(SetListEntryAttributeKeys.VALUE); } }); } private void configureTextFieldBorder(final Composite aBorder) { aBorder.addPaintListener(new PaintListener() { public void paintControl(PaintEvent anEvent) { GC tempGC = anEvent.gc; tempGC.setForeground(aBorder.getForeground()); Rectangle tempRect = aBorder.getBounds(); tempGC.drawRectangle(0, 0, tempRect.width - 1, tempRect.height - 1); } }); } private void attachTreeInteractionListeners() { treeViewer.addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent anEvent) { if (anEvent.getSelection().isEmpty()) { updateDetailPanel(null, null); } else { if (anEvent.getSelection() instanceof TreeSelection) { TreeSelection tempSelection = (TreeSelection) anEvent.getSelection(); if (tempSelection.getFirstElement() instanceof SetListEntry) { SetListEntry tempEntry = (SetListEntry) tempSelection.getFirstElement(); if (tempEntry.getType() == SetListEntryTypes.COMMENT) { updateDetailPanel(null, null); } else { updateDetailPanel(tempEntry, (ILabelProvider) ((TreeViewer) anEvent.getSource()).getLabelProvider()); } } } } } }); } private void hookContextMenu() { MenuManager tempMenuMgr = new MenuManager("#PopupMenu"); tempMenuMgr.setRemoveAllWhenShown(true); tempMenuMgr.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager aManager) { IntegrityTestRunnerView.this.fillContextMenu(aManager); } }); Menu tempMenu = tempMenuMgr.createContextMenu(treeViewer.getControl()); treeViewer.getControl().setMenu(tempMenu); getSite().registerContextMenu(tempMenuMgr, treeViewer); } private void contributeToActionBars() { IActionBars tempBars = getViewSite().getActionBars(); fillLocalPullDown(tempBars.getMenuManager()); fillLocalToolBar(tempBars.getToolBarManager()); } private void fillLocalPullDown(IMenuManager aManager) { aManager.add(executeTestAction); aManager.add(configureTestAction); aManager.add(new Separator()); aManager.add(playAction); aManager.add(pauseAction); aManager.add(stepIntoAction); aManager.add(new Separator()); aManager.add(connectToTestRunnerAction); } private void fillContextMenu(IMenuManager aManager) { if (treeViewer.getSelection().isEmpty()) { return; } if (treeViewer.getSelection() instanceof IStructuredSelection) { IStructuredSelection tempSelection = (IStructuredSelection) treeViewer.getSelection(); if (tempSelection.getFirstElement() instanceof SetListEntry) { final SetListEntry tempEntry = (SetListEntry) tempSelection.getFirstElement(); if (tempEntry.getType() == SetListEntryTypes.TEST || tempEntry.getType() == SetListEntryTypes.CALL) { if (breakpointSet.contains(tempEntry.getId())) { aManager.add(new BreakpointAction(tempEntry.getId(), "Remove Breakpoint", "Removes the breakpoint from the selected step.") { public void run() { if (client == null || !client.isActive()) { showMessage("Sorry, but breakpoints can only be added or removed while connected " + "to a (running or paused) test runner instance!"); } else { client.deleteBreakpoint(tempEntry.getId()); } } }); } else { aManager.add(new BreakpointAction(tempEntry.getId(), "Add Breakpoint", "Adds a breakpoint to the selected step.") { public void run() { if (client == null || !client.isActive()) { showMessage("Sorry, but breakpoints can only be added or removed while connected " + "to a (running or paused) test runner instance!"); } else { client.createBreakpoint(tempEntry.getId()); } } }); } } } } } private void fillLocalToolBar(IToolBarManager aManager) { // These are still in development... aManager.add(executeTestAction); aManager.add(configureTestAction); aManager.add(new Separator()); aManager.add(expandAllAction); aManager.add(collapseAllAction); aManager.add(scrollLockAction); aManager.add(new Separator()); aManager.add(playAction); aManager.add(pauseAction); aManager.add(stepIntoAction); aManager.add(stepOverAction); aManager.add(new Separator()); aManager.add(connectToTestRunnerAction); } private void makeActions() { connectToTestRunnerAction = new Action() { private String lastHostname = "localhost"; public void run() { if (client == null || !client.isActive()) { InputDialog tempDialog = new InputDialog(getSite().getShell(), "Connect to test runner", "Please enter the hostname or IP address to connect to", lastHostname, null); if (tempDialog.open() == IStatus.OK && tempDialog.getValue() != null && tempDialog.getValue().length() > 0) { lastHostname = tempDialog.getValue(); String tempHost = lastHostname; int tempPort = IntegrityRemotingConstants.DEFAULT_PORT; if (tempHost.contains(":")) { try { tempPort = Integer.parseInt(tempHost.substring(tempHost.indexOf(':') + 1)); } catch (NumberFormatException exc) { showMessage("The port number given is illegal."); return; } catch (IndexOutOfBoundsException exc) { showMessage("No port number given."); return; } tempHost = tempHost.substring(0, tempHost.indexOf(':')); } connectToTestRunnerAsync(tempHost, tempPort); } } else { disconnectFromTestRunner(); } } }; playAction = new Action() { public void run() { client.controlExecution(ExecutionCommands.RUN); updateStatus("Continuing test execution..."); } }; playAction.setText("Start or continue test execution"); playAction.setToolTipText("Continues test execution if currently paused."); playAction.setImageDescriptor(Activator.getImageDescriptor("icons/play_enabled.gif")); playAction.setDisabledImageDescriptor(Activator.getImageDescriptor("icons/play_disabled.gif")); pauseAction = new Action() { public void run() { client.controlExecution(ExecutionCommands.PAUSE); updateStatus("Pausing test execution..."); } }; pauseAction.setText("Pause test execution"); pauseAction.setToolTipText("Interrupts test execution; the currently running test will be finished though."); pauseAction.setImageDescriptor(Activator.getImageDescriptor("icons/pause_enabled.gif")); pauseAction.setDisabledImageDescriptor(Activator.getImageDescriptor("icons/pause_disabled.gif")); stepIntoAction = new Action() { public void run() { client.controlExecution(ExecutionCommands.STEP_INTO); updateStatus("Executing single step..."); } }; stepIntoAction.setText("Single step / step into"); stepIntoAction.setToolTipText("Executes a single test or call."); stepIntoAction.setImageDescriptor(Activator.getImageDescriptor("icons/stepinto_enabled.gif")); stepIntoAction.setDisabledImageDescriptor(Activator.getImageDescriptor("icons/stepinto_disabled.gif")); stepOverAction = new Action() { @SuppressWarnings("unchecked") public void run() { SetListEntry tempTarget = null; SetListEntry tempCurrentSuite = setList.getParent(setList.getEntryInExecution()); if (tempCurrentSuite != null) { SetListEntry tempOuterSuite = setList.getParent(tempCurrentSuite); while (tempOuterSuite != null && tempTarget == null) { List<Integer> tempSetupStatements = (List<Integer>) tempOuterSuite .getAttribute(SetListEntryAttributeKeys.SETUP); List<Integer> tempSuiteStatements = (List<Integer>) tempOuterSuite .getAttribute(SetListEntryAttributeKeys.STATEMENTS); List<Integer> tempTeardownStatements = (List<Integer>) tempOuterSuite .getAttribute(SetListEntryAttributeKeys.TEARDOWN); List<Integer> tempAllStatements = new LinkedList<Integer>(); if (tempSetupStatements != null) { tempAllStatements.addAll(tempSetupStatements); } if (tempSuiteStatements != null) { tempAllStatements.addAll(tempSuiteStatements); } if (tempTeardownStatements != null) { tempAllStatements.addAll(tempTeardownStatements); } int tempPos = tempAllStatements.indexOf(tempCurrentSuite.getId()) + 1; if (tempPos == 0 || tempPos >= tempAllStatements.size()) { tempOuterSuite = setList.getParent(tempOuterSuite); } else { tempTarget = setList.resolveReference(tempAllStatements.get(tempPos)); } } } if (tempTarget != null) { while (tempTarget != null && tempTarget.getType() != SetListEntryTypes.CALL && tempTarget.getType() != SetListEntryTypes.TEST) { tempTarget = setList.resolveReference(tempTarget.getId() + 1); } } if (tempTarget != null) { client.createBreakpoint(tempTarget.getId()); client.controlExecution(ExecutionCommands.RUN); updateStatus("Executing until end of current suite..."); } else { client.controlExecution(ExecutionCommands.RUN); updateStatus("Continuing test execution..."); } } }; stepOverAction.setText("Single step / step into"); stepOverAction.setToolTipText("Places a breakpoint after the current suite call and continues execution."); stepOverAction.setImageDescriptor(Activator.getImageDescriptor("icons/stepover_enabled.gif")); stepOverAction.setDisabledImageDescriptor(Activator.getImageDescriptor("icons/stepover_disabled.gif")); executeTestAction = new Action() { public void run() { if (launchConfiguration != null) { try { executeTestAction.setEnabled(false); final ILaunch tempLaunch = launchConfiguration.launch(ILaunchManager.RUN_MODE, null); new Thread() { @Override public void run() { boolean tempSuccess = false; while (!tempLaunch.isTerminated()) { try { if (!tempSuccess && !isConnected()) { // try to connect at least once connectToTestRunner("localhost", IntegrityRemotingConstants.DEFAULT_PORT); tempSuccess = true; } else { // Now we'll wait until the launch has terminated try { Thread.sleep(1000); } catch (InterruptedException exc) { // don't care } } } catch (UnknownHostException exc) { // exceptions are expected, that just means we need to retry } catch (IOException exc) { // exceptions are expected, that just means we need to retry } } executeTestAction.setEnabled(true); }; }.start(); } catch (CoreException exc) { showException(exc); } } } }; executeTestAction.setText("Launch test application"); executeTestAction.setToolTipText("Launches the test run configuration."); executeTestAction.setImageDescriptor(Activator.getImageDescriptor("icons/exec_enabled.gif")); executeTestAction.setEnabled(false); configureTestAction = new Action() { @Override public void run() { TestActionConfigurationDialog tempDialog = new TestActionConfigurationDialog(getSite().getShell()); if (tempDialog.open() == Dialog.OK) { launchConfiguration = tempDialog.getSelectedConfiguration(); if (launchConfiguration != null) { executeTestAction.setEnabled(true); } } } }; configureTestAction.setText("Configure test application"); configureTestAction.setToolTipText("Configures the test run configuration(s) to launch."); configureTestAction.setImageDescriptor(Activator.getImageDescriptor("icons/exec_config_enabled.gif")); expandAllAction = new Action() { @Override public void run() { lastExpansionLevel++; ((TestTreeContentProvider) treeViewer.getContentProvider()).expandToLevel(lastExpansionLevel + 1); } }; expandAllAction.setText("Expand all (one level)"); expandAllAction.setToolTipText("Expands all nodes one level deeper (except table tests)."); expandAllAction.setImageDescriptor(Activator.getImageDescriptor("icons/expandall.gif")); collapseAllAction = new Action() { @Override public void run() { lastExpansionLevel = 0; treeViewer.collapseAll(); } }; collapseAllAction.setText("Collapse all"); collapseAllAction.setToolTipText("Collapses all nodes."); collapseAllAction.setImageDescriptor(Activator.getImageDescriptor("icons/collapseall.gif")); scrollLockAction = new Action("Toggle scroll lock", IAction.AS_CHECK_BOX) { @Override public void run() { scrollLockActive = isChecked(); }; }; scrollLockAction.setToolTipText("Toggles the scroll lock setting."); scrollLockAction.setImageDescriptor(Activator.getImageDescriptor("icons/scrolllock.gif")); updateActionStatus(null); } private boolean isConnected() { return (client != null && client.isActive()); } private void updateActionStatus(final ExecutionStates anExecutionState) { Runnable tempRunnable = new Runnable() { @Override public void run() { if (!isConnected()) { connectToTestRunnerAction.setText("Connect to test runner"); connectToTestRunnerAction.setToolTipText("Connects to a local or remote test runner"); connectToTestRunnerAction.setImageDescriptor(Activator.getImageDescriptor("icons/connect.gif")); playAction.setEnabled(false); pauseAction.setEnabled(false); stepIntoAction.setEnabled(false); stepOverAction.setEnabled(false); } else { connectToTestRunnerAction.setText("Disconnect from test runner"); connectToTestRunnerAction .setToolTipText("Disconnects the client from the currently connected test runner"); connectToTestRunnerAction.setImageDescriptor(Activator.getImageDescriptor("icons/disconnect.gif")); if (anExecutionState == null) { playAction.setEnabled(false); pauseAction.setEnabled(false); stepIntoAction.setEnabled(false); stepOverAction.setEnabled(false); } else { switch (anExecutionState) { case BLOCKED: playAction.setEnabled(true); pauseAction.setEnabled(false); stepIntoAction.setEnabled(true); stepOverAction.setEnabled(true); updateStatus("Waiting for execution start"); break; case PAUSED: playAction.setEnabled(true); pauseAction.setEnabled(false); stepIntoAction.setEnabled(true); stepOverAction.setEnabled(true); updateStatus("Paused test execution"); break; case RUNNING: playAction.setEnabled(false); pauseAction.setEnabled(true); stepIntoAction.setEnabled(false); stepOverAction.setEnabled(false); updateStatus("Running tests..."); break; case ENDED: playAction.setEnabled(false); pauseAction.setEnabled(false); stepIntoAction.setEnabled(false); stepOverAction.setEnabled(false); updateStatus("Test execution finished"); break; default: break; } } } } }; if (Display.getCurrent() != null) { Display.getCurrent().syncExec(tempRunnable); } else { Display.getDefault().asyncExec(tempRunnable); } } // SUPPRESS CHECKSTYLE MethodLength private void updateDetailPanel(SetListEntry anEntry, ILabelProvider aProvider) { fixtureLink.setVisible(false); forkLabel.setVisible(false); resultTableComposite.setVisible(false); varUpdateTableComposite.setVisible(false); resultLine1Name.setVisible(false); resultLine1Border.setVisible(false); resultLine1Text.setText(""); resultLine2Name.setVisible(false); resultLine2Border.setVisible(false); resultSuccessIcon.setVisible(false); resultFailureIcon.setVisible(false); resultExceptionIcon.setVisible(false); resultSuccessCountLabel.setVisible(false); resultFailureCountLabel.setVisible(false); resultExceptionCountLabel.setVisible(false); if (anEntry == null) { details.setText("Details"); details.setImage(null); } else { details.setImage(aProvider.getImage(anEntry)); if (anEntry.getType() == SetListEntryTypes.SUITE) { details.setText((String) anEntry.getAttribute(SetListEntryAttributeKeys.NAME)); } else { details.setText((String) anEntry.getAttribute(SetListEntryAttributeKeys.DESCRIPTION)); if (anEntry.getType() == SetListEntryTypes.RESULT) { fixtureLink.setText((String) setList.getParent(anEntry).getAttribute( SetListEntryAttributeKeys.FIXTURE)); } else { fixtureLink.setText((String) anEntry.getAttribute(SetListEntryAttributeKeys.FIXTURE)); } fixtureLink.setVisible(true); } String[] tempForkName = setList.getForkExecutingEntry(anEntry); if (tempForkName != null) { String tempLabelText = "executed on fork '" + tempForkName[0] + "'"; if (tempForkName[1] != null) { tempLabelText += " (" + tempForkName[1] + ")"; } forkLabel.setText(tempLabelText); forkLabel.setVisible(true); } List<SetListEntry> tempVariables = setList.resolveReferences(anEntry, SetListEntryAttributeKeys.VARIABLE_DEFINITIONS); if (tempVariables.size() > 0) { variableTable.setInput(tempVariables); } else { variableTable.setInput(null); } List<SetListEntry> tempParameters = setList .resolveReferences(anEntry, SetListEntryAttributeKeys.PARAMETERS); if (tempParameters.size() > 0) { parameterTable.setInput(tempParameters); } else { parameterTable.setInput(null); } SetListEntry tempResultEntry = null; if (anEntry.getType() == SetListEntryTypes.TABLETEST) { // High-level table test summary information is stored in the // tabletest entry itself tempResultEntry = anEntry; } else if (anEntry.getType() == SetListEntryTypes.RESULT) { // result entries are results by themselves ;-) tempResultEntry = anEntry; } else { tempResultEntry = setList.resolveReferences(anEntry, SetListEntryAttributeKeys.RESULT).get(0); } if (tempResultEntry != null) { switch (anEntry.getType()) { case SUITE: case TABLETEST: if (tempResultEntry.getAttribute(SetListEntryAttributeKeys.SUCCESS_COUNT) != null) { int tempSuccessCount = (Integer) tempResultEntry .getAttribute(SetListEntryAttributeKeys.SUCCESS_COUNT); int tempFailureCount = (Integer) tempResultEntry .getAttribute(SetListEntryAttributeKeys.FAILURE_COUNT); int tempExceptionCount = (Integer) tempResultEntry .getAttribute(SetListEntryAttributeKeys.EXCEPTION_COUNT); resultSuccessCountLabel.setText(Integer.toString(tempSuccessCount)); resultFailureCountLabel.setText(Integer.toString(tempFailureCount)); resultExceptionCountLabel.setText(Integer.toString(tempExceptionCount)); resultSuccessIcon.setVisible(true); resultFailureIcon.setVisible(true); resultExceptionIcon.setVisible(true); resultSuccessCountLabel.setVisible(true); resultFailureCountLabel.setVisible(true); resultExceptionCountLabel.setVisible(true); } else { resultLine1Name.setText("No results available - please run the tests first."); resultLine1Name.setVisible(true); } break; case TEST: case RESULT: @SuppressWarnings("unchecked") List<SetListEntry> tempComparisonEntries = setList .resolveReferences(((List<Integer>) tempResultEntry .getAttribute(SetListEntryAttributeKeys.COMPARISONS))); if (tempComparisonEntries.size() > 1) { resultTable.setInput(tempComparisonEntries); resultTableComposite.setVisible(true); } else { SetListEntry tempComparisonEntry = tempComparisonEntries.get(0); resultLine2Name.setText("Expected value: "); resultLine2Text.setText((String) tempComparisonEntry .getAttribute(SetListEntryAttributeKeys.EXPECTED_RESULT)); resultLine2Border.setForeground(resultNeutralColor); resultLine2Name.setVisible(true); resultLine2Border.setVisible(true); if (tempResultEntry.getAttribute(SetListEntryAttributeKeys.EXCEPTION) != null) { resultLine1Name.setText("Exception occurred while running the test fixture:"); resultLine1Text.setText((String) tempResultEntry .getAttribute(SetListEntryAttributeKeys.EXCEPTION)); resultLine1Border.setForeground(resultExceptionColor); resultLine1Name.setVisible(true); resultLine1Border.setVisible(true); } else { if (tempComparisonEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG) != null) { resultLine1Name.setText("Result returned by the test fixture: "); resultLine1Text.setText((String) tempComparisonEntry .getAttribute(SetListEntryAttributeKeys.VALUE)); if (tempComparisonEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG) != null) { if (Boolean.TRUE.equals(tempComparisonEntry .getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG))) { resultLine1Border.setForeground(resultSuccessColor); } else { resultLine1Border.setForeground(resultFailureColor); } } resultLine1Border.setVisible(true); } else { resultLine1Name.setText("No result available - please run the tests first."); } resultLine1Name.setVisible(true); } } break; case CALL: if (tempResultEntry.getAttribute(SetListEntryAttributeKeys.RESULT_SUCCESS_FLAG) != null) { if (tempResultEntry.getAttribute(SetListEntryAttributeKeys.EXCEPTION) != null) { resultLine1Name.setText("Exception occurred while running the test fixture:"); resultLine1Text.setText((String) tempResultEntry .getAttribute(SetListEntryAttributeKeys.EXCEPTION)); resultLine1Border.setForeground(resultExceptionColor); resultLine1Border.setVisible(true); } else { List<SetListEntry> tempVarUpdates = setList.resolveReferences(tempResultEntry, SetListEntryAttributeKeys.VARIABLE_UPDATES); if (tempVarUpdates.size() == 1) { String tempResultValue = (String) tempVarUpdates.get(0).getAttribute( SetListEntryAttributeKeys.VALUE); String tempTargetVariable = (String) tempVarUpdates.get(0).getAttribute( SetListEntryAttributeKeys.VARIABLE_NAME); if (tempTargetVariable != null) { tempResultValue += " ➔ " + tempTargetVariable; } resultLine1Name.setText("Result returned by the fixture:"); resultLine1Text.setText(tempResultValue); resultLine1Border.setForeground(resultNeutralColor); resultLine1Border.setVisible(true); } else if (tempVarUpdates.size() > 1) { varUpdateTable.setInput(tempVarUpdates); varUpdateTableComposite.setVisible(true); } else { resultLine1Name.setText("No result returned by the fixture."); } } } else { resultLine1Name.setText("No result available - please run the tests first."); } resultLine1Name.setVisible(true); break; default: break; } } } } private void showMessage(final String aMessage) { Runnable tempRunnable = new Runnable() { @Override public void run() { MessageDialog.openInformation(treeViewer.getControl().getShell(), "Integrity Test Control", aMessage); } }; Display.getDefault().asyncExec(tempRunnable); } private void showException(final Exception anException) { Runnable tempRunnable = new Runnable() { @Override public void run() { MessageDialog.openError(treeViewer.getControl().getShell(), "Integrity Test Runner", anException.getLocalizedMessage()); } }; Display.getDefault().asyncExec(tempRunnable); } private void updateStatus(final String aStatus) { Runnable tempRunnable = new Runnable() { @Override public void run() { treeContainer.setText(aStatus); } }; Display.getDefault().asyncExec(tempRunnable); } /** * Passing the focus request to the viewer's control. */ public void setFocus() { treeViewer.getControl().setFocus(); } private void connectToTestRunnerAsync(final String aHost, final int aPort) { new Thread("Test Runner Connect Thread") { @Override public void run() { try { connectToTestRunner(aHost, aPort); return; } catch (UnknownHostException exc) { showMessage("Target host name '" + aHost + "' could not be resolved."); } catch (IOException exc) { showMessage("Error while connecting to '" + aHost + "': " + exc.getMessage()); } } }.start(); } private void connectToTestRunner(final String aHost, final int aPort) throws UnknownHostException, IOException { updateStatus("Connecting..."); boolean tempSuccessful = false; try { client = new IntegrityRemotingClient(aHost, aPort, new RemotingListener()); tempSuccessful = true; updateStatus("Connected, downloading test data..."); } finally { if (!tempSuccessful) { updateStatus("Not connected"); } } } private void disconnectFromTestRunner() { client.close(); client = null; updateActionStatus(null); updateStatus("Not connected"); } private void jumpToJavaMethod(String aJavaClassAndMethod) { Matcher tempMatcher = Pattern.compile("([^#]*)\\.([^#]*)#(.*)").matcher(aJavaClassAndMethod); if (tempMatcher.matches()) { final String tempPackageName = tempMatcher.group(1); String tempClassName = tempMatcher.group(2); final String tempMethodName = tempMatcher.group(3); SearchPattern tempPattern = SearchPattern.createPattern(tempClassName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); IJavaSearchScope tempScope = SearchEngine.createWorkspaceScope(); SearchRequestor tempRequestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch aMatch) throws CoreException { IType tempType = (IType) aMatch.getElement(); if (tempPackageName.equals(tempType.getPackageFragment().getElementName())) { for (IMethod tempMethod : tempType.getMethods()) { if (tempMethodName.equals(tempMethod.getElementName())) { JavaUI.openInEditor(tempMethod); return; } } } } }; SearchEngine tempSearchEngine = new SearchEngine(); try { tempSearchEngine.search(tempPattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, tempScope, tempRequestor, null); } catch (CoreException exc) { exc.printStackTrace(); } } } private class RemotingListener implements IntegrityRemotingClientListener { @Override public void onConnectionSuccessful(IntegrityRemotingVersionMessage aRemoteVersion, Endpoint anEndpoint) { // request set list baseline and execution state anEndpoint.sendMessage(new SetListBaselineMessage(null)); anEndpoint.sendMessage(new ExecutionStateMessage(null)); updateActionStatus(client.getExecutionState()); } @Override public void onVersionMismatch(IntegrityRemotingVersionMessage aRemoteVersion, Endpoint anEndpoint) { // TODO Auto-generated method stub } @Override public void onBaselineReceived(SetList aSetList, Endpoint anEndpoint) { setList = aSetList; breakpointSet.clear(); Display.getDefault().asyncExec(new Runnable() { @Override public void run() { treeViewer.setSelection(null); treeViewer.setInput(null); executionProgress.setSetList(setList); executionProgress.redraw(); // the following will automatically dispose the old // provider! treeViewer.setLabelProvider(new TestTreeLabelProvider(setList, breakpointSet, Display.getCurrent(), treeViewer)); // the drawer must be manually disposed TestTreeContentDrawer tempOldContentDrawer = viewerContentDrawer; viewerContentDrawer = new TestTreeContentDrawer(setList, breakpointSet, Display.getCurrent()); viewerContentDrawer.attachToTree(treeViewer.getTree()); if (tempOldContentDrawer != null) { tempOldContentDrawer.dispose(treeViewer.getTree()); } treeViewer.setInput(setList); ((TestTreeContentProvider) treeViewer.getContentProvider()).expandToLevel(lastExpansionLevel + 1); updateStatus("Connected and ready"); } }); } @Override public void onExecutionStateUpdate(ExecutionStates aState, Endpoint anEndpoint) { updateActionStatus(aState); } @Override public void onConnectionLost(Endpoint anEndpoint) { client = null; updateActionStatus(null); updateStatus("Not connected"); } @Override public void onSetListUpdate(final SetListEntry[] someUpdatedEntries, final Integer anEntryInExecutionReference, Endpoint anEndpoint) { setList.integrateUpdates(someUpdatedEntries); if (anEntryInExecutionReference != null) { setList.setEntryInExecutionReference(anEntryInExecutionReference); } Display.getDefault().syncExec(new Runnable() { @Override public void run() { for (SetListEntry tempEntry : someUpdatedEntries) { switch (tempEntry.getType()) { case RESULT: treeViewer.update(setList.getParent(tempEntry), null); treeViewer.update(tempEntry, null); break; default: treeViewer.update(tempEntry, null); } } if (anEntryInExecutionReference != null) { List<SetListEntry> tempExecutionPath = setList.getEntriesInExecution(); for (SetListEntry tempEntry : tempExecutionPath) { treeViewer.update(tempEntry, null); } if (!scrollLockActive && !treeViewerIsScrolledManually && tempExecutionPath.size() > 0) { treeViewer.reveal(tempExecutionPath.get(0)); } } executionProgress.redraw(); } }); } @Override public void onConfirmCreateBreakpoint(final int anEntryReference, Endpoint anEndpoint) { breakpointSet.add(anEntryReference); Display.getDefault().syncExec(new Runnable() { @Override public void run() { treeViewer.update(setList.resolveReference(anEntryReference), null); } }); } @Override public void onConfirmRemoveBreakpoint(final int anEntryReference, Endpoint anEndpoint) { breakpointSet.remove(anEntryReference); Display.getDefault().syncExec(new Runnable() { @Override public void run() { treeViewer.update(setList.resolveReference(anEntryReference), null); } }); } @Override public void onTestRunnerCallbackMessageRetrieval(String aCallbackClassName, TestRunnerCallbackMethods aMethod, Serializable[] someData) { // not used in this context } @Override public void onVariableUpdateRetrieval(String aVariableName, Serializable aValue) { // not used in this context } } }
0fe9e086646db200550be680038d8f7af6d64864
2df5568d53e2de3e42543ff195d1c81f3043f33c
/src/test/java/ArrayHelperTest.java
322726fe871ade71c0e1ea9e747cc26596057bca
[]
no_license
kikimarik/gb_java_3
f7bdcd57e1da9d5e0d05840e01d9db63b621efd8
72e250fc5b0b639726e9c695d3c8016a5d60d8bd
refs/heads/main
2023-08-24T18:17:32.844429
2021-10-18T17:16:49
2021-10-18T17:16:49
410,074,853
0
0
null
2021-10-14T22:32:33
2021-09-24T19:07:55
Java
UTF-8
Java
false
false
2,383
java
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; public class ArrayHelperTest { private static Stream<Arguments> getPartAfterLastFourPositiveDataProvider() { List<Arguments> out = new ArrayList<>(List.of( Arguments.arguments(new int[]{5, 6, 7}, new int[]{1, 2, 3, 4, 5, 6, 7}), Arguments.arguments(new int[]{5, 7}, new int[]{4, 2, 3, 4, 4, 5, 7}), Arguments.arguments(new int[]{}, new int[]{4, 2, 3, 4, 5, 4}) )); return out.stream(); } private static Stream<Arguments> getPartAfterLastFourNegativeDataProvider() { List<Arguments> out = new ArrayList<>(List.of( Arguments.arguments(RuntimeException.class, new int[]{1, 2, 3}), Arguments.arguments(RuntimeException.class, new int[]{2}), Arguments.arguments(RuntimeException.class, new int[]{5, 9, 88}) )); return out.stream(); } private static Stream<Arguments> hasOneAndFourDataProvider() { List<Arguments> out = new ArrayList<>(List.of( Arguments.arguments(true, new int[]{1, 2, 3, 4}), // 1 and 4 Arguments.arguments(false, new int[]{1, 2, 3}), // only 1 Arguments.arguments(false, new int[]{2, 3, 4}), // only 4 Arguments.arguments(false, new int[]{2, 3}) // other )); return out.stream(); } @ParameterizedTest @MethodSource("getPartAfterLastFourPositiveDataProvider") public void getPartAfterLastFourPositive(int[] expected, int[] input) { Assertions.assertArrayEquals(expected, ArrayHelper.getPartAfterLastFour(input)); } @ParameterizedTest @MethodSource("getPartAfterLastFourNegativeDataProvider") public void getPartAfterLastFourNegative(Class<Throwable> expected, int[] input) { Assertions.assertThrows(expected, () -> ArrayHelper.getPartAfterLastFour(input)); } @ParameterizedTest @MethodSource("hasOneAndFourDataProvider") public void hasOneAndFour(boolean expected, int[] input) { Assertions.assertEquals(expected, ArrayHelper.hasOneAndFour(input)); } }
4d0928b838894b8a405a9cee8b29fe552fd93266
a2097209d9ccbd36faa4ce7eab1ec9de3237362b
/Toolbar.java
320aab8010cad862e0ca630afcb4a1e656737984
[]
no_license
oguzelyte/simple-java-web-browser
dd9b41b5c52ef03443e0dedffd233e308ec0aae0
a71db522d7e6fee784f0782b1df012885147c60e
refs/heads/master
2022-11-24T23:14:39.655836
2020-07-22T13:23:51
2020-07-22T13:23:51
281,684,031
0
0
null
null
null
null
UTF-8
Java
false
false
2,711
java
package websitePack; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.border.EtchedBorder; /* * * @author: Olivija Guzelyte (160421859) * @version: 03/05/2017 * */ public class Toolbar { /* * Creates a toolbar panel, back, forward * navigation buttons, an url bar, favourites button * in order to add them all to the toolbar. */ private JPanel toolbar = new JPanel(); private URLBar b = new URLBar(); private NavigationBtn nBack = new NavigationBtn(); private NavigationBtn nForward = new NavigationBtn(); private FavouritesBtn f = new FavouritesBtn(); private int heigth; /* * Sets up a toolbar's heigth, makes a medium empty border * and sets its layout to stretch all through the web browser, also makes it * visible. */ public Toolbar(int heigth) { toolbar.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(10, 10, 10, 10), new EtchedBorder())); toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.LINE_AXIS)); this.setHeigth(heigth); toolbar.setVisible(true); } /* * Adds either a home, refresh, favourites, navigation * button or a url bar. * */ public void addHomeButton(int heigth, int width) { HomeBtn b = new HomeBtn(width, heigth); toolbar.add(b.getHomeBtn()); } public void addRefreshButton(int heigth, int width) { RefreshBtn b = new RefreshBtn(width, heigth); toolbar.add(b.getRefreshBtn()); } public void addFavouritesButton(int heigth, int width) throws IOException { f = new FavouritesBtn(width, heigth); toolbar.add(f.getFavBtn()); } /* * Depending on the button type, the upcoming method adds either * back or forwards button. * */ public void addNavigationButton(NavigationBtnType way, int heigth, int width) { NavigationBtn n = new NavigationBtn(way, width, heigth); if (n.getButtonType() == NavigationBtnType.BACK) { nBack = n; } else nForward = n; toolbar.add(n.getNavigationBtn()); } public void addURLBar() { toolbar.add(b.getURLBar()); } public URLBar getURL() { return b; } /* * Returns all the buttons it has added because other classes * use them through the main method in order to react to user * clicks. * */ public NavigationBtn getBackBtn() { return nBack; } public NavigationBtn getForwardBtn() { return nForward; } public FavouritesBtn getFavouritesBtn() { return f; } public JPanel getToolbar() { return toolbar; } /* * Sets and gets the heigth of the toolbar. */ public int getHeigth() { return heigth; } public void setHeigth(int heigth) { this.heigth = heigth; } }
2d6545d451cbea58daea573bfc69153910dbe534
c2682f48b24cdad0569b0e10c75ae98c1d355de7
/src/main/java/br/uem/din/bibliotec/config/model/Multa.java
afccfb0a75d28d4092c2766c76b1e4d76676468a
[]
no_license
Luiz1996/Trab2_ISS
9fcf432f66d403c65fa267205c2afd28ae339b1c
cd0058616a69890cce0b1a261729859a7999fa73
refs/heads/master
2022-07-09T21:57:39.902864
2020-01-12T20:31:00
2020-01-12T20:31:00
233,453,649
1
0
null
2022-06-29T17:54:14
2020-01-12T20:25:54
HTML
UTF-8
Java
false
false
6,128
java
package br.uem.din.bibliotec.config.model; import java.util.Objects; public class Multa { //atributos persistentes private int codMulta; private int codLivro; private int codUsuario; private int codEmprestimo; private int codCotacao; private String dataCad; private String dataAlt; private int diasAtraso; private double valor; private int ativo; //atributo(s) auxiliar(es) private String cpfUsuario; private String idMultasSeparadosVirgula; private String nomeUsuario; private String tituloLivro; private String autorLivro; private String editoraLivro; private double valorCotacao; private String msgRetorno; private String colorMsgRetorno; private String totMulta; public Multa(){} public Multa(int codMulta, int diasAtraso, double valor, String nomeUsuario, String tituloLivro, String autorLivro, String editoraLivro, double valorCotacao, String totMulta) { this.codMulta = codMulta; this.diasAtraso = diasAtraso; this.valor = valor; this.nomeUsuario = nomeUsuario; this.tituloLivro = tituloLivro; this.autorLivro = autorLivro; this.editoraLivro = editoraLivro; this.valorCotacao = valorCotacao; this.totMulta = totMulta; } public int getCodMulta() { return codMulta; } public void setCodMulta(int codMulta) { this.codMulta = codMulta; } public int getCodLivro() { return codLivro; } public void setCodLivro(int codLivro) { this.codLivro = codLivro; } public int getCodUsuario() { return codUsuario; } public void setCodUsuario(int codUsuario) { this.codUsuario = codUsuario; } public String getDataCad() { return dataCad; } public void setDataCad(String dataCad) { this.dataCad = dataCad; } public String getDataAlt() { return dataAlt; } public void setDataAlt(String dataAlt) { this.dataAlt = dataAlt; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public int getAtivo() { return ativo; } public void setAtivo(int ativo) { this.ativo = ativo; } public String getCpfUsuario() { return cpfUsuario; } public String getIdMultasSeparadosVirgula() { return idMultasSeparadosVirgula; } public void setIdMultasSeparadosVirgula(String idMultasSeparadosVirgula) { this.idMultasSeparadosVirgula = idMultasSeparadosVirgula; } public void setCpfUsuario(String cpfUsuario) { this.cpfUsuario = cpfUsuario; } public String getMsgRetorno() { return msgRetorno; } public void setMsgRetorno(String msgRetorno) { this.msgRetorno = msgRetorno; } public String getColorMsgRetorno() { return colorMsgRetorno; } public void setColorMsgRetorno(String colorMsgRetorno) { this.colorMsgRetorno = colorMsgRetorno; } public int getCodEmprestimo() { return codEmprestimo; } public void setCodEmprestimo(int codEmprestimo) { this.codEmprestimo = codEmprestimo; } public int getCodCotacao() { return codCotacao; } public void setCodCotacao(int codCotacao) { this.codCotacao = codCotacao; } public int getDiasAtraso() { return diasAtraso; } public void setDiasAtraso(int diasAtraso) { this.diasAtraso = diasAtraso; } public String getNomeUsuario() { return nomeUsuario; } public void setNomeUsuario(String nomeUsuario) { this.nomeUsuario = nomeUsuario; } public String getTituloLivro() { return tituloLivro; } public void setTituloLivro(String tituloLivro) { this.tituloLivro = tituloLivro; } public String getAutorLivro() { return autorLivro; } public void setAutorLivro(String autorLivro) { this.autorLivro = autorLivro; } public String getEditoraLivro() { return editoraLivro; } public void setEditoraLivro(String editoraLivro) { this.editoraLivro = editoraLivro; } public double getValorCotacao() { return valorCotacao; } public void setValorCotacao(double valorCotacao) { this.valorCotacao = valorCotacao; } public String getTotMulta() { return totMulta; } public void setTotMulta(String totMulta) { this.totMulta = totMulta; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Multa multa = (Multa) o; return codMulta == multa.codMulta && codLivro == multa.codLivro && codUsuario == multa.codUsuario && Double.compare(multa.valor, valor) == 0 && ativo == multa.ativo && Objects.equals(dataCad, multa.dataCad) && Objects.equals(dataAlt, multa.dataAlt); } @Override public int hashCode() { return Objects.hash(codMulta, codLivro, codUsuario, dataCad, dataAlt, valor, ativo); } @Override public String toString() { return "Multa{" + "codMulta=" + codMulta + ", codLivro=" + codLivro + ", codUsuario=" + codUsuario + ", codEmprestimo=" + codEmprestimo + ", codCotacao=" + codCotacao + ", dataCad='" + dataCad + '\'' + ", dataAlt='" + dataAlt + '\'' + ", diasAtraso=" + diasAtraso + ", valor=" + valor + ", ativo=" + ativo + ", cpfUsuario='" + cpfUsuario + '\'' + ", idMultasSeparadosVirgula='" + idMultasSeparadosVirgula + '\'' + ", nomeUsuario='" + nomeUsuario + '\'' + ", tituloLivro='" + tituloLivro + '\'' + ", autorLivro='" + autorLivro + '\'' + ", editoraLivro='" + editoraLivro + '\'' + ", valorCotacao=" + valorCotacao + ", msgRetorno='" + msgRetorno + '\'' + ", colorMsgRetorno='" + colorMsgRetorno + '\'' + ", totMulta=" + totMulta + '}'; } }
5f7ee17a5d81d6c00f178b72caed8af2fb50d9f8
028cbe18b4e5c347f664c592cbc7f56729b74060
/v2/appserv-tests/devtests/web/networkListenerDynamicConfigEnabled/WebTest2.java
0f67a4246697420bf45d1f6606e9646c5a3c5004
[]
no_license
dmatej/Glassfish-SVN-Patched
8d355ff753b23a9a1bd9d7475fa4b2cfd3b40f9e
269e29ba90db6d9c38271f7acd2affcacf2416f1
refs/heads/master
2021-05-28T12:55:06.267463
2014-11-11T04:21:44
2014-11-11T04:21:44
23,610,469
1
0
null
null
null
null
UTF-8
Java
false
false
4,011
java
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ import java.lang.*; import java.io.*; import java.net.*; import com.sun.ejte.ccl.reporter.*; public class WebTest2 { private static int count = 0; private static int EXPECTED_COUNT = 1; static SimpleReporterAdapter stat= new SimpleReporterAdapter("appserv-tests"); private static URLConnection conn = null; private static URL url; private static ObjectOutputStream objectWriter = null; private static ObjectInputStream objectReader = null; public static void main(String args[]) { // The stat reporter writes out the test info and results // into the top-level quicklook directory during a run. stat.addDescription("Dynamic virtual-server/listener creation"); String host = args[0]; String port = args[1]; String contextRoot = args[2]; try{ System.out.println("Running test"); url = new URL("http://" + host + ":" + port + "/" + contextRoot + "/ServletTest"); String originalLoc = url.toString(); System.out.println("\n Invoking url: " + url.toString()); conn = url.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection urlConnection = (HttpURLConnection)conn; urlConnection.setDoOutput(true); int responseCode= urlConnection.getResponseCode(); System.out.println("Response code: " + responseCode + " Expected code: 200"); if (urlConnection.getResponseCode() == 200){ stat.addStatus("networkListenerDynamicConfigEnabled-afterReconf", stat.PASS); } else { stat.addStatus("networkListenerDynamicConfigEnabled-afterReconf", stat.FAIL); } } }catch(Exception ex){ stat.addStatus("networkListenerDynamicConfigEnabled-afterReconf", stat.FAIL); } stat.printSummary("web/networkListenerDynamicConfigEnabled-afterReconf"); } }
[ "swchan2@6f3ba3e3-413c-0410-a8aa-90bee3ab43b5" ]
swchan2@6f3ba3e3-413c-0410-a8aa-90bee3ab43b5
d1b1df38dde78ca47e302494a821ad1f6224df6b
ff3a8cf2361c29c25c10a770422afb985d4c8d35
/app/src/main/java/com/avanzados/lenguajes/basedatos/NewActivity.java
9763314054c68f8c86ff0f56a890dfd740d2e62a
[]
no_license
andresRA30/BaseDatosAndroid
e853eb592099cde5fe87bb4206b9f794f6161d47
50078576cb16da6e2e95ed34fc06ce856c749f10
refs/heads/master
2020-06-01T13:53:11.769309
2015-10-07T13:38:51
2015-10-07T13:38:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
457
java
package com.avanzados.lenguajes.basedatos; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; /** * Created by estudiante on 29/09/2015. */ public class NewActivity extends Activity{ protected void onCreate(Bundle bundle){ super.onCreate(bundle); setContentView(R.layout.nueva_activity); Toast.makeText(this, "Estamos en nueva Activity", Toast.LENGTH_SHORT).show(); } }
92b3c8c9d58143b720385a0e54689447460e8390
c47e88a4bc34d66c158215b4bbe6073d6c0c924b
/android/SnacksPop_buyer/app/src/main/java/com/snackspop/snackspopnew/Location/LocationUpdateService.java
43ec6ba33406a039193185db1ec7264de29e2b22
[]
no_license
vanguard1127/Snackspop_final
3ad5ffb016918fc2908e07808507c7706ce3919c
49cf1179afe92663909bd610e4087cec3e84313a
refs/heads/master
2022-11-13T03:03:57.354150
2020-07-09T15:17:25
2020-07-09T15:17:25
278,395,934
0
0
null
null
null
null
UTF-8
Java
false
false
13,630
java
package com.snackspop.snackspopnew.Location; import android.app.Service; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.NonNull; import android.util.Log; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.snackspop.snackspopnew.Utils.AppUtils; import java.util.ArrayList; public class LocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { Context mContext; protected static final String TAG = "LocationUpdateService"; /** * The desired interval for location updates. Inexact. Updates may be more or less frequent. */ public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 15000; /** * The fastest rate for active location updates. Exact. Updates will never be more frequent * than this value. */ public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2; /* the smallest displacement in METERS the user must move between location updates. */ private static final long MINIMUM_DISTANCE_COVER = 100; /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * Stores parameters for requests to the FusedLocationProviderApi. */ protected LocationRequest mLocationRequest; private ArrayList<LocationChange> locationChangeCallback = new ArrayList<LocationChange>(); private LocationBinder binder = new LocationBinder(); private Location currentLocation; SharedPreferences mPreferences; //-------------------Location Variables and methods public static final String LOCATION_LAT = "loc_lat"; public static final String LOCATION_LONG = "loc_long"; public static final String LOCATION_SERVICE_LAT = "loc_service_lat"; public static final String LOCATION_SERVICE_LONG = "loc_service_long"; public static String PREF_NAME = "PREF_LOCATION"; protected SharedPreferences sharedPreference; BroadcastReceiver mReceiver; IntentFilter intentFilter; private void initSharedPrefrence() { if (sharedPreference == null) sharedPreference = getApplication().getSharedPreferences(PREF_NAME, MODE_PRIVATE); } //------------------------------------------------------------ private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 10000; private static final float LOCATION_DISTANCE = 10f; private class LocationListener implements android.location.LocationListener { Location mLastLocation; public LocationListener(String provider) { Log.e(TAG, "LocationListener " + provider); mLastLocation = new Location(provider); } @Override public void onLocationChanged(Location location) { Log.e(TAG, "onLocationChanged: " + location); if( mLastLocation.getLatitude() != location.getLatitude() || mLastLocation.getLongitude() != location.getLongitude() ) { mLastLocation.set(location); saveCurrentLocation(location); } } @Override public void onProviderDisabled(String provider) { Log.e(TAG, "onProviderDisabled: " + provider); } @Override public void onProviderEnabled(String provider) { Log.e(TAG, "onProviderEnabled: " + provider); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.e(TAG, "onStatusChanged: " + provider); } } LocationListener[] mLocationListeners = new LocationListener[] { new LocationListener(LocationManager.GPS_PROVIDER), new LocationListener(LocationManager.NETWORK_PROVIDER) }; private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager"); if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } } @Override public void onCreate() { super.onCreate(); /* if (sharedPreference == null) initSharedPrefrence(); sharedPreference.edit().putString(LOCATION_LAT, "41.820135").apply(); sharedPreference.edit().putString(LOCATION_LONG, "123.440950").apply();*/ initializeLocationManager(); try { mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[1]); } catch (SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } try { mLocationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListeners[0]); } catch (SecurityException ex) { Log.i(TAG, "fail to request location update, ignore", ex); } catch (IllegalArgumentException ex) { Log.d(TAG, "gps provider does not exist " + ex.getMessage()); } toggleLocationSettingReceiver(this, true); mContext = this; Log.e(TAG, "onCreate()"); intentFilter = new IntentFilter( AppUtils.BROADCAST.BR_CLOSE_LOCATION_SERVICE); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(AppUtils.BROADCAST.BR_CLOSE_LOCATION_SERVICE)) { LocationUpdateService.this.stopSelf(); } } }; this.registerReceiver(mReceiver, intentFilter); } @Override public int onStartCommand(Intent intent, int flags, int startId) { buildGoogleApiClient(); return START_STICKY; } public class LocationBinder extends Binder { public LocationUpdateService getService() { return LocationUpdateService.this; } } @Override public IBinder onBind(Intent intent) { return binder; } protected synchronized void buildGoogleApiClient() { Log.i(TAG, "Building GoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); createLocationRequest(); mGoogleApiClient.connect(); } /** * Sets up the location request. Android has two location request settings: * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in * the AndroidManifest.xml. * <p/> * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update * interval (5 seconds), the Fused Location Provider API returns location updates that are * accurate to within a few feet. * <p/> * These settings are appropriate for mapping applications that show real-time location * updates. */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); // Sets the desired interval for active location updates. This interval is // inexact. You may not receive updates at all if no location sources are available, or // you may receive them slower than requested. You may also receive updates faster than // requested if other applications are requesting location at a faster interval. mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); // Sets the fastest rate for active location updates. This interval is exact, and your // application will never receive updates faster than this value. mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); //Set the minimum displacement between location updates in meters //the smallest displacement in meters the user must move between location updates. mLocationRequest.setSmallestDisplacement(MINIMUM_DISTANCE_COVER); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); } @Override public void onConnected(Bundle bundle) { if(mGoogleApiClient.isConnected()) startLocationUpdates(); } @Override public void onConnectionSuspended(int i) { // The connection to Google Play services was lost for some reason. We call connect() to // attempt to re-establish the connection. Log.i(TAG, "Connection suspended"); mGoogleApiClient.connect(); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode()); } public void startLocationUpdates() { // The final argument to {@code requestLocationUpdates()} is a LocationListener // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html). LocationServices.FusedLocationApi.requestLocationUpdates( mGoogleApiClient, mLocationRequest, this); } /** * Removes location updates from the FusedLocationApi. */ protected void stopLocationUpdates() { // It is a good practice to remove location requests when the activity is in a paused or // stopped state. Doing so helps battery performance and is especially // recommended in applications that request frequent location updates. // The final argument to {@code requestLocationUpdates()} is a LocationListener // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html). if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } public void removeLocationChangeListener(LocationChange locationListener) { this.locationChangeCallback.remove(locationListener); } @Override public void onLocationChanged(Location location) { Log.e(TAG, "===Current Location===>" + location.getLatitude() + " - " + location.getLongitude()); currentLocation = location; saveCurrentLocation(currentLocation); // App.instance().setCurrentLocation(location); for (LocationChange locationListener : locationChangeCallback) { locationListener.notifyLocationChange(location); } } public void saveCurrentLocation(Location location) { if (sharedPreference == null) initSharedPrefrence(); sharedPreference.edit().putString(LOCATION_SERVICE_LAT, String.valueOf(location.getLatitude())).apply(); sharedPreference.edit().putString(LOCATION_SERVICE_LONG, String.valueOf(location.getLongitude())).apply(); sendBroadcast(new Intent(AppUtils.BROADCAST.BR_UPDATE_LOCATION)); // StartAsyncUpdateLocation(); } @Override public void onTaskRemoved(Intent rootIntent) { super.onTaskRemoved(rootIntent); } @Override public void onDestroy() { stopLocationUpdates(); toggleLocationSettingReceiver(this, false); this.unregisterReceiver(mReceiver); if (mLocationManager != null) { for (int i = 0; i < mLocationListeners.length; i++) { try { mLocationManager.removeUpdates(mLocationListeners[i]); } catch (Exception ex) { Log.i(TAG, "fail to remove location listners, ignore", ex); } } } super.onDestroy(); } /* This will enable/disable Location Setting Broadcast receiver. It will enable broadcast receiver to listen for location Setting changes in device. */ private void toggleLocationSettingReceiver(Context context, boolean enable) { int flag = enable ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED; ComponentName receiver = new ComponentName(context, LocationSettingChangeReceiver.class); context.getPackageManager().setComponentEnabledSetting(receiver, flag, PackageManager.DONT_KILL_APP); } }
5ae5613ca84c85b86b534b246bedbb99fd9184a8
01cc71f0a70410fbfd4d3101973ff3ddf35f7f19
/src/main/java/life/majiang/community/community/dto/QuestionDTO.java
a0113357b1e8aa6118b5e4f1bc63371037fff954
[]
no_license
ericzhou2016/community
ecb75bb670844d0fff12a8850f8a546ef06817e5
d55e051d23c493a729d56c988d9c37c726c0aa9f
refs/heads/master
2022-06-24T11:31:07.836380
2020-06-10T03:16:34
2020-06-10T03:16:34
229,508,757
3
0
null
2022-06-17T02:59:44
2019-12-22T02:33:40
Java
UTF-8
Java
false
false
473
java
package life.majiang.community.community.dto; import life.majiang.community.community.model.User; import lombok.Data; @Data public class QuestionDTO { private Integer id; private String title; private String description; private String tag; private long gmtCreater; private long gmtModified; private Integer creator; private Integer viewCount; private Integer likeCount; private Integer commentCount; private User user; }
49272a67e34bade527570a583ab958f4affe035c
122e71e2adfb52afeb6f1a9e9e1b9a83634cd635
/team/wt.javalearn/java/src/main/day10/socket/SocketOptionTest.java
915864dbd0c49082cefb1768a67f7691143a8af8
[]
no_license
youboyTizzyT/Java-grammar1
b6985c532ba0c278fa6c069bfde260dddd386f9d
20b103c8f442eaffc62b2abb0eec7bfcf3a4fe6d
refs/heads/master
2022-12-29T18:55:23.571748
2021-06-24T03:36:16
2021-06-24T03:36:16
125,482,532
3
0
null
2022-12-10T03:06:22
2018-03-16T07:53:36
Java
UTF-8
Java
false
false
4,462
java
package day10.socket; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @author weicong * @date 2018/5/8 0008 */ public class SocketOptionTest { public static void main(String[] args) throws IOException { Socket socket = new Socket("127.0.0.1",30000); // Nagle算法:数据凑够了大小一起发,提高网络的利用率,避免1个自己的数据体无法占用满包的情况\ // 将Nagle算法关闭了,客户端每次发送消息,无轮数据包大小都将会发送出去 socket.setTcpNoDelay(true); // 看reuse包例子 socket.setReuseAddress(true); // 在默认情况下,当调用了close后,将立即返回,如果这时仍然有未被消息被送出去的数据包,那么这些数据包将会丢弃, // 如果将linger参数设为一个正整数n时(n的值最大是65535),在调用close方法后,将最多被阻塞n秒。在这n秒内, // 系统将尽量将未送出的数据包发送出去;如果超过了n秒,如果还有未发送的数据包,这些数据包将全部被丢弃; // 而close方法会立即返回。如果将linger设为0,和关闭SO_LINGER选项的作用是一样的。 socket.setSoLinger(true,60); // 如果将这个Socket选项打开,客户端Socket每隔端时间(大约两个小时)就会利用空闲连接向服务器发送一个数据包, // 这个数据包并没有其它的作用,只是为了检测一下服务器是否仍处于活动状态。如果服务器未响应这个数据包, // 在大约11分钟后,客户端Socket再发送一个数据包,如果在12分钟内,服务器还没响应,那么客户端Socket将关闭。 // 如果将Socket选项关闭,客户端Socket在服务器无效的情况下可能会长时间不会关闭。 socket.setKeepAlive(true); // 如果这个Socket选项打开,可以通过Socket类的sendUrgentData方法向服务器发送一个单字节的数据。 // 这个单字节数据并不经过输出缓冲区,而是立即发出。 // 如oobinline包例子 socket.setOOBInline(true); //100字节 socket.setSendBufferSize(100); //可以通过这个选项来设置读取数据超时。当输入流的read方法被阻塞时,如果设置timeout(timeout的单位是毫秒), // 那么系统在等待了timeout毫秒后会抛出一个InterruptedIOException。在抛出后,输入流并未关闭,你可以继续通过read方法读取数据。 // 如果将timeout设为0,就意味着read将会无限等待下去 socket.setSoTimeout(60); /* 默认情况下套接字使用 tcp/ip 协议。有些实现可能提供与 tcp/ip 具有不同性能特征的替代协议。 此方法允许应用程序在实现从可用协议中作出选择时表明它自己关于应该如何进行折衷的首选项。 性能首选项由三个整数描述,它们的值分别指示短连接时间、低延迟和高带宽的相对重要性。 这些整数的绝对值没有意义;为了选择协议,需要简单地比较它们的值,较大的值指示更强的首选项。 例如,如果应用程序相对于低延迟和高带宽更希望短连接时间,则其可以使用值 (1, 0, 0) 调用此方法。 如果应用程序相对于低延迟更希望高带宽,且相对于短连接时间更希望低延迟,则其可以使用值 (0, 1, 2) 调用此方法。 */ /* 参数 connectionTime: 表示用最少时间建立连接. 参数 latency: 表示最小延迟. 参数 bandwidth: 表示最高带宽. */ socket.setPerformancePreferences(1,2,3); /* * 低成本:发送成本低 * 高可靠性:保证把数据可靠的送到目的地 * 最高吞吐量:一次可以接收或者发送大批量的数据 * 最小延迟:传输数据的速度快,把数据快速送达目的地 * 低成本: 0x02 * 高可靠性: 0x04 * 最高吞吐量: 0x08 * 最小延迟: 0x10 */ socket.setTrafficClass(0x02|0x04); //backlog是等待队列的大小 int backlog=2; ServerSocket ss=new ServerSocket(8000,backlog); } }
e543867f9a32b01ac9c6175c35a4bd189c137c3c
dbc099539d83473b2c259f5f2b70504f485712d4
/PubMedBA/src/de/ur/jonbrem/pubmed/indexing/combined_way/ThirdFormula.java
ebc8dc5742eb722ded389da0341c226c88ec5c86
[]
no_license
JonBrem/PubMed-Bachelorarbeit
ca534779759448c22ceb1246d08d64c181e86f63
2b9573497f7b980e8c1258a95b93a56ed75df0d1
refs/heads/master
2021-01-04T02:37:42.347467
2015-09-30T12:05:30
2015-09-30T12:05:30
42,414,937
0
0
null
null
null
null
MacCentralEurope
Java
false
false
10,034
java
package de.ur.jonbrem.pubmed.indexing.combined_way; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import de.ur.jonbrem.pubmed.advanced_querying.DocScore; import de.ur.jonbrem.pubmed.solrconnection.SolrConnection; import util.Const; import util.FileUtil; public class ThirdFormula extends GeneralCombination { private static final boolean FIRST_RUN = false; public static void main(String[] args) { new ThirdFormula().run(new String[]{ "PRNP", "prions", "prion protein", "g1-dependent" }, "PRNP"); new ThirdFormula().run(new String[]{ "Mad Cow Disease", "Bovine Spongiform Encephalopathy", "BSE" }, "BSE"); new ThirdFormula().run(new String[]{ "IDE", "IDE Gene", "Insulin Degrading Enzyme", "Insulin Protease", "Insulinase" }, "IDE"); new ThirdFormula().run(new String[]{ "Alzheimer's Disease", "Alzheimer Sclerosis", "Senile Dementia", "Presenila Dementia" }, "Alzheimer"); new ThirdFormula().run(new String[]{ "DDVit1", "UEV-2", "UBE2V2", "ubiquitin-conjugating enzyme", "EDPF-1" }, "MMS2"); new ThirdFormula().run(new String[]{ "Neoplasm", "Tumor", "Cancer" }, "Cancer"); new ThirdFormula().run(new String[]{ "APC", "adenomatous polyposis coli" }, "APC"); new ThirdFormula().run(new String[]{ "Colon Cancer", "Colon Neoplasm" }, "ColonCancer"); new ThirdFormula().run(new String[]{ "Nurr-77", "Nur77", "NGFI-B", "Nerve Growth Factor-inducible B-Protein", "Orphan Nuclear Receptor HMR", "Early Response Protein NAK1" }, "Nurr77"); new ThirdFormula().run(new String[]{ "Parkinsonís Disease", "Paralysis Agitans", "Idiopathic Parkinson Disease" }, "Parkinson"); new ThirdFormula().run(new String[]{ "Cathepsin D gene", "CTSD" }, "CTSD"); new ThirdFormula().run(new String[]{ "apolipoprotein E", "Apo E Isoproteins", "Aspartic Acid Endopeptidases", "ApoE" }, "ApoE"); // + Alzheimer new ThirdFormula().run(new String[]{ "TGF-beta1", "Transforming growth factor-beta1" }, "TGFb1"); new ThirdFormula().run(new String[]{ "CAA", "Cerebral Amyloid Angiopathy" }, "CAA"); new ThirdFormula().run(new String[]{ "NM23", "nucleoside diphosphate kinase", "Non-Metastatic Cells 1 Protein", "Granzyme A-activated DNase" }, "NM23"); // + cancer new ThirdFormula().run(new String[]{ "BARD1", "Ubiquitin-Protein Ligases" }, "BARD1"); new ThirdFormula().run(new String[]{ "BRCA1", "BRCA1 regulations" }, "BRCA1"); // + APC new ThirdFormula().run(new String[]{ "actin", "actin assembly", "Isoactin" }, "actin"); new ThirdFormula().run(new String[]{ "COP2"," Coat Protein Complex II" }, "COP2"); new ThirdFormula().run(new String[]{ "CFTR", "Cystic Fibrosis Transmembrane Conductance Regulator" }, "CFTR"); new ThirdFormula().run(new String[]{ "endoplasmatic reticulum" }, "endoplasmaticreticulum"); new ThirdFormula().run(new String[]{ "P53","phosphoprotein p53", "tumor suppressor gene" }, "P53"); new ThirdFormula().run(new String[]{ "apoptosis", "programmed cell death", "intrinsic pathway apoptosis" }, "apoptosis"); new ThirdFormula().run(new String[]{ "L1", "L2", "NILE Glycoprotein", "L1CAM", "CALL Protein" }, "L1L2"); new ThirdFormula().run(new String[]{ "Humane Papillomavirus type 11", "HPV11" }, "HPV11"); new ThirdFormula().run(new String[]{ "HNF4", "Hepatocyte Nuclear Factor 4", "HNF4 Transcription Factor" }, "HNF4"); new ThirdFormula().run(new String[]{ "COUP-TF I", "COUP-TF1 Protein", "Chicken Ovalbumin Upstream Promoter-Transcription Factor I", "Nuclear Receptor Subfamily 2 Group F Member 1" }, "COUP_TFI"); new ThirdFormula().run(new String[]{ "liver" }, "liver"); new ThirdFormula().run(new String[]{ "Huntingtin", "Huntingtin mutations", "HAPP" }, "Huntingtin"); new ThirdFormula().run(new String[]{ "Huntingtonís Disease", "Huntington Chorea", "Chronic Progressive Hereditary Chorea" }, "Huntington"); new ThirdFormula().run(new String[]{ "Sonic hedgehog", "Sonic hedgehog mutations", "Vertebrate Hedgehog Protein" }, "sonichedgehog"); new ThirdFormula().run(new String[]{ "developmental disorders" }, "devdisorder"); // another nm23 new ThirdFormula().run(new String[]{ "tracheal development" }, "tracheal"); new ThirdFormula().run(new String[]{ "pescadillo", "Pes" }, "Pes"); new ThirdFormula().run(new String[]{ "orexin receptor", "HCRT receptor" }, "hypocretinreceptor2"); new ThirdFormula().run(new String[]{ "narcolepsy", "Paroxysmal Sleep", "Gelineaus Syndrome" }, "narcolepsy"); new ThirdFormula().run(new String[]{ "presenilin-1 gene", "psen1" }, "psen1"); // + alzheimer new ThirdFormula().run(new String[]{ "FHM1", "familial hemiplegic migraine type 1", "Migraine with Auras" }, "FHM1"); new ThirdFormula().run(new String[]{ "hippocampal neurons" }, "hippneur"); } private Map<String, Double> oldScores; private Map<String, List<Double>> citationScores; private double totalCitations; private FileUtil fileUtil; public ThirdFormula() { super(); scores = new HashMap<String, Double>(); citationScores = new HashMap<>(); oldScores = new HashMap<String, Double>(); new HashSet<>(); this.totalCitations = 0d; this.fieldName = "rank2_for_"; this.fields = new ArrayList<>(); this.fileUtil = new FileUtil(); fields.add("pubmed_language_worddelimiter_rank_lm_4_abstract"); fields.add("pubmed_language_stemming_rank_lm_4_title"); } public void run(String[] searchTerms, String termId) { Const.log(Const.LEVEL_INFO, "Starting with: " + termId); this.solr = new SolrConnection(); solr.openConnection(); if(FIRST_RUN) { findDocsInD1(termId); Const.log(Const.LEVEL_INFO, "Found docs in d1."); storeScores(termId); Const.log(Const.LEVEL_INFO, "Stored scores."); } else { findDocsInD1(termId); Const.log(Const.LEVEL_INFO, "Found docs in d1."); calculateScores(); Const.log(Const.LEVEL_INFO, "Calculated scores."); storeScores(termId); Const.log(Const.LEVEL_INFO, "Stored scores."); solr.closeConnection(); Const.log(Const.LEVEL_INFO, "Done."); } } private void storeScores(String termId) { if(FIRST_RUN) { fileUtil.closeWriter("files/combined_approach_3_scores/" + termId + ".csv"); } else { SolrQuery q = new SolrQuery(); List<String> pmids = new ArrayList<>(scores.keySet()); Collections.sort(pmids); FileUtil fileUtil = new FileUtil(); for(int i = 0; i < pmids.size(); i++) { fileUtil.writeLine("files/combined_approach_3_scores/" + termId + ".csv", pmids.get(i) + "\t" + scores.get(pmids.get(i))); } fileUtil.closeWriter("files/combined_approach_3_scores/" + termId + ".csv"); } } private void findDocsInD1(String rankName) { SolrQuery q = new SolrQuery(); if(FIRST_RUN) { q.set("q", "rank1_for_" + rankName + ":*"); q.set("fl", "pmid,rank1_for_" + rankName); } else { q.set("q", "rank3_for_" + rankName + ":*"); q.set("fl", "pmid,rank3_for_" + rankName); } int start = 0, rows = 2000; q.set("start", start); q.set("rows", rows); while(true) { QueryResponse response = solr.query(q); SolrDocumentList results; if(response == null || (results = response.getResults()) == null || results.size() == 0) break; for(SolrDocument result : results) { if(FIRST_RUN) { forEveryDocInD1((String) result.get("pmid"), (Double) result.get("rank1_for_" + rankName), rankName); } else { forEveryDocInD1((String) result.get("pmid"), (Double) result.get("rank3_for_" + rankName), rankName); } } if(results.size() < rows) { break; } start += rows; q.set("start", start); } } private void forEveryDocInD1(String pmid, double score, String termId) { if(FIRST_RUN) { fileUtil.writeLine("files/combined_approach_3_scores/" + termId + ".csv", pmid + "\t" + score); } else { oldScores.put(pmid, score); increaseCountersForDocsCitedBy(pmid, score); } } private void calculateScores() { double total = 0; for(String pmid : oldScores.keySet()) { if(!citationScores.containsKey(pmid)) { citationScores.put(pmid, new ArrayList<>()); } } for(String pmid : citationScores.keySet()) { double score = 0; if(oldScores.containsKey(pmid)) { score += oldScores.get(pmid) / 2; } score += getTotal(citationScores.get(pmid)); scores.put(pmid, score); total += score; } double normalize = 1 / total; for(String pmid : scores.keySet()) { scores.put(pmid, scores.get(pmid) * normalize); } } private double getTotal(List<Double> scores) { double total = 0; for(double d : scores) total += d; return total; } private void increaseCountersForDocsCitedBy(String pmid, double score) { SolrQuery q = new SolrQuery(); q.set("q", "cited_by:" + pmid); int start = 0; int rows = 2000; q.set("fl", "pmid"); q.set("start", start); q.set("rows", rows); while(true) { QueryResponse response = solr.query(q); SolrDocumentList results; if(response == null || (results = response.getResults()) == null) break; for(SolrDocument doc : results) { addValuesForDoc(String.valueOf(doc.get("pmid")), score); } if(results.size() < rows) break; start += rows; q.set("start", start); } } private void addValuesForDoc(String pmid, double score) { if(citationScores.containsKey(pmid)) { citationScores.get(pmid).add(score); } else { List<Double> scores = new ArrayList<>(); scores.add(score); citationScores.put(pmid, scores); } } }
4a0c7a047ff23d92b43d2660c8a7c132afad3751
9208ba403c8902b1374444a895ef2438a029ed5c
/sources/io/reactivex/subjects/AsyncSubject.java
a5aa6e773a56f398e695e242ddfec6592f2dedc5
[]
no_license
MewX/kantv-decompiled-v3.1.2
3e68b7046cebd8810e4f852601b1ee6a60d050a8
d70dfaedf66cdde267d99ad22d0089505a355aa1
refs/heads/main
2023-02-27T05:32:32.517948
2021-02-02T13:38:05
2021-02-02T13:44:31
335,299,807
0
0
null
null
null
null
UTF-8
Java
false
false
8,095
java
package io.reactivex.subjects; import io.reactivex.Observer; import io.reactivex.annotations.CheckReturnValue; import io.reactivex.annotations.NonNull; import io.reactivex.annotations.Nullable; import io.reactivex.disposables.Disposable; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.observers.DeferredScalarDisposable; import io.reactivex.plugins.RxJavaPlugins; import java.util.Arrays; import java.util.concurrent.atomic.AtomicReference; public final class AsyncSubject<T> extends Subject<T> { static final AsyncDisposable[] EMPTY = new AsyncDisposable[0]; static final AsyncDisposable[] TERMINATED = new AsyncDisposable[0]; Throwable error; final AtomicReference<AsyncDisposable<T>[]> subscribers = new AtomicReference<>(EMPTY); T value; static final class AsyncDisposable<T> extends DeferredScalarDisposable<T> { private static final long serialVersionUID = 5629876084736248016L; final AsyncSubject<T> parent; AsyncDisposable(Observer<? super T> observer, AsyncSubject<T> asyncSubject) { super(observer); this.parent = asyncSubject; } public void dispose() { if (super.tryDispose()) { this.parent.remove(this); } } /* access modifiers changed from: 0000 */ public void onComplete() { if (!isDisposed()) { this.downstream.onComplete(); } } /* access modifiers changed from: 0000 */ public void onError(Throwable th) { if (isDisposed()) { RxJavaPlugins.onError(th); } else { this.downstream.onError(th); } } } @CheckReturnValue @NonNull public static <T> AsyncSubject<T> create() { return new AsyncSubject<>(); } AsyncSubject() { } public void onSubscribe(Disposable disposable) { if (this.subscribers.get() == TERMINATED) { disposable.dispose(); } } public void onNext(T t) { ObjectHelper.requireNonNull(t, "onNext called with null. Null values are generally not allowed in 2.x operators and sources."); if (this.subscribers.get() != TERMINATED) { this.value = t; } } public void onError(Throwable th) { ObjectHelper.requireNonNull(th, "onError called with null. Null values are generally not allowed in 2.x operators and sources."); Object obj = this.subscribers.get(); Object obj2 = TERMINATED; if (obj == obj2) { RxJavaPlugins.onError(th); return; } this.value = null; this.error = th; for (AsyncDisposable onError : (AsyncDisposable[]) this.subscribers.getAndSet(obj2)) { onError.onError(th); } } public void onComplete() { Object obj = this.subscribers.get(); Object obj2 = TERMINATED; if (obj != obj2) { T t = this.value; AsyncDisposable[] asyncDisposableArr = (AsyncDisposable[]) this.subscribers.getAndSet(obj2); int i = 0; if (t == null) { int length = asyncDisposableArr.length; while (i < length) { asyncDisposableArr[i].onComplete(); i++; } } else { int length2 = asyncDisposableArr.length; while (i < length2) { asyncDisposableArr[i].complete(t); i++; } } } } public boolean hasObservers() { return ((AsyncDisposable[]) this.subscribers.get()).length != 0; } public boolean hasThrowable() { return this.subscribers.get() == TERMINATED && this.error != null; } public boolean hasComplete() { return this.subscribers.get() == TERMINATED && this.error == null; } public Throwable getThrowable() { if (this.subscribers.get() == TERMINATED) { return this.error; } return null; } /* access modifiers changed from: protected */ public void subscribeActual(Observer<? super T> observer) { AsyncDisposable asyncDisposable = new AsyncDisposable(observer, this); observer.onSubscribe(asyncDisposable); if (!add(asyncDisposable)) { Throwable th = this.error; if (th != null) { observer.onError(th); return; } T t = this.value; if (t != null) { asyncDisposable.complete(t); } else { asyncDisposable.onComplete(); } } else if (asyncDisposable.isDisposed()) { remove(asyncDisposable); } } /* access modifiers changed from: 0000 */ public boolean add(AsyncDisposable<T> asyncDisposable) { AsyncDisposable[] asyncDisposableArr; AsyncDisposable[] asyncDisposableArr2; do { asyncDisposableArr = (AsyncDisposable[]) this.subscribers.get(); if (asyncDisposableArr == TERMINATED) { return false; } int length = asyncDisposableArr.length; asyncDisposableArr2 = new AsyncDisposable[(length + 1)]; System.arraycopy(asyncDisposableArr, 0, asyncDisposableArr2, 0, length); asyncDisposableArr2[length] = asyncDisposable; } while (!this.subscribers.compareAndSet(asyncDisposableArr, asyncDisposableArr2)); return true; } /* access modifiers changed from: 0000 */ public void remove(AsyncDisposable<T> asyncDisposable) { AsyncDisposable<T>[] asyncDisposableArr; AsyncDisposable[] asyncDisposableArr2; do { asyncDisposableArr = (AsyncDisposable[]) this.subscribers.get(); int length = asyncDisposableArr.length; if (length != 0) { int i = -1; int i2 = 0; while (true) { if (i2 >= length) { break; } else if (asyncDisposableArr[i2] == asyncDisposable) { i = i2; break; } else { i2++; } } if (i >= 0) { if (length == 1) { asyncDisposableArr2 = EMPTY; } else { AsyncDisposable[] asyncDisposableArr3 = new AsyncDisposable[(length - 1)]; System.arraycopy(asyncDisposableArr, 0, asyncDisposableArr3, 0, i); System.arraycopy(asyncDisposableArr, i + 1, asyncDisposableArr3, i, (length - i) - 1); asyncDisposableArr2 = asyncDisposableArr3; } } else { return; } } else { return; } } while (!this.subscribers.compareAndSet(asyncDisposableArr, asyncDisposableArr2)); } public boolean hasValue() { return this.subscribers.get() == TERMINATED && this.value != null; } @Nullable public T getValue() { if (this.subscribers.get() == TERMINATED) { return this.value; } return null; } @Deprecated public Object[] getValues() { Object value2 = getValue(); if (value2 == null) { return new Object[0]; } return new Object[]{value2}; } @Deprecated public T[] getValues(T[] tArr) { T value2 = getValue(); if (value2 == null) { if (tArr.length != 0) { tArr[0] = null; } return tArr; } if (tArr.length == 0) { tArr = Arrays.copyOf(tArr, 1); } tArr[0] = value2; if (tArr.length != 1) { tArr[1] = null; } return tArr; } }
453023ce6d0f536411cd3dcde336b070cf03f70e
c885ef92397be9d54b87741f01557f61d3f794f3
/results/Codec-13/org.apache.commons.codec.binary.StringUtils/BBC-F0-opt-80/tests/5/org/apache/commons/codec/binary/StringUtils_ESTest_scaffolding.java
4a534aee258d14317733a770d037cc59e789507d
[ "CC-BY-4.0", "MIT" ]
permissive
pderakhshanfar/EMSE-BBC-experiment
f60ac5f7664dd9a85f755a00a57ec12c7551e8c6
fea1a92c2e7ba7080b8529e2052259c9b697bbda
refs/heads/main
2022-11-25T00:39:58.983828
2022-04-12T16:04:26
2022-04-12T16:04:26
309,335,889
0
1
null
2021-11-05T11:18:43
2020-11-02T10:30:38
null
UTF-8
Java
false
false
3,309
java
/** * Scaffolding file used to store all the setups needed to run * tests automatically generated by EvoSuite * Wed Oct 13 19:16:39 GMT 2021 */ package org.apache.commons.codec.binary; import org.evosuite.runtime.annotation.EvoSuiteClassExclude; import org.junit.BeforeClass; import org.junit.Before; import org.junit.After; import org.evosuite.runtime.sandbox.Sandbox; import org.evosuite.runtime.sandbox.Sandbox.SandboxMode; @EvoSuiteClassExclude public class StringUtils_ESTest_scaffolding { @org.junit.Rule public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule(); private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000); @BeforeClass public static void initEvoSuiteFramework() { org.evosuite.runtime.RuntimeSettings.className = "org.apache.commons.codec.binary.StringUtils"; org.evosuite.runtime.GuiSupport.initialize(); org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100; org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000; org.evosuite.runtime.RuntimeSettings.mockSystemIn = true; org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED; org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT(); org.evosuite.runtime.classhandling.JDKClassResetter.init(); setSystemProperties(); initializeClasses(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); } @Before public void initTestCase(){ threadStopper.storeCurrentThreads(); threadStopper.startRecordingTime(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler(); org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode(); org.evosuite.runtime.GuiSupport.setHeadless(); org.evosuite.runtime.Runtime.getInstance().resetRuntime(); org.evosuite.runtime.agent.InstrumentingAgent.activate(); } @After public void doneWithTestCase(){ threadStopper.killAndJoinClientThreads(); org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks(); org.evosuite.runtime.classhandling.JDKClassResetter.reset(); resetClasses(); org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode(); org.evosuite.runtime.agent.InstrumentingAgent.deactivate(); org.evosuite.runtime.GuiSupport.restoreHeadlessMode(); } public static void setSystemProperties() { /*No java.lang.System property to set*/ } private static void initializeClasses() { org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(StringUtils_ESTest_scaffolding.class.getClassLoader() , "org.apache.commons.codec.binary.StringUtils", "org.apache.commons.codec.Charsets" ); } private static void resetClasses() { org.evosuite.runtime.classhandling.ClassResetter.getInstance().setClassLoader(StringUtils_ESTest_scaffolding.class.getClassLoader()); org.evosuite.runtime.classhandling.ClassStateSupport.resetClasses( "org.apache.commons.codec.binary.StringUtils", "org.apache.commons.codec.Charsets" ); } }
c3dfbe79d92ad7444423eeee8d526ae4002355c0
fd3a63458b10935e9322879b1a1c05d7561a8d9b
/app/src/main/java/com/priteshjain/popularmovies/presenters/IMoviesListingView.java
08a29f8c69989234f1e92da8fc6bcdb509686f9e
[]
no_license
PriteshJain/PopularMovies
250fecfec25367f9e95709758acaa944c81498c5
0b93b1e6aa00f1054067f4569fc7f1a11e82db24
refs/heads/master
2021-01-16T21:46:38.432085
2016-07-21T13:14:19
2016-07-21T13:14:19
62,074,519
1
0
null
2016-07-19T19:40:21
2016-06-27T17:25:20
Java
UTF-8
Java
false
false
367
java
package com.priteshjain.popularmovies.presenters; import com.priteshjain.popularmovies.models.Movie; import java.util.List; public interface IMoviesListingView { void listMovies(List<Movie> movies, String currentPage); void onMovieClicked(Movie movie); void loadingStarted(); void loadingFailed(String errorMessage); void loadingComplete(); }
d66786e6100bf59dd911ea341bd9603c8136ef62
b616680ab58cb7552ffc621bb95946f490eefa33
/NawadnianieWindows/src/MainThread.java
0c57c5402e89f9a3b5bd81fd2b0a5c4d497eb16b
[]
no_license
KatangaDev/nawadnianie
d41c2db8f6d580161ad4b4c3ef157180ec197363
994c374540f3d7f4ea456f0573be7b8d879b9b12
refs/heads/master
2021-04-13T19:14:56.982355
2020-03-22T11:54:59
2020-03-22T11:54:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
575
java
public class MainThread { public static int a=0, b=50; public static NetworkManager networkThread; public static GuiThread gui; //public static GuiThread guiThread; public static void main(String[] args) { // TODO Auto-generated method stub networkThread = new NetworkManager(); gui = new GuiThread(); Thread guiThread = new Thread(gui); guiThread.start(); //guiThread System.out.println("poszlo"); while(a<b) { if(!networkThread.isAlive()) { a++; networkThread = new NetworkManager(); networkThread.start(); } } } }
36fe3f70dabda83317f9ab9d507beac453374281
da2bdd5e4e784725622b3af07958e8b86ee14c07
/post-service/src/main/java/com/trilogyed/post/viewmodel/PostViewModel.java
ca6c1411c3e838207aa1fd47afb4ff0c29da844c
[]
no_license
raghir01/stwitter_system
5f83d104beff3c82c07f12450ff509c31ee92b73
735f041cba1edb48061e961c66aaa08fcb5e5c74
refs/heads/master
2022-12-01T16:53:00.145867
2019-09-06T02:05:13
2019-09-06T02:05:13
206,692,178
0
0
null
2022-11-16T12:23:24
2019-09-06T01:58:56
Java
UTF-8
Java
false
false
1,649
java
package com.trilogyed.post.viewmodel; import java.time.LocalDate; import java.util.Objects; public class PostViewModel { private int postId; private LocalDate postDate; private String posterName; private String post; public int getPostId() { return postId; } public void setPostId(int postId) { this.postId = postId; } public LocalDate getPostDate() { return postDate; } public void setPostDate(LocalDate postDate) { this.postDate = postDate; } public String getPosterName() { return posterName; } public void setPosterName(String posterName) { this.posterName = posterName; } public String getPost() { return post; } public void setPost(String post) { this.post = post; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PostViewModel that = (PostViewModel) o; return postId == that.postId && Objects.equals(postDate, that.postDate) && Objects.equals(posterName, that.posterName) && Objects.equals(post, that.post); } @Override public int hashCode() { return Objects.hash(postId, postDate, posterName, post); } @Override public String toString() { return "PostViewModel{" + "postId=" + postId + ", postDate=" + postDate + ", posterName='" + posterName + '\'' + ", post='" + post + '\'' + '}'; } }
6df142c938820d24a0e955e546eb4da889a68130
6c688653c87ae43218f2d0a7a2570b7551d58c47
/src/main/java/com/cn/common/CrossDomainFilter.java
c618b36b441c484887624eec861eb2bed8f29fb0
[]
no_license
songzhili111111/all-union-activity
c4842427645e1dc6292e7a2f9fd79f4090ac4661
a4c34d774ff6c2d6859d8384c1f4368af9187e3d
refs/heads/master
2020-04-06T07:19:16.180944
2016-09-01T04:51:07
2016-09-01T04:51:07
63,564,910
0
0
null
null
null
null
UTF-8
Java
false
false
3,336
java
package com.cn.common; import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 跨域支持过滤器,在HTTP响应中增加一些头信息 * @author songzhili * 2016年7月1日上午9:04:29 */ public class CrossDomainFilter implements Filter { private String allowOrigin; private String allowMethods; private String allowCredentials; private String allowHeaders; private String exposeHeaders; private String maxAge; @Override public void init(FilterConfig filterConfig) throws ServletException { allowOrigin = filterConfig.getInitParameter("allowOrigin"); allowMethods = filterConfig.getInitParameter("allowMethods"); allowCredentials = filterConfig.getInitParameter("allowCredentials"); allowHeaders = filterConfig.getInitParameter("allowHeaders"); exposeHeaders = filterConfig.getInitParameter("exposeHeaders"); maxAge = filterConfig.getInitParameter("maxAge"); } /** * 跨域支持配置 * @param servletRequest * @param servletResponse * @param filterChain * @throws IOException * @throws ServletException */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)servletRequest; request.setCharacterEncoding("UTF-8"); /* * ()); * System.out.println("------------------------------->"+request.getHeader * ("TestKey")); */ HttpServletResponse response = (HttpServletResponse)servletResponse; if(!Utils.isEmpty(allowOrigin)){ List<String> allowOriginList = Arrays .asList(allowOrigin.split(",")); if (allowOriginList != null && !allowOriginList.isEmpty()) { String currentOrigin = request.getHeader("Origin"); if (allowOriginList.contains(currentOrigin)) { response.setHeader("Access-Control-Allow-Origin", currentOrigin); // 允许来自currentOrigin域的客户端访问 } } } if(!Utils.isEmpty(allowMethods)){ response.setHeader("Access-Control-Allow-Methods", allowMethods); // 允许访问allowMethods请求 } if(!Utils.isEmpty(allowCredentials)){ response.setHeader("Access-Control-Allow-Credentials", allowCredentials); } if(!Utils.isEmpty(allowHeaders)){ response.setHeader("Access-Control-Allow-Headers", allowHeaders); } if(!Utils.isEmpty(exposeHeaders)){ response.setHeader("Access-Control-Expose-Headers", exposeHeaders); } if(!Utils.isEmpty(maxAge)){ response.setHeader("Access-Control-Max-Age", maxAge); // 请求的结果将缓存maxAge秒 } response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS"); response.setHeader("Access-Control-Allow-Headers", "Content-Type,TestKey,x-requested-with"); filterChain.doFilter(request, response); } @Override public void destroy() { } }
b18b223954225db850724c4fa0753b6111408290
e62b2321dd23bbf98ae83cbb17f6e8343be70ea1
/mbennett20-U3-ParkingApp/src/com/company/first/Garage.java
917a1919a402a98217739fb8c99f9109209504a7
[]
no_license
michaelmunkwitzbennett/mbennett20-U3-ParkingApp
f973ae77826e1856ebdbfa855a77ae08584923b2
2f5909f8f4da1e6b80f583d92422435bd7f7ef44
refs/heads/master
2020-09-30T06:16:32.703518
2019-12-10T22:19:32
2019-12-10T22:19:32
227,225,842
0
0
null
null
null
null
UTF-8
Java
false
false
2,209
java
package com.company.first; import java.text.DecimalFormat; import java.util.List; /** * This class represents the real world object of the garage */ public class Garage { public int checkInCount; public double moneyFromCheckIns; public int lostTicketCount; public double moneyFromLostTickets; public int specialTicketCount; public double moneyFromSpecialTickets; public double totalMoney; /** * constructor creates the garage object, * the purpose of the garage class is to process and display the garage's monetary transactions * this constructor determines the money from checkins, lost tickets, and the total money generated * @param listOfTickets the list of tickets in the garage */ public Garage(List<Ticket> listOfTickets) { for (Ticket t: listOfTickets) { if (t.isLost()) { lostTicketCount++; moneyFromLostTickets += t.getBill(); } else if (t.isSpecial()) { specialTicketCount++; moneyFromSpecialTickets += t.getBill(); } else { checkInCount++; moneyFromCheckIns += t.getBill(); } } totalMoney = moneyFromCheckIns + moneyFromLostTickets + moneyFromSpecialTickets; } /** * This closes the garage and processes the tickets */ public void closeGarage() { DecimalFormat df = new DecimalFormat("$0.00"); System.out.println("Best Value Parking Garage\n"); System.out.println("========================="); System.out.println("Activity to Date"); System.out.println(); System.out.println(df.format(moneyFromCheckIns) + " was collected from " + checkInCount + " Check Ins"); System.out.println(df.format(moneyFromLostTickets) + " was collected from " + lostTicketCount + " Lost Tickets"); System.out.println(df.format(moneyFromSpecialTickets) + " was collected from " + specialTicketCount + " Special Tickets"); System.out.println(); System.out.println(df.format(totalMoney) + " was collected overall"); } }
3498f0e75155c7c600cfbf6c38071fbbfb567124
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/6/6_26b62dcbd4fed716da3399e739b2bb7c9dd02bc4/FindReplaceDocumentAdapter/6_26b62dcbd4fed716da3399e739b2bb7c9dd02bc4_FindReplaceDocumentAdapter_s.java
b49e1434cf25873c9faf8bcbd6339f07c994347a
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
11,133
java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.text; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** * Adapts {@link org.eclipse.jface.text.IDocument} for doing search and * replace operations. * * @since 3.0 */ public class FindReplaceDocumentAdapter implements CharSequence { private static class FindReplaceOperationCode { } // Shortcuts to findReplace operation codes private static final FindReplaceOperationCode FIND_FIRST= new FindReplaceOperationCode(); private static final FindReplaceOperationCode FIND_NEXT= new FindReplaceOperationCode(); private static final FindReplaceOperationCode REPLACE= new FindReplaceOperationCode(); private static final FindReplaceOperationCode REPLACE_FIND_NEXT= new FindReplaceOperationCode(); /** * The adapted document. */ private IDocument fDocument; /** * State for findReplace. */ private FindReplaceOperationCode fFindReplaceState= null; /** * The matcher used in findReplace. */ private Matcher fFindReplaceMatcher; /** * The match offset from the last findReplace call. */ private int fFindReplaceMatchOffset; /** * Constructs a new find replace document adapter. * * @param document the adapted document */ public FindReplaceDocumentAdapter(IDocument document) { Assert.isNotNull(document); fDocument= document; } /** * Returns the location of a given string in this adapter's document based on a set of search criteria. * * @param startOffset document offset at which search starts * @param findString the string to find * @param forwardSearch the search direction * @param caseSensitive indicates whether lower and upper case should be distinguished * @param wholeWord indicates whether the findString should be limited by white spaces as * defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>. * @param regExSearch if <code>true</code> findString represents a regular expression * Must not be used in combination with <code>wholeWord</code>. * @return the find or replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws PatternSyntaxException if a regular expression has invalid syntax */ public IRegion find(int startOffset, String findString, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { Assert.isTrue(!(regExSearch && wholeWord)); // Adjust offset to special meaning of -1 if (startOffset == -1 && forwardSearch) startOffset= 0; if (startOffset == -1 && !forwardSearch) startOffset= length() - 1; return findReplace(FIND_FIRST, startOffset, findString, null, forwardSearch, caseSensitive, wholeWord, regExSearch); } /** * Stateful findReplace executes a FIND, REPLACE, REPLACE_FIND or FIND_FIRST operation. * In case of REPLACE and REPLACE_FIND it sends a <code>DocumentEvent</code> to all * registered <code>IDocumentListener</code>. * * @param startOffset document offset at which search starts * this value is only used in the FIND_FIRST operation and otherwise ignored * @param findString the string to find * this value is only used in the FIND_FIRST operation and otherwise ignored * @param replaceText the string to replace the current match * this value is only used in the REPLACE and REPLACE_FIND operations and otherwise ignored * @param forwardSearch the search direction * @param caseSensitive indicates whether lower and upper case should be distinguished * @param wholeWord indicates whether the findString should be limited by white spaces as * defined by Character.isWhiteSpace. Must not be used in combination with <code>regExSearch</code>. * @param regExSearch if <code>true</code> this operation represents a regular expression * Must not be used in combination with <code>wholeWord</code>. * @param operationCode specifies what kind of operation is executed * @return the find or replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation * @throws PatternSyntaxException if a regular expression has invalid syntax */ private IRegion findReplace(FindReplaceOperationCode operationCode, int startOffset, String findString, String replaceText, boolean forwardSearch, boolean caseSensitive, boolean wholeWord, boolean regExSearch) throws BadLocationException { // Validate option combinations Assert.isTrue(!(regExSearch && wholeWord)); // Validate state if ((operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) && (fFindReplaceState != FIND_FIRST && fFindReplaceState != FIND_NEXT)) throw new IllegalStateException("illegal findReplace state: cannot replace without preceding find"); //$NON-NLS-1$ if (operationCode == FIND_FIRST) { // Reset if (findString == null || findString.length() == 0) return null; // Validate start offset if (startOffset < 0 || startOffset >= length()) throw new BadLocationException(); int patternFlags= 0; if (regExSearch) patternFlags |= Pattern.MULTILINE; if (!caseSensitive) patternFlags |= Pattern.CASE_INSENSITIVE; if (wholeWord) findString= "\\b" + findString + "\\b"; //$NON-NLS-1$ //$NON-NLS-2$ if (!regExSearch && !wholeWord) findString= asRegPattern(findString); fFindReplaceMatchOffset= startOffset; if (fFindReplaceMatcher != null && fFindReplaceMatcher.pattern().pattern().equals(findString) && fFindReplaceMatcher.pattern().flags() == patternFlags) { /* * Commented out for optimazation: * The call is not needed since FIND_FIRST uses find(int) which resets the matcher */ // fFindReplaceMatcher.reset(); } else { Pattern pattern= Pattern.compile(findString, patternFlags); fFindReplaceMatcher= pattern.matcher(this); } } // Set state fFindReplaceState= operationCode; if (operationCode == REPLACE || operationCode == REPLACE_FIND_NEXT) { if (regExSearch) { Pattern pattern= fFindReplaceMatcher.pattern(); Matcher replaceTextMatcher= pattern.matcher(fFindReplaceMatcher.group()); try { replaceText= replaceTextMatcher.replaceFirst(replaceText); } catch (IndexOutOfBoundsException ex) { throw new PatternSyntaxException(ex.getLocalizedMessage(), replaceText, -1); } } int offset= fFindReplaceMatcher.start(); fDocument.replace(offset, fFindReplaceMatcher.group().length(), replaceText); if (operationCode == REPLACE) { return new Region(offset, replaceText.length()); } } if (operationCode != REPLACE) { if (forwardSearch) { boolean found= false; if (operationCode == FIND_FIRST) found= fFindReplaceMatcher.find(startOffset); else found= fFindReplaceMatcher.find(); fFindReplaceState= operationCode; if (found && fFindReplaceMatcher.group().length() > 0) { return new Region(fFindReplaceMatcher.start(), fFindReplaceMatcher.group().length()); } else { return null; } } else { // backward search boolean found= fFindReplaceMatcher.find(0); int index= -1; int length= -1; while (found && fFindReplaceMatcher.start() <= fFindReplaceMatchOffset) { index= fFindReplaceMatcher.start(); length= fFindReplaceMatcher.group().length(); found= fFindReplaceMatcher.find(index + 1); } fFindReplaceMatchOffset= index; if (index > -1) { // must set matcher to correct position fFindReplaceMatcher.find(index); return new Region(index, length); } else return null; } } return null; } /** * Converts a non-regex string to a pattern * that can be used with the regex search engine. * * @param string the non-regex pattern * @return the string converted to a regex pattern */ private String asRegPattern(String string) { StringBuffer out= new StringBuffer(string.length()); boolean quoting= false; for (int i= 0, length= string.length(); i < length; i++) { char ch= string.charAt(i); if (ch == '\\') { if (quoting) { out.append("\\E"); //$NON-NLS-1$ quoting= false; } out.append("\\\\"); //$NON-NLS-1$ continue; } if (!quoting) { out.append("\\Q"); //$NON-NLS-1$ quoting= true; } out.append(ch); } if (quoting) out.append("\\E"); //$NON-NLS-1$ return out.toString(); } /** * Substitutes the previous match with the given text. * Sends a <code>DocumentEvent</code> to all registered <code>IDocumentListener</code>. * * @param text the substitution text * @param regExReplace if <code>true</code> <code>text</code> represents a regular expression * @return the replace region or <code>null</code> if there was no match * @throws BadLocationException if startOffset is an invalid document offset * @throws IllegalStateException if a REPLACE or REPLACE_FIND operation is not preceded by a successful FIND operation * @throws PatternSyntaxException if a regular expression has invalid syntax * * @see DocumentEvent * @see IDocumentListener */ public IRegion replace(String text, boolean regExReplace) throws BadLocationException { return findReplace(REPLACE, -1, null, text, false, false, false, regExReplace); } // ---------- CharSequence implementation ---------- /* * @see java.lang.CharSequence#length() */ public int length() { return fDocument.getLength(); } /* * @see java.lang.CharSequence#charAt(int) */ public char charAt(int index) { try { return fDocument.getChar(index); } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } } /* * @see java.lang.CharSequence#subSequence(int, int) */ public CharSequence subSequence(int start, int end) { try { return fDocument.get(start, end - start); } catch (BadLocationException e) { throw new IndexOutOfBoundsException(); } } /* * @see java.lang.Object#toString() */ public String toString() { return fDocument.get(); } }
dc196511ecd72d3279add5dbac3b0d7743bbab74
2254bb23dc727ae9bc5123573fe44e6c1abbc952
/SpringDataMongoDB-06-SpecialTypes-Collection-OneToMany/src/main/java/org/rose/dto/PersonDTO.java
559b015d88de22117b1b4eb0e1eed69ef4f47529
[]
no_license
Nilesh-Shinde1/NTSP713
dd4558f450ca0071323e8df4d558889a818488b0
635cef85dd04f48709a0eb8ca06748a5f1e62db3
refs/heads/main
2023-03-26T17:13:48.806906
2021-03-09T17:18:24
2021-03-09T17:18:24
321,302,031
0
0
null
2020-12-14T10:35:48
2020-12-14T09:47:09
Java
UTF-8
Java
false
false
506
java
package org.rose.dto; import java.util.Map; import java.util.Set; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Document @Data @AllArgsConstructor @NoArgsConstructor public class PersonDTO { @Id private Integer pid; private String name; private String education; private Set<IdentitiesDTO> identities; private Map<String,SchoolsDTO> schools; }
dbfb261d970d931bea4c7358ad7d2d1962beb19b
8fb52cc2f274f7276498ae7cf3512f34049b76f9
/vertx-stock-broker/src/main/java/com/ilham/github/broker/assets/GetAssetsHandler.java
7552a86f2bc71da3efbbd73ed222876286967301
[]
no_license
ilham-raslan/java-vertx-tutorials
3209947dedd936b5316eef9321afe071454b9e88
61ab9cd52b82c3301eb630c705a41ef11ce27084
refs/heads/master
2023-06-12T01:46:44.337469
2021-06-28T10:56:41
2021-06-28T10:56:41
377,758,889
0
0
null
null
null
null
UTF-8
Java
false
false
902
java
package com.ilham.github.broker.assets; import io.netty.handler.codec.http.HttpHeaderValues; import io.vertx.core.Handler; import io.vertx.core.http.HttpHeaders; import io.vertx.core.json.JsonArray; import io.vertx.ext.web.RoutingContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GetAssetsHandler implements Handler<RoutingContext> { private static final Logger LOG = LoggerFactory.getLogger(GetAssetsHandler.class); @Override public void handle(RoutingContext context) { final JsonArray response = new JsonArray(); AssetsRestApi.ASSETS.stream().map(Asset::new).forEach(response::add); LOG.info("Path {} responds with {}", context.normalizedPath(), response.encode()); context.response() .putHeader(HttpHeaders.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON) .putHeader("my-header", "my-value") .end(response.toBuffer()); } }
578f4fffe93c2180e9c34f9a04898b4f88fb5b0b
3916559346d2588093e05cfb3abbc6b84aaa651f
/MainModule/src/test/java/com/sire/hefeilife/ExampleUnitTest.java
1b6f40ab8c70d5e1bf826d23323d8e0925f224da
[]
no_license
SireAI/HeFeiLife
5953044d44d4ff5295330cffb22a7304d54fee63
1ec062e75797841b5bfcb488daabba94405c4158
refs/heads/master
2021-09-13T09:45:46.274585
2017-09-12T01:22:36
2017-09-12T01:22:36
103,205,738
0
0
null
null
null
null
UTF-8
Java
false
false
396
java
package com.sire.hefeilife; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
8c81aa3278f5cf2ae01f17011937400f719922ea
a5d01febfd8d45a61f815b6f5ed447e25fad4959
/Source Code/5.27.0/sources/okhttp3/internal/platform/OptionalMethod.java
a6bb700a24d4bfdc27b2531bd35b0cf86ed6d88e
[]
no_license
kkagill/Decompiler-IQ-Option
7fe5911f90ed2490687f5d216cb2940f07b57194
c2a9dbbe79a959aa1ab8bb7a89c735e8f9dbc5a6
refs/heads/master
2020-09-14T20:44:49.115289
2019-11-04T06:58:55
2019-11-04T06:58:55
223,236,327
1
0
null
2019-11-21T18:17:17
2019-11-21T18:17:16
null
UTF-8
Java
false
false
3,893
java
package okhttp3.internal.platform; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; class OptionalMethod<T> { private final String methodName; private final Class[] methodParams; private final Class<?> returnType; OptionalMethod(Class<?> cls, String str, Class... clsArr) { this.returnType = cls; this.methodName = str; this.methodParams = clsArr; } public boolean isSupported(T t) { return getMethod(t.getClass()) != null; } public Object invokeOptional(T t, Object... objArr) { Method method = getMethod(t.getClass()); if (method == null) { return null; } try { return method.invoke(t, objArr); } catch (IllegalAccessException unused) { return null; } } public Object invokeOptionalWithoutCheckedException(T t, Object... objArr) { try { return invokeOptional(t, objArr); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw ((RuntimeException) targetException); } AssertionError assertionError = new AssertionError("Unexpected exception"); assertionError.initCause(targetException); throw assertionError; } } public Object invoke(T t, Object... objArr) { Method method = getMethod(t.getClass()); if (method != null) { try { return method.invoke(t, objArr); } catch (IllegalAccessException e) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Unexpectedly could not call: "); stringBuilder.append(method); AssertionError assertionError = new AssertionError(stringBuilder.toString()); assertionError.initCause(e); throw assertionError; } } StringBuilder stringBuilder2 = new StringBuilder(); stringBuilder2.append("Method "); stringBuilder2.append(this.methodName); stringBuilder2.append(" not supported for object "); stringBuilder2.append(t); throw new AssertionError(stringBuilder2.toString()); } public Object invokeWithoutCheckedException(T t, Object... objArr) { try { return invoke(t, objArr); } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof RuntimeException) { throw ((RuntimeException) targetException); } AssertionError assertionError = new AssertionError("Unexpected exception"); assertionError.initCause(targetException); throw assertionError; } } private Method getMethod(Class<?> cls) { String str = this.methodName; if (str == null) { return null; } Method publicMethod = getPublicMethod(cls, str, this.methodParams); if (publicMethod != null) { Class cls2 = this.returnType; if (!(cls2 == null || cls2.isAssignableFrom(publicMethod.getReturnType()))) { return null; } } return publicMethod; } private static Method getPublicMethod(Class<?> cls, String str, Class[] clsArr) { try { Method method = cls.getMethod(str, clsArr); try { if ((method.getModifiers() & 1) != 0) { return method; } } catch (NoSuchMethodException unused) { return method; } } catch (NoSuchMethodException unused2) { } return null; } }
6707bcdc62a3133c050171d8cac4b067b697e205
85f8f7b86b3c0679f8e92494f3c16968a86e9105
/Java/Introduction/JavaCurrencyFormatter.java
ad75feca78d53ef8bb0e172b17760de0cf929541
[]
no_license
jerrychlee/HackerRank
cc5d81ae520a9a31d402e4acb675071376423586
6de5d978b0c0bf8dd4e94de4e07c2dee84633696
refs/heads/master
2022-06-06T10:04:18.592315
2022-05-22T12:35:05
2022-05-22T12:35:05
109,255,473
0
0
null
null
null
null
UTF-8
Java
false
false
774
java
import java.util.*; import java.text.*; public class Solution { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double payment = scanner.nextDouble(); scanner.close(); NumberFormat np; np = NumberFormat.getCurrencyInstance(Locale.US); System.out.println("US: " + np.format(payment)); np = NumberFormat.getCurrencyInstance(new Locale("en", "in")); System.out.println("India: " + np.format(payment)); np = NumberFormat.getCurrencyInstance(Locale.CHINA); System.out.println("China: " + np.format(payment)); np = NumberFormat.getCurrencyInstance(Locale.FRANCE); System.out.println("France: " + np.format(payment)); } }
1720bfbfe04278e314366ee85e5f567041eff401
7081452bbe86b4b48f0133cb4f2c921509fe1dd7
/src/test/java/gov/nist/itl/versus/similarity/comparisons/measure/impl/RandIndexMeasureTest.java
29a630def3ca738d73c8cf74ce8ef5c6697ca2fc
[]
no_license
VersusProject/similarity-2d
8c21d4ad26a98711c65cc3ccaa7cd8c4d5161ea5
3e7801ed27e4aa89332c718b82500aa0af28011b
refs/heads/master
2021-01-18T13:53:51.224029
2013-08-08T15:03:18
2013-08-08T15:03:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,655
java
/* * This software was developed at the National Institute of Standards and * Technology by employees of the Federal Government in the course of * their official duties. Pursuant to title 17 Section 105 of the United * States Code this software is not subject to copyright protection and is * in the public domain. This software is an experimental system. NIST assumes * no responsibility whatsoever for its use by other parties, and makes no * guarantees, expressed or implied, about its quality, reliability, or * any other characteristic. We would appreciate acknowledgment if the * software is used. * * name RandIndex * description * @author Benjamin Long * @version 1.4 * date */ package gov.nist.itl.versus.similarity.comparisons.measure.impl; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.io.IOException; import gov.nist.itl.versus.similarity.comparisons.measure.impl.RandIndexMeasure; import gov.nist.itl.versus.similarity.comparisons.measure.impl.AdjustedRandIndexMeasure; import gov.nist.itl.versus.similarity.comparisons.measure.impl.TotalErrorRateEvaluationMeasure; import gov.nist.itl.versus.similarity.comparisons.measure.impl.TotalErrorRateTestMeasure; import gov.nist.itl.versus.similarity.comparisons.adapter.impl.LabeledImageObjectAdapter; import gov.nist.itl.versus.similarity.comparisons.extract.impl.LabeledArrayFeatureExtractor; import gov.nist.itl.versus.similarity.comparisons.descriptor.impl.LabeledThreeDimensionalDoubleArrayFeature; import gov.nist.itl.versus.similarity.comparisons.measure.LabeledMeasure; import edu.illinois.ncsa.versus.adapter.impl.ImageObjectAdapter; import edu.illinois.ncsa.versus.descriptor.impl.ThreeDimensionalDoubleArrayFeature; import edu.illinois.ncsa.versus.extract.impl.ArrayFeatureExtractor; import edu.illinois.ncsa.versus.measure.SimilarityNumber; import gov.nist.itl.versus.similarity.comparisons.MathOpsE; import gov.nist.itl.versus.similarity.comparisons.exception.*; /** * RandIndex Test */ public class RandIndexMeasureTest extends junit.framework.TestCase { // default settings if no external file pairs are specified private static String fileName1 = "test/data/01_GSC_100x100.tif"; private static String fileName2 = "test/data/02_GSC_100x100.tif"; public RandIndexMeasureTest(){ } public static SimilarityNumber unlabeled( String fileName1, String fileName2 ) throws Exception { // unlabeled case: whole image (no labels) ImageObjectAdapter a1 = new ImageObjectAdapter(); if ( a1 == null ) throw new SWIndependenceException("failed to create ImageObjectAdapter adapter for file1"); ImageObjectAdapter a2 = new ImageObjectAdapter(); if ( a2 == null ) throw new SWIndependenceException("failed to create ImageObjectAdapter adapter for file2"); SimilarityNumber result = null; try { File f1 = new File(fileName1); if ( f1 == null ) throw new ImageCompatibilityException("failed to create file object for file1"); File f2 = new File(fileName2); if ( f2 == null ) throw new ImageCompatibilityException("failed to create file object for file2"); a1.load( f1 ); if ( a1 == null ) throw new SWIndependenceException("failed to load file1 into adapter1"); a2.load( f2 ); if ( a2 == null ) throw new SWIndependenceException("failed to load file2 into adapter2"); ArrayFeatureExtractor x1 = new ArrayFeatureExtractor(); if ( x1 == null ) throw new SWIndependenceException("failed to create ArrayFeatureExtractor object for extractor1"); ArrayFeatureExtractor x2 = new ArrayFeatureExtractor(); if ( x2 == null ) throw new SWIndependenceException("failed to create ArrayFeatureExtractor object for extractor2"); ThreeDimensionalDoubleArrayFeature desc1 = (ThreeDimensionalDoubleArrayFeature) x1.extract(a1); if ( desc1 == null ) throw new SWIndependenceException("failed to extract ThreeDimensionalDoubleArrayFeature feature1 via extractor1"); ThreeDimensionalDoubleArrayFeature desc2 = (ThreeDimensionalDoubleArrayFeature) x2.extract(a2); if ( desc2 == null ) throw new SWIndependenceException("failed to extract ThreeDimensionalDoubleArrayFeature feature2 via extractor2"); RandIndexMeasure m = new RandIndexMeasure(); if ( m == null ) throw new SWIndependenceException("failed to create RandIndexMeasure object for measure"); result = m.compare(desc1, desc2); if ( result == null ) throw new SingularityTreatmentException("received null comparison result"); String SEP = ","; String rString = fileName1 + SEP + fileName2 + SEP + "ImageObjectAdapter" + SEP + "ThreeDimensionalDoubleArrayFeature" + SEP + "RandIndexMeasure" + SEP + result.getValue() ; System.out.println ( rString ); } catch (IOException e) { throw new SWIndependenceException( "failed to load file via adapter into memory" ); } return result; } public static SimilarityNumber[] labeled( String fileName1, String fileName2 ) throws Exception { // labeled case LabeledImageObjectAdapter la1 = new LabeledImageObjectAdapter(); if ( la1 == null ) throw new SWIndependenceException("failed to create LabeledImageObjectAdapter adapter for file1"); LabeledImageObjectAdapter la2 = new LabeledImageObjectAdapter(); if ( la2 == null ) throw new SWIndependenceException("failed to create LabeledImageObjectAdapter adapter for file2"); SimilarityNumber[] lresult = null; try { File f1 = new File(fileName1); if ( f1 == null ) throw new ImageCompatibilityException("failed to create file object for file1"); File f2 = new File(fileName2); if ( f2 == null ) throw new ImageCompatibilityException("failed to create file object for file2"); la1.load( f1 ); if ( la1 == null ) throw new SWIndependenceException("failed to load file1 into adapter1"); la2.load( f2 ); if ( la2 == null ) throw new SWIndependenceException("failed to load file2 into adapter2"); LabeledArrayFeatureExtractor lx1 = new LabeledArrayFeatureExtractor(); if ( lx1 == null ) throw new SWIndependenceException("failed to create LabeledArrayFeatureExtractor object for extractor1"); LabeledArrayFeatureExtractor lx2 = new LabeledArrayFeatureExtractor(); if ( lx2 == null ) throw new SWIndependenceException("failed to create LabeledArrayFeatureExtractor object for extractor2"); LabeledThreeDimensionalDoubleArrayFeature ldesc1 = (LabeledThreeDimensionalDoubleArrayFeature) lx1.extract(la1); if ( ldesc1 == null ) throw new SWIndependenceException("failed to extract LabeledThreeDimensionalDoubleArrayFeature feature1 via extractor1"); LabeledThreeDimensionalDoubleArrayFeature ldesc2 = (LabeledThreeDimensionalDoubleArrayFeature) lx2.extract(la2); if ( ldesc2 == null ) throw new SWIndependenceException("failed to extract LabeledThreeDimensionalDoubleArrayFeature feature2 via extractor2"); RandIndexMeasure lm = new RandIndexMeasure(); if ( lm == null ) throw new SWIndependenceException("failed to create RandIndexMeasure object for measure"); lresult = lm.compare(ldesc1, ldesc2); if ( lresult == null ) throw new SingularityTreatmentException("received null comparison result"); String SEP = ","; String rString = fileName1 + SEP + fileName2 + SEP + "LabeledImageObjectAdapter" + SEP + "LabeledThreeDimensionalDoubleArrayFeature" + SEP + "AdjustedRandIndexMeasure" + SEP; rString += "["; for (int i=0; i < lresult.length; i++) { if ( i!=0 ) rString += SEP; rString += lresult[i].getValue(); } rString +="]"; System.out.println ( rString ); } catch (IOException e) { throw new SWIndependenceException( "failed to load file via adapter into memory" ); } return lresult; } //////////////// public void setFileNames( String fileName1, String fileName2 ) { this.fileName1=fileName1; this.fileName2=fileName2; } public String o( String category, String message, String details ) { String str = "[Pixel metric]\t[" + category + "]\t[" + message + "]\t[" + details + "]"; return str; } @Test public void test() { try { unlabeled(fileName1, fileName2); labeled(fileName1, fileName2); } catch( Exception e ) { System.out.println("Error:" + e.getMessage() ); } } public static void main( String[] args ) { org.junit.runner.JUnitCore.runClasses( RandIndexMeasureTest.class ); } }
12f2b09defa8fa93d0bd692a3b7e6ecf1175653c
4aec4eabc56635efd9eedef44ada7ef389d3bf48
/plugins/org.eclipse.wst.sse.sieditor.model/api/org/eclipse/wst/sse/sieditor/model/wsdl/api/IDescription.java
c06f7a85892524f2be8f9d4f5ffe8d6a3658e305
[]
no_license
HarshPath/org.eclipse.wst.sse.sieditor
060a05e3c4a84e9126e75e32838097bf9b39c7bf
e7f85698571b7428d9f3af28387d8b1a3282f631
refs/heads/master
2020-04-30T06:48:35.341020
2011-07-11T13:47:48
2011-07-11T13:47:48
176,663,700
0
0
null
2019-03-20T06:00:11
2019-03-20T05:49:50
Java
UTF-8
Java
false
false
2,291
java
/******************************************************************************* * Copyright (c) 2010 SAP AG. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Emil Simeonov - initial API and implementation. * Dimitar Donchev - initial API and implementation. * Dimitar Tenev - initial API and implementation. * Nevena Manova - initial API and implementation. * Georgi Konstantinov - initial API and implementation. * Keshav Veerapaneni - initial API and implementation. *******************************************************************************/ package org.eclipse.wst.sse.sieditor.model.wsdl.api; import java.net.URI; import java.util.Collection; import java.util.List; import org.eclipse.wst.wsdl.Definition; import org.eclipse.wst.sse.sieditor.model.api.IExtensibleObject; import org.eclipse.wst.sse.sieditor.model.api.INamespacedObject; import org.eclipse.wst.sse.sieditor.model.xsd.api.ISchema; /** * Represents the root of the ServiceInterface Objects * */ public interface IDescription extends INamespacedObject, IExtensibleObject { String getLocation(); String getRawLocation(); Collection<IServiceInterface> getAllInterfaces(); /** * Returns a list of service interfaces having the given name.<br> * By spec, service interface names should be unique, but in the case<br> * of an invalid model, such with duplicate names could exist. * * @param name * the name of the service interface, which is searched for * @return a list, containing one or more service interfaces */ List<IServiceInterface> getInterface(String name); List<ISchema> getContainedSchemas(); List<ISchema> getAllVisibleSchemas(); ISchema[] getSchema(String namespace); Collection<IDescription> getReferencedServices(); URI getContainingResource(); Definition getComponent(); /** * @return The first imported IDescription that corresponds to the given targetNamspace */ IDescription getReferencedDescription(String targetNamspace); }
eaf1dac36aa5afa237a997d10e49eb81a11b757c
f03de1f7c51c977036becdce1706516a04b84d74
/src/main/java/com/learninspringboot/ecofootprintapi/repo/EcoFootprintRepo.java
d71e53771e502ddcd86af777df2eec5387cacde1
[]
no_license
rlrc40/eco-footprint-api
1c8cde6123d6e623957e29741937c70f60791d8b
66a7f8ba5f6e671cf4b3b741e3f67d44b9347ff4
refs/heads/master
2022-12-04T06:33:13.745852
2020-08-14T15:54:06
2020-08-14T15:54:06
291,242,009
0
0
null
null
null
null
UTF-8
Java
false
false
418
java
package com.learninspringboot.ecofootprintapi.repo; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import com.learninspringboot.ecofootprintapi.model.EcoFootprint; public interface EcoFootprintRepo extends MongoRepository<EcoFootprint, String> { public EcoFootprint findByFirstName(String firstName); public List<EcoFootprint> findByLastName(String lastName); }
7c4a6434326454666cc264b5020611399344a9d0
f5be62eebe42fb789d367ec8fc7c3d6ab2dba1bf
/src/test/java/StepsDefinition/AgileProjectSteps.java
a0527b203ae229949f0e1443d38ccbef6a41a7d6
[]
no_license
Nusik/DemoCucumber
e8e774df7c163c61aa8831bb3c5f0519b08bf7e3
76874d60817eaad0e83cb70e83cbd5cb6025e2a7
refs/heads/master
2023-01-24T23:22:53.284919
2020-12-09T20:12:18
2020-12-09T20:12:18
310,933,170
0
0
null
null
null
null
UTF-8
Java
false
false
1,545
java
package StepsDefinition; import com.codeborne.selenide.Selenide; import cucumber.api.java.en.And; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import pages.AgileProjectPage; import pages.HomePage; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class AgileProjectSteps { HomePage homePage = new HomePage(); AgileProjectPage agileProjectPage = new AgileProjectPage(); @Given("user is on home page") public void userIsOnHomePage() { homePage.navigate(); } @When("user navigates to agile page") public void userNavigatesToAgilePage() { homePage.getMainMenuFragment().clickAgileProjectMenu(); } @And("user enters username {string} and password {string}") public void userEntersUsernameAndPassword(String userId, String password) { agileProjectPage.getAgileProjectMenuFragment().enterCredentials(userId, password); } @And("click login button") public void clickLoginButton() { agileProjectPage.getAgileProjectMenuFragment().clickLoginButton(); } @Then("welcome message is correct") public void welcomeMessageIsCorrect() { assertTrue(agileProjectPage.isWelcomeMessagePresent()); } @Then("invalid credentials message is shown") public void invalidCredentialsMessageIsShown() { assertEquals("User or Password is not valid", Selenide.switchTo().alert().getText()); Selenide.switchTo().alert().accept(); } }
98c0f0697570729b07d576c4f3c2a6c27a1fa06b
ce8b0c8ea8875e97656cfe0ab0efd0e661da6cc4
/src/main/java/shopex/toolkit/ToolkitApplication.java
5a30bb7ca62f2a33c488f81dad8bf93cb65415ca
[]
no_license
Karlenkko/javatoolkit
56b76146d5c0cd44041542b5f51d7be2e8cc0907
72a740f165555c410dba5e91a8b13842c269c468
refs/heads/master
2022-11-29T15:37:03.314127
2020-08-11T10:42:33
2020-08-11T10:42:33
286,373,872
2
0
null
null
null
null
UTF-8
Java
false
false
446
java
package shopex.toolkit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class ToolkitApplication { public static void main(String[] args) { SpringApplication.run(ToolkitApplication.class, args); } }
6759184948d52e60f4dcb2931e182e7c9d805eb9
568d1eb8b082cc403db5eeea06753f7d5db0d141
/abstract-factory/src/main/java/org/junbin/af/servlet/LaunchServlet.java
f6f03dc1e35906ccac7bd7b69455371c0710851d
[]
no_license
Reka-Downey/design-pattern
8da40e842b84b9411265d97e719e1f443c507833
1b986e3049925822804080fb68cd3df81c99d026
refs/heads/master
2021-01-10T16:10:09.224159
2016-04-03T14:05:22
2016-04-03T14:05:22
54,314,874
0
0
null
null
null
null
UTF-8
Java
false
false
2,414
java
package org.junbin.af.servlet; import org.junbin.af.enumerations.FactoryType; import org.junbin.af.enumerations.ProductType; import org.junbin.af.factory.AbstractFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * @Date : 2016-04-03 15:23 * @Author : junbin chung * @Email : [email protected] * @Intro : */ public class LaunchServlet extends HttpServlet { private Set<String> factories; private Set<String> products; private AbstractFactory factory; @Override public void init() throws ServletException { super.init(); factories = new HashSet<>(); products = new HashSet<>(); for (FactoryType type : FactoryType.values()) { factories.add(type.getName()); } for (ProductType type : ProductType.values()) { products.add(type.getName()); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); req.setAttribute("products", products); req.setAttribute("factories", factories); req.getRequestDispatcher("/WEB-INF/view/launch.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String type = req.getParameter("type"); if ("factory".equals(type)) { String factoryName = req.getParameter("factoryName"); factory = AbstractFactory.factory(factoryName); } else { String productName = req.getParameter("productName"); String responseText; switch (productName) { case "CPU": responseText = factory.createCpu().getCpuInfo(); break; case "MainBoard": responseText = factory.createMainBoard().getMainBoardInfo(); break; default: responseText = "不存在该产品类型!"; } resp.setContentType("text/html;charset=UTF-8"); resp.getWriter().write(responseText); } } }
c9db07a223ba6d77071725b6d54c48fb5296deef
8f62007331126cd2bb729f746d2b4695ebcd3ced
/app/build/generated/source/r/debug/com/twocentscode/nlevelexpandablelistview/R.java
d07806ce79e3ad19f61e5de08fa6fcfbab8cf811
[]
no_license
Scatum/NlevelListAndroid
5bb7c97f0898462cfa426344f8be42a8f3024ba5
6618fab70059c50ec3264a9c56307a8e75bc7677
refs/heads/master
2021-01-22T04:43:54.781401
2017-02-10T15:18:21
2017-02-10T15:18:21
81,576,667
0
0
null
null
null
null
UTF-8
Java
false
false
1,948
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.twocentscode.nlevelexpandablelistview; public final class R { public static final class attr { } public static final class dimen { public static final int activity_horizontal_margin=0x7f040000; public static final int activity_vertical_margin=0x7f040001; } public static final class drawable { public static final int ic_launcher=0x7f020000; } public static final class id { public static final int action_settings=0x7f080004; public static final int listItemContainer=0x7f080002; public static final int listView1=0x7f080001; public static final int textView=0x7f080003; public static final int textView1=0x7f080000; } public static final class layout { public static final int activity_main=0x7f030000; public static final int list_item=0x7f030001; } public static final class menu { public static final int main=0x7f070000; } public static final class string { public static final int action_settings=0x7f060000; public static final int app_name=0x7f060001; public static final int hello_world=0x7f060002; } public static final class style { /** API 11 theme customizations can go here. API 14 theme customizations can go here. Theme customizations available in newer API levels can go in res/values-vXX/styles.xml, while customizations related to backward-compatibility can go here. */ public static final int AppBaseTheme=0x7f050000; /** All customizations that are NOT specific to a particular API-level can go here. */ public static final int AppTheme=0x7f050001; } }
30ff9b27d37c133a8a4c46def8b0895a22e3b682
48a80995cb543c18eb1656c1e8f4b556188a1497
/src/main/java/br/com/palm/pontointeligente/api/services/impl/LancamentoServiceImpl.java
dd9299ddf9c60ad126ac86269736329bb4961a24
[ "MIT" ]
permissive
piedroalex/pontointeligente-api
0fc1c659a7f5b75fccfbbcb2e1d025387e8fee3d
690eff3df215a5fa58da506c5376862ed46e0f8f
refs/heads/master
2023-03-28T06:13:49.376857
2021-03-31T02:57:00
2021-03-31T02:57:00
276,266,696
0
0
MIT
2020-07-10T15:27:14
2020-07-01T03:24:25
Java
UTF-8
Java
false
false
1,693
java
package br.com.palm.pontointeligente.api.services.impl; import java.util.Optional; 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.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import br.com.palm.pontointeligente.api.entities.Lancamento; import br.com.palm.pontointeligente.api.repositories.LancamentoRepository; import br.com.palm.pontointeligente.api.services.LancamentoService; @Service public class LancamentoServiceImpl implements LancamentoService { private static final Logger log = LoggerFactory.getLogger(LancamentoServiceImpl.class); @Autowired private LancamentoRepository lancamentoRepository; public Page<Lancamento> buscarPorFuncionarioId(Long funcionarioId, PageRequest pageRequest) { log.info("Buscando lançamentos para o funcionário ID {}", funcionarioId); return this.lancamentoRepository.findByFuncionarioId(funcionarioId, pageRequest); } @Cacheable("lancamentoPorId") public Optional<Lancamento> buscarPorId(Long id) { log.info("Buscando um lançamento pelo ID {}", id); return Optional.ofNullable(this.lancamentoRepository.findOne(id)); } @CachePut("lancamentoPorId") public Lancamento persistir(Lancamento lancamento) { log.info("Persistindo o lançamento: {}", lancamento); return this.lancamentoRepository.save(lancamento); } public void remover(Long id) { log.info("Removendo o lançamento ID {}", id); this.lancamentoRepository.delete(id); } }
918b01332677bedbc81808ec654c86dcae9fb861
e01bf9ee203302cb5de8a98c7880f5f2df0f28a3
/src/com/cxy/studydemo/layout/FrameLayoutActivity.java
68ab9e696c68cf249df1c816570ba45207a41757
[]
no_license
cxy200927099/AndroidBaseDemo
0e31ff0f4cd9f1d7571ffdf38e38157357f5e89e
6b250fab448ad3fedaa7ea6cac643e8f536188ba
refs/heads/master
2021-01-10T12:41:27.758530
2016-03-20T07:11:00
2016-03-20T07:11:00
54,255,308
1
0
null
null
null
null
GB18030
Java
false
false
612
java
package com.cxy.studydemo.layout; import com.cxy.studydemo.R; import android.app.Activity; import android.os.Bundle; public class FrameLayoutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //这是一个仿照乐视手机的计算器的布局,主要都是使用了linearLayout来实现 //其中值得关注的是android:layout_weight="1"这个属性,包裹在linearLayout下 //的组件采用这个属性,可以很好的掌控布局适配不同的手机 setContentView(R.layout.layout_linearlayout); } }
f4a924b165cf8f2f0cfd4d4be61cde4436c91f33
eee49f6611a901ef602f65b023a9dac79af0d8ae
/src/main/java/br/com/demo/clientsapi/application/adapter/http/client/ClientFeign.java
61dfddde77fe24f8b76183ac24b27e541fb74fdb
[]
no_license
rogeriofontes/demo-hexagonal-api
bc908fc2508847c959932c54ea111523871cee1e
7cfafc7a7dec24557e2b4518f9f0f2ad85f9e64d
refs/heads/main
2023-05-31T17:56:28.919160
2021-06-17T19:27:45
2021-06-17T19:27:45
368,574,422
0
0
null
null
null
null
UTF-8
Java
false
false
642
java
package br.com.demo.clientsapi.application.adapter.http.client; import br.com.demo.clientsapi.core.model.Cliente; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; @FeignClient(name = "client", url = "http://localhost:8080/clients") public interface ClientFeign { @GetMapping Cliente retornaCliente(); @PostMapping public Page<Cliente> searchHellos(@RequestHeader("id") String clientId); }
b1fc9d04de5ba97625568b5b434bc67c72897dd8
adeea15381f73ddb6f069724cc8346f36b169f94
/src/main/java/HW3/ManagerProfile.java
757457437dd559a81a73e1a016bfd8076d130c18
[]
no_license
pirooz193/maktab39
445ceaa989d503cc6797c8531726d8e961435874
186cb04d8badb0fcf3ba220b6c8b1dbb47fdecb1
refs/heads/main
2022-12-28T01:39:43.311843
2020-10-09T04:49:28
2020-10-09T04:49:28
300,698,432
0
0
null
null
null
null
UTF-8
Java
false
false
538
java
package HW3; public class ManagerProfile extends UserProfile{ @Override public void setName(String name) { super.setName(name); } @Override public String getName() { return super.getName(); } @Override public void setLastName(String lastName) { super.setLastName(lastName); } @Override public void setPassWord(String passWord) { super.setPassWord(passWord); } @Override public String getPassWord() { return super.getPassWord(); } }
84b8b643b268273b04880f0fe88e6cc6c2c02c6d
8a4d6708416d74905bd64789b1b96234ae1f8072
/pippo-security-parent/pippo-pac4j/src/test/java/ro/pippo/pac4j/PippoSessionStoreTest.java
3a674646407fcbda0a2ee8cbad43e920fce629d2
[ "Apache-2.0" ]
permissive
mhagnumdw/pippo
453052f4e79df7b27dcd837de5a1a02eb4681e74
1af56321c528870a087ad14577d51237ba00e107
refs/heads/master
2021-11-26T03:22:29.928990
2021-11-19T08:11:01
2021-11-19T08:11:01
126,986,546
0
0
Apache-2.0
2018-03-27T12:58:00
2018-03-27T12:57:58
null
UTF-8
Java
false
false
6,827
java
/* * Copyright (C) 2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ro.pippo.pac4j; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import ro.pippo.core.Session; import ro.pippo.core.route.RouteContext; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; import static org.mockito.Mockito.*; /** * @author Ranganath Kini */ @RunWith(MockitoJUnitRunner.class) public class PippoSessionStoreTest { @Mock private PippoWebContext mockPippoWebContext; @Mock private RouteContext mockRouteContext; @Mock private Session mockSession; @Test public void shouldGetSessionFromSuppliedPippoWebContext() { when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); Session session = sessionStore.getSession(mockPippoWebContext); assertThat(session, is(mockSession)); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldGetSessionFromSuppliedPippoWebContextAsTrackableSession() { when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); Object session = sessionStore.getTrackableSession(mockPippoWebContext); assertThat(session, is(mockSession)); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldGetValueOfEntryWithSpecifiedKeyFromSession() { String expectedKey = "FooBar"; String expectedValue = "value_FOO_BAR"; when(mockSession.get(anyString())).thenReturn(expectedValue); when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); assertThat(sessionStore.get(mockPippoWebContext, expectedKey), is(expectedValue)); verify(mockSession, times(1)).get(expectedKey); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldReturnNullValueFromSessionIfNoEntryWithSpecifiedKeyExists() { String expectedKey = "FooBar"; when(mockSession.get(anyString())).thenReturn(null); when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); assertThat(sessionStore.get(mockPippoWebContext, expectedKey), is(nullValue())); verify(mockSession, times(1)).get(expectedKey); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldCreateEntryInSessionWithSpecifiedKeyAndValue() { String expectedKey = "FooBar"; String expectedValue = "value_FOO_BAR"; when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); sessionStore.set(mockPippoWebContext, expectedKey, expectedValue); verify(mockSession, times(1)).put(expectedKey, expectedValue); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldRemoveExistingEntryWithSpecifiedKeyWhenSpecifiedValueIsNull() { String expectedKey = "FooBar"; when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); sessionStore.set(mockPippoWebContext, expectedKey, null); verify(mockSession, times(1)).remove(expectedKey); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldInvalidateSessionOnDestroy() { when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); assertThat(sessionStore.destroySession(mockPippoWebContext), is(true)); verify(mockSession, times(1)).invalidate(); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldGetSessionIdFromUnderlyingSession() { String expectedSessionId = "FOO_SESSION_ID"; when(mockSession.getId()).thenReturn(expectedSessionId); when(mockRouteContext.getSession()).thenReturn(mockSession); when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); assertThat(sessionStore.getOrCreateSessionId(mockPippoWebContext), is(expectedSessionId)); verify(mockSession, times(1)).getId(); verify(mockRouteContext, times(1)).getSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldAskRouteContextToRecreateSessionOnRenewSession() { when(mockPippoWebContext.getRouteContext()).thenReturn(mockRouteContext); PippoSessionStore sessionStore = new PippoSessionStore(); assertThat(sessionStore.renewSession(mockPippoWebContext), is(true)); verify(mockRouteContext, times(1)).recreateSession(); verify(mockPippoWebContext, times(1)).getRouteContext(); } @Test public void shouldBuildFromProvidedTrackableSession() { } }
c4c50ebea48b93b0f7145d1d372f77e0c5124d19
c252c61e377499304d4eaba3377bc2d4264c18cd
/app/src/main/java/com/example/tatangit/umrota_maker/View/Lisence/Fragment_Lisence.java
2929a8e6835d78f46e6e15f0200bd20778cb680e
[]
no_license
id10111137/UmrotaMaker
e8d5ccf01c60e736bcbddaaef96b410aefb5d1a0
ca22e7925cb3a68699ac34187bff4fe1a175c09e
refs/heads/master
2020-04-14T09:02:26.791797
2019-06-15T14:20:00
2019-06-15T14:20:00
163,750,402
0
0
null
null
null
null
UTF-8
Java
false
false
1,241
java
package com.example.tatangit.umrota_maker.View.Lisence; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.tatangit.umrota_maker.R; import butterknife.ButterKnife; import de.hdodenhof.circleimageview.CircleImageView; public class Fragment_Lisence extends Fragment { Intent intent; Toolbar toolbar; TextView mTitle; View root; CircleImageView toolbar_iconView; public Fragment_Lisence() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { root = inflater.inflate(R.layout.fragment_lisensi, container, false); ButterKnife.bind(this, root); toolbar = getActivity().findViewById(R.id.toolbar); mTitle = toolbar.findViewById(R.id.id_title_toolbar); mTitle.setText("Lisence Apps"); toolbar_iconView = getActivity().findViewById(R.id.id_icon_toolbar); toolbar_iconView.setImageDrawable(null); return root; } }
42a7c09cce951fd81a11bdbaeda4930a4707576c
6250e8c9f8d11cb1451f5a9cf477749b92716408
/nano-server/src/main/java/org/util/ServerRunner.java
0e876da19c0af0390ba6a8d2f187a6bccc825b11
[ "Apache-2.0" ]
permissive
feijeff0486/JUPnP
df01213c47da6004ff4c09df4188c1513022f16e
e3e28968cc647158b065c879893a5f549419eaa6
refs/heads/master
2022-12-18T12:20:25.872205
2020-08-28T05:58:54
2020-08-28T05:58:54
290,435,737
0
0
null
null
null
null
UTF-8
Java
false
false
2,703
java
package org.util; /* * #%L * NanoHttpd-Webserver * %% * Copyright (C) 2012 - 2015 nanohttpd * %% * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the nanohttpd nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * #L% */ import org.protocols.http.NanoHTTPD; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class ServerRunner { /** * logger to log to. */ private static final Logger LOG = Logger.getLogger(ServerRunner.class.getName()); public static void executeInstance(NanoHTTPD server) { try { server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false); } catch (IOException ioe) { System.err.println("Couldn't start server:\n" + ioe); System.exit(-1); } System.out.println("Server started, Hit Enter to stop.\n"); try { System.in.read(); } catch (Throwable ignored) { } server.stop(); System.out.println("Server stopped.\n"); } public static <T extends NanoHTTPD> void run(Class<T> serverClass) { try { executeInstance(serverClass.newInstance()); } catch (Exception e) { ServerRunner.LOG.log(Level.SEVERE, "Could not create server", e); } } }
a125d281da49d47b40a0b839f9f42716b8dcf1b5
84c05931d9a651c61fad77df7d67732cdecd15b2
/src/org/dvijok/widgets/gallery/GalleryItem.java
8a858df9fb44b815b8f1e6e857e7b7e8460dab7e
[]
no_license
parilo/dvijok
ab56ba187550b504db258e7db591554957255ea8
f0abe9c3dad061af1cf02eb399b07f8cf6d96181
refs/heads/master
2020-03-31T01:10:05.559005
2014-02-18T15:47:17
2014-02-18T15:47:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,146
java
// dvijok - cms written in gwt // Copyright (C) 2010 Pechenko Anton Vladimirovich aka Parilo // mailto: forpost78 at gmail dot com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // package org.dvijok.widgets.gallery; import org.dvijok.event.CustomEventListener; import com.google.gwt.user.client.ui.IsWidget; public interface GalleryItem extends IsWidget { public void addItemSelectedListsner(CustomEventListener listsner); public void removeItemSelectedListsner(CustomEventListener listsner); }
4e9157894d55651396077b69094b752d854fce40
8ed9f95fd028b7d89e7276847573878e32f12674
/docx4j-openxml-objects/src/main/java/org/docx4j/dml/chart/CTSkip.java
daf5e5306cfd53fe2cd1925de1a7793e0e5e3ba2
[ "Apache-2.0" ]
permissive
plutext/docx4j
a75b7502841a06f314cb31bbaa219b416f35d8a8
1f496eca1f70e07d8c112168857bee4c8e6b0514
refs/heads/VERSION_11_4_8
2023-06-23T10:02:08.676214
2023-03-11T23:02:44
2023-03-11T23:02:44
4,302,287
1,826
1,024
null
2023-03-11T23:02:45
2012-05-11T22:13:30
Java
UTF-8
Java
false
false
2,740
java
/* * Copyright 2007-2008, Plutext Pty Ltd. * * This file is part of docx4j. docx4j is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.docx4j.dml.chart; import jakarta.xml.bind.Unmarshaller; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlAttribute; import jakarta.xml.bind.annotation.XmlTransient; import jakarta.xml.bind.annotation.XmlType; import org.jvnet.jaxb2_commons.ppp.Child; /** * <p>Java class for CT_Skip complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CT_Skip"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="val" use="required" type="{http://schemas.openxmlformats.org/drawingml/2006/chart}ST_Skip" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CT_Skip") public class CTSkip implements Child { @XmlAttribute(name = "val", required = true) protected int val; @XmlTransient private Object parent; /** * Gets the value of the val property. * */ public int getVal() { return val; } /** * Sets the value of the val property. * */ public void setVal(int value) { this.val = value; } /** * Gets the parent object in the object tree representing the unmarshalled xml document. * * @return * The parent object. */ public Object getParent() { return this.parent; } public void setParent(Object parent) { this.parent = parent; } /** * This method is invoked by the JAXB implementation on each instance when unmarshalling completes. * * @param parent * The parent object in the object tree. * @param unmarshaller * The unmarshaller that generated the instance. */ public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) { setParent(parent); } }
2a636d170ac02831fb52dca19596fa38ee33358f
2c566fb62ac4b8d9b3b905af562bb9c427e493a2
/InclusaoEnderecosClientes/src/main/java/com/algaworks/pedidovenda/controller/CadastroUsuarioBean.java
814f5075b2db0902a7a023ac364f05aa2809d62d
[]
no_license
tvttavares/java-EE-primefaces
aa4d2be02aea979244a0e9cdb28d107ccf95c3b4
c9aebad883590a3538fcda84031ea0d032f6bdfc
refs/heads/master
2022-12-07T05:07:21.533168
2019-11-26T12:40:39
2019-11-26T12:40:39
208,525,974
1
0
null
2022-11-24T06:13:43
2019-09-15T01:30:18
Java
UTF-8
Java
false
false
1,947
java
package com.algaworks.pedidovenda.controller; import java.io.Serializable; import java.util.List; import javax.faces.bean.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import com.algaworks.pedidovenda.model.Grupo; import com.algaworks.pedidovenda.model.Usuario; import com.algaworks.pedidovenda.repository.Grupos; import com.algaworks.pedidovenda.service.CadastroUsuarioService; import com.algaworks.pedidovenda.util.jsf.FacesUtil; @Named @ViewScoped public class CadastroUsuarioBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private Grupos grupos; @Inject private CadastroUsuarioService cadastroUsuarioService; private Usuario usuario; private Grupo grupo; private List<Grupo> gruposUsuario; public CadastroUsuarioBean() { limpar(); } public void inicializar() { if (FacesUtil.isNotPostback()) { gruposUsuario = grupos.raizesGrupos(); } } public void salvar() { this.usuario = cadastroUsuarioService.salvar(this.usuario); limpar(); FacesUtil.addInfoMessage("Usuario salvo com sucesso!"); } public void adicionarGrupo() { if (grupo != null && !this.usuario.getGrupos().contains(this.grupo)) { this.usuario.getGrupos().add(this.grupo); grupo = new Grupo(); } } public void removerGrupo() { if (grupo != null) { this.usuario.getGrupos().remove(this.grupo); } } private void limpar() { usuario = new Usuario(); grupo = new Grupo(); } public boolean isEditando() { return this.usuario.getId() != null; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Grupo getGrupo() { return grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } public List<Grupo> getGruposUsuario() { return gruposUsuario; } public void setGruposUsuario(List<Grupo> gruposUsuario) { this.gruposUsuario = gruposUsuario; } }
6e1c097fdb09fbc24f03b24e121f1cfbe8b928f0
cccfb7be281ca89f8682c144eac0d5d5559b2deb
/content/public/android/java/src/org/chromium/content_public/browser/AttributionReporter.java
26eca1e6ed04b890860e7795c9b1d58f3be78a51
[ "BSD-3-Clause" ]
permissive
SREERAGI18/chromium
172b23d07568a4e3873983bf49b37adc92453dd0
fd8a8914ca0183f0add65ae55f04e287543c7d4a
refs/heads/master
2023-08-27T17:45:48.928019
2021-11-11T22:24:28
2021-11-11T22:24:28
428,659,250
1
0
BSD-3-Clause
2021-11-16T13:08:14
2021-11-16T13:08:14
null
UTF-8
Java
false
false
2,514
java
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content_public.browser; import org.chromium.content.browser.AttributionReporterImpl; /** * Allows attributions to be reported independently from navigations. */ public abstract class AttributionReporter { private static AttributionReporter sAttributionReporterForTesting; /** * @return an AttributionReporter instance. */ public static AttributionReporter getInstance() { if (sAttributionReporterForTesting != null) return sAttributionReporterForTesting; return new AttributionReporterImpl(); } /** * Normally, Attributions should be reported through LoadUrlParams at the start of a navigation. * However, in some cases, like with speculative navigation, the attribution parameters aren't * available at the start of the navigation. * * This method allows Attributions to be reported for ongoing or already completed navigations, * as long as the current navigation finishes on the |destination| URL. * * @param webContents The WebContents the navigation to report an Attribution for is taking * place in. * @see LoadUrlParams#setAttributionParameters for the rest of the parameters. */ public abstract void reportAttributionForCurrentNavigation(WebContents webContents, String sourcePackageName, String sourceEventId, String destination, String reportTo, long expiry); /** * Report an Impression Attribution coming from an app - for example, when the user is shown an * ad in an app. This Attribution is not associated with any navigation. * * @param browserContext The BrowserContextHandle in which we're currently running. * @param eventTime The time at which the event took place in {@link System#currentTimeMillis()} * timebase. Optional if the event was just received (and not cached). * @see LoadUrlParams#setAttributionParameters for the rest of the parameters. */ public abstract void reportAppImpression(BrowserContextHandle browserContext, String sourcePackageName, String sourceEventId, String destination, String reportTo, long expiry, long eventTime); public static void setInstanceForTesting(AttributionReporter reporter) { sAttributionReporterForTesting = reporter; } }
ef7af7fb08efb80cf93dbf55903ebe3c9cca097d
96f8d42c474f8dd42ecc6811b6e555363f168d3e
/budejie/sources/cn/v6/sixrooms/ui/fragment/o.java
a2e210944405917d1e0a3c907906f5e818888908
[]
no_license
aheadlcx/analyzeApk
050b261595cecc85790558a02d79739a789ae3a3
25cecc394dde4ed7d4971baf0e9504dcb7fabaca
refs/heads/master
2020-03-10T10:24:49.773318
2018-04-13T09:44:45
2018-04-13T09:44:45
129,332,351
6
2
null
null
null
null
UTF-8
Java
false
false
568
java
package cn.v6.sixrooms.ui.fragment; import cn.v6.sixrooms.widgets.phone.HideOrDisplayThePasswordView.OnHideOrDisplayListener; final class o implements OnHideOrDisplayListener { final /* synthetic */ LoginFragment a; o(LoginFragment loginFragment) { this.a = loginFragment; } public final void clickCleanButton() { this.a.clearPassword(); } public final void isShowPassword(boolean z) { this.a.setPasswordType(z); LoginFragment.g(this.a).clearFocus(); LoginFragment.f(this.a).requestFocus(); } }
80963460b16153a08a047200e548336c92d5f35f
04de9695c1e095d4832fe05643442c47c5ea3fe7
/app/src/main/java/info/palamarchuk/api/cooking/RecipeIngredientEndpoint.java
4bd05c0ef97e97f4428068fe1eb564b3e526f63f
[]
no_license
fankandin/cooking-app-endpoint
3c8327ea667ae61e5ec65286ea310de776a92afc
7d2a5ce6848db471b08bad94de77db38a0b837e1
refs/heads/master
2021-06-07T10:47:22.993376
2017-07-03T02:11:00
2017-07-03T02:11:00
95,615,857
5
0
null
2017-07-03T02:11:01
2017-06-28T01:28:50
Java
UTF-8
Java
false
false
3,882
java
package info.palamarchuk.api.cooking; import info.palamarchuk.api.cooking.data.RecipeIngredientPatch; import info.palamarchuk.api.cooking.entity.RecipeIngredient; import info.palamarchuk.api.cooking.service.RecipeIngredientService; import info.palamarchuk.api.cooking.util.CurrentUrlService; import info.palamarchuk.api.cooking.validation.RecipeIngredientAddValidator; import info.palamarchuk.api.cooking.validation.RecipeIngredientUpdateValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/recipes/ingredients") public class RecipeIngredientEndpoint { private final RecipeIngredientService service; @Autowired public RecipeIngredientEndpoint(RecipeIngredientService service) { this.service = service; } @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseData<RecipeIngredient> get(@PathVariable("id") long id) { return new ResponseData<>(service.getById(id)); } @PostMapping(value = "", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity add(@RequestBody RecipeIngredientPatch data, BindingResult result, @Autowired CurrentUrlService urlService) { new RecipeIngredientAddValidator().validate(data, result); if (result.hasErrors()) { return ResponseEntity.badRequest().build(); // @todo Provide additional information } RecipeIngredient candidate = new RecipeIngredient(data.recipeId, data.ingredientId, data.amount, data.measurement); if (data.isAmountNetto != null) { candidate.setAmountNetto(data.isAmountNetto); } service.add(candidate); return ResponseEntity.created(urlService.getUrl(candidate.getId())).build(); } @PatchMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) public ResponseEntity patch(@PathVariable("id") long id, @RequestBody RecipeIngredientPatch patch, BindingResult result, @Autowired CurrentUrlService urlService) { RecipeIngredient current = service.getById(id); if (current == null) { return ResponseEntity.notFound().build(); // @todo Provide additional information } new RecipeIngredientUpdateValidator(service, current).validate(patch, result); if (result.hasErrors()) { return new ErrorResponseData(result.getAllErrors()).export(HttpStatus.UNPROCESSABLE_ENTITY); } // only touch fields which are really changed // it is allowed to change ingredientId, but it is not allowed to change recipeId if (patch.ingredientId != null) { current.setIngredientId(patch.ingredientId); // updated.ingredientId itself is empty } if (patch.amount != null) { current.setAmount(patch.amount); } if (patch.measurement != null) { current.setMeasurement(patch.measurement); } if (patch.isAmountNetto != null) { current.setAmountNetto(patch.isAmountNetto); } if (patch.preparation != null) { current.setPreparation(patch.preparation); } service.update(current); return ResponseEntity.noContent().location(urlService.getUrl()).build(); } @DeleteMapping(value = "/{id}") public ResponseEntity delete(@PathVariable("id") long id) { RecipeIngredient current = service.getById(id); if (current == null) { return ResponseEntity.notFound().build(); } service.deleteById(id); return ResponseEntity.noContent().build(); } }
fde7568f11b2d661ab05baa842271b7b64020835
41297b5c6d38649d2f1461f5d7846d34fe55791f
/backend/src/main/java/app/service/TreatmentService.java
9aba7dff5f22ea101e8e0f2ef5d020bf1ced337b
[]
no_license
vsostaric/alert-test
0fc587ca764c3a8483139becb8c6dd432237ad19
dafeee199fc6443d2801177fb3dd6ca7b6339b2f
refs/heads/master
2020-04-06T13:59:39.779672
2018-12-18T09:43:45
2018-12-18T09:43:45
157,523,105
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package app.service; import app.model.Alert; import app.model.Treatment; import java.util.List; public interface TreatmentService { Treatment saveTreatment(Treatment treatment); List<Treatment> findTreatments(); List<Alert> checkForAlerts(Treatment treatment); }
591705ef327ddfb52276cf3d6c55e08e4bb16e2e
31f043184e2839ad5c3acbaf46eb1a26408d4296
/src/main/java/com/github/highcharts4gwt/model/highcharts/option/jso/plotoptions/polygon/JsoStates.java
a7ec4c97626401365a1097f158c9dc4e27ce4cc1
[]
no_license
highcharts4gwt/highchart-wrapper
52ffa84f2f441aa85de52adb3503266aec66e0ac
0a4278ddfa829998deb750de0a5bd635050b4430
refs/heads/master
2021-01-17T20:25:22.231745
2015-06-30T15:05:01
2015-06-30T15:05:01
24,794,406
1
0
null
null
null
null
UTF-8
Java
false
false
1,736
java
package com.github.highcharts4gwt.model.highcharts.option.jso.plotoptions.polygon; import com.github.highcharts4gwt.model.highcharts.option.api.plotoptions.polygon.States; import com.github.highcharts4gwt.model.highcharts.option.api.plotoptions.polygon.states.Hover; import com.google.gwt.core.client.JavaScriptObject; /** * A wrapper object for all the series options in specific states. * */ public class JsoStates extends JavaScriptObject implements States { protected JsoStates() { } public final native Hover hover() throws RuntimeException /*-{ return this["hover"] = (this["hover"] || {}); }-*/ ; public final native JsoStates hover(Hover hover) throws RuntimeException /*-{ this["hover"] = hover; return this; }-*/ ; public final native String getFieldAsJsonObject(String fieldName) throws RuntimeException /*-{ this[fieldName] = (this[fieldName] || {}); return JSON.stringify(this[fieldName]); }-*/ ; public final native JsoStates setFieldAsJsonObject(String fieldName, String fieldValueAsJsonObject) throws RuntimeException /*-{ this[fieldName] = JSON.parse(fieldValueAsJsonObject); return this; }-*/ ; public final native String getFunctionAsString(String fieldName) throws RuntimeException /*-{ this[fieldName] = (this[fieldName] || {}); return JSON.stringify(this[fieldName]); }-*/ ; public final native JsoStates setFunctionAsString(String fieldName, String functionAsString) throws RuntimeException /*-{ this[fieldName] = eval('(' + functionAsString + ')'); return this; }-*/ ; }
80763f5ed39896010b468003c2c634d9e4a15587
7a621cd3d645a2a4a4e77af6d3286cd53fb6976c
/HumanResourceManagementSystem/src/main/java/kodlamaio/HumanResourceManagementSystem/api/SchoolController.java
cb224a7d0672a59f8ee609a19d4551dff72f7bb0
[]
no_license
emresimsek05/HumanResourceManagementSystem
eed34cc5fb0e2c415b571f03174e7c99a477c38e
26158711d57846e4f40661d308f5011552af2f1c
refs/heads/main
2023-05-27T13:05:11.292005
2021-06-15T21:36:17
2021-06-15T21:36:17
377,298,211
2
0
null
null
null
null
UTF-8
Java
false
false
953
java
package kodlamaio.HumanResourceManagementSystem.api; import kodlamaio.HumanResourceManagementSystem.business.abstracts.SchoolService; import kodlamaio.HumanResourceManagementSystem.entities.concretes.School; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("/api/school") public class SchoolController { private SchoolService schoolService; @Autowired public SchoolController(SchoolService schoolService) { this.schoolService = schoolService; } @GetMapping("/getall") public ResponseEntity<?> getAll(){ return ResponseEntity.ok(this.schoolService.getAll()); } @PostMapping("/add") public ResponseEntity<?> add(@Valid @RequestBody School school){ return ResponseEntity.ok(this.schoolService.add(school)); } }
06d2e8f1ea3de5d8ce452d257902754e3dddd3e8
bba740d5626524f14d082e903d70f0a9e28ced96
/src/lab5/ex5.java
097361ed41b7be21f873139250b3a3140085cebe
[]
no_license
Numtip1/360411760009
03c5428ba82350df203a3025a0dd88764e2768a6
c8c46f82eb39522bc8118b195de3c57d00e41ec5
refs/heads/master
2020-03-21T15:18:19.843886
2018-10-16T09:07:29
2018-10-16T09:07:29
138,705,001
0
0
null
null
null
null
UTF-8
Java
false
false
1,101
java
package lab5; public class ex5 { public static void main(String[] args) { String msg1 = " Hallo "; //length(); System.out.println(msg1.length()); System.out.println("*"+msg1+"*"); System.out.println("*"+msg1.trim()+"*"); //compare String String msg2 = "MIT421"; String msg3 = "MIT421"; String msg4 = "MT MIT421"; //== if (msg2 == msg3) System.out.println("Yes"); else System.out.println("No"); if (msg3 == msg4) System.out.println("Yes"); else System.out.println( "No"); //eguals() if (msg2.equals(msg3)) System.out.println("Yes"); else System.out.println( "No"); if (msg2.equals(msg4)) System.out.println("Yes"); else System.out.println( "No"); //compareTo() if (msg2.compareTo(msg3)==0) System.out.println("2 String are equal"); else if (msg2.compareTo(msg3)>1); else System.out.println("msg2 less than msg3"); }//main }//class
35e51a03d1869ac94cd264120796bd37cb689a59
2bdc54629d9dec9ad519ac5f0bf5cbccefaabfb7
/src/main/java/com/finedu/springboot/controller/FrontController.java
3f75da69c69f922f6244dc8b48caa77d45a8f746
[]
no_license
simhw/Springboot-Fintech
adf700c12725fb258b5bbcef4de6b4ddfcb6ea7d
25d8f3ed0520ac75107fcf6bfccc0d1f7d0e3034
refs/heads/master
2023-06-30T14:50:36.173284
2021-08-07T04:27:25
2021-08-07T04:27:25
393,544,491
0
0
null
null
null
null
UTF-8
Java
false
false
74
java
package com.finedu.springboot.controller;public class FrontController { }
0afcf5d4f6e4cb85797e090198134a82fca1509e
230f7a01d816dc4106a48555efdff63cbac5d4d3
/结构型模式/组合模式/Client.java
c8605cec7f18dc7ec8d7514870f418f1e8da2bd9
[]
no_license
GuoWeize/Design_Patterns
6326b24e1442301afb67d9683d371d94b28e85d3
c8b55147b4fb59f809c11e264b909b769238d38c
refs/heads/master
2020-04-14T19:20:21.533588
2019-01-04T03:37:33
2019-01-04T03:37:33
164,053,904
0
0
null
null
null
null
UTF-8
Java
false
false
48
java
package 组合模式; public class Client { }
0a49ef6d3ece558b621217fe06ea9c54398ea78f
c2db8a01b396117f18bed8e83ee81ada86465809
/src/com/bawei/version_update/Httputils.java
a6a51b70eba6cc7e67a6d7c83dc1d19597312aa3
[]
no_license
wxpsudichina/app_update
d442ec6bda6fc92caa23e8e4244d3bfe7650ac53
4c164d46ff1bcfc6c7a9199d1237d95ca785b12d
refs/heads/master
2021-01-11T07:16:13.258577
2016-11-01T08:28:28
2016-11-01T08:28:28
72,517,526
0
0
null
null
null
null
GB18030
Java
false
false
1,174
java
package com.bawei.version_update; import java.util.List; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; 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.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.util.Log; public class Httputils { //请求服务器 public static String http_post(String url,List<NameValuePair> pair){ String str = ""; HttpPost httpRequest = new HttpPost(url); try { httpRequest.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8)); // HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest); HttpResponse response = new DefaultHttpClient().execute(httpRequest); if(response.getStatusLine().getStatusCode()==200){ str = EntityUtils.toString(response.getEntity()); Log.i("TAG", "请求返回结果==="+str.toString()); }else{ //请求失败返回值 str = "000"; } } catch (Exception e) { e.printStackTrace(); //请求失败返回值 str = "000"; } return str; } }
9531ee953f383fcefeab1a5ea3c1b8e2a41ed44b
5ef559cacea10daba53c4b0784bc3553e3931837
/src/main/java/ru/finam/canvasui/client/js/Array.java
7a2c40bb9f403edd8b9cb8b669e5f09281ac847f
[]
no_license
BenjaminLinus/pixi-ui
66f52db5071ec972438c29fc91c1fc91f30e4c13
093d66e5518c7962be53d2f0b29b6a847fdceb47
refs/heads/master
2021-01-15T20:28:12.716430
2014-10-17T14:30:44
2014-10-17T14:30:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
694
java
package ru.finam.canvasui.client.js; import com.google.gwt.core.client.js.JsProperty; import com.google.gwt.core.client.js.JsType; /** * Created by ikusch on 19.08.14. */ @JsType(isNative = true, prototype = "Array") public interface Array<T extends JsObject> extends JsObject{ void push(T data); T pop(); @JsProperty(value = "length") int getLength(); public static class Factory { public static final native Array<JsObject> newArray() /*-{ return []; }-*/; } public static class Static { public static final native <T extends JsObject> T get(int i, Array<T> array) /*-{ array[i]; }-*/; } }
b9e6d1c6c349e812c05aa4cf4bfc2b82f74f4cb3
d80b5395e72407e1d75e51d9da3f357efa4fbf1a
/PumaPayload/yoctolib/src/main/java/com/yoctopuce/YoctoAPI/YGroundSpeed.java
b5334c4bfa088af69dc9528bdb48fd24a63a5dc2
[]
no_license
Taylorjtt/PumaPayloadTool
46bf127690734ca0007a2672be9a2cb0b29eabeb
405aa5dd2ac967f9afcad6d77c6bde8356e80f1b
refs/heads/master
2021-01-21T21:55:48.555068
2017-06-22T15:47:49
2017-06-22T15:47:49
95,131,619
0
0
null
null
null
null
UTF-8
Java
false
false
12,287
java
/********************************************************************* * * $Id: YGroundSpeed.java 27277 2017-04-25 15:41:31Z seb $ * * Implements FindGroundSpeed(), the high-level API for GroundSpeed functions * * - - - - - - - - - License information: - - - - - - - - - * * Copyright (C) 2011 and beyond by Yoctopuce Sarl, Switzerland. * * Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual * non-exclusive license to use, modify, copy and integrate this * file into your software for the sole purpose of interfacing * with Yoctopuce products. * * You may reproduce and distribute copies of this file in * source or object form, as long as the sole purpose of this * code is to interface with Yoctopuce products. You must retain * this notice in the distributed source file. * * You should refer to Yoctopuce General Terms and Conditions * for additional information regarding your rights and * obligations. * * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 'AS IS' WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO * EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, * COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR * SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT * LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR * CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE * BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF * WARRANTY, OR OTHERWISE. * *********************************************************************/ package com.yoctopuce.YoctoAPI; //--- (YGroundSpeed return codes) //--- (end of YGroundSpeed return codes) //--- (YGroundSpeed class start) /** * YGroundSpeed Class: GroundSpeed function interface * * The Yoctopuce class YGroundSpeed allows you to read the ground speed from Yoctopuce * geolocalization sensors. It inherits from the YSensor class the core functions to * read measurements, register callback functions, access the autonomous * datalogger. */ @SuppressWarnings({"UnusedDeclaration", "UnusedAssignment"}) public class YGroundSpeed extends YSensor { //--- (end of YGroundSpeed class start) //--- (YGroundSpeed definitions) protected UpdateCallback _valueCallbackGroundSpeed = null; protected TimedReportCallback _timedReportCallbackGroundSpeed = null; /** * Deprecated UpdateCallback for GroundSpeed */ public interface UpdateCallback { /** * * @param function : the function object of which the value has changed * @param functionValue : the character string describing the new advertised value */ void yNewValue(YGroundSpeed function, String functionValue); } /** * TimedReportCallback for GroundSpeed */ public interface TimedReportCallback { /** * * @param function : the function object of which the value has changed * @param measure : measure */ void timedReportCallback(YGroundSpeed function, YMeasure measure); } //--- (end of YGroundSpeed definitions) /** * * @param func : functionid */ protected YGroundSpeed(YAPIContext ctx, String func) { super(ctx, func); _className = "GroundSpeed"; //--- (YGroundSpeed attributes initialization) //--- (end of YGroundSpeed attributes initialization) } /** * * @param func : functionid */ protected YGroundSpeed(String func) { this(YAPI.GetYCtx(true), func); } //--- (YGroundSpeed implementation) @SuppressWarnings("EmptyMethod") @Override protected void _parseAttr(YJSONObject json_val) throws Exception { super._parseAttr(json_val); } /** * Retrieves a ground speed sensor for a given identifier. * The identifier can be specified using several formats: * <ul> * <li>FunctionLogicalName</li> * <li>ModuleSerialNumber.FunctionIdentifier</li> * <li>ModuleSerialNumber.FunctionLogicalName</li> * <li>ModuleLogicalName.FunctionIdentifier</li> * <li>ModuleLogicalName.FunctionLogicalName</li> * </ul> * * This function does not require that the ground speed sensor is online at the time * it is invoked. The returned object is nevertheless valid. * Use the method YGroundSpeed.isOnline() to test if the ground speed sensor is * indeed online at a given time. In case of ambiguity when looking for * a ground speed sensor by logical name, no error is notified: the first instance * found is returned. The search is performed first by hardware name, * then by logical name. * * @param func : a string that uniquely characterizes the ground speed sensor * * @return a YGroundSpeed object allowing you to drive the ground speed sensor. */ public static YGroundSpeed FindGroundSpeed(String func) { YGroundSpeed obj; synchronized (YAPI.class) { obj = (YGroundSpeed) YFunction._FindFromCache("GroundSpeed", func); if (obj == null) { obj = new YGroundSpeed(func); YFunction._AddToCache("GroundSpeed", func, obj); } } return obj; } /** * Retrieves a ground speed sensor for a given identifier in a YAPI context. * The identifier can be specified using several formats: * <ul> * <li>FunctionLogicalName</li> * <li>ModuleSerialNumber.FunctionIdentifier</li> * <li>ModuleSerialNumber.FunctionLogicalName</li> * <li>ModuleLogicalName.FunctionIdentifier</li> * <li>ModuleLogicalName.FunctionLogicalName</li> * </ul> * * This function does not require that the ground speed sensor is online at the time * it is invoked. The returned object is nevertheless valid. * Use the method YGroundSpeed.isOnline() to test if the ground speed sensor is * indeed online at a given time. In case of ambiguity when looking for * a ground speed sensor by logical name, no error is notified: the first instance * found is returned. The search is performed first by hardware name, * then by logical name. * * @param yctx : a YAPI context * @param func : a string that uniquely characterizes the ground speed sensor * * @return a YGroundSpeed object allowing you to drive the ground speed sensor. */ public static YGroundSpeed FindGroundSpeedInContext(YAPIContext yctx,String func) { YGroundSpeed obj; synchronized (yctx) { obj = (YGroundSpeed) YFunction._FindFromCacheInContext(yctx, "GroundSpeed", func); if (obj == null) { obj = new YGroundSpeed(yctx, func); YFunction._AddToCache("GroundSpeed", func, obj); } } return obj; } /** * Registers the callback function that is invoked on every change of advertised value. * The callback is invoked only during the execution of ySleep or yHandleEvents. * This provides control over the time when the callback is triggered. For good responsiveness, remember to call * one of these two functions periodically. To unregister a callback, pass a null pointer as argument. * * @param callback : the callback function to call, or a null pointer. The callback function should take two * arguments: the function object of which the value has changed, and the character string describing * the new advertised value. * */ public int registerValueCallback(UpdateCallback callback) { String val; if (callback != null) { YFunction._UpdateValueCallbackList(this, true); } else { YFunction._UpdateValueCallbackList(this, false); } _valueCallbackGroundSpeed = callback; // Immediately invoke value callback with current value if (callback != null && isOnline()) { val = _advertisedValue; if (!(val.equals(""))) { _invokeValueCallback(val); } } return 0; } @Override public int _invokeValueCallback(String value) { if (_valueCallbackGroundSpeed != null) { _valueCallbackGroundSpeed.yNewValue(this, value); } else { super._invokeValueCallback(value); } return 0; } /** * Registers the callback function that is invoked on every periodic timed notification. * The callback is invoked only during the execution of ySleep or yHandleEvents. * This provides control over the time when the callback is triggered. For good responsiveness, remember to call * one of these two functions periodically. To unregister a callback, pass a null pointer as argument. * * @param callback : the callback function to call, or a null pointer. The callback function should take two * arguments: the function object of which the value has changed, and an YMeasure object describing * the new advertised value. * */ public int registerTimedReportCallback(TimedReportCallback callback) { YSensor sensor; sensor = this; if (callback != null) { YFunction._UpdateTimedReportCallbackList(sensor, true); } else { YFunction._UpdateTimedReportCallbackList(sensor, false); } _timedReportCallbackGroundSpeed = callback; return 0; } @Override public int _invokeTimedReportCallback(YMeasure value) { if (_timedReportCallbackGroundSpeed != null) { _timedReportCallbackGroundSpeed.timedReportCallback(this, value); } else { super._invokeTimedReportCallback(value); } return 0; } /** * Continues the enumeration of ground speed sensors started using yFirstGroundSpeed(). * * @return a pointer to a YGroundSpeed object, corresponding to * a ground speed sensor currently online, or a null pointer * if there are no more ground speed sensors to enumerate. */ public YGroundSpeed nextGroundSpeed() { String next_hwid; try { String hwid = _yapi._yHash.resolveHwID(_className, _func); next_hwid = _yapi._yHash.getNextHardwareId(_className, hwid); } catch (YAPI_Exception ignored) { next_hwid = null; } if(next_hwid == null) return null; return FindGroundSpeedInContext(_yapi, next_hwid); } /** * Starts the enumeration of ground speed sensors currently accessible. * Use the method YGroundSpeed.nextGroundSpeed() to iterate on * next ground speed sensors. * * @return a pointer to a YGroundSpeed object, corresponding to * the first ground speed sensor currently online, or a null pointer * if there are none. */ public static YGroundSpeed FirstGroundSpeed() { YAPIContext yctx = YAPI.GetYCtx(false); if (yctx == null) return null; String next_hwid = yctx._yHash.getFirstHardwareId("GroundSpeed"); if (next_hwid == null) return null; return FindGroundSpeedInContext(yctx, next_hwid); } /** * Starts the enumeration of ground speed sensors currently accessible. * Use the method YGroundSpeed.nextGroundSpeed() to iterate on * next ground speed sensors. * * @param yctx : a YAPI context. * * @return a pointer to a YGroundSpeed object, corresponding to * the first ground speed sensor currently online, or a null pointer * if there are none. */ public static YGroundSpeed FirstGroundSpeedInContext(YAPIContext yctx) { String next_hwid = yctx._yHash.getFirstHardwareId("GroundSpeed"); if (next_hwid == null) return null; return FindGroundSpeedInContext(yctx, next_hwid); } //--- (end of YGroundSpeed implementation) }
bbecc895e609b96f9f1ddb0aaa1ef0fd020afb48
c5de69afc4f112d280f67536ddf2b3a13e24002a
/ndp-kernel/src/main/java/com/novbank/ndp/kernel/core/metadata/schema/SimpleClass.java
8e117f7aadceb2adb9b2116fee3fc1e45c3bf2ae
[ "Apache-2.0" ]
permissive
hitakaken/ndp
f381d95b8ff23a441cd9d4fe992053803c9e7f47
659ce2dd6dd8233a8a745fbe54ee0799c75879cc
refs/heads/master
2016-09-06T12:02:41.066243
2015-06-09T00:03:57
2015-06-09T00:03:57
35,423,284
1
0
null
null
null
null
UTF-8
Java
false
false
122
java
package com.novbank.ndp.kernel.core.metadata.schema; /** * Created by hp on 2015/5/27. */ public class SimpleClass { }
4c3ced6afd9ce4fd73a75f86de93879466781d45
0a371ccc1b4e5932dd1e6c2f8b8c8d345c98ee03
/src/main/java/com/hyf/servlet/http/HttpSessionListener.java
3a45c52c513c36215d52c1e09c248aa1a3cea426
[]
no_license
hyfsy/learn-servlet
4b31bf145132213389f5da256a10ac58a77b8a43
e6623009520e39888c6809ec6ae3309be55a121e
refs/heads/master
2023-04-18T03:17:14.631877
2021-04-18T06:42:50
2021-04-18T06:42:50
226,457,892
0
0
null
2020-10-13T18:02:25
2019-12-07T04:55:10
Java
UTF-8
Java
false
false
1,057
java
package com.hyf.servlet.http; import com.hyf.servlet.ServletContext; /** * 用于接收关于HttpSession生命周期更改的通知事件 * <p> * 为了接收这些通知事件,实现类必须在web应用程序的部署描述符中声明, * 并使用{@link com.hyf.servlet.annotation.WebListener}注解注释或通过定义在{@link ServletContext}上 * 的addListener方法之一注册 * <p> * 此接口的实现在其{@link #sessionCreated}方法中按声明的顺序调用, * 在其{@link #sessionDestroyed}方法中按相反的顺序调用 * * @see com.hyf.servlet.ServletContext#addListener * @see HttpSessionEvent */ public interface HttpSessionListener { /** * 接收创建会话的通知 * * @param event 设置包含会话的HttpSessionEvent */ void sessionCreated(HttpSessionEvent event); /** * 接收会话即将失效的通知 * * @param event 设置包含会话的HttpSessionEvent */ void sessionDestroyed(HttpSessionEvent event); }
95078a32532c54f1a443d4bab96b334ddac1ae3d
f6e94910c3f79cab62dfd889d73b076278ab748d
/GojekApp PratiktoAryaWicaksana/src/com/lawencon/service/GoSendServiceImpl.java
24af6dc71f03e82fab2f633d813abb6d7408112b
[]
no_license
tiktostarting/practice_java
cf0c3818612f1d9e6f16f5f432efea9103892ac0
31affa7d8b2232ca9c0088a37db37e915eaf4cda
refs/heads/main
2023-08-24T16:05:04.705773
2021-10-23T04:12:37
2021-10-23T04:12:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
624
java
package com.lawencon.service; import com.lawencon.model.Drivers; public class GoSendServiceImpl implements GoSendService { @Override public Integer calculatePrice(String source, String dest, String receiver, Integer weight, Integer qty, String type) { return defaultPrice * (type.length() + (weight * qty) / receiver.length()); } @Override public Drivers getDriver() { Drivers driver = new Drivers(); driver.setNama("Mr. Bean"); driver.setNoHp("77718281728"); driver.setPlatNo("B0000YAH"); return driver; } @Override public Integer analysisItem(Integer weight, Integer qty) { return null; } }
7fcf9222f4a53d39f88fc61a6d2533c59d85a482
22721368a5f76424e6f759d78e41740575f2ea75
/src/main/java/com/istiak/blooddb/utils/SimpleCORSFilter.java
dd4be75c067a7104ad3251bce90876ebeecda7be
[]
no_license
Istiakmorsalin/Spring-Boot-REST-API-BloodDB
6f0f4c47203279a39e3c811590d40d52333df5af
525abe6cf596a2a723261d43d101532b5c36834c
refs/heads/master
2021-08-26T04:54:49.259977
2021-08-23T22:07:20
2021-08-23T22:07:20
72,204,802
0
1
null
2017-06-07T11:40:59
2016-10-28T12:17:53
Java
UTF-8
Java
false
false
1,610
java
package com.istiak.blooddb.utils; /** * Created by Istiak-Morsalin on 6/7/2017. */ import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component public class SimpleCORSFilter implements Filter { private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class); public SimpleCORSFilter() { log.info("SimpleCORSFilter init"); } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.setHeader("Access-Control-Allow-Credentials", "true"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me"); chain.doFilter(req, res); } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } }
3c5bdea6397f0eb9757109b0e7ad52104c1c1352
c343802f337b1965d5c1bb997f3dbb5e46bdb188
/src/main/java/com/test/quiz/model/Question.java
0ec5dc4bd15f8cb6cda8316ead11c057f1792711
[]
no_license
akhrulenko/quiz
ef7642bcd6f711f7cd4fccf7889be95b42a2d25c
c3979ac87ee97b4088929b53077ca6e27933288f
refs/heads/master
2023-05-28T07:09:14.119823
2021-02-19T12:22:17
2021-02-19T12:22:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,216
java
package com.test.quiz.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; @Entity @Table(name = "questions") public class Question { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @JsonBackReference @ManyToOne(cascade = CascadeType.PERSIST) @JoinColumn(name = "quiz_id") private Quiz quiz; @Column private String text; @Column(name = "display_order") private Integer displayOrder; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Quiz getQuiz() { return quiz; } public void setQuiz(Quiz quiz) { this.quiz = quiz; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Integer getDisplayOrder() { return displayOrder; } public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder; } }
52811a78b5079b655c2162e2aaee7401fcf3a870
a7b5c58e5b5c92f8ac8230ba74bae5d974649ec8
/src/com/javarush/test/level08/lesson11/home01/Solution.java
af09d03a533770a2cd96534572a11b249f804d6f
[]
no_license
olegmur/Rush
956d650118a703f3f5c2e12a5edb450203764172
eb07f73a804d078ed3d4e73980457fefdf7849b1
refs/heads/master
2021-01-10T05:54:34.174926
2016-02-08T13:50:20
2016-02-08T13:50:20
50,169,429
0
0
null
null
null
null
UTF-8
Java
false
false
1,462
java
package com.javarush.test.level08.lesson11.home01; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /* Set из котов 1. Внутри класса Solution создать public static класс кот – Cat. 2. Реализовать метод createCats, он должен создавать множество (Set) котов и добавлять в него 3 кота. 3. В методе main удалите одного кота из Set cats. 4. Реализовать метод printCats, он должен вывести на экран всех котов, которые остались во множестве. Каждый кот с новой строки. */ public class Solution { public static void main(String[] args) { Set<Cat> cats = createCats(); Iterator<Cat> it = cats.iterator(); it.next(); it.remove(); printCats(cats); } public static Set<Cat> createCats() { Set<Cat> c = new HashSet<Cat>(); for (int i = 0; i < 3; i++) {c.add(new Cat());} // printCats(c); return c; } public static void printCats(Set<Cat> cats) { for (Cat x : cats) System.out.println(x.toString()); } public static class Cat { public Cat() {} //@Override //public String toString() //{ // return "Cat!"; //} } }
ec8339b9524e31ec3b7f363a7bbe51f8a05d7e63
6a95484a8989e92db07325c7acd77868cb0ac3bc
/modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201411/ActivateProducts.java
6bd1eb2069015f64d378f50108a904ca8d682e80
[ "Apache-2.0" ]
permissive
popovsh6/googleads-java-lib
776687dd86db0ce785b9d56555fe83571db9570a
d3cabb6fb0621c2920e3725a95622ea934117daf
refs/heads/master
2020-04-05T23:21:57.987610
2015-03-12T19:59:29
2015-03-12T19:59:29
33,672,406
1
0
null
2015-04-09T14:06:00
2015-04-09T14:06:00
null
UTF-8
Java
false
false
2,599
java
/** * ActivateProducts.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201411; /** * The action used to activate products. */ public class ActivateProducts extends com.google.api.ads.dfp.axis.v201411.ProductAction implements java.io.Serializable { public ActivateProducts() { } public ActivateProducts( java.lang.String productActionType) { super( productActionType); } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ActivateProducts)) return false; ActivateProducts other = (ActivateProducts) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ActivateProducts.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "ActivateProducts")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
673dc102d1e688bf6d4ca45d592653a71586761b
4266e5085a5632df04c63dc3b11b146ef4be40fa
/exercises/week2/exercise2/src/main/java/academy/everyonecodes/basicyml/Message.java
2238a53262cf9a2dcd144ecf48f2d560ad6196b5
[]
no_license
uanave/springboot-module
ab918e8e4d6b228dcabcfb1b040458eb9c705977
3842925501ef3f08add19ca7ed055a3f84260088
refs/heads/master
2022-12-27T17:29:22.130619
2020-10-13T14:04:33
2020-10-13T14:04:33
246,023,900
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package academy.everyonecodes.basicyml; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class Message { private final String message; public Message(@Value("${basic.message}") String message) { this.message = message; } public String get() { return message; } }
2948a4705258f4fe9847b2f4219fb20a52e869ee
aba6f7d04d9d8898263927dfb4eb5bb9d2e9449c
/app/src/main/java/android/edu/itunes_acdc/DetalleCancion.java
658b55d53b2ba24c7e4b6c6617f97b882f951a86
[]
no_license
jcobreti/Itunes_ACDC
ab8782df2faa415d6785ccb3f3ac1285ed337529
ce3cdae07049ba763927f268b1e05225ae62b778
refs/heads/master
2020-04-28T04:23:26.374835
2019-03-12T12:38:02
2019-03-12T12:38:02
174,976,605
1
0
null
null
null
null
UTF-8
Java
false
false
1,016
java
package android.edu.itunes_acdc; import android.edu.itunes_acdc.Utils.Cancion; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class DetalleCancion extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detalle_cancion); ActionBar actionBar=getSupportActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP); actionBar.setHomeAsUpIndicator(R.mipmap.ic_launcher); TextView textView=findViewById(R.id.texto); Bundle loadInfo = getIntent().getExtras(); Cancion cancion= (Cancion) loadInfo.getSerializable("cancion"); String id=cancion.getTrackId(); textView.setText("ID cancion Seleccionada: "+id); } }
340158630dedfe582f7cfb80f76c66670fa6d3b6
048f85f0c623a2225d212e511d0f6104277cb52a
/dsmanage/ds-manage-service/src/main/java/ds/service/impl/ItemForItemsServiceImpl.java
9371e947a823fadbbde59a2a0f945022e12fafcc
[]
no_license
Crepho/pro
64050470676e4e1b5a063f9d1f5216a911e54323
618e653b4ecb8762133a0a815593333da16e56c7
refs/heads/master
2020-04-14T20:52:16.570748
2018-12-25T09:23:10
2018-12-25T09:23:10
164,109,276
0
0
null
null
null
null
UTF-8
Java
false
false
1,211
java
package ds.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import ds.common.pojo.DataGridResult; import ds.mapper.ItemForItemsMapper; import ds.pojo.ItemForItems; import ds.pojo.ItemForItemsExample; import ds.service.ItemForItemsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ItemForItemsServiceImpl implements ItemForItemsService{ @Autowired private ItemForItemsMapper itemForItemsMapper; @Override public DataGridResult getItemForItemsByItemsId(long id,long page,long rows) { ItemForItemsExample itemForItemsExample=new ItemForItemsExample(); ItemForItemsExample.Criteria criteria=itemForItemsExample.createCriteria(); criteria.andItemsIdEqualTo(id); PageHelper.startPage((int)page,(int)rows); List<ItemForItems> list=itemForItemsMapper.selectByExample(itemForItemsExample); PageInfo<ItemForItems> pageInfo=new PageInfo<>(list); long total=pageInfo.getTotal(); DataGridResult dataGridResult=new DataGridResult(total,list); return dataGridResult; } }
432265ac6c6ba2a7bdca54fba6858f4af307d7c8
5e15ab3e12c5e59419cc957813a9faf8e0546ce8
/CellSim.java
7c6708361bd0f2d478242df7cd85994700646989
[]
no_license
emilysarinaorr/CellSimulator
aedfc37308f29430a3d231b098b0a8619f60876a
d764b34745ab041ec21c0396747e6cf12dbacd8d
refs/heads/master
2021-01-19T15:01:21.567940
2015-02-27T22:01:11
2015-02-27T22:01:11
31,437,955
0
0
null
null
null
null
UTF-8
Java
false
false
10,413
java
import java.util.Random; import java.util.Arrays; import java.awt.Color; public class CellSim{ public static void main(String[] args){ // Create a n x n 2-D character array representing the tissue sample // You can pick n // Write your code to test your methods here System.out.println("Enter an integer n to determine the dimensions of the grid: "); int n = IO.readInt(); while(n <= 1){ System.out.println("Enter an integer n to determine the dimensions of the grid: "); n = IO.readInt(); } CellSimGUI cellSimGUI = new CellSimGUI(n, 75); System.out.println("Enter the threshold: "); int threshold = IO.readInt(); while(threshold < 0 || threshold > 100){ System.out.println("Enter the threshold: "); threshold = IO.readInt(); } System.out.println("Enter the maximum rounds: "); int maxRounds = IO.readInt(); while(maxRounds <= 0){ System.out.println("Enter the maximum rounds: "); maxRounds = IO.readInt(); } System.out.println("Enter the frequency: "); int frequency = IO.readInt(); while(frequency <=0 || frequency > maxRounds){ System.out.println("Enter the frequency: "); frequency = IO.readInt(); } System.out.println("Enter percent of X agents as a percentage without the \"%\" sign: "); int percentX = IO.readInt(); while(percentX < 0 || percentX > 100){ System.out.println("Enter percent of X agents as a percentage without the \"%\" sign: "); percentX = IO.readInt(); } System.out.println("Enter percent blank cells as a percentage without the \"%\" sign: "); int percentBlank = IO.readInt(); while(percentBlank < 0 || percentBlank > 100){ System.out.println("Enter percent blank cells as a percentage without the \"%\" sign: "); percentBlank = IO.readInt(); } char[][] tissue = new char[n][n]; assignCellTypes(tissue, percentBlank, percentX); char[][] initialTissue = new char[tissue.length][tissue[0].length]; for(int i = 0; i < initialTissue.length; i++){ //stores initial tissue for(int j = 0; j < initialTissue[i].length; j++){ initialTissue[i][j] = tissue[i][j]; } } int i; int numMoved = 0; for(i = 1; i <= maxRounds; i++){ for(int j = 0; j < n; j++){ for(int k = 0; k < n; k++){ if(tissue[j][k] == 'X') cellSimGUI.setCell(j, k, Color.blue); if(tissue[j][k] == 'O') cellSimGUI.setCell(j, k, Color.green); if(tissue[j][k] == ' ') cellSimGUI.setCell(j, k, Color.red); } } if(boardSatisfied(tissue, threshold) == false){ numMoved += moveAllUnsatisfied(tissue, threshold); if(i%frequency == 0){ System.out.println("Round "+ i + ": "); printTissue(tissue); } }else if(boardSatisfied(tissue, threshold) == true){ break; } } System.out.println("The initial tissue sample is: "); printTissue(initialTissue); System.out.println("The final tissue sample is: "); printTissue(tissue); if(boardSatisfied(tissue, threshold) == true) System.out.println("This board was satisfied in " + (i-1) + " round(s)."); else if(boardSatisfied(tissue, threshold) == false){ double agentSatisfied = 0; double totalAgents = 0; double percentSatisfied = 0; for(int k = 0; k < tissue.length; k++){ for(int l = 0; l < tissue[k].length; l++){ if(tissue[k][l] != ' '){ totalAgents++; } if(isSatisfied(tissue, k, l, threshold) == true && tissue[k][l] != ' '){ agentSatisfied++; } } } percentSatisfied = (agentSatisfied*100/totalAgents); System.out.println("This board was not satisfied in " + maxRounds + " round(s), but " + percentSatisfied + "% " + "of the agents in the tissue sample were satisfied."); } System.out.println("There was/were " + numMoved + " movement(s) that occurred in this simulation."); } /** * Given a tissue sample, prints the cell make up in grid form * * @param tissue a 2-D character array representing a tissue sample * ***/ public static void printTissue(char[][] tissue){ //Prints any 2D array. for(int i = 0; i < tissue.length; i++){ for(int j = 0; j < tissue[i].length; j++){ System.out.print(tissue[i][j] + "\t"); } System.out.println(); //Prints new line } } /** * Given a blank tissue sample, populate it with the correct cell makeup given the parameters. * Cell type 'X' will be represented by the character 'X' * Cell type 'O' will be represented by the character 'O' * Vacant spaces will be represented by the character ' ' * * Phase I: alternate X and O cells throughout, vacant cells at the "end" (50% credit) * e.g.: 'X' 'O' 'X' 'O' 'X' * 'O' 'X' 'O' 'X' 'O' * 'X' 'O' 'X' 'O' 'X' * ' ' ' ' ' ' ' ' ' ' * ' ' ' ' ' ' ' ' ' ' * * Phase II: Random assignment of all cells (100% credit) * * @param tissue a 2-D character array that has been initialized * @param percentBlank the percentage of blank cells that should appear in the tissue * @param percentX Of the remaining cells, not blank, the percentage of X cells that should appear in the tissue. Round up if not a whole number * **/ public static void assignCellTypes(char[][] tissue, int percentBlank, int percentX){ //Randomizes Xs, Os, and blanks //Your code goes here //given parameters Random r = new Random(); int row = 0; int col = 0; int rRow = r.nextInt(tissue.length); int rCol = r.nextInt(tissue.length); int numCells = (tissue.length * tissue.length); double numBlank = numCells * (percentBlank/100.0); //Determins # that need to be blank based off percentBlank parameter numBlank = Math.ceil(numBlank); double numX = (numCells-numBlank) * (percentX/100.0); //Determinds # that need to be Xs based off percentX parameter numX = Math.ceil(numX); double numO = numCells - (numBlank + numX); int countX = 0; while (countX < numX){ //randomizes and counts Xs rRow = r.nextInt(tissue.length); rCol = r.nextInt(tissue.length); if (tissue[rRow][rCol] == '\0'){ tissue[rRow][rCol] = 'X'; countX++; } } int countO = 0; while (countO < numO){ //randomizes and counts Os rRow = r.nextInt(tissue.length); rCol = r.nextInt(tissue.length); if (tissue[rRow][rCol] == '\0') { tissue[rRow][rCol] = 'O'; countO++; } } int countBlank = 0; //randomizes and counts blanks while (countBlank < numBlank){ rRow = r.nextInt(tissue.length); rCol = r.nextInt(tissue.length); if (tissue[rRow][rCol] == '\0'){ tissue[rRow][rCol] = ' '; countBlank++; } } } /** * Given a tissue sample, and a (row,col) index into the array, determines if the agent at that location is satisfied. * Note: Blank cells are always satisfied (as there is no agent) * * @param tissue a 2-D character array that has been initialized * @param row the row index of the agent * @param col the col index of the agent * @param threshold the percentage of like agents that must surround the agent to be satisfied * @return boolean indicating if given agent is satisfied * **/ public static boolean isSatisfied(char[][] tissue, int row, int col, int threshold){ int happy = 0; int n = 0; char element = tissue[row][col]; //element == X, O, blank if(element == ' ') //Blanks elements are always satisfied. return true; for(int i = -1; i <= 1; i++){ //Goes through rows for(int j = -1; j <= 1; j++){ //Goes through columns if(row+i == -1 || col+j == -1 || row+i > tissue.length-1 || col+j > tissue[0].length-1) //Skips boarders continue; if(row == row+i && col == col+j) //Skips the element continue; if(element == tissue[row+i][col+j]) happy++; if(tissue[row+i][col+j] != ' ') n++; } } if((happy*100) >= (threshold*n)) return true; return false; } // /** // * Given a tissue sample, determines if all agents are satisfied. // * Note: Blank cells are always satisfied (as there is no agent) // * // * @param tissue a 2-D character array that has been initialized // * @return boolean indicating whether entire board has been satisfied (all agents) // **/ public static boolean boardSatisfied(char[][] tissue, int threshold){ for(int i = 0; i < tissue.length; i++){ //Goes through rows for(int j = 0; j < tissue[i].length; j++){ //Goes through columns if(isSatisfied(tissue, i, j, threshold) == false){ //checks for element's satisfaction return false; } } } return true; } /** * Given a tissue sample, move all unsatisfied agents to a vacant cell * * @param tissue a 2-D character array that has been initialized * @param threshold the percentage of like agents that must surround the agent to be satisfied * @return an integer representing how many cells were moved in this round **/ public static int moveAllUnsatisfied(char[][] tissue, int threshold){ int count = 0; boolean[][] tempArray = new boolean[tissue.length][tissue[0].length]; if(boardSatisfied(tissue, threshold) == true) return count; for(int i = 0; i < tissue.length; i++){ for(int j = 0; j < tissue[i].length; j++){ tempArray[i][j] = isSatisfied(tissue, i, j, threshold); } } for(int k = 0; k < tempArray.length; k++){ for(int l = 0; l < tempArray[k].length; l++){ if(tempArray[k][l] == false){ count++; moveTo(tissue, k, l); } } } return count; } public static void moveTo(char[][] tissue, int i, int j){ for(int k = 0; k < tissue.length; k++){ for(int l = 0; l < tissue[k].length; l++){ if(tissue[k][l] == ' '){ tissue[k][l] = tissue[i][j]; tissue[i][j] = ' '; return; } } } } }
5e6026430b0166200f136f1b04e513502bbe1d27
a62801bf9452189b2937bb4fd116ec7fa0187250
/sp2p_shha.wechat/.svn/pristine/5e/5e6026430b0166200f136f1b04e513502bbe1d27.svn-base
f8059a7f9837e8a96b59da7a896851affe9b1f9b
[]
no_license
git-9522/play
da5cd4245cf5022a05ef426da80b6a6a013ea23b
2460fbbbd5616db960af68f422c4d40b88c586e9
refs/heads/master
2020-03-16T15:05:53.858084
2017-11-20T05:21:17
2017-11-20T05:21:17
132,727,879
0
3
null
null
null
null
UTF-8
Java
false
false
3,394
package dao.wechat; import java.util.HashMap; import java.util.Map; import models.common.entity.t_deal_user; import models.wechat.bean.WXUserFundInfo; import daos.common.UserDao; /** * 微信userdao拓展 * * @author liudong * @createDate 2016年5月9日 */ public class UserWechatDao extends UserDao { /** * 微信-查询用户资产信息 * (包含用户昵称) * * @param * @return * * @author liudong * @createDate 2016年5月9日 */ public WXUserFundInfo findUserFundInfo(String openId) { /** SQL: SELECT t.id AS id, t.name AS name, tuf.balance AS balance, (IFNULL((SELECT SUM(tbi.receive_interest) FROM t_bill_invest tbi WHERE tbi.user_id = t.id AND tbi.status = 1),0) - IFNULL((SELECT SUM(tdu.amount) FROM t_deal_user tdu WHERE tdu.operation_type =:invest_service_fee AND tdu.user_id = t.id),0) + IFNULL((SELECT SUM(tdu.amount) FROM t_deal_user tdu WHERE tdu.operation_type =:conversion AND tdu.user_id = t.id),0)) AS total_income, tuf.freeze AS freeze,tuf.visual_balance AS reward, (SELECT IFNULL(SUM(tbi.receive_corpus + tbi.receive_interest),0) FROM t_bill_invest tbi WHERE t.id = tbi.user_id AND tbi.status = 0) AS no_receive, (SELECT IFNULL(SUM(tb.repayment_corpus + tb.repayment_interest),0) FROM t_bill tb WHERE t.id = tb.user_id AND tb.status IN (0, 1)) AS no_repayment, (SELECT COUNT(1) FROM t_bill_invest tbi WHERE t.id = tbi.user_id AND tbi.status = 0) AS no_payment_count, (SELECT COUNT(1) FROM t_invest ti,t_bid tb WHERE ti.user_id = t.id AND tb.id = ti.bid_id AND tb.status IN (4, 5) AND ti.debt_id=0) AS invest_count FROM t_user t INNER JOIN t_user_fund tuf ON t.id = tuf.user_id INNER JOIN t_wechat_bind twb ON tuf.user_id = twb.user_id WHERE twb.open_id =:openId */ String sql = "SELECT t.id AS id,t.name AS name, tuf.balance AS balance,(IFNULL((SELECT SUM(tbi.receive_interest) FROM t_bill_invest tbi WHERE tbi.user_id = t.id AND tbi.status = 1),0) - IFNULL((SELECT SUM(tdu.amount) FROM t_deal_user tdu WHERE tdu.operation_type =:invest_service_fee AND tdu.user_id = t.id),0) + IFNULL((SELECT SUM(tdu.amount) FROM t_deal_user tdu WHERE tdu.operation_type =:conversion AND tdu.user_id = t.id),0)) AS total_income,tuf.freeze AS freeze,tuf.visual_balance AS reward,(SELECT IFNULL(SUM(tbi.receive_corpus + tbi.receive_interest),0) FROM t_bill_invest tbi WHERE t.id = tbi.user_id AND tbi.status = 0) AS no_receive,(SELECT IFNULL(SUM(tb.repayment_corpus + tb.repayment_interest),0) FROM t_bill tb WHERE t.id = tb.user_id AND tb.status IN (0, 1)) AS no_repayment,(SELECT COUNT(1) FROM t_bill_invest tbi WHERE t.id = tbi.user_id AND tbi.status = 0) AS no_payment_count,(SELECT COUNT(1) FROM t_invest ti, t_bid tb WHERE ti.user_id = t.id AND tb.id = ti.bid_id AND tb.status IN (4, 5) AND ti.debt_id=0) AS invest_count FROM t_user t INNER JOIN t_user_fund tuf ON t.id = tuf.user_id INNER JOIN t_wechat_bind twb ON tuf.user_id = twb.user_id WHERE twb.open_id =:openId"; Map<String, Object> condition = new HashMap<String, Object>(); condition.put("invest_service_fee", t_deal_user.OperationType.INVEST_SERVICE_FEE.code); condition.put("conversion", t_deal_user.OperationType.CONVERSION.code); condition.put("openId", openId); return findBeanBySQL(sql, WXUserFundInfo.class, condition); } }
80820fa4a0e87f132180a0747c611c54de59f7fc
9fae85def2d6721b1b9eea5ed463dc7af5714b94
/src/main/java/com/SecurityConfig.java
2e8b021dd4f184ba0ececa076e740ed71e091845
[]
no_license
ucsb-cs56-f19/springboot-postgres-flyway-migrations
f952b6cb4d1cbc433596b2bc2df5e391ed798812
d02f0d53e99ef89a959d02b4365cb7c5129a57c6
refs/heads/master
2022-02-28T17:22:26.137019
2019-11-06T00:38:09
2019-11-06T00:38:09
219,835,742
0
0
null
2022-01-21T23:33:35
2019-11-05T19:38:43
Java
UTF-8
Java
false
false
1,039
java
package com; import org.springframework.security.web.csrf.CsrfToken; //for csrf import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/user/**", "/user").permitAll(); //Even if you permit all, Postman will be forbidden for POST methods http.csrf().disable(); //disables csrf support so you won't get 403 forbiddens } }
ae398995c2563fc7e8bca25236422512d28073c2
1a8054ea97f51738517492790e83ddbcd33b04f9
/08_01_20/src/myonlineshop/Product.java
c39a0ca3754c4e683b77301619485319849bc7c4
[]
no_license
sakshiKkhatri/ctsfsd1
38c2cd7a616ab60076c6f9093c970cdff5579c74
a63e7350166f9aa262bb81573303b70ad7ed4566
refs/heads/master
2020-12-17T03:19:30.806084
2020-02-07T09:40:47
2020-02-07T09:40:47
235,282,132
0
0
null
2020-01-21T07:39:46
2020-01-21T07:39:45
null
UTF-8
Java
false
false
561
java
package myonlineshop; // Product class is now an abstract class public abstract class Product { private double regularPrice; /** Creates a new instance of Product */ public Product(double regularPrice) { this.regularPrice = regularPrice; } // computeSalePrice() is now an abstract method public abstract double computeSalePrice(); public double getRegularPrice() { return regularPrice; } public void setRegularPrice(double regularPrice) { this.regularPrice = regularPrice; } }
80cdf4f10d197aab45ed5a032dc2ec5a595c9bf3
48a6748db54943ad83e6d99258235d61b86798ee
/src/main/java/uk/ac/ebi/pride/utilities/data/core/Reference.java
9326c3d712c4669da5f5ab43da0b1f7d35b5401f
[]
no_license
ouyoungchao/protein02
548cf037bd926acc712942091e7c829f6e07b1ba
4c65b267b5095007ca4de8599bca7566bc35e6ad
refs/heads/master
2021-05-31T05:24:17.423577
2016-04-11T03:27:39
2016-04-11T03:27:39
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,177
java
package uk.ac.ebi.pride.utilities.data.core; import java.util.List; /** * Reference is added by PRIDE XML 2.0., also a generic reference for mzIdentML References. * <p/> * This object represents the information for MzIdentMl and PRIDE Reference Objects. * <p/> * @author Rui Wang * Date: 27-Jan-2010 * Time: 09:45:42 */ public class Reference extends IdentifiableParamGroup { /** * The names of the authors of the reference. */ private String authors; /** * The DOI of the referenced publication. */ private String doi; /** * The editor(s) of the reference. */ private String editor; /** * the full reference line used by PRIDE XML Objects */ private String fullReference; /** * The issue name or number. */ private String issue; /** * The page numbers. */ private String pages; /** * The name of the journal, book etc. */ private String publication; /** * The publisher of the publication. */ private String publisher; /** * The title of the BibliographicReference. */ private String title; /** * The volume name or number. */ private String volume; /** * The year of publication. */ private String year; public Reference(ParamGroup params, String fullReference) { this(params, null, null, null, null, null, null, null, null, null, null, null, null, fullReference); } public Reference(List<CvParam> cvParams, List<UserParam> userParams, String id, String name, String fullReference) { this(new ParamGroup(cvParams, userParams), id, name, null, null, null, null, null, null, null, null, null, null, fullReference); } public Reference(String id, String name, String doi, String title, String pages, String issue, String volume, String year, String editor, String publisher, String publication, String authors, String fullReference) { this(null, id, name, doi, title, pages, issue, volume, year, editor, publisher, publication, authors, fullReference); } public Reference(ParamGroup params, String id, String name, String doi, String title, String pages, String issue, String volume, String year, String editor, String publisher, String publication, String authors, String fullReference) { super(params, id, name); this.doi = doi; this.title = title; this.pages = pages; this.issue = issue; this.volume = volume; this.year = year; this.editor = editor; this.publisher = publisher; this.publication = publication; this.authors = authors; this.fullReference = fullReference; } public Reference(List<CvParam> cvParams, List<UserParam> userParams, String id, String name, String doi, String title, String pages, String issue, String volume, String year, String editor, String publisher, String publication, String authors, String fullReference) { this(new ParamGroup(cvParams, userParams), id, name, doi, title, pages, issue, volume, year, editor, publisher, publication, authors, fullReference); } public String getFullReference() { return fullReference; } public void setFullReference(String fullReference) { this.fullReference = fullReference; } public String getDoi() { return doi; } public void setDoi(String doi) { this.doi = doi; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getPages() { return pages; } public void setPages(String pages) { this.pages = pages; } public String getIssue() { return issue; } public void setIssue(String issue) { this.issue = issue; } public String getVolume() { return volume; } public void setVolume(String volume) { this.volume = volume; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getEditor() { return editor; } public void setEditor(String editor) { this.editor = editor; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public String getPublication() { return publication; } public void setPublication(String publication) { this.publication = publication; } public String getAuthors() { return authors; } public void setAuthors(String authors) { this.authors = authors; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Reference reference = (Reference) o; return !(authors != null ? !authors.equals(reference.authors) : reference.authors != null) && !(doi != null ? !doi.equals(reference.doi) : reference.doi != null) && !(editor != null ? !editor.equals(reference.editor) : reference.editor != null) && !(fullReference != null ? !fullReference.equals(reference.fullReference) : reference.fullReference != null) && !(issue != null ? !issue.equals(reference.issue) : reference.issue != null) && !(pages != null ? !pages.equals(reference.pages) : reference.pages != null) && !(publication != null ? !publication.equals(reference.publication) : reference.publication != null) && !(publisher != null ? !publisher.equals(reference.publisher) : reference.publisher != null) && !(title != null ? !title.equals(reference.title) : reference.title != null) && !(volume != null ? !volume.equals(reference.volume) : reference.volume != null) && !(year != null ? !year.equals(reference.year) : reference.year != null); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (authors != null ? authors.hashCode() : 0); result = 31 * result + (doi != null ? doi.hashCode() : 0); result = 31 * result + (editor != null ? editor.hashCode() : 0); result = 31 * result + (fullReference != null ? fullReference.hashCode() : 0); result = 31 * result + (issue != null ? issue.hashCode() : 0); result = 31 * result + (pages != null ? pages.hashCode() : 0); result = 31 * result + (publication != null ? publication.hashCode() : 0); result = 31 * result + (publisher != null ? publisher.hashCode() : 0); result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (volume != null ? volume.hashCode() : 0); result = 31 * result + (year != null ? year.hashCode() : 0); return result; } }
48043803254d6ca472b3f84398131c50a12dbc61
c2882688b3d1bb00785e745cce06063e5663afc7
/rest/client/client-impl/src/main/java/org/bndly/rest/client/impl/hateoas/UnknownResourceErrorExceptionThrowerStrategy.java
90c9c2216d690c70b78d2e91c7b4b52c9e0aeb28
[ "Apache-2.0" ]
permissive
bndly/bndly-commons
e04be01aabcb9e5ff6d15287a3cfa354054a26fe
6734e6a98f7e253ed225a4f2cce47572c5a969cb
refs/heads/master
2023-04-03T04:20:47.954354
2023-03-17T13:49:57
2023-03-17T13:49:57
275,222,708
1
2
Apache-2.0
2023-01-02T21:59:50
2020-06-26T18:31:34
Java
UTF-8
Java
false
false
1,371
java
package org.bndly.rest.client.impl.hateoas; /*- * #%L * REST Client Impl * %% * Copyright (C) 2013 - 2020 Cybercon GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import org.bndly.rest.atomlink.api.annotation.ErrorBean; import org.bndly.rest.client.api.ExceptionThrower; import org.bndly.rest.client.exception.ClientException; import org.bndly.rest.client.exception.UnknownResourceClientException; /** * * @author cybercon &lt;[email protected]&gt; */ public class UnknownResourceErrorExceptionThrowerStrategy implements ExceptionThrower.Strategy { @Override public void throwException(ErrorBean errorBean, ExceptionThrower.Context context) throws ClientException { if ("UnknownResourceError".equals(errorBean.getName())) { throw new UnknownResourceClientException(errorBean.getMessage(), context.getCause()); } } }
3263ec1b277240e96f4600ff987a0d4e52e265cd
18cfdc9c91ac787199017ff6ba8f1a77249ebd8b
/src/com/basic/Runtime.java
fefceff68b1349c1a69b051867a5f25bef85e145
[]
no_license
sakthiskv/javabasics
03511ecc5ce918957e08177cab9a41fc94e0d90d
92c239ee1b5e5df621e82f8302e9156b37afe24f
refs/heads/master
2020-03-18T21:12:08.443934
2018-06-27T13:08:08
2018-06-27T13:08:08
135,266,058
0
0
null
null
null
null
UTF-8
Java
false
false
556
java
package com.basic; import java.util.*; public class Runtime { public static void main(String args[]){ String input = "10 tea 20 coffee 30 tea buiscuits"; Scanner a = new Scanner(input).useDelimiter("\\s"); System.out.println(a.next()); System.out.println(a.next()); System.out.println(a.next()); System.out.println(a.next()); System.out.println(a.next()); System.out.println(a.next()); System.out.println(a.next()); a.close(); }}