hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
f5c9f94a98d35a58934ff5d4b523a73c14ac52f1 | 8,109 | /*
* Copyright 2016 Sebastian Kruse,
* code from: https://github.com/sekruse/profiledb-java.git
* Original license:
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.apache.wayang.commons.util.profiledb;
import org.apache.wayang.commons.util.profiledb.measurement.TestMemoryMeasurement;
import org.apache.wayang.commons.util.profiledb.measurement.TestTimeMeasurement;
import org.apache.wayang.commons.util.profiledb.model.Experiment;
import org.apache.wayang.commons.util.profiledb.model.Measurement;
import org.apache.wayang.commons.util.profiledb.model.Subject;
import org.apache.wayang.commons.util.profiledb.storage.FileStorage;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
public class ProfileDBTest {
@Test
public void testPolymorphSaveAndLoad() throws IOException {
File tempDir = Files.createTempDirectory("profiledb").toFile();
File file = new File(tempDir, "new-profiledb.json");
file.createNewFile();
FileStorage store = new FileStorage(file.toURI());
ProfileDB profileDB = new ProfileDB(store)
.registerMeasurementClass(TestMemoryMeasurement.class)
.registerMeasurementClass(TestTimeMeasurement.class);
final Experiment experiment = new Experiment("test-xp", new Subject("PageRank", "1.0"), "test experiment");
Measurement timeMeasurement = new TestTimeMeasurement("exec-time", 12345L);
Measurement memoryMeasurement = new TestMemoryMeasurement("exec-time", System.currentTimeMillis(), 54321L);
experiment.addMeasurement(timeMeasurement);
experiment.addMeasurement(memoryMeasurement);
// Save the experiment.
byte[] buffer;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
profileDB.save(Collections.singleton(experiment), bos);
bos.close();
buffer = bos.toByteArray();
System.out.println("Buffer contents: " + new String(buffer, "UTF-8"));
// Load the experiment.
ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
Collection<Experiment> loadedExperiments = profileDB.load(bis);
// Compare the experiments.
Assert.assertEquals(1, loadedExperiments.size());
Experiment loadedExperiment = loadedExperiments.iterator().next();
Assert.assertEquals(experiment, loadedExperiment);
// Compare the measurements.
Assert.assertEquals(2, loadedExperiment.getMeasurements().size());
Set<Measurement> expectedMeasurements = new HashSet<>(2);
expectedMeasurements.add(timeMeasurement);
expectedMeasurements.add(memoryMeasurement);
Set<Measurement> loadedMeasurements = new HashSet<>(loadedExperiment.getMeasurements());
Assert.assertEquals(expectedMeasurements, loadedMeasurements);
}
@Test
public void testRecursiveSaveAndLoad() throws IOException {
File tempDir = Files.createTempDirectory("profiledb").toFile();
File file = new File(tempDir, "new-profiledb.json");
file.createNewFile();
FileStorage store = new FileStorage(file.toURI());
ProfileDB profileDB = new ProfileDB(store)
.registerMeasurementClass(TestMemoryMeasurement.class)
.registerMeasurementClass(TestTimeMeasurement.class);
// Create an example experiment.
final Experiment experiment = new Experiment("test-xp", new Subject("PageRank", "1.0"), "test experiment");
TestTimeMeasurement topLevelMeasurement = new TestTimeMeasurement("exec-time", 12345L);
TestTimeMeasurement childMeasurement = new TestTimeMeasurement("sub-exec-time", 2345L);
topLevelMeasurement.addSubmeasurements(childMeasurement);
experiment.addMeasurement(topLevelMeasurement);
// Save the experiment.
byte[] buffer;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
profileDB.save(Collections.singleton(experiment), bos);
bos.close();
buffer = bos.toByteArray();
System.out.println("Buffer contents: " + new String(buffer, "UTF-8"));
// Load the experiment.
ByteArrayInputStream bis = new ByteArrayInputStream(buffer);
Collection<Experiment> loadedExperiments = profileDB.load(bis);
// Compare the experiments.
Assert.assertEquals(1, loadedExperiments.size());
Experiment loadedExperiment = loadedExperiments.iterator().next();
Assert.assertEquals(experiment, loadedExperiment);
// Compare the measurements.
Assert.assertEquals(1, loadedExperiment.getMeasurements().size());
final Measurement loadedMeasurement = loadedExperiment.getMeasurements().iterator().next();
Assert.assertEquals(topLevelMeasurement, loadedMeasurement);
}
@Test
public void testFileOperations() throws IOException {
File tempDir = Files.createTempDirectory("profiledb").toFile();
File file = new File(tempDir, "profiledb.json");
file.createNewFile();
FileStorage store = new FileStorage(file.toURI());
ProfileDB profileDB = new ProfileDB(store)
.registerMeasurementClass(TestMemoryMeasurement.class)
.registerMeasurementClass(TestTimeMeasurement.class);
// Create example experiments.
final Experiment experiment1 = new Experiment("xp1", new Subject("PageRank", "1.0"), "test experiment 1");
experiment1.addMeasurement(new TestTimeMeasurement("exec-time", 1L));
final Experiment experiment2 = new Experiment("xp2", new Subject("KMeans", "1.1"), "test experiment 2");
experiment2.addMeasurement(new TestTimeMeasurement("exec-time", 2L));
final Experiment experiment3 = new Experiment("xp3", new Subject("Apriori", "2.0"), "test experiment 3");
experiment3.addMeasurement(new TestMemoryMeasurement("ram", System.currentTimeMillis(), 3L));
// Save the experiments.
profileDB.save(experiment1);
profileDB.append(experiment2, experiment3);
Files.lines(file.toPath()).forEach(System.out::println);
// Load and compare.
final Set<Experiment> loadedExperiments = new HashSet<>(profileDB.load());
final List<Experiment> expectedExperiments = Arrays.asList(experiment1, experiment2, experiment3);
Assert.assertEquals(expectedExperiments.size(), loadedExperiments.size());
Assert.assertEquals(new HashSet<>(expectedExperiments), new HashSet<>(loadedExperiments));
}
@Test
public void testAppendOnNonExistentFile() throws IOException {
File tempDir = Files.createTempDirectory("profiledb").toFile();
File file = new File(tempDir, "new-profiledb.json");
file.createNewFile();
FileStorage store = new FileStorage(file.toURI());
// This seems to be an issue on Linux.
ProfileDB profileDB = new ProfileDB(store)
.registerMeasurementClass(TestMemoryMeasurement.class)
.registerMeasurementClass(TestTimeMeasurement.class);
// Create example experiments.
final Experiment experiment1 = new Experiment("xp1", new Subject("PageRank", "1.0"), "test experiment 1");
experiment1.addMeasurement(new TestTimeMeasurement("exec-time", 1L));
// Save the experiments.
Assert.assertTrue(!file.exists() || file.delete());
profileDB.append(experiment1);
Files.lines(file.toPath()).forEach(System.out::println);
// Load and compare.
final Set<Experiment> loadedExperiments = new HashSet<>(profileDB.load());
final List<Experiment> expectedExperiments = Collections.singletonList(experiment1);
Assert.assertEquals(expectedExperiments.size(), loadedExperiments.size());
Assert.assertEquals(new HashSet<>(expectedExperiments), new HashSet<>(loadedExperiments));
}
}
| 45.301676 | 115 | 0.70132 |
18947534f951382d4991944bebe94cdcd6e65df7 | 869 | package get.set;
/**
* Created by soumyay on 7/23/2016.
*/
public class CourseGetSet {
String easysubscribedon;
String intermediatesubscribedon;
String advancedsubscribedon;
public String getEasysubscribedon() {
return easysubscribedon;
}
public void setEasysubscribedon(String easysubscribedon) {
this.easysubscribedon = easysubscribedon;
}
public String getIntermediatesubscribedon() {
return intermediatesubscribedon;
}
public void setIntermediatesubscribedon(String intermediatesubscribedon) {
this.intermediatesubscribedon = intermediatesubscribedon;
}
public String getAdvancedsubscribedon() {
return advancedsubscribedon;
}
public void setAdvancedsubscribedon(String advancedsubscribedon) {
this.advancedsubscribedon = advancedsubscribedon;
}
}
| 24.828571 | 78 | 0.726122 |
c5c5b8bab3954a81d377a75614d1ecb3883ed8d2 | 5,157 | package csv2html;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* 属性リスト:情報テーブルを入出力する際の属性情報を記憶。
*
* @author Okayama Kodai (Created by Aoki Atsushi)
* @version 3.0.0
*/
abstract class Attributes extends Object {
/**
* ベースとなるディレクトリを記憶する(クラス変数)フィールド。
*/
private static String baseDirectory = null;
/**
* 属性リストのキー群を記憶する(インスタンス変数)フィールド。
*/
private List<String> keys;
/**
* 属性リストの名前群を記憶する(インスタンス変数)フィールド。
*/
private List<String> names;
/**
* 属性リストを作成するコンストラクタ。
*/
public Attributes() {
super();
this.keys = Collections.synchronizedList(new ArrayList<String>());
this.names = Collections.synchronizedList(new ArrayList<String>());
return;
}
/**
* 指定されたインデックスに対応する名前を応答する。名前が無いときはキーを応答する。
* @param index インデックス
* @return 名前(キー)
*/
protected String at(int index) {
String aString = this.nameAt(index);
if (aString.length() < 1) {
aString = this.keyAt(index);
}
return aString;
}
/**
* 標題文字列を応答する。
* @return 標題文字列
*/
abstract String captionString();
/**
* ページのためのディレクトリを応答する。
* @return ページのためのディレクトリ
*/
abstract String baseDirectory();
/**
* ページのためのディレクトリ(存在しなければ作成して)を応答する。
* @param kindString 種別を表す文字列
* @return ページのためのディレクトリ
*/
public String baseDirectory(String kindString) {
// ベースとなるディレクトリ(ページを生成するためのフォルダ)の記憶が水に流されるまで
// シングルトン(1回だけ)であることを保証する。
if (Attributes.baseDirectory != null) {
return Attributes.baseDirectory;
}
Date aDate = new Date();
// SimpleDateFormat aFormat = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat aFormat = new SimpleDateFormat("yyyyMMdd");
String dateString = aFormat.format(aDate);
String aString = System.getProperty("user.home");
aString = aString + File.separator + "Desktop";
aString = aString + File.separator + "CSV2HTML_" + kindString + "_" + dateString;
File aDirectory = new File(aString);
// ページのためのディレクトリが存在するならば消去しておく。
if (aDirectory.exists()) {
IO.deleteFileOrDirectory(aDirectory);
}
aDirectory.mkdirs();
Attributes.baseDirectory = aDirectory.getPath() + File.separator;
return Attributes.baseDirectory;
}
/**
* 情報の在処(URL)を文字列で応答する。
* @return 情報の在処の文字列
*/
abstract String baseUrl();
/**
* 情報を記したCSVファイルの在処(URL)を文字列で応答する。
* @return 情報を記したCSVファイル文字列
*/
abstract String csvUrl();
/**
* ページのためのローカルなHTMLのインデックスファイル(index.html)を文字列で応答する。
* @return ページのためのローカルなHTMLのインデックスファイル文字列
*/
public String indexHTML() {
return "index.html";
}
/**
* ベースとなるディレクトリの記憶を水に流す。
*/
public static void flushBaseDirectory() {
Attributes.baseDirectory = null;
return;
}
/**
* 指定されたキー文字列のインデックスを応答する。
* @param aString キー
* @return インデックス
*/
protected int indexOf(String aString) {
int index = 0;
for (String aKey : this.keys) {
if (aString.compareTo(aKey) == 0) {
return index;
}
index++;
}
return -1;
}
/**
* 在位日数のインデックスを応答する。
* @return インデックス
*/
public int indexOfDays() {
return this.indexOf("days");
}
/**
* 画像のインデックスを応答する。
* @return インデックス
*/
public int indexOfImage() {
return this.indexOf("image");
}
/**
* ふりがなのインデックスを応答する。
* @return インデックス
*/
public int indexOfKana() {
return this.indexOf("kana");
}
/**
* 氏名のインデックスを応答する。
* @return インデックス
*/
public int indexOfName() {
return this.indexOf("name");
}
/**
* 番号のインデックスを応答する。
* @return インデックス
*/
public int indexOfNo() {
return this.indexOf("no");
}
/**
* 在位期間のインデックスを応答する。
* @return インデックス
*/
public int indexOfPeriod() {
return this.indexOf("period");
}
/**
* 縮小画像のインデックスを応答する。
* @return インデックス
*/
public int indexOfThumbnail() {
return this.indexOf("thumbnail");
}
/**
* 指定されたインデックスに対応するキーを応答する。
* @param index インデックス
* @return キー
*/
protected String keyAt(int index) {
return this.keys().get(index);
}
/**
* キー群を応答する。
* @return キー群
*/
public List<String> keys() {
return this.keys;
}
/**
* 指定されたインデックスに対応する名前を応答する。
* @param index インデックス
* @return 名前
*/
protected String nameAt(int index) {
return this.names().get(index);
}
/**
* 名前群を応答する。
* @return 名前群
*/
public List<String> names() {
return this.names;
}
/**
* 名前群を設定する。
* @param aCollection 名前群
*/
public void names(List<String> aCollection) {
List<String> aList = Collections.synchronizedList(new ArrayList<String>());
for (String aString : aCollection) {
aList.add(aString);
}
this.names = aList;
return;
}
/**
* 属性リストの長さを応答する。
* @return 属性リストの長さ
*/
public int size() {
return this.keys().size();
}
/**
* タイトル文字列を応答する。
* @return タイトル文字列
*/
abstract String titleString();
/**
* 自分自身を文字列にして、それを応答する。
* @return 自分自身の文字列
*/
public String toString() {
StringBuffer aBuffer = new StringBuffer();
Class<?> aClass = this.getClass();
aBuffer.append(aClass.getName());
aBuffer.append("[");
for (int index = 0; index < this.size(); index++) {
if (index != 0) {
aBuffer.append(",");
}
aBuffer.append(this.at(index));
}
aBuffer.append("]");
return aBuffer.toString();
}
}
| 18.031469 | 83 | 0.656389 |
bf1861dcdcded26afbdb2d4e445830637f89e854 | 1,708 | package no.nav.vedtak.felles.prosesstask.api;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.enterprise.inject.Stereotype;
import javax.inject.Qualifier;
import no.nav.vedtak.felles.jpa.Transaction;
/**
* Marker type som implementerer interface {@link ProsessTaskHandler}.<br>
* Dette er en CDI stereotype som også angir at den skal kjøres i en transaksjon.
* <p>
* <h3>Eksempel</h3>
* Merk skal ha både {@link ProsessTask} annotation + {@link ProsessTaskHandler} interface!!!
* <p>
* <p>
* <pre>
* @Dependent
* @ProsessTask("vuin.happyTask")
* public class HappyTask implements ProsessTaskHandler {
*
* private static final Logger log = LoggerFactory.getLogger(HappyTask.class);
*
* @Override
* public void doTask(ProsessTaskData prosessTaskData) {
* log.info("I am a HAPPY task :-)");
* }
*
* }
* </pre>
* <p>
* Denne må matche ett innslag i <code>PROSESS_TASK_TYPE</code> tabell for å kunne kjøres. <br/>
* En konkret kjøring utføres
* ved å registrere typen i tillegg i <code>PROSESS_TASK</code> tabellen.
*/
@Qualifier
@Stereotype
@Transaction
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Documented
public @interface ProsessTask {
/**
* Settes til task type, slik det er definert i PROSESS_TASK_TYPE tabell.
* Markerer implementasjonen slik at det kan oppdages runtime.
* <p>
* Må spesifiseres.
*/
String value();
}
| 28.466667 | 96 | 0.723068 |
ad854b141662a2aeac5cad6961e4c796714615d6 | 1,440 | // ============================================================================
//
// Copyright (C) 2006-2018 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.commons.utils.data.text;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.talend.commons.utils.data.text.StringHelper;
/**
* DOC amaumont class global comment. Detailled comment <br/>
*
* $Id: StringHelperTest.java 38013 2010-03-05 14:21:59Z mhirt $
*
*/
public class StringHelperTest {
/**
* Test method for
* {@link org.talend.designer.mapper.utils.StringHelper#replacePrms(java.lang.String, java.lang.Object[])}.
*/
@Test
public void testReplacePrms() {
assertEquals("abcdef", StringHelper.replacePrms("a{0}{1}d{2}f", new Object[] { "b", "c", "e" })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
assertEquals("ab\\{c\\}def", StringHelper.replacePrms("a{0}\\{{1}\\}d{2}f", new Object[] { "b", "c", "e" })); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
}
}
| 36.923077 | 187 | 0.583333 |
99bb303e401f52f5cb1caf2bb9289bf214ea5e41 | 5,635 | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.siddhi.extension.io.nats.sink.nats;
import io.nats.client.Connection;
import io.nats.client.ConnectionListener;
import io.nats.client.Nats;
import io.nats.client.Options;
import io.siddhi.core.exception.ConnectionUnavailableException;
import io.siddhi.core.util.transport.DynamicOptions;
import io.siddhi.core.util.transport.Option;
import io.siddhi.core.util.transport.OptionHolder;
import io.siddhi.extension.io.nats.util.NATSConstants;
import io.siddhi.extension.io.nats.util.NATSUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A class which use to create and handle nats client for publishing message.
*/
public class NATSCore {
private static final Logger log = Logger.getLogger(NATSCore.class);
protected Option destination;
protected String[] natsUrls;
protected String streamId;
protected String siddhiAppName;
protected Options.Builder natsOptionBuilder;
protected Connection connection;
protected AtomicBoolean isConnected = new AtomicBoolean(true);
protected String authType;
public void initiateClient(OptionHolder optionHolder, String siddhiAppName, String streamId) {
this.destination = optionHolder.validateAndGetOption(NATSConstants.DESTINATION);
String serverUrls;
if (optionHolder.isOptionExists(NATSConstants.BOOTSTRAP_SERVERS)) {
serverUrls = optionHolder.validateAndGetStaticValue(NATSConstants.BOOTSTRAP_SERVERS);
} else {
serverUrls = optionHolder.validateAndGetStaticValue(NATSConstants.SERVER_URLS);
}
natsUrls = serverUrls.split(",");
for (String url: natsUrls) {
NATSUtils.validateNatsUrl(url, siddhiAppName);
}
this.siddhiAppName = siddhiAppName;
this.streamId = streamId;
Properties properties = new Properties();
if (optionHolder.isOptionExists(NATSConstants.OPTIONAL_CONFIGURATION)) {
String optionalConfigs = optionHolder.validateAndGetStaticValue(NATSConstants.OPTIONAL_CONFIGURATION);
NATSUtils.splitHeaderValues(optionalConfigs, properties);
}
natsOptionBuilder = new Options.Builder(properties);
natsOptionBuilder.servers(this.natsUrls);
if (optionHolder.isOptionExists(NATSConstants.AUTH_TYPE)) {
authType = optionHolder.validateAndGetStaticValue(NATSConstants.AUTH_TYPE);
NATSUtils.addAuthentication(optionHolder, natsOptionBuilder, authType, siddhiAppName, streamId);
}
}
public void createNATSClient() throws ConnectionUnavailableException {
natsOptionBuilder.connectionListener((conn, type) -> {
if (type == ConnectionListener.Events.CLOSED) {
isConnected = new AtomicBoolean(false);
}
});
this.connection = createNatsConnection();
isConnected.set(true);
}
public void publishMessages(Object payload, byte[] messageBytes, DynamicOptions dynamicOptions)
throws ConnectionUnavailableException {
if (!isConnected.get()) {
this.connection = createNatsConnection();
}
String subjectName = destination.getValue(dynamicOptions);
connection.publish(subjectName, messageBytes);
}
public void disconnect() {
if (connection != null) {
if (isConnected.get()) {
try {
connection.flush(Duration.ofMillis(50));
connection.close();
} catch (TimeoutException | InterruptedException e) {
log.error("Error disconnecting the nats receiver in Siddhi App '" + siddhiAppName +
"' when publishing messages to NATS endpoint " + Arrays.toString(natsUrls) + " . " +
e.getMessage(), e);
}
}
}
}
private Connection createNatsConnection() throws ConnectionUnavailableException {
try {
return Nats.connect(natsOptionBuilder.build());
} catch (IOException e) {
throw new ConnectionUnavailableException("Error in Siddhi App '" + siddhiAppName + "' while connecting to "
+ "NATS server endpoint " + Arrays.toString(natsUrls) + " at destination: " + destination.getValue()
, e);
} catch (InterruptedException e) {
throw new ConnectionUnavailableException("Error in Siddhi App '" + siddhiAppName + "' while connecting to" +
" NATS server endpoint " + Arrays.toString(natsUrls) + " at destination: " +
destination.getValue() + ". The calling thread is interrupted before the connection " +
"can be established.", e);
}
}
}
| 43.015267 | 120 | 0.677196 |
155a8dffcf946d2487215acc2ae94aa7a43b0602 | 1,277 | package br.com.zupacademy.adriano.casadocodigo.controller;
import br.com.zupacademy.adriano.casadocodigo.controller.form.CategoriaForm;
import br.com.zupacademy.adriano.casadocodigo.model.Categoria;
import br.com.zupacademy.adriano.casadocodigo.repository.CategoriaRepository;
import br.com.zupacademy.adriano.casadocodigo.validator.NomeCategoriaDuplicadoValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/categorias")
public class CategoriaController {
private final CategoriaRepository categoriaRepository;
private final NomeCategoriaDuplicadoValidator nomeCategoriaDuplicado;
public CategoriaController(CategoriaRepository categoriaRepository, NomeCategoriaDuplicadoValidator nomeCategoriaDuplicado) {
this.categoriaRepository = categoriaRepository;
this.nomeCategoriaDuplicado = nomeCategoriaDuplicado;
}
@PostMapping
@Transactional
public void cadastrar(@RequestBody @Valid CategoriaForm categoriaForm) throws Exception {
Categoria categoria = categoriaForm.toModel();
categoriaRepository.save(categoria);
}
}
| 38.69697 | 129 | 0.821457 |
4d05bdb869dab9e3db96f97cf9d14d30b16d581a | 6,487 | /*
* This file is part of ThermalRecycling, licensed under the MIT License (MIT).
*
* Copyright (c) OreCruncher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.blockartistry.mod.ThermalRecycling.support.handlers;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.util.Constants;
import org.blockartistry.mod.ThermalRecycling.data.ScrapHandler;
import org.blockartistry.mod.ThermalRecycling.util.ItemStackHelper;
import org.blockartistry.mod.ThermalRecycling.util.MyUtils;
import com.google.common.collect.ImmutableList;
import buildcraft.api.transport.pluggable.IPipePluggableItem;
public final class BuildCraftGateScrapHandler extends ScrapHandler {
private static final ItemStack pulsatingChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:4").get();
private static final ItemStack quartzChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:5").get();
private static final ItemStack redstoneCompChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:6").get();
private static final List<ItemStack> basicGate;
private static final List<ItemStack> ironGate;
private static final List<ItemStack> goldGate;
private static final List<ItemStack> diamondGate;
private static final List<ItemStack> quartzGate;
private static final List<ItemStack> emeraldGate;
static {
final ItemStack redstoneChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset").get();
final ItemStack ironChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:1").get();
final ItemStack goldenChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:2").get();
final ItemStack diamondChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:3").get();
final ItemStack emeraldChipset = ItemStackHelper
.getItemStack("BuildCraft|Silicon:redstoneChipset:7").get();
final ItemStack redPipeWire = ItemStackHelper
.getItemStack("BuildCraft|Transport:pipeWire").get();
final ItemStack bluePipeWire = ItemStackHelper
.getItemStack("BuildCraft|Transport:pipeWire:1").get();
final ItemStack greenPipeWire = ItemStackHelper
.getItemStack("BuildCraft|Transport:pipeWire:2").get();
final ItemStack yellowPipeWire = ItemStackHelper
.getItemStack("BuildCraft|Transport:pipeWire:3").get();
basicGate = new ImmutableList.Builder<ItemStack>()
.add(redstoneChipset).build();
ironGate = new ImmutableList.Builder<ItemStack>()
.add(ironChipset)
.add(redPipeWire).build();
goldGate = new ImmutableList.Builder<ItemStack>()
.add(goldenChipset)
.add(redPipeWire)
.add(bluePipeWire).build();
diamondGate = new ImmutableList.Builder<ItemStack>()
.add(diamondChipset)
.add(redPipeWire)
.add(bluePipeWire)
.add(greenPipeWire)
.add(yellowPipeWire).build();
quartzGate = new ImmutableList.Builder<ItemStack>()
.add(quartzChipset)
.add(redPipeWire)
.add(bluePipeWire)
.add(greenPipeWire).build();
emeraldGate = new ImmutableList.Builder<ItemStack>()
.add(emeraldChipset)
.add(redPipeWire)
.add(bluePipeWire)
.add(greenPipeWire)
.add(yellowPipeWire).build();
}
private static final int MATERIAL_REDSTONE = 0;
private static final int MATERIAL_IRON = 1;
private static final int MATERIAL_GOLD = 2;
private static final int MATERIAL_DIAMOND = 3;
private static final int MATERIAL_EMERALD = 4;
private static final int MATERIAL_QUARTZ = 5;
private static int getMaterial(final ItemStack stack) {
int result = MATERIAL_REDSTONE;
if(stack.hasTagCompound()) {
final NBTTagCompound nbt = stack.getTagCompound();
result = nbt.getInteger("mat");
}
return result;
}
private static List<String> getExpansions(final ItemStack stack) {
final List<String> result = new ArrayList<String>();
if(stack.hasTagCompound()) {
final NBTTagCompound nbt = stack.getTagCompound();
final NBTTagList expansionList = nbt.getTagList("ex", Constants.NBT.TAG_STRING);
for (int i = 0; i < expansionList.tagCount(); i++) {
result.add(expansionList.getStringTagAt(i));
}
}
return result;
}
@Override
protected List<ItemStack> getRecipeOutput(final ScrappingContext ctx) {
final ItemStack stack = ctx.toProcess;
if (stack.getItem() instanceof IPipePluggableItem) {
final List<ItemStack> output = new ArrayList<ItemStack>();
final int mat = getMaterial(stack);
switch (mat) {
case MATERIAL_REDSTONE:
output.addAll(basicGate);
break;
case MATERIAL_IRON:
output.addAll(ironGate);
break;
case MATERIAL_GOLD:
output.addAll(goldGate);
break;
case MATERIAL_DIAMOND:
output.addAll(diamondGate);
break;
case MATERIAL_QUARTZ:
output.addAll(quartzGate);
break;
case MATERIAL_EMERALD:
output.addAll(emeraldGate);
break;
default:
;
}
for (final String id: getExpansions(stack)) {
if (id.compareTo("buildcraft:pulsar") == 0)
output.add(pulsatingChipset);
else if (id.compareTo("buildcraft:timer") == 0)
output.add(quartzChipset);
else if (id.compareTo("buildcraft:fader") == 0)
output.add(redstoneCompChipset);
}
return MyUtils.clone(output);
}
return super.getRecipeOutput(ctx);
}
}
| 33.096939 | 83 | 0.75027 |
cbdeee07238dd4ee6b49b60097a233cb6a2fa11b | 1,265 | package me.xiaolei.room_lite.runtime.sqlite;
import android.database.ContentObserver;
import android.net.Uri;
import androidx.annotation.Nullable;
import java.util.List;
public abstract class RoomLiteContentObserver extends ContentObserver
{
private final String dbName;
private final String tableName;
private final RoomLiteDatabase database;
public RoomLiteContentObserver(RoomLiteDatabase database, String tableName)
{
super(database.getHandler());
this.database = database;
this.dbName = database.getDatabaseName();
this.tableName = tableName;
}
@Override
public void onChange(boolean selfChange, @Nullable Uri uri)
{
if (uri == null)
return;
List<String> paths = uri.getPathSegments();
if (paths.size() != 2)
return;
String dbName = paths.get(0);
String tableName = paths.get(1);
if (this.dbName.equals(dbName) && this.tableName.equals(tableName))
{
super.onChange(selfChange, uri);
}
}
@Override
public boolean deliverSelfNotifications()
{
return super.deliverSelfNotifications();
}
@Override
public abstract void onChange(boolean selfChange);
}
| 25.3 | 79 | 0.66166 |
ab9e118bcbed03ebf4845f591b8d8c3afb989d5a | 839 | package com.logicaalternativa.forcomprehensions.poc.dummy;
import java.util.Scanner;
import com.logicaalternativa.forcomprehensions.option.AlterOption;
public class LanguageIOImpure implements LanguageIO {
public LanguageIOImpure() {
}
/* (non-Javadoc)
* @see com.logicaalternativa.forcomprehensions.poc.dummy.LanguageIO#read()
*/
@Override
public AlterOption<String> read(){
Scanner scanner = new Scanner(System.in);
System.out.println("Escribe: ");
String next = scanner.nextLine();
return AlterOption.some( next );
}
/* (non-Javadoc)
* @see com.logicaalternativa.forcomprehensions.poc.dummy.LanguageIO#echo(java.lang.String)
*/
@Override
public AlterOption<String> echo( String message ){
System.out.println( message );
return AlterOption.some( message );
}
}
| 19.511628 | 92 | 0.713945 |
3bdbe8f8c3a887e90e2b978a0c962f0aa8f82cb3 | 120 | @ParametersAreNonnullByDefault
package im.getsocial.demo.utils;
import javax.annotation.ParametersAreNonnullByDefault;
| 24 | 54 | 0.883333 |
a707b9b952be6577368c0282424bb4b3bc096e02 | 4,050 | package com.github.nagyesta.abortmission.strongback.rmi.stats;
import com.github.nagyesta.abortmission.core.healthcheck.StageStatisticsSnapshot;
import com.github.nagyesta.abortmission.core.healthcheck.impl.DefaultStageStatisticsSnapshot;
import java.io.Serializable;
import java.util.Objects;
import java.util.StringJoiner;
/**
* RMI specific serializable DTO replacement of the StageStatisticsSnapshot.
*/
public class RmiStageStatisticsSnapshot implements Serializable {
public static final long serialVersionUID = 1L;
private int failed;
private int succeeded;
private int aborted;
private int suppressed;
/**
* Default constructor for serialization.
*/
public RmiStageStatisticsSnapshot() {
}
/**
* Construct the instance and sets all of the fields to let this instance represent the recorded outcome of a matcher.
*
* @param failed The number of failed measurements.
* @param succeeded The number of success measurements.
* @param aborted The number of aborted measurements.
* @param suppressed The number of suppressed measurements.
*/
public RmiStageStatisticsSnapshot(final int failed, final int succeeded, final int aborted, final int suppressed) {
this.failed = failed;
this.succeeded = succeeded;
this.aborted = aborted;
this.suppressed = suppressed;
}
/**
* See {@link StageStatisticsSnapshot#getFailed()}.
*
* @return count
*/
public int getFailed() {
return failed;
}
/**
* Sets the number of failed cases.
*
* @param failed The count set.
*/
public void setFailed(final int failed) {
this.failed = failed;
}
/**
* See {@link StageStatisticsSnapshot#getSucceeded()}.
*
* @return count
*/
public int getSucceeded() {
return succeeded;
}
/**
* Sets the number of succeeded cases.
*
* @param succeeded The count set.
*/
public void setSucceeded(final int succeeded) {
this.succeeded = succeeded;
}
/**
* See {@link StageStatisticsSnapshot#getSuppressed()}.
*
* @return count
*/
public int getSuppressed() {
return suppressed;
}
/**
* Sets the number of suppressed cases.
*
* @param suppressed The count set.
*/
public void setSuppressed(final int suppressed) {
this.suppressed = suppressed;
}
/**
* See {@link StageStatisticsSnapshot#getAborted()}.
*
* @return count
*/
public int getAborted() {
return aborted;
}
/**
* Sets the number of aborted cases.
*
* @param aborted The count set.
*/
public void setAborted(final int aborted) {
this.aborted = aborted;
}
/**
* Converts back to the generic variant.
*
* @return snapshot
*/
public StageStatisticsSnapshot toStageStatisticsSnapshot() {
return new DefaultStageStatisticsSnapshot(failed, succeeded, aborted, suppressed);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RmiStageStatisticsSnapshot)) {
return false;
}
final RmiStageStatisticsSnapshot that = (RmiStageStatisticsSnapshot) o;
return failed == that.failed
&& succeeded == that.succeeded
&& aborted == that.aborted
&& suppressed == that.suppressed;
}
@Override
public int hashCode() {
return Objects.hash(failed, succeeded, aborted, suppressed);
}
@Override
public String toString() {
return new StringJoiner(", ", RmiStageStatisticsSnapshot.class.getSimpleName() + "[", "]")
.add("failed=" + failed)
.add("succeeded=" + succeeded)
.add("aborted=" + aborted)
.add("suppressed=" + suppressed)
.toString();
}
}
| 26.298701 | 122 | 0.613086 |
ea05b2fdb757cda8a861cbe009fa2aecc14ade05 | 282 | package daily._09_10;
public class NullpointerExceptionGenerator {
public static void main(String[] args) {
String str = null;
try {
str.concat(" world");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
}
| 21.692308 | 44 | 0.567376 |
bbb2c360cdadb640366aa72d505c57d45a65a3ab | 601 | package com.example.cropad;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class wheat extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wheat);
webView = (WebView) findViewById(R.id.webview3);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://ekheti.herokuapp.com/Wheat");
}
}
| 25.041667 | 62 | 0.737105 |
7737e6b49aa3e24759e956d2141a5027de7b6ed7 | 6,686 | /*
* Copyright (c) 2015-2019 Rocket Partners, LLC
* https://github.com/inversion-api
*
* 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 io.inversion.redis;
import io.inversion.ApiException;
import io.inversion.Collection;
import io.inversion.Db;
import io.inversion.Results;
import io.inversion.rql.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.List;
import java.util.Map;
public class RedisDb extends Db<RedisDb> {
protected final Logger log = LoggerFactory.getLogger(getClass());
protected transient JedisPool jedis = null;
// configurable props
protected String host = null;
protected int port = 6379;
protected int poolMin = 16;
protected int poolMax = 128;
protected boolean testOnBorrow = true;
protected boolean testOnReturn = true;
protected boolean testWhileIdle = true;
protected int minEvictableIdleTimeMillis = 60000;
protected int timeBetweenEvictionRunsMillis = 30000;
protected int numTestsPerEvictionRun = 3;
protected boolean blockWhenExhausted = true;
protected String nocacheParam = "nocache";
protected int readSocketTimeout = 2500; // time in milliseconds
protected int ttl = 15552000; // time to live 15,552,000s == 180 days
@Override
public Results doSelect(Collection table, List<Term> queryTerms) throws ApiException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<String> doUpsert(Collection table, List<Map<String, Object>> rows) throws ApiException {
// TODO Auto-generated method stub
return null;
}
@Override
public void delete(Collection table, List<Map<String, Object>> indexValues) throws ApiException {
// TODO Auto-generated method stub
}
protected Jedis getRedisClient() {
if (jedis == null) {
synchronized (this) {
if (jedis == null) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(this.poolMax);
poolConfig.setMaxIdle(this.poolMax);
poolConfig.setMinIdle(this.poolMin);
poolConfig.setTestOnBorrow(this.testOnBorrow);
poolConfig.setTestOnReturn(this.testOnReturn);
poolConfig.setTestWhileIdle(this.testWhileIdle);
poolConfig.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
poolConfig.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
poolConfig.setNumTestsPerEvictionRun(this.numTestsPerEvictionRun);
poolConfig.setBlockWhenExhausted(this.blockWhenExhausted);
jedis = new JedisPool(poolConfig, this.host, this.port, this.readSocketTimeout);
}
}
}
return jedis.getResource();
}
public String getHost() {
return host;
}
public RedisDb withHost(String host) {
this.host = host;
return this;
}
public int getPort() {
return port;
}
public RedisDb withPort(int port) {
this.port = port;
return this;
}
public int getPoolMin() {
return poolMin;
}
public RedisDb withPoolMin(int poolMin) {
this.poolMin = poolMin;
return this;
}
public int getPoolMax() {
return poolMax;
}
public RedisDb withPoolMax(int poolMax) {
this.poolMax = poolMax;
return this;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public RedisDb withTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
return this;
}
public boolean isTestOnReturn() {
return testOnReturn;
}
public RedisDb withTestOnReturn(boolean testOnReturn) {
this.testOnReturn = testOnReturn;
return this;
}
public boolean isTestWhileIdle() {
return testWhileIdle;
}
public RedisDb withTestWhileIdle(boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
return this;
}
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public RedisDb withMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
return this;
}
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public RedisDb withTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
return this;
}
public int getNumTestsPerEvictionRun() {
return numTestsPerEvictionRun;
}
public RedisDb withNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
this.numTestsPerEvictionRun = numTestsPerEvictionRun;
return this;
}
public boolean isBlockWhenExhausted() {
return blockWhenExhausted;
}
public RedisDb withBlockWhenExhausted(boolean blockWhenExhausted) {
this.blockWhenExhausted = blockWhenExhausted;
return this;
}
public String getNocacheParam() {
return nocacheParam;
}
public RedisDb withNocacheParam(String nocacheParam) {
this.nocacheParam = nocacheParam;
return this;
}
public int getReadSocketTimeout() {
return readSocketTimeout;
}
public RedisDb withReadSocketTimeout(int readSocketTimeout) {
this.readSocketTimeout = readSocketTimeout;
return this;
}
public int getTtl() {
return ttl;
}
public RedisDb withTtl(int ttl) {
this.ttl = ttl;
return this;
}
}
| 29.715556 | 116 | 0.64822 |
b330a63a1062e3abf3f85bdffcb6a38a7d27b4a0 | 247 | package io.github.vm.patlego.html.sample.submit.constants;
public class Submit {
private Submit() {
throw new IllegalStateException("Utility class");
}
public static final String SUBMIT_URL = "/submit/examples/html";
}
| 20.583333 | 68 | 0.692308 |
262c3bfad3737322b62faed27021d36fdad448a8 | 270 | package cemthecebi.application.model.response;
import cemthecebi.domain.model.vo.HomePageTvShowVo;
import lombok.Data;
import java.util.List;
@Data
public class RetrieveTvShowListResponse extends Response {
private List<HomePageTvShowVo> homePageTvShowVoList;
}
| 20.769231 | 58 | 0.825926 |
4c44ca6e9f15819632732306c15098f005d8aeb9 | 667 | package com.quickblox.convo.ui.chats.emoji;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.List;
public class EmojisPagerAdapter extends FragmentPagerAdapter {
private List<EmojiGridFragment> fragmentsList;
public EmojisPagerAdapter(FragmentManager fm, List<EmojiGridFragment> fragmentsList) {
super(fm);
this.fragmentsList = fragmentsList;
}
@Override
public Fragment getItem(int i) {
return fragmentsList.get(i);
}
@Override
public int getCount() {
return fragmentsList.size();
}
} | 24.703704 | 90 | 0.727136 |
8a8fd53ddbc2ccc49e0b4a2bed353eb841babcac | 752 | package ro.webdata.parser.xml.lido.core.leaf.legalBodyName;
import ro.webdata.parser.xml.lido.core.complex.appellationComplexType.AppellationComplexType;
/**
* <link rel="stylesheet" type="text/css" href="../../../../javadoc.css"/>
* <div class="lido">
* <div class="lido-title">Lido documentation:</div>
* <div class="lido-doc">
* <b>Definition:</b> Appellation of the institution or person.
* </div>
* </div>
* @author WebData
*
*/
public class LegalBodyName extends AppellationComplexType {
public LegalBodyName() {}
public LegalBodyName(AppellationComplexType appellationComplexType) {
super(
appellationComplexType.getAppellationValue(),
appellationComplexType.getSourceAppellation()
);
}
}
| 28.923077 | 94 | 0.702128 |
1eebf796342760d498c684f026617261a4e1f641 | 1,388 | package net.varanus.util.collect;
import java.util.Collection;
import java.util.LinkedList;
/**
* A fixed length queue that evicts the oldest element when trying to add past
* the fixed limit.
*
* @param <E>
*/
public class LimitedQueue<E> extends LinkedList<E>
{
private static final long serialVersionUID = 7331072201706998872L;
private final int limit;
public LimitedQueue( int limit )
{
if (limit < 0) {
throw new IllegalArgumentException("limit must be non-negative");
}
this.limit = limit;
}
/**
* Constructs a new limited queue with the elements from the provided
* collection initially inserted, and the limit
* set to the size of the collection.
*
* @param col
*/
public LimitedQueue( Collection<E> col )
{
this(col.size());
addAll(0, col);
}
public int getLimit()
{
return limit;
}
@Override
public boolean add( E o )
{
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
@Override
public boolean addAll( int index, Collection<? extends E> c )
{
boolean added = super.addAll(index, c);
while (added && size() > limit) {
super.remove();
}
return added;
}
}
| 20.716418 | 78 | 0.577089 |
a81a48cbb76f27d33a5cafaa70e033ce90904500 | 529 | package org.openstack4j.model.trove;
import org.openstack4j.common.Buildable;
import org.openstack4j.model.ModelEntity;
import org.openstack4j.model.trove.builder.InstanceCreateBuilder;
public interface InstanceCreate extends ModelEntity, Buildable<InstanceCreateBuilder> {
void setFlavor(String flavorRef);
void setName(String name);
void setDatastore(Datastore datastore);
void setVolumetype(String volumeType);
void setvolumeSize(int size);
void setAvailabilityZone(String availabilityZone);
}
| 25.190476 | 87 | 0.797732 |
a2edcd473953331090264b4cc4bb8eae7ff06dce | 4,811 | package seedu.address.model.person;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.logic.commands.CommandTestUtil.VALID_EMAIL_AMY;
import static seedu.address.logic.commands.CommandTestUtil.VALID_EMAIL_BOB;
import static seedu.address.logic.commands.CommandTestUtil.VALID_LEVEL_OF_EDUCATION_BOB;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_BOB;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NOTES_BOB;
import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_AMY;
import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_BOB;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_HUSBAND;
import static seedu.address.testutil.Assert.assertThrows;
import static seedu.address.testutil.TypicalPersons.ALICE;
import static seedu.address.testutil.TypicalPersons.AMY;
import static seedu.address.testutil.TypicalPersons.BOB;
import org.junit.jupiter.api.Test;
import seedu.address.model.done.Done;
import seedu.address.testutil.PersonBuilder;
public class PersonTest {
@Test
public void asObservableList_modifyList_throwsUnsupportedOperationException() {
Person person = new PersonBuilder().build();
assertThrows(UnsupportedOperationException.class, () -> person.getTags().remove(0));
}
@Test
public void isSamePerson() {
// same object -> returns true
assertTrue(ALICE.isSamePerson(ALICE));
// null -> returns false
assertFalse(ALICE.isSamePerson(null));
// same email and same contact number, all other attributes different -> returns true
Person editedBob = new PersonBuilder(BOB).withPhone(VALID_PHONE_AMY).withEmail(VALID_EMAIL_AMY).build();
assertTrue(AMY.isSamePerson(editedBob));
// same email but different contact number, all other attributes same -> returns true
editedBob = new PersonBuilder(BOB).withPhone(VALID_PHONE_AMY).build();
assertTrue(BOB.isSamePerson(editedBob));
// different email but same contact number, all other attributes same -> returns true
editedBob = new PersonBuilder(BOB).withEmail(VALID_EMAIL_AMY).build();
assertTrue(BOB.isSamePerson(editedBob));
// different email and contact number, all other attributes same -> returns false
editedBob = new PersonBuilder(BOB).withPhone(VALID_PHONE_AMY).withEmail(VALID_EMAIL_AMY).build();
assertFalse(BOB.isSamePerson(editedBob));
// checks case sensitiveness of email
// email same but differing in case, different phone number, all other attributes same -> returns false
editedBob = new PersonBuilder(BOB).withEmail(VALID_EMAIL_BOB.toUpperCase()).withPhone(VALID_PHONE_AMY).build();
assertFalse(BOB.isSamePerson(editedBob));
}
@Test
public void equals() {
// same values -> returns true
Person aliceCopy = new PersonBuilder(ALICE).build();
assertTrue(ALICE.equals(aliceCopy));
// same object -> returns true
assertTrue(ALICE.equals(ALICE));
// null -> returns false
assertFalse(ALICE.equals(null));
// different type -> returns false
assertFalse(ALICE.equals(5));
// different person -> returns false
assertFalse(ALICE.equals(BOB));
// different name -> returns false
Person editedAlice = new PersonBuilder(ALICE).withName(VALID_NAME_BOB).build();
assertFalse(ALICE.equals(editedAlice));
// different phone -> returns false
editedAlice = new PersonBuilder(ALICE).withPhone(VALID_PHONE_BOB).build();
assertFalse(ALICE.equals(editedAlice));
// different email -> returns false
editedAlice = new PersonBuilder(ALICE).withEmail(VALID_EMAIL_BOB).build();
assertFalse(ALICE.equals(editedAlice));
// different level of education -> returns false
editedAlice = new PersonBuilder(ALICE).withLevelOfEducation(VALID_LEVEL_OF_EDUCATION_BOB).build();
assertFalse(ALICE.equals(editedAlice));
// different tags -> returns false
editedAlice = new PersonBuilder(ALICE).withTags(VALID_TAG_HUSBAND).build();
assertFalse(ALICE.equals(editedAlice));
// different notes -> returns false
editedAlice = new PersonBuilder(ALICE).withNotes(VALID_NOTES_BOB).build();
assertFalse(ALICE.equals(editedAlice));
// different done status -> return false
Person aliceWithDone = new PersonBuilder(ALICE).withDone(Done.STATUS_DONE).build();
Person aliceWithNotDone = new PersonBuilder(ALICE).withDone(Done.STATUS_UNDONE).build();
assertFalse(aliceWithDone.equals(aliceWithNotDone));
}
}
| 44.137615 | 119 | 0.727499 |
fcfccfabe2621d981351f4c04106aafbf090c9d1 | 1,858 | package net.minecraft.entity.ai;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.util.math.MathHelper;
public class EntityAILeapAtTarget extends EntityAIBase
{
EntityLiving leaper;
EntityLivingBase leapTarget;
float leapMotionY;
public EntityAILeapAtTarget(EntityLiving leapingEntity, float leapMotionYIn)
{
this.leaper = leapingEntity;
this.leapMotionY = leapMotionYIn;
this.setMutexBits(5);
}
public boolean shouldExecute()
{
this.leapTarget = this.leaper.getAttackTarget();
if (this.leapTarget == null)
{
return false;
}
else
{
double d0 = this.leaper.getDistanceSq(this.leapTarget);
if (d0 >= 4.0D && d0 <= 16.0D)
{
if (!this.leaper.onGround)
{
return false;
}
else
{
return this.leaper.getRNG().nextInt(5) == 0;
}
}
else
{
return false;
}
}
}
public boolean shouldContinueExecuting()
{
return !this.leaper.onGround;
}
public void startExecuting()
{
double d0 = this.leapTarget.posX - this.leaper.posX;
double d1 = this.leapTarget.posZ - this.leaper.posZ;
float f = MathHelper.sqrt(d0 * d0 + d1 * d1);
if ((double)f >= 1.0E-4D)
{
this.leaper.motionX += d0 / (double)f * 0.5D * 0.800000011920929D + this.leaper.motionX * 0.20000000298023224D;
this.leaper.motionZ += d1 / (double)f * 0.5D * 0.800000011920929D + this.leaper.motionZ * 0.20000000298023224D;
}
this.leaper.motionY = (double)this.leapMotionY;
}
} | 26.927536 | 123 | 0.555974 |
7858d878afe14eb9b3854e16018dd5ee3965dad8 | 345 | public class A{
public void methodA() throws IOException{
}
}
public class B extends A {
public void MethodA() throws EOFException{
// Legal, because EOFException is the subclass of the IOException.
}
}
class C extends A {
public void methodA() throws Exception{
// Illegal, because Exception is the superclass of IOException.
}
} | 18.157895 | 68 | 0.727536 |
f63972df718a3cb83c332bec6b82f94032675419 | 12,973 | package com.mayinews.mv.home.fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.mayinews.mv.MyApplication;
import com.mayinews.mv.R;
import com.mayinews.mv.base.BaseFragment;
import com.mayinews.mv.home.activity.NoskinVpActivity;
import com.mayinews.mv.home.adapter.MyRcAdapter;
import com.mayinews.mv.home.bean.VideoLists;
import com.mayinews.mv.utils.Constants;
import com.mayinews.mv.utils.NetUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
/**
* Created by gary on 2017/6/14 0014.
* 微信:GH-12-10
* QQ:1683701403
* 涨姿势
*/
public class YagamiFragment extends BaseFragment {
private static final int CACLEPOP = 1;
private static final int FINISHREFRESH = 2;
private LRecyclerView lRecyclerView;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case CACLEPOP:
popupWindow.dismiss();
break;
case FINISHREFRESH:
lRecyclerView.refreshComplete(data.size());
mLRecyclerViewAdapter.notifyDataSetChanged();
break;
}
}
};
private MyRcAdapter madapter;
private ProgressBar progressBar;
private LinearLayout check_linear;
private LRecyclerViewAdapter mLRecyclerViewAdapter = null;
private boolean isPulldownRefresh = false; //是否下拉刷新
private boolean isLoadMore = true; //是否上拉加载更多
private boolean isRefresh = false; //在页面时就刷新
private List<VideoLists.ResultBean> datas = new ArrayList();
List<VideoLists.ResultBean> data;
int count;//视频的数量
int status;//接口返回的状态
//列表的总页数
private int totalPages;
//当前的页数
private int currentPage_up =1 ; //上啦加载更多
private PopupWindow popupWindow;//显示更新的视频条数
@Override
protected View initView() {
View view = View.inflate(mContext, R.layout.newest_fragment, null);
lRecyclerView = (LRecyclerView) view.findViewById(R.id.lrecyclerview);
progressBar = (ProgressBar) view.findViewById(R.id.head_progressBar);
check_linear = (LinearLayout) view.findViewById(R.id.check_linear);
check_linear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getNetState();
}
});
return view;
}
private void setListener() {
lRecyclerView.setLScrollListener(new LRecyclerView.LScrollListener() {
@Override
public void onScrollUp() {
}
@Override
public void onScrollDown() {
}
@Override
public void onScrolled(int distanceX, int distanceY) {
}
@Override
public void onScrollStateChanged(int state) {
}
});
/**
* 下拉刷新
*/
lRecyclerView.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
isLoadMore = false;
isRefresh = false;
isPulldownRefresh = true;
boolean connected = NetUtils.isConnected(mContext);
if (connected) {
if (status == 1 && count != 0) {
getNetState();
} else {
Toast.makeText(mContext, "没有新的数据", Toast.LENGTH_SHORT).show();
lRecyclerView.refreshComplete(datas.size());
mLRecyclerViewAdapter.notifyDataSetChanged();
}
check_linear.setVisibility(View.GONE);
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
//提示网不给力,但是还是有视频页面
Toast.makeText(mContext, "网络不给力,请检查网络设置", Toast.LENGTH_SHORT).show();
mLRecyclerViewAdapter.notifyDataSetChanged();
}
}
});
/**
* 加载更多
*/
lRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
isLoadMore = true;
isRefresh = false;
isPulldownRefresh = false;
boolean connected = NetUtils.isConnected(mContext);
if (connected) {
if (status == 1 && count != 0) {
currentPage_up++;
getNetState();
} else {
Toast.makeText(mContext, "没有新的数据", Toast.LENGTH_SHORT).show();
lRecyclerView.refreshComplete(datas.size());
mLRecyclerViewAdapter.notifyDataSetChanged();
}
} else {
progressBar.setVisibility(View.GONE);
//提示网不给力,但是还是有视频页面
Toast.makeText(mContext, "网络不给力,请检查网络设置", Toast.LENGTH_SHORT).show();
mLRecyclerViewAdapter.notifyDataSetChanged();
}
}
});
/**
* 点击事件
*/
mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
// //进入播放视频的页面
VideoLists.ResultBean dataBean = datas.get(position);
// Intent intent=new Intent(getActivity(),VideoDetailsActivity.class);
// Intent intent=new Intent(getActivity(),AliVideoPlayer.class);
Intent intent = new Intent(getActivity(), NoskinVpActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("dataBean", dataBean);
intent.putExtra("bundle", bundle);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.activity_open, R.anim.activity_backgroud);
}
});
}
@Override
protected void initData() {
getNetState();
}
/**
* 根据网络状态去请求数据
*/
private void getNetState() {
boolean connected = NetUtils.isConnected(mContext);
if (connected) {
check_linear.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
RequestNetData();
} else {
//显示没有网的图片
check_linear.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
private void RequestNetData() {
if (isPulldownRefresh) { // 下拉刷新
OkHttpUtils.get().url(Constants.PULLDOWNHEQUEST).build().execute(new MyCallBack());
} else if (isRefresh) {
//刷新
OkHttpUtils.get().url(Constants.REFRESHEQUEST).build().execute(new MyCallBack());
} else if (isLoadMore) { // 上拉加载更多--默认
OkHttpUtils.get().url(Constants.PULLUPEQUEST+129+"/pgnum/" + currentPage_up).build().execute(new MyCallBack());
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
/**
* 请求网络毁掉
*/
class MyCallBack extends StringCallback {
@Override
public void onError(Call call, Exception e, int id) {
}
@Override
public void onResponse(String response, int id) {
// VideoList videoList = JSON.parseObject(response, VideoList.class);
//
Log.i("TAG", response);
VideoLists videoLists = JSON.parseObject(response, VideoLists.class);
status = videoLists.getStauts();
count = videoLists.getCount();
if (status == 1 && count!=0) {
//
data = videoLists.getResult();
//
if (isLoadMore) {
//加载更多 不清楚数据
datas.addAll(data);
} else if (isRefresh) {
datas.clear();
datas.addAll(0, data);
} else if (isPulldownRefresh) {
// 显示popwindows
// showPopwindows(count);
datas.clear();
datas.addAll(0, data);
}
if (null != datas && datas.size() > 0) {
SolveNetData();
} else {
//提示没有数据
Toast.makeText(mContext, "没有新的数据", Toast.LENGTH_SHORT).show();
lRecyclerView.refreshComplete(datas.size());
progressBar.setVisibility(View.GONE);
mLRecyclerViewAdapter.notifyDataSetChanged();
}
} else {
//请求出错----提示信息请重试
Toast.makeText(mContext, "没有新的数据", Toast.LENGTH_SHORT).show();
lRecyclerView.refreshComplete(datas.size());
progressBar.setVisibility(View.GONE);
mLRecyclerViewAdapter.notifyDataSetChanged();
}
}
/**
* 处理网络数据
*/
private void SolveNetData() {
if (madapter == null && mLRecyclerViewAdapter == null) {
madapter = new MyRcAdapter(mContext, datas);
mLRecyclerViewAdapter = new LRecyclerViewAdapter(madapter);
//根据需要选择使用GridItemDecoration还是SpacesItemDecoration
GridItemDecoration divider = new GridItemDecoration.Builder(getActivity())
.setHorizontal(R.dimen.default_divider_height)
.setColorResource(R.color.gh_gray)
.build();
lRecyclerView.addItemDecoration(divider);
lRecyclerView.setAdapter(mLRecyclerViewAdapter);
lRecyclerView.setPullRefreshEnabled(true); //允许下拉刷新
lRecyclerView.setLoadMoreEnabled(true); //允许加载更多
progressBar.setVisibility(View.GONE);
GridLayoutManager manager = new GridLayoutManager(mContext, 2);
//setLayoutManager
final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//防止item位置互换
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
lRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//防止第一行到顶部有空白区域
layoutManager.invalidateSpanAssignments();
}
});
lRecyclerView.setLayoutManager(layoutManager);
setListener();
} else {
handler.sendEmptyMessageDelayed(FINISHREFRESH, 1000);
// lRecyclerView.refreshComplete(data.size());
// mLRecyclerViewAdapter.notifyDataSetChanged();
}
progressBar.setVisibility(View.GONE);
}
}
private void showPopwindows(int count) {
View inflate = View.inflate(getActivity(), R.layout.refresh_count, null);
TextView tv = (TextView) inflate.findViewById(R.id.tv_refresf_count);
popupWindow = new PopupWindow(getActivity());
popupWindow.setContentView(inflate);
popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
tv.setText("更新了" + count + "条数据");
popupWindow.showAsDropDown(getActivity().findViewById(R.id.tabs));
handler.sendEmptyMessageDelayed(CACLEPOP, 1000);
}
}
| 32.513784 | 136 | 0.582055 |
93504af62bd717cc1ed194beb6ef4e72ad1073bc | 691 | /**
* you can invoke multiple methods in an object to create a object using method chaining
*
*/
package com.konzerntech.pattern;
/**
* @author konzerntech
*
*/
public class Hotel {
private int hotelId;
private String hotelName;
private String hotelDescription;
public Hotel setHotelId(int hotelId) {
this.hotelId = hotelId;
return this;
}
public Hotel setHotelName(String hotelName) {
this.hotelName = hotelName;
return this;
}
public Hotel setHotelDescription(String hotelDescription) {
this.hotelDescription = hotelDescription;
return this;
}
@Override
public String toString() {
return hotelId +" @ "+hotelName +" @ "+hotelDescription;
}
}
| 18.184211 | 89 | 0.713459 |
612ef92a3b17fc5c347f5ea77167156fedec95a4 | 4,348 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2017 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* 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.jboss.modules;
import static org.jboss.modules.Utils.MODULES_DIR;
import static org.jboss.modules.Utils.MODULE_FILE;
import java.io.IOException;
import java.io.InputStream;
import org.jboss.modules.xml.ModuleXmlParser;
/**
* A module loader which loads modules which are stored inside the {@code modules} directory of a single JAR or JAR-like
* root.
*/
public final class ResourceLoaderModuleFinder implements ModuleFinder {
private final ResourceLoader resourceLoader;
private final String modulesDirectory;
private final NestedResourceRootFactory factory;
/**
* Construct a new instance. The given resource loader should support the nested {@link ResourceLoader#createSubloader(String, String)}
* operation if {@code <resource-root>} elements are to be supported in {@code module.xml} files found within
* the loader.
*
* @param resourceLoader the base resource loader to use (must not be {@code null})
* @param modulesDirectory the modules directory to use (must not be {@code null})
*/
public ResourceLoaderModuleFinder(final ResourceLoader resourceLoader, final String modulesDirectory) {
factory = new NestedResourceRootFactory(resourceLoader);
this.resourceLoader = resourceLoader;
this.modulesDirectory = modulesDirectory;
}
/**
* Construct a new instance. The given resource loader should support the nested {@link ResourceLoader#createSubloader(String, String)}
* operation if {@code <resource-root>} elements are to be supported in {@code module.xml} files found within
* the loader.
*
* @param resourceLoader the base resource loader to use (must not be {@code null})
*/
public ResourceLoaderModuleFinder(final ResourceLoader resourceLoader) {
this(resourceLoader, MODULES_DIR);
}
public ModuleSpec findModule(final String name, final ModuleLoader delegateLoader) throws ModuleLoadException {
final ResourceLoader resourceLoader = this.resourceLoader;
final String path = PathUtils.basicModuleNameToPath(name);
if (path == null) {
return null; // not valid, so not found
}
String basePath = modulesDirectory + "/" + path;
Resource moduleXmlResource = resourceLoader.getResource(basePath + "/" + MODULE_FILE);
if (moduleXmlResource == null) {
return null;
}
ModuleSpec moduleSpec;
try {
try (final InputStream inputStream = moduleXmlResource.openStream()) {
moduleSpec = ModuleXmlParser.parseModuleXml(factory, basePath, inputStream, moduleXmlResource.getName(), delegateLoader, name);
}
} catch (IOException e) {
throw new ModuleLoadException("Failed to read " + MODULE_FILE + " file", e);
}
return moduleSpec;
}
static class NestedResourceRootFactory implements ModuleXmlParser.ResourceRootFactory {
private final ResourceLoader resourceLoader;
NestedResourceRootFactory(final ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public ResourceLoader createResourceLoader(final String rootPath, final String loaderPath, final String loaderName) throws IOException {
final ResourceLoader subloader = resourceLoader.createSubloader(rootPath + "/" + loaderPath, loaderName);
if (subloader == null) {
throw new IllegalArgumentException("Nested resource loaders not supported by " + resourceLoader);
}
return subloader;
}
}
}
| 43.049505 | 144 | 0.704692 |
f8dcb03cbda500685d2a13bcf80e255455ad9dd9 | 256 | package com.totoro.pay.routing.mapping;
/**
* 标题、简要说明. <br>
* 类详细说明.
* <p>
* Copyright: Copyright (c)
* <p>
* Company: xx
* <p>
*
* @author [email protected]
* @version 1.0.0
*/
public interface HandlerDefinition {
//TODO 没想好 , 扩展使用
}
| 14.222222 | 39 | 0.605469 |
e30746983c5e7ffa2c2b931a23d30a92d14b5793 | 1,540 | package uk.ac.ox.well.cortexjdk.utils.performance;
/**
* A set of utilities for measuring performance metrics.
*/
public class PerformanceUtils {
private PerformanceUtils() {}
/**
* Get a string containing memory usage stats (used, free, total, and maximum available memory).
*
* @return a string with memory usage stats
*/
public static String getMemoryUsageStats() {
int mb = 1024*1024;
Runtime runtime = Runtime.getRuntime();
long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / mb;
long freeMemory = runtime.freeMemory() / mb;
long totalMemory = runtime.totalMemory() / mb;
long maxMemory = runtime.maxMemory() / mb;
return String.format("Used: %dmb; Free: %dmb; Total: %dmb; Max: %dmb", usedMemory, freeMemory, totalMemory, maxMemory);
}
/**
* Get a compact string containing memory usage stats (used, free, total, and maximum available memory).
*
* @return a compact string with memory usage stats
*/
public static String getCompactMemoryUsageStats() {
int mb = 1024*1024;
Runtime runtime = Runtime.getRuntime();
long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / mb;
long freeMemory = runtime.freeMemory() / mb;
long totalMemory = runtime.totalMemory() / mb;
long maxMemory = runtime.maxMemory() / mb;
return String.format("U:%dmb, F:%dmb, T:%dmb, M:%dmb", usedMemory, freeMemory, totalMemory, maxMemory);
}
}
| 34.222222 | 127 | 0.645455 |
58c87a8095482a46b813a9f3e9d254eef18c28a4 | 15,452 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Copyright 2015 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|util
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|cos
operator|.
name|COSArray
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|pdfbox
operator|.
name|cos
operator|.
name|COSFloat
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|*
import|;
end_import
begin_comment
comment|/** * * @author Neil McErlean * @author Tilman Hausherr */
end_comment
begin_class
specifier|public
class|class
name|MatrixTest
block|{
annotation|@
name|Test
specifier|public
name|void
name|testConstructionAndCopy
parameter_list|()
throws|throws
name|Exception
block|{
name|Matrix
name|m1
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|assertMatrixIsPristine
argument_list|(
name|m1
argument_list|)
expr_stmt|;
name|Matrix
name|m2
init|=
name|m1
operator|.
name|clone
argument_list|()
decl_stmt|;
name|assertNotSame
argument_list|(
name|m1
argument_list|,
name|m2
argument_list|)
expr_stmt|;
name|assertMatrixIsPristine
argument_list|(
name|m2
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|testMultiplication
parameter_list|()
throws|throws
name|Exception
block|{
comment|// This matrix will not change - we use it to drive the various multiplications.
specifier|final
name|Matrix
name|testMatrix
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
comment|// Create matrix with values
comment|// [ 0, 1, 2
comment|// 1, 2, 3
comment|// 2, 3, 4]
for|for
control|(
name|int
name|x
init|=
literal|0
init|;
name|x
operator|<
literal|3
condition|;
name|x
operator|++
control|)
block|{
for|for
control|(
name|int
name|y
init|=
literal|0
init|;
name|y
operator|<
literal|3
condition|;
name|y
operator|++
control|)
block|{
name|testMatrix
operator|.
name|setValue
argument_list|(
name|x
argument_list|,
name|y
argument_list|,
name|x
operator|+
name|y
argument_list|)
expr_stmt|;
block|}
block|}
name|Matrix
name|m1
init|=
name|testMatrix
operator|.
name|clone
argument_list|()
decl_stmt|;
name|Matrix
name|m2
init|=
name|testMatrix
operator|.
name|clone
argument_list|()
decl_stmt|;
comment|// Multiply two matrices together producing a new result matrix.
name|Matrix
name|product
init|=
name|m1
operator|.
name|multiply
argument_list|(
name|m2
argument_list|)
decl_stmt|;
name|assertNotSame
argument_list|(
name|m1
argument_list|,
name|product
argument_list|)
expr_stmt|;
name|assertNotSame
argument_list|(
name|m2
argument_list|,
name|product
argument_list|)
expr_stmt|;
comment|// Operand 1 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m1
argument_list|)
expr_stmt|;
comment|// Operand 2 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m2
argument_list|)
expr_stmt|;
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|5
block|,
literal|8
block|,
literal|11
block|,
literal|8
block|,
literal|14
block|,
literal|20
block|,
literal|11
block|,
literal|20
block|,
literal|29
block|}
argument_list|,
name|product
argument_list|)
expr_stmt|;
comment|// Multiply two matrices together with the result being written to a third matrix
comment|// (Any existing values there will be overwritten).
name|Matrix
name|resultMatrix
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|Matrix
name|retVal
init|=
name|m1
operator|.
name|multiply
argument_list|(
name|m2
argument_list|,
name|resultMatrix
argument_list|)
decl_stmt|;
name|assertSame
argument_list|(
name|retVal
argument_list|,
name|resultMatrix
argument_list|)
expr_stmt|;
comment|// Operand 1 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m1
argument_list|)
expr_stmt|;
comment|// Operand 2 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m2
argument_list|)
expr_stmt|;
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|5
block|,
literal|8
block|,
literal|11
block|,
literal|8
block|,
literal|14
block|,
literal|20
block|,
literal|11
block|,
literal|20
block|,
literal|29
block|}
argument_list|,
name|resultMatrix
argument_list|)
expr_stmt|;
comment|// Multiply two matrices together with the result being written into the other matrix
name|retVal
operator|=
name|m1
operator|.
name|multiply
argument_list|(
name|m2
argument_list|,
name|m2
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|retVal
argument_list|,
name|m2
argument_list|)
expr_stmt|;
comment|// Operand 1 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m1
argument_list|)
expr_stmt|;
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|5
block|,
literal|8
block|,
literal|11
block|,
literal|8
block|,
literal|14
block|,
literal|20
block|,
literal|11
block|,
literal|20
block|,
literal|29
block|}
argument_list|,
name|retVal
argument_list|)
expr_stmt|;
comment|// Multiply two matrices together with the result being written into 'this' matrix
name|m1
operator|=
name|testMatrix
operator|.
name|clone
argument_list|()
expr_stmt|;
name|m2
operator|=
name|testMatrix
operator|.
name|clone
argument_list|()
expr_stmt|;
name|retVal
operator|=
name|m1
operator|.
name|multiply
argument_list|(
name|m2
argument_list|,
name|m1
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|retVal
argument_list|,
name|m1
argument_list|)
expr_stmt|;
comment|// Operand 2 should not have changed
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|0
block|,
literal|1
block|,
literal|2
block|,
literal|1
block|,
literal|2
block|,
literal|3
block|,
literal|2
block|,
literal|3
block|,
literal|4
block|}
argument_list|,
name|m2
argument_list|)
expr_stmt|;
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|5
block|,
literal|8
block|,
literal|11
block|,
literal|8
block|,
literal|14
block|,
literal|20
block|,
literal|11
block|,
literal|20
block|,
literal|29
block|}
argument_list|,
name|retVal
argument_list|)
expr_stmt|;
comment|// Multiply the same matrix with itself with the result being written into 'this' matrix
name|m1
operator|=
name|testMatrix
operator|.
name|clone
argument_list|()
expr_stmt|;
name|retVal
operator|=
name|m1
operator|.
name|multiply
argument_list|(
name|m1
argument_list|,
name|m1
argument_list|)
expr_stmt|;
name|assertSame
argument_list|(
name|retVal
argument_list|,
name|m1
argument_list|)
expr_stmt|;
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|5
block|,
literal|8
block|,
literal|11
block|,
literal|8
block|,
literal|14
block|,
literal|20
block|,
literal|11
block|,
literal|20
block|,
literal|29
block|}
argument_list|,
name|retVal
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|expected
operator|=
name|IllegalArgumentException
operator|.
name|class
argument_list|)
specifier|public
name|void
name|testIllegalValueNaN1
parameter_list|()
block|{
name|Matrix
name|m
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|m
operator|.
name|setValue
argument_list|(
literal|0
argument_list|,
literal|0
argument_list|,
name|Float
operator|.
name|MAX_VALUE
argument_list|)
expr_stmt|;
name|m
operator|.
name|multiply
argument_list|(
name|m
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|expected
operator|=
name|IllegalArgumentException
operator|.
name|class
argument_list|)
specifier|public
name|void
name|testIllegalValueNaN2
parameter_list|()
block|{
name|Matrix
name|m
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|m
operator|.
name|setValue
argument_list|(
literal|0
argument_list|,
literal|0
argument_list|,
name|Float
operator|.
name|NaN
argument_list|)
expr_stmt|;
name|m
operator|.
name|multiply
argument_list|(
name|m
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|expected
operator|=
name|IllegalArgumentException
operator|.
name|class
argument_list|)
specifier|public
name|void
name|testIllegalValuePositiveInfinity
parameter_list|()
block|{
name|Matrix
name|m
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|m
operator|.
name|setValue
argument_list|(
literal|0
argument_list|,
literal|0
argument_list|,
name|Float
operator|.
name|POSITIVE_INFINITY
argument_list|)
expr_stmt|;
name|m
operator|.
name|multiply
argument_list|(
name|m
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
argument_list|(
name|expected
operator|=
name|IllegalArgumentException
operator|.
name|class
argument_list|)
specifier|public
name|void
name|testIllegalValueNegativeInfinity
parameter_list|()
block|{
name|Matrix
name|m
init|=
operator|new
name|Matrix
argument_list|()
decl_stmt|;
name|m
operator|.
name|setValue
argument_list|(
literal|0
argument_list|,
literal|0
argument_list|,
name|Float
operator|.
name|NEGATIVE_INFINITY
argument_list|)
expr_stmt|;
name|m
operator|.
name|multiply
argument_list|(
name|m
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
comment|/** * Test of PDFBOX-2872 bug */
annotation|@
name|Test
specifier|public
name|void
name|testPdfbox2872
parameter_list|()
block|{
name|Matrix
name|m
init|=
operator|new
name|Matrix
argument_list|(
literal|2
argument_list|,
literal|4
argument_list|,
literal|5
argument_list|,
literal|8
argument_list|,
literal|2
argument_list|,
literal|0
argument_list|)
decl_stmt|;
name|COSArray
name|toCOSArray
init|=
name|m
operator|.
name|toCOSArray
argument_list|()
decl_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|2
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|0
argument_list|)
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|4
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|1
argument_list|)
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|5
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|2
argument_list|)
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|8
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|3
argument_list|)
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|2
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|4
argument_list|)
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
operator|new
name|COSFloat
argument_list|(
literal|0
argument_list|)
argument_list|,
name|toCOSArray
operator|.
name|get
argument_list|(
literal|5
argument_list|)
argument_list|)
expr_stmt|;
block|}
comment|/** * This method asserts that the matrix values for the given {@link Matrix} object are equal to the pristine, or * original, values. * * @param m the Matrix to test. */
specifier|private
name|void
name|assertMatrixIsPristine
parameter_list|(
name|Matrix
name|m
parameter_list|)
block|{
name|assertMatrixValuesEqualTo
argument_list|(
operator|new
name|float
index|[]
block|{
literal|1
block|,
literal|0
block|,
literal|0
block|,
literal|0
block|,
literal|1
block|,
literal|0
block|,
literal|0
block|,
literal|0
block|,
literal|1
block|}
argument_list|,
name|m
argument_list|)
expr_stmt|;
block|}
comment|/** * This method asserts that the matrix values for the given {@link Matrix} object have the specified values. * * @param values the expected values * @param m the matrix to test */
specifier|private
name|void
name|assertMatrixValuesEqualTo
parameter_list|(
name|float
index|[]
name|values
parameter_list|,
name|Matrix
name|m
parameter_list|)
block|{
name|float
name|delta
init|=
literal|0.00001f
decl_stmt|;
for|for
control|(
name|int
name|i
init|=
literal|0
init|;
name|i
operator|<
name|values
operator|.
name|length
condition|;
name|i
operator|++
control|)
block|{
comment|// Need to convert a (row, column) coordinate into a straight index.
name|int
name|row
init|=
operator|(
name|int
operator|)
name|Math
operator|.
name|floor
argument_list|(
name|i
operator|/
literal|3
argument_list|)
decl_stmt|;
name|int
name|column
init|=
name|i
operator|%
literal|3
decl_stmt|;
name|StringBuilder
name|failureMsg
init|=
operator|new
name|StringBuilder
argument_list|()
decl_stmt|;
name|failureMsg
operator|.
name|append
argument_list|(
literal|"Incorrect value for matrix["
argument_list|)
operator|.
name|append
argument_list|(
name|row
argument_list|)
operator|.
name|append
argument_list|(
literal|","
argument_list|)
operator|.
name|append
argument_list|(
name|column
argument_list|)
operator|.
name|append
argument_list|(
literal|"]"
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|failureMsg
operator|.
name|toString
argument_list|()
argument_list|,
name|values
index|[
name|i
index|]
argument_list|,
name|m
operator|.
name|getValue
argument_list|(
name|row
argument_list|,
name|column
argument_list|)
argument_list|,
name|delta
argument_list|)
expr_stmt|;
block|}
block|}
block|}
end_class
end_unit
| 13.833483 | 623 | 0.780805 |
7f878a6a141a620c5bb4f7305b79c4e5024187e2 | 3,246 | /*******************************************************************************
* (c) Copyright 2021 Micro Focus or one of its affiliates
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including without
* limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
******************************************************************************/
package com.fortify.cli.common.picocli.executor;
import com.fortify.cli.common.picocli.annotation.SubcommandOf;
import com.fortify.cli.common.picocli.command.FCLIRootCommand;
import com.fortify.cli.common.picocli.util.DefaultValueProvider;
import io.micronaut.context.annotation.Executable;
import jakarta.annotation.PostConstruct;
import jakarta.inject.Inject;
import jakarta.inject.Singleton;
import picocli.CommandLine;
/**
* This class is responsible for actually running the (sub-)commands
* specified on the command line by generating a {@link CommandLine}
* instance containing an {@link FCLIRootCommand} instance and the
* full sub-command hierarchy underneath that, based on the {@link SubcommandOf}
* annotation. Once the {@link CommandLine} has been constructed,
* it will be executed in order to have picocli invoke the appropriate
* sub-command.
*
* @author Ruud Senden
*/
@Singleton
public class CommandLineExecutor {
private final FCLIRootCommand rootCommand;
private final SubcommandsHelper subcommandsHelper;
private final MicronautFactorySupplier micronautFactorySupplier;
private CommandLine commandLine;
@Inject
public CommandLineExecutor(
FCLIRootCommand rootCommand,
MicronautFactorySupplier micronautFactorySupplier,
SubcommandsHelper subcommandsHelper) {
this.rootCommand = rootCommand;
this.subcommandsHelper = subcommandsHelper;
this.micronautFactorySupplier = micronautFactorySupplier;
}
@PostConstruct @Executable
public void createCommandLine() {
this.commandLine = new CommandLine(rootCommand, micronautFactorySupplier.getMicronautFactory())
.setCaseInsensitiveEnumValuesAllowed(true)
.setDefaultValueProvider(new DefaultValueProvider())
.setUsageHelpAutoWidth(true); // TODO Add ExceptionHandler?
subcommandsHelper.addSubcommands(commandLine);
}
public final int execute(String[] args) {
return commandLine.execute(args);
}
}
| 42.155844 | 97 | 0.745841 |
60c7fd6a9976fbc6401acf58b4a3244723962370 | 1,419 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.lib.integration.impl;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import org.lib.integration.BorrowDAO;
import org.lib.model.BookId;
import org.lib.model.Borrow;
import org.lib.model.ReaderId;
import org.lib.utils.LibraryException;
/**
*
* @author danecek
*/
public class BorrowDAOImpl implements BorrowDAO {
Map<BookId, Borrow> bookToBorrow;
Map<ReaderId, Collection<Borrow>> readerToBorrows;
public void borrowBook(ReaderId readerId, BookId bookId) throws LibraryException {
Borrow brw = new Borrow(readerId, bookId);
bookToBorrow.put(bookId, brw);
Collection<Borrow> brws = readerToBorrows.get(readerId);
if (brws == null) {
brws = new HashSet<Borrow>();
readerToBorrows.put(readerId, brws);
}
brws.add(brw);
}
public void returnBook(ReaderId readerId, BookId bookId) throws LibraryException {
Borrow brw = bookToBorrow.remove(bookId);
readerToBorrows.get(readerId).remove(brw);
}
public Collection<Borrow> borrows(ReaderId readerId) throws LibraryException {
return readerToBorrows.get(readerId);
}
public Borrow findReader(BookId bookId) throws LibraryException {
return bookToBorrow.get(bookId);
}
}
| 28.38 | 86 | 0.692037 |
9b038b688b6e64c4c7b1d6b2f23937bdd826ab2f | 1,298 | package cn.cicoding.vo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
@TableName(value = "user")
public class User implements Serializable {
@TableId(type = IdType.AUTO)
private Integer userId;
private String userName;
private String password;
private String phone;
@TableField(exist = false)
private PageInfo pageInfo;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public PageInfo getPageInfo() {
return pageInfo;
}
public void setPageInfo(PageInfo pageInfo) {
this.pageInfo = pageInfo;
}
}
| 20.28125 | 54 | 0.664099 |
1b2b4341836b712ea5b7a7ccf662973821973c58 | 2,904 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.test.func.api.java.beans.statement;
/**
* There are very different methods in this class: static, no static, with
* parameters, without parameters. All methods in this class are invoked by
* ExpressionTest and StatementTest tests.
*
*/
public class Methods {
static boolean static_without_params = false,
no_static_without_params = false, constructor = false;
public Methods() {
}
public Methods(String str, int a) throws StatementException {
if (!str.equals("abcde"))
throw new StatementException("String is not abcde");
if (a != 7)
throw new StatementException("a != 7");
constructor = true;
}
public static void static_without_params() {
static_without_params = true;
}
public void no_static_without_params() {
no_static_without_params = true;
}
public static String static_return_string() {
return "abc";
}
public static int static_return_primitive() {
return 5;
}
public static void static_array_of_primitive_as_param(int[] ints)
throws StatementException {
if (ints[0] != 3)
throw new StatementException("ints[0]!=3");
}
public static void static_with_params(String str, int a)
throws StatementException {
if (!str.equals("abc"))
throw new StatementException("String is not abc");
if (a != 9)
throw new StatementException("a != 9");
}
public static void static_with_params_2(Integer a)
throws StatementException {
if (!a.equals(new Integer(10)))
throw new StatementException("a != 10");
}
public void no_static_with_params(String str, int a)
throws StatementException {
if (!str.equals("abcd"))
throw new StatementException("String is not abcd");
if (a != 8)
throw new StatementException("a != 8");
}
public static void throwException() throws StatementException {
throw new StatementException();
}
} | 33.37931 | 76 | 0.664256 |
c7478b1b366d85f363ab97268a3259490cd68195 | 357 | /*
* File: IntLiteralToken.java
* Author: Dale Skrien
* Date: Jun 6, 2006
*/
package ast6.token;
public class IntLiteralToken extends Token
{
public IntLiteralToken(String s, int p)
{
super(s, p);
}
public Object accept(TokenVisitor v, Object o)
{
return v.visitIntLiteralToken(this, o);
}
}
| 17.85 | 51 | 0.59944 |
04e56c00f5335a1362d30a63e4712247d4f5439e | 336 | package com.twu.biblioteca;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class MovieTest {
@Test
public void checkoutMovie()
{
Movie movie = new Movie("A Movie", "A Person", 2018, 5);
movie.checkout("movie");
assertEquals(true, movie.getIsItemCheckedOut());
}
}
| 19.764706 | 64 | 0.654762 |
b09de356b278ec5894d318986801543f4fd33e5a | 3,024 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* $Id: AFPGraphicsObjectInfo.java 746664 2009-02-22 12:40:44Z jeremias $ */
package org.apache.fop.afp;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import org.apache.xmlgraphics.java2d.Graphics2DImagePainter;
import org.apache.xmlgraphics.util.MimeConstants;
/**
* A graphics object info which contains necessary painting objects
*/
public class AFPGraphicsObjectInfo extends AFPDataObjectInfo {
/** the graphics object painter implementation */
private Graphics2DImagePainter painter;
/** the graphics object area */
private Rectangle2D area;
/** the AFP graphics 2d implementation */
private AFPGraphics2D g2d;
/**
* Returns the graphics painter
*
* @return the graphics painter
*/
public Graphics2DImagePainter getPainter() {
return this.painter;
}
/**
* Sets the graphics painter
*
* @param graphicsPainter the graphics painter
*/
public void setPainter(Graphics2DImagePainter graphicsPainter) {
this.painter = graphicsPainter;
}
/**
* Returns the graphics area
*
* @return the graphics area
*/
public Rectangle2D getArea() {
AFPObjectAreaInfo objectAreaInfo = getObjectAreaInfo();
int width = objectAreaInfo.getWidth();
int height = objectAreaInfo.getHeight();
return new Rectangle(width, height);
}
/**
* Sets the graphics area area
*
* @param area the graphics object area
*/
public void setArea(Rectangle2D area) {
this.area = area;
}
/**
* Sets the AFP graphics 2D implementation
*
* @param g2d the AFP graphics 2D implementation
*/
public void setGraphics2D(AFPGraphics2D g2d) {
this.g2d = g2d;
}
/**
* Returns the AFP graphics 2D implementation
*
* @return the AFP graphics 2D implementation
*/
public AFPGraphics2D getGraphics2D() {
return this.g2d;
}
/** {@inheritDoc} */
public String toString() {
return "GraphicsObjectInfo{" + super.toString() + "}";
}
/** {@inheritDoc} */
public String getMimeType() {
return MimeConstants.MIME_SVG;
}
}
| 27.490909 | 76 | 0.671296 |
e644acbe77ca4639ca9eef0b3b7504baacde1398 | 8,218 | package com.idvsbruck.pplflw.api;
import static org.springframework.test.web.client.ExpectedCount.manyTimes;
import static org.springframework.test.web.client.MockRestServiceServer.bindTo;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.test.web.client.SimpleRequestExpectationManager;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
@TestConfiguration
public class PplflwTestConfiguration {
private final static String MOCK_PRIVATE_KEY_STR = "MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCJi9ujELWj9Qx"
+ "Tao6bChiX+7BJ1j6IGFu8D84nzh+Mp0mGfMPURPbQXGhpTRt7INeaU8tJhthZ4aBSBQzvi3SRVzP0GneqqzC8CMkwfSNLDkfJ6lpGTeb"
+ "2n0BcZ/ODjGxT8zST1NGwRZUyzy6+8p22AzBj5vlwa3czlL5EzgrHeYKrjgdNh805kh0/+i02a5GiglXN8qJPMoxDJnvPMpdgNSD5UGx"
+ "ULoCYgicvxzloD6PpWCyH/+KNabVAsnaDtvvORNx66UweWQFVNp4giKnb34tslsvXW1Ouu+QhpFOzxRk59DLClaOFQALvPfSpp8+Q7Z6"
+ "j6Xq2yGQtMh/7Llfj+RTJmAUI+mMIvdo6akRoOZbESlryPoQW0DTeKy9kgrQWz9ZDCVtasd8gDm4GyQlO8jbJ29EEQT/neDYIMCLpOwm"
+ "BOJVaMm8/gjK/mFvfirsQ6/eksKbJ0CMANSRd65oeHI0oSQgr0DifbQhRqGDM06v84w20WimJbFLVtF9P+uq1gvm0JIgxKWwoUuQive2"
+ "ICSuUmJFoAlH+Ja4n0Ek9vG32woFdVQQ7lJZUC4RnK+Y4+3jMPBE+z5vjW94r9aSCKgOYaZ+2YiUs7lrgm+w3bXe2V+yW3auWfatKDsQ"
+ "8DLH3Q2BS/T47HUcgjQSMva3Vtdd/JQbKXovkpJBklEA+fwIDAQABAoICAHz//EgSPHDXly8LzLO7liQxGMHRkZyPPncHihwEqAlkUl6"
+ "FblavofozsLPZ3lqkuyvGcR3ODTqJ4PAJJPthqjsXm+CAWTZiQ3TvKyAE6ZkhTj6C2y2/SGHi0lPoKJbpe91DTgn3Q+VFJ1U4kkv4Izm"
+ "xZj20QAZZs8fNqqjO817a39TWy247N1fVoP1ud75YPc8JUb9LfRQqZOv1wljHqmhFgETzQK+0Xyu6RLCYBmS6qgS7HCUweAx5/73fMfN"
+ "7zRVk4VZWRNXjn2F4tHXunSdz3bp+xJtfpQpMOQQV2feq7MUNV0AdS7EiPkh77qhsGCemuyBNZDdOoDOutP/J2xa+3Faf2iYMaxVNyY4"
+ "5qG2CUhlugqTnZYJuMiqAE/XkfMyQksWmpRLubm2Yd2LzOOJDEWxsEFPHIH9jyZeB/bXIlpTHX5q5CaaH/aBJkSn5lprgNu5zabuxlpP"
+ "WXMXROg1z/ZPY4G4auTxK0QcQ63iCw05EFmH5mheP5bTf2T3P/JLlpPcWJW54mNmb8yC/FhXWdyl5iU2J9hH03BJWyeucj5tmSSkFR+N"
+ "to+FiSHkrqmxLcrwu1g2zjRaFXtoBrPwxAg5A/4UqofvcCXA8Tp3yWzuyuQyEwvmHgEb3DTTHfqbokr/0lNDAz+J2cnvEmR/6tctgONo"
+ "L1vcvHnVGkEVRAoIBAQDFSmbHkeAz1dPkFXchGn0a6UyGXJSrWE9G/f5lUJCdLuR1iYVIbbtPaR/LzvWlfiB2oxA3MnAbKP5dkx7bj7E"
+ "rJsFQdWenaN0dje0iVuvwUKXwFuUpmgRNHg52657TdUtgpEVvK8Y+NEYeFgyp6LHDofYvQgDutJccTqicT33E43ESU6EO1xzO36oI9C+"
+ "hbN5SAXiMXtNGAmSgTi1hMquKxg6MGgkQOsn1gNQGWDCSKqXvVW+SiVIT7uhTOIdHbHEVZjQbkKuxeVpnKZjQp+XAwt/5uhP6gEZDh8D"
+ "hQQ0vqlS4CIdEccWuNfL8fuHTZb1mdPpvKv4NJGaDUZOO7XhHAoIBAQCyeiKqjZXc604csW76lIXsNqOk1uoRTlIsXXcWeUOocGbIAun"
+ "SZt2LOnc5Ph0W9YbqUZlA6e+78EImXLK37sTBdC8XCeSE9nlbIZCi+0LO6ptwXsL7Ww4ljXE5sfPJYyzTSa3oTC6BNZbzEdhTXtAatDT"
+ "/R2iltflkT8Df1Nvsk/0RBqUKTJIXLkmY6iX3qJx93mMsF3RRJf9IVuqrJG9/EQwFkrBOMATLu6P8weBv4MWOivo1Sa8DBf4w5ybD3Fw"
+ "RZye/G7VAwtVIfy9qVmRik+3+5KJnLNnVdQziNMmwHqiyzWyJFsdKn6w0/sh2Bu5NzdZC3KtlB7KCEcpgJtwJAoIBAAmAL7rkl3tnjLC"
+ "rJ/V8JRIqsfi2dKJbulWc3adbXdtz6qSOXtDCGAcW9OUHrmSt0jpkV9+Qmj10l+tBrna8ULfXQe/x92/kaOGHeCfzL6F/AL6zG44JULO"
+ "2AtRPPHLKbzrULlPQM9fDBK1mOm3kOstE/WoBL7JPGAfQ8eW1HkVg/oz3YgYo7cY4lyOfPrvzVjF0yK1Z06rHarkdiqnnmsMwDntIta8"
+ "GZbtg3NUBYjVnwF3qK1lPK5iyJJX9XuZdnoR9S30YVmxRf70AD8/chf/mYorQHy4tBzUxUGSIkW3+Md466uis4ewlxPHL2mwnths8/uJ"
+ "jm6BeZGFmiEiVvvkCggEAVERkX8CP1InpDJUeAAPmI3w80ZSDWX5wP/A1TRAeSMYhUShG/AeDbLxDFGzmUTPF6pZyVHrfrQ2oPfKgk0W"
+ "R8oEHxsnt8nVpIQT9BGa7yXRtxaWITCNWz5Yzsnj50MkZnfz4tmhZwLnrtoJjcCGhAiq5pxoxJ6R+xsT9HPGkkNPitYo8nFtA0t8Q8rk"
+ "DCia7FJbOnj/ItJPLL32SORHv7r++vFbhFVmIuiSzLaDgdhJbVIz7y/MpRbUrqi1JWUqO0cyxsILFlnknOJ6MZZm6teyAf0u1/h7oDuf"
+ "AGIGyBIzFO/7P0v5FRE+VgEQXo9pr46JfGpyT9BSpTM5XjgRq+QKCAQEAnEmbWou2KBCrxfFD1rzUmAT559/X7QKj2xxuxnd1L7PTkfT"
+ "x1rXgtRNrP2XHj6eIP6ak9Z9d+rrisM0RaBghYGNbEbnDUveavc8lHR6Mtq0gV4VCNX1ZD5QcX5JSd59rKBlXmEDHfYIEaPmXwa7kUIQ"
+ "noyy8VhpLiY3R7U17xN/X65/mgKdjvs981dQvkiSVylHTC29mpM0ewr4ZWZRl7gx40wBk4mKGmWpCxMQt8llFEVoq+n1RlGaFMTJcx6h"
+ "ROYkhvUUj6/Z1OJnZHdoI1IM4bA6zjXEf0qyNDIbIcS84E7+k9jFaXQt4rpzhd591hgbukqvZa6MgicFJEQjxAw==";
private final static int MOCK_EXPIRATION = 3600000;
private final static String MOCK_ISSUER = "http://localhost:999";
private final static String CLIENT_ID = "com.idvsbruck.pplflw.api";
@Value("${security.oauth2.client.jwtKeyUri}")
private String jwtKeyUri;
@Value(value = "${security.oauth2.client.scopes}")
private String clientScopes;
@Autowired
private RestTemplate restTemplate;
@PostConstruct
public void init() throws Exception {
mockAuthorizationServer();
}
@Bean
public MockRestServiceServer mockAuthorizationServer() throws Exception {
var mockServer = bindTo(restTemplate).bufferContent().build(new SimpleRequestExpectationManager());
mockServer.expect(manyTimes(), requestTo(jwtKeyUri)).andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.OK).body(getPublicKey()));
((OAuth2RestTemplate) restTemplate).getOAuth2ClientContext()
.setAccessToken(new DefaultOAuth2AccessToken(getClientToken()));
return mockServer;
}
public static String getToken(final String email, final List<String> scopes) throws Exception {
var now = System.currentTimeMillis();
return Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(new Date(now)).setSubject(email)
.setIssuer(MOCK_ISSUER).setExpiration(new Date(now + MOCK_EXPIRATION)).claim("user_name", email)
.claim("azp", CLIENT_ID).claim("scope", scopes).claim("authorities", List.of("USER"))
.claim("client_id", CLIENT_ID).setHeaderParam("typ", "JWT")
.signWith(SignatureAlgorithm.RS256, getPrivateKey()).compact();
}
private String getClientToken() throws Exception {
var now = System.currentTimeMillis();
return Jwts.builder().setId(UUID.randomUUID().toString()).setIssuedAt(new Date(now)).setIssuer(MOCK_ISSUER)
.setExpiration(new Date(now + MOCK_EXPIRATION)).setAudience(CLIENT_ID).claim("azp", CLIENT_ID)
.claim("scope", clientScopes).claim("client_id", CLIENT_ID)
.setHeaderParam("typ", "JWT").signWith(SignatureAlgorithm.RS256, getPrivateKey()).compact();
}
private String getPublicKey() throws Exception {
var privateKeySpec = KeyFactory.getInstance("RSA").getKeySpec(getPrivateKey(), RSAPrivateKeySpec.class);
var modulus = Base64Utils.encodeToString(privateKeySpec.getModulus().toByteArray());
var exponent = Base64Utils.encodeToString(BigInteger.valueOf(65537).toByteArray());
return modulus + "|" + exponent;
}
private static PrivateKey getPrivateKey() throws Exception {
var keySpec = new PKCS8EncodedKeySpec(Base64Utils.decode(MOCK_PRIVATE_KEY_STR.getBytes()));
return KeyFactory.getInstance("RSA").generatePrivate(keySpec);
}
}
| 66.274194 | 120 | 0.790582 |
38c780f75ca86a4a2590d0c9ddd51f137a6e3873 | 1,415 | package com.jerry.bookcloud.homepage.dao;
import com.jerry.bookcloud.common.pojo.index.IndexBanner;
public interface IndexBannerMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
int insert(IndexBanner record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
int insertSelective(IndexBanner record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
IndexBanner selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
int updateByPrimaryKeySelective(IndexBanner record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table index_banner
*
* @mbg.generated
*/
int updateByPrimaryKey(IndexBanner record);
} | 26.698113 | 65 | 0.669965 |
97bbfa7e6b54b3fcd07a451046d5256b64f898e0 | 4,888 | package pl.edu.uwb.mobiuwb.controls.dialogs;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.ListAdapter;
import pl.edu.uwb.mobiuwb.interfaces.OnValueChangedListener;
import pl.edu.uwb.mobiuwb.view.settings.adapter.items.dialog.itempicker.ListPickerItemModel;
/**
* {@inheritDoc}
* Ten twórca tworzy okienko z listą.
*/
public class ListDialog extends DialogCreator<Integer>
{
/**
* Jest to adapter kontrolki listy przechowujący jej elementy.
*/
private ListAdapter listAdapter;
/**
* Pobiera adapter kontrolki listy, który przechowuje jej elementy.
* @return Adapter kontrolki listy.
*/
public ListAdapter getAdapter()
{
return listAdapter;
}
/**
* Inicjuje zmienne.
* @param listAdapter Adapter kontrolki listy
*/
public ListDialog(ListAdapter listAdapter)
{
super();
this.listAdapter = listAdapter;
}
/**
* {@inheritDoc}
*/
@Override public DialogFragment create()
{
DialogFragment dialogFragment =
new SimpleDialogFragment((ListPickerItemModel) model, valueChange, listAdapter);
return dialogFragment;
}
/**
* Jest to klasa fragmentu tego okienka. Fragment ten tworzony jest
* przez tą klasę, aby utworzyć jej okno.
*/
public static class SimpleDialogFragment extends DialogFragment
implements DialogInterface.OnClickListener
{
/**
* Reprezentuje instancję modelu w ekranie Opcji, który to jest
* odpowiedzialny za funkcjonalność wyświetlenia okienka z listą.
*/
private ListPickerItemModel model;
/**
* Jest to adapter kontrolki listy przechowujący jej elementy.
*/
private ListAdapter listAdapter;
/**
* Pobiera reprezentację instancji modelu w ekranie Opcji, który to jest
* odpowiedzialny za funkcjonalność wyświetlenia okienka z listą.
* @return Model reprezentujący element Opcji.
*/
public ListPickerItemModel getModel()
{
return model;
}
/**
* Nadaje reprezentację instancji modelu w ekranie Opcji, który to jest
* odpowiedzialny za funkcjonalność wyświetlenia okienka z listą.
* @param model Model reprezentujący element Opcji.
*/
private void setModel(ListPickerItemModel model)
{
this.model = model;
}
/**
* Wydarza się, gdy zostanie zmieniona wartość w okienku, czyli kiedy
* user wybierze nową wartość z listy.
*/
private OnValueChangedListener valueChange;
/**
* Tworzy obiekt.
* Fragmenty wymagają takiego konstruktora.
*/
public SimpleDialogFragment()
{
}
/**
* Tworzy obiekt i nadaje pola.
* @param model Reprezentuje instancję modelu w ekranie Opcji,
* który to jest odpowiedzialny za funkcjonalność
* wyświetlenia okienka z listą.
* @param valueChange Nasłuchiwacz na zmianę wartości.
* @param listAdapter Jest to adapter kontrolki
* listy przechowujący jej elementy.
*/
public SimpleDialogFragment(ListPickerItemModel model,
OnValueChangedListener valueChange,
ListAdapter listAdapter)
{
this.model = model;
this.valueChange = valueChange;
this.listAdapter = listAdapter;
}
/**
* Metoda ta wywołuje się, gdy tworzy się niniejszy fragment dialoga.
* Nadaje dialogowi tytuł oraz adapter, oraz wydarzenie
* dotknięcia opcji na dialogu.
* @param savedInstanceState Zapisany stan tej kontrolki, w przypadku re-kreacji jej.
* @return Nowy dialog.
*/
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(model.getTitle())
.setAdapter(listAdapter,this);
return builder.create();
}
/**
* Wywołuje się gdy dotkniemy opcji na dialogu.
* Dodatkowo wywołuje wydarzenie zmiany wartości w dialogu.
* @param dialog Dotknięty dialog.
* @param which Która opcja została dotknięta.
*/
@Override
public void onClick(DialogInterface dialog, int which)
{
if (valueChange != null)
{
valueChange.notifyChanged(model.getValue(), which);
}
}
}
}
| 31.133758 | 96 | 0.611702 |
e38f6625340dec5780d7c978cfb2ff97eaa17598 | 300 | package com.foreseeti.corelib.math;
public class FTruncatedNormalDistribution implements FDistribution<Double> {
public static FDistribution<Double> getDist(double m, double sd) {
return new FTruncatedNormalDistribution();
}
public Double sample() {
return Double.valueOf(0.0);
}
}
| 25 | 76 | 0.756667 |
9c8803176425aa7b793b3c3d497fe49ab938a927 | 7,997 | package dk.muj.derius;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.logging.Level;
import org.bukkit.Material;
import org.bukkit.plugin.Plugin;
import com.massivecraft.massivecore.MassivePlugin;
import com.massivecraft.massivecore.util.ReflectionUtil;
import com.massivecraft.massivecore.util.Txt;
import com.massivecraft.massivecore.xlib.gson.Gson;
import com.massivecraft.massivecore.xlib.gson.JsonElement;
import dk.muj.derius.api.BlockBreakExpGain;
import dk.muj.derius.api.Derius;
import dk.muj.derius.api.DeriusAPI;
import dk.muj.derius.api.ScheduledDeactivate;
import dk.muj.derius.api.ability.Ability;
import dk.muj.derius.api.events.AbilityRegisteredEvent;
import dk.muj.derius.api.events.SkillRegisteredEvent;
import dk.muj.derius.api.inventory.SpecialItemManager;
import dk.muj.derius.api.player.DPlayer;
import dk.muj.derius.api.skill.Skill;
import dk.muj.derius.engine.EngineActivate;
import dk.muj.derius.engine.EngineMain;
import dk.muj.derius.engine.EngineScheduledDeactivate;
import dk.muj.derius.entity.AbilityColl;
import dk.muj.derius.entity.MConf;
import dk.muj.derius.entity.SkillColl;
import dk.muj.derius.entity.mplayer.MPlayerColl;
import dk.muj.derius.inventory.ItemManager;
public class DeriusCore implements Derius
{
// -------------------------------------------- //
// INSTANCE & CONSTRUCT
// -------------------------------------------- //
private static DeriusCore i = new DeriusCore();
public static DeriusCore get() { return i; }
private DeriusCore() {}
// -------------------------------------------- //
// INJECT
// -------------------------------------------- //
public static void inject()
{
Class<DeriusAPI> apiClass = DeriusAPI.class;
Field coreField = ReflectionUtil.getField(apiClass, DeriusConst.API_DERIUS_FIELD);
if (coreField != null)
{
if (ReflectionUtil.makeAccessible(coreField))
{
ReflectionUtil.setField(coreField, null, get());
}
}
}
// -------------------------------------------- //
// DEBUG
// -------------------------------------------- //
@Override
public void debug(int level, String format, Object... args)
{
if (MConf.get().debugLevel < level) return;
String message = Txt.parse(format, args);
DeriusPlugin.get().log(Level.INFO, message);
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: DATABASE
// -------------------------------------------- //
@Override
public Gson getGson(Plugin plugin)
{
if (plugin instanceof MassivePlugin)
{
return ((MassivePlugin) plugin).gson;
}
return DeriusPlugin.get().gson;
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: DPLAYER
// -------------------------------------------- //
@Override
public Collection<? extends DPlayer> getAllDPlayers()
{
return MPlayerColl.get().getAll();
}
@Override
public DPlayer getDPlayer(Object senderObject)
{
return MPlayerColl.get().get(senderObject, false);
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: SKILL
// -------------------------------------------- //
@Override
public Collection<? extends Skill> getAllSkills()
{
return SkillColl.getAllSkills();
}
@Override
public Skill getSkill(String id)
{
return SkillColl.get().get(id);
}
@Override
public void registerSkill(Skill skill)
{
SkillRegisteredEvent event = new SkillRegisteredEvent(skill);
if ( ! event.runEvent()) return;
DeriusAPI.debug(1000, "<i>Registering skill <h>%s<i>.", skill.getName());
if ( skill.isRegistered()) throw new IllegalArgumentException("Skill is already registered.");
this.ensureSkillIsLoaded(skill.getId());
Skill old = SkillColl.get().get(skill.getId(), false);
// If an old skill was in the system...
if (old != null)
{
DeriusAPI.debug(1000, "<i>Loading old values for skill <h>%s<i>.", skill.getName());
// ...it configurations we would like to keep.
skill.load(old);
// Now remove the old one from the system.
SkillColl.get().removeAtLocal(skill.getId());
}
SkillColl.get().attach(skill, skill.getId());
return;
}
// Sometimes skills aren't loaded properly on init.
// This method should counter that.
private void ensureSkillIsLoaded(String id)
{
SkillColl coll = SkillColl.get();
// This might fail if the skill actually wasn't in the database...
try
{
// First we load the value.
Entry<JsonElement, Long> value = coll.getDb().load(coll, id);
if (value.getValue() == null || value.getValue().longValue() == 0) return;
// Then we load it into our system.
coll.loadFromRemote(id, value);
}
// ...so we fail silently.
catch(Throwable t) { t.printStackTrace(); } // We might fail silently, when releasing the plugin.
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: ABILITY
// -------------------------------------------- //
@Override
public Collection<? extends Ability<?>> getAllAbilities()
{
return AbilityColl.getAllAbilities();
}
@Override
public Ability<?> getAbility(String id)
{
return AbilityColl.get().get(id);
}
@Override
public void registerAbility(Ability<?> ability)
{
AbilityRegisteredEvent event = new AbilityRegisteredEvent(ability);
if ( ! event.runEvent()) return;
if (ability.isRegistered()) throw new IllegalArgumentException("Ability<?> is already registered.");
this.ensureAbilityIsLoaded(ability.getId());
Ability<?> old = AbilityColl.get().get(ability.getId(), false);
if (old != null)
{
ability.load(old);
AbilityColl.get().removeAtLocal(ability.getId());
}
AbilityColl.get().attach(ability, ability.getId());
return;
}
private void ensureAbilityIsLoaded(String id)
{
AbilityColl coll = AbilityColl.get();
// This might fail if the ability actually wasn't in the database...
try
{
// First we load the value.
Entry<JsonElement, Long> value = coll.getDb().load(coll, id);
if (value.getValue() == null || value.getValue().longValue() == 0) return;
// Then we load it into our system.
coll.loadFromRemote(id, value);
}
catch(Throwable t) { t.printStackTrace(); } // We might fail silently, when releasing the plugin.
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: EXP
// -------------------------------------------- //
public void registerExpGain(BlockBreakExpGain gainer)
{
EngineActivate.registerExpGain(gainer);
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: PREPARABLE TOOLS
// -------------------------------------------- //
@Override
public Collection<Material> getPreparableTools()
{
return EngineMain.getPreparableTools();
}
@Override
public void registerPreparableTools(Collection<Material> materials)
{
EngineMain.registerPreparableTools(materials);
}
@Override
public void registerPreparableTool(Material material)
{
EngineMain.registerPreparableTool(material);
}
@Override
public boolean isRegisteredAsPreparable(Material material)
{
return EngineMain.isRegisteredAsPreparable(material);
}
@Override
public void unregisterPreparableTool(Material material)
{
EngineMain.unregisterPreparableTool(material);
}
// -------------------------------------------- //
// OVERRIDE: DERIUS: SCHEDULED TELEPORT
// -------------------------------------------- //
@Override
public boolean isScheduled(ScheduledDeactivate sd)
{
return EngineScheduledDeactivate.get().isScheduled(sd);
}
@Override
public void schedule(ScheduledDeactivate sd)
{
EngineScheduledDeactivate.get().schedule(sd);
}
// -------------------------------------------- //
// OTHER
// -------------------------------------------- //
/**
* Registers a special item manager, used to avoid cheating.
* @param {SpecialItemManager} manager to activate.
*/
public void registerSpecialItemManager(SpecialItemManager manager)
{
ItemManager.addManager(manager);
}
}
| 27.4811 | 102 | 0.623859 |
7e93356cc891be2edbd3fd5cbbb3fa4d485cf8dd | 93 |
class i
{
public static void main(int f)
{
int c;
c=(5*f-160)/9;
System.out.println(c);
}
}
| 8.454545 | 30 | 0.623656 |
d99b7bafd7312c12620bd9766a74b32bcf350c33 | 1,363 | package tv.dyndns.kishibe.qmaclone.client.game;
import org.junit.Test;
import tv.dyndns.kishibe.qmaclone.client.QMACloneGWTTestCaseBase;
public class AnswerViewImplTest extends QMACloneGWTTestCaseBase {
private AnswerViewImpl view;
@Test
public void testSetGetWithoutFrame() {
view = new AnswerViewImpl(2, 4, false);
assertEquals("", view.get());
assertEquals("", view.getText());
view.set("あ", false);
assertEquals("あ", view.get());
assertEquals("あ", view.getText());
}
@Test
public void testSetGetWithFrame() {
view = new AnswerViewImpl(2, 4, true);
assertEquals("", view.get());
assertEquals("□□", view.getText());
view.set("あ", true);
assertEquals("あ", view.get());
assertEquals("あ□", view.getText());
}
@Test
public void testSetGetLongString() {
view = new AnswerViewImpl(2, 4, false);
view.set("あいう", false);
assertEquals("あい", view.get());
assertEquals("あいう", view.getText());
view.set("あいうえお", false);
assertEquals("あい", view.get());
assertEquals("あいうえ", view.getText());
}
@Test
public void testGetRaw() {
view = new AnswerViewImpl(2, 4, false);
view.set("あいう", false);
assertEquals("あい", view.get());
assertEquals("あいう", view.getText());
assertEquals("あいう", view.getRaw());
view.set("あいうえお", false);
assertEquals("あい", view.get());
assertEquals("あいうえ", view.getRaw());
}
}
| 23.101695 | 65 | 0.669846 |
839a87815524427b812807655d981668e2139275 | 9,107 | package com.alisenturk.elasticlogviewer.dao;
import com.alisenturk.elasticlogger.data.Bucket;
import com.alisenturk.elasticlogger.data.ElasticData;
import com.alisenturk.elasticlogger.data.FilterType;
import com.alisenturk.elasticlogger.data.OrderByType;
import com.alisenturk.elasticlogger.data.SearchParam;
import com.alisenturk.elasticlogger.data.VariableType;
import com.alisenturk.elasticlogger.service.DataReader;
import com.alisenturk.elasticlogger.service.ElasticService;
import com.alisenturk.elasticlogger.service.ElasticSetting;
import com.alisenturk.elasticlogger.service.HttpResponseData;
import com.alisenturk.elasticlogviewer.entity.AppLogData;
import com.alisenturk.elasticlogviewer.entity.AppLogSearchCriteria;
import com.alisenturk.elasticlogviewer.enums.Index;
import com.alisenturk.elasticlogviewer.util.Helper;
import com.google.gson.Gson;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
/**
*
* @author alisenturk
*/
@Stateless
public class AppLogDAO implements Serializable{
private ElasticSetting setting = null;
private ElasticService<AppLogData> elasticService = null;
private void init(){
setting = new ElasticSetting();
setting.setHostAddress(Helper.getAppParameterValue("elastic.host")); //host adresi
setting.setPortNumber(Helper.getAppParameterValue("elastic.port")); //port
setting.setIndexName(Index.APPLOG.getIndexName());
setting.setMappingName(Index.APPLOG.getMappingName());
setting.setDebugMode(true); //Debug modu açar
elasticService = ElasticService.createElasticService(setting);
}
private AppLogSearchCriteria criteria = new AppLogSearchCriteria();
@PostConstruct
private void loadInit(){
init();
}
public List<String> getProjectList(){
List<String> list = new ArrayList<>();
HttpResponseData responseData = null;
try{
responseData = elasticService.groupBy("project");
if(responseData.getStatusCode().equals("OK")){
Gson gson = new Gson();
ElasticData elasticData = gson.fromJson(responseData.getResponseData(),new ElasticData().getClass());
List<Bucket> buckets = elasticData.getAggregations().getGroup_by_state().getBuckets();
if(elasticData!=null){
for(Bucket bucket:buckets){
list.add(bucket.getKey());
}
}
}
}catch(Exception e){
}
return list;
}
public List<String> getServiceNametList(){
List<String> list = new ArrayList<>();
HttpResponseData responseData = null;
try{
responseData = elasticService.groupBy("serviceName");
if(responseData.getStatusCode().equals("OK")){
Gson gson = new Gson();
ElasticData elasticData = gson.fromJson(responseData.getResponseData(),new ElasticData().getClass());
List<Bucket> buckets = elasticData.getAggregations().getGroup_by_state().getBuckets();
if(elasticData!=null){
for(Bucket bucket:buckets){
list.add(bucket.getKey());
}
}
}
}catch(Exception e){
}
return list;
}
public List<String> getTransactiontList(){
List<String> list = new ArrayList<>();
HttpResponseData responseData = null;
try{
responseData = elasticService.groupBy("transactionId");
if(responseData.getStatusCode().equals("OK")){
Gson gson = new Gson();
ElasticData elasticData = gson.fromJson(responseData.getResponseData(),new ElasticData().getClass());
List<Bucket> buckets = elasticData.getAggregations().getGroup_by_state().getBuckets();
if(elasticData!=null){
for(Bucket bucket:buckets){
list.add(bucket.getKey());
}
}
}
}catch(Exception e){
}
return list;
}
private List<String> getObjectFields(Class clzz){
List<String> fields = new ArrayList<>();
Field[] fieldList = clzz.getDeclaredFields();
for(Field field:fieldList){
fields.add(field.getName());
}
return fields;
}
public List<AppLogData> getAppLogs(){
List<AppLogData> list = new ArrayList<>();
try{
String[] query = new String[1];
if(criteria.getKeyword()!=null && criteria.getKeyword().length()>2){
query[0] = criteria.getKeyword();
}
String[] project = new String[1];
project[0] = criteria.getProjectName();
String[] dateRange = new String[2];
dateRange[0] = Helper.date2String(criteria.getBeginDate(),"yyyyMMddHHmmss");
dateRange[1] = Helper.date2String(criteria.getEndDate(),"yyyyMMddHHmmss");
List<String> fields = new ArrayList<String>();
fields.addAll(getObjectFields(AppLogData.class));
List<SearchParam> mustParams = new ArrayList<>();
List<SearchParam> shouldParams = new ArrayList<>();
mustParams.add(new SearchParam("project", FilterType.TERM,project, VariableType.STRING));
mustParams.add(new SearchParam("processDate", FilterType.RANGE,dateRange, VariableType.INT));
if(criteria.getServiceName()!=null && criteria.getServiceName().length()>2){
String[] service = new String[1];
service[0] = criteria.getServiceName();
mustParams.add(new SearchParam("serviceName", FilterType.TERM,service, VariableType.STRING));
}
if(criteria.getTransactionId()!=null && criteria.getTransactionId().length()>2){
String[] service = new String[1];
service[0] = criteria.getTransactionId();
mustParams.add(new SearchParam("transactionId", FilterType.TERM,service, VariableType.STRING));
}
if(query[0]!=null){
if(criteria.getKeyword()!=null && (criteria.getKeyword().indexOf("*")>-1 || criteria.getKeyword().indexOf("?")>-1) ){
String words[] = criteria.getKeyword().split(" ");
String str2[] = new String[1];
for(String word:words){
str2 = new String[1];
str2[0] = word;
shouldParams.add(new SearchParam("requestData", FilterType.WILDCARD,str2, VariableType.STRING));
}
for(String word:words){
str2 = new String[1];
str2[0] = word;
shouldParams.add(new SearchParam("responseData", FilterType.WILDCARD,str2, VariableType.STRING));
}
}else if(criteria.getKeyword()!=null && criteria.getKeyword().indexOf(" ")>-1 && (criteria.getKeyword().indexOf("*")>-1 || criteria.getKeyword().indexOf("?")>-1) ){
shouldParams.add(new SearchParam("requestData", FilterType.REGEXP,query, VariableType.STRING));
shouldParams.add(new SearchParam("responseData", FilterType.REGEXP,query, VariableType.STRING));
}else{
shouldParams.add(new SearchParam("requestData", FilterType.TERM,query, VariableType.STRING));
shouldParams.add(new SearchParam("responseData", FilterType.TERM,query, VariableType.STRING));
}
}
HttpResponseData responseData = elasticService.search(mustParams,shouldParams,250, 0, fields, "processDate",OrderByType.DESC);
if(responseData.getStatusCode().equals("OK")){
DataReader<AppLogData> reader = new DataReader<>();
list = reader.read(responseData.getResponseData(),AppLogData.class);
}else{
System.out.println("HATA..:" + responseData.toString());
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
public AppLogSearchCriteria getCriteria() {
return criteria;
}
public void setCriteria(AppLogSearchCriteria criteria) {
this.criteria = criteria;
}
}
| 41.967742 | 180 | 0.571758 |
7aba2e2ed5a56d290ea3d696c2cdd55a8d1454f1 | 4,636 | package com.example.android.miwok;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.provider.UserDictionary;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class FamilyActivity extends AppCompatActivity {
MediaPlayer nm;
AudioManager maudioManager;
private AudioManager.OnAudioFocusChangeListener monaudiofocuschange=new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int i) {
if (i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
i == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
nm.pause();
nm.seekTo(0);
} else if (i == AudioManager.AUDIOFOCUS_GAIN) {
// The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
nm.start();
} else if (i == AudioManager.AUDIOFOCUS_LOSS) {
// The AUDIOFOCUS_LOSS case means we've lost audio focus and
// Stop playback and clean up resources
releaseMediaPlayer();
}
}
};
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
// Now that the sound file has finished playing, release the media player resources.
releaseMediaPlayer();
}
};
@Override
protected void onStop() {
super.onStop();
releaseMediaPlayer();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_family);
maudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
final ArrayList<word> Numbers = new ArrayList<word>();
Numbers.add(new word("Brother","ભાઈ ",R.drawable.family_son,R.raw.bro));
Numbers.add(new word("Father","પિતા ",R.drawable.family_father,R.raw.father));
Numbers.add(new word("Mother","માતા ",R.drawable.family_mother,R.raw.mother));
Numbers.add(new word("Sister","બહેન ",R.drawable.family_daughter,R.raw.sis));
Numbers.add(new word("GrandFather","દાદા ",R.drawable.family_grandfather,R.raw.gfather));
Numbers.add(new word("GrandMother","દાદી ",R.drawable.family_grandmother,R.raw.gmother));
Numbers.add(new word("Uncle","કાકા ",R.drawable.family_older_brother,R.raw.uncle));
Numbers.add(new word("Aunt","કાકી ",R.drawable.family_older_sister,R.raw.aunt));
Numbers.add(new word("Grandson","પૌત્ર ",R.drawable.family_younger_brother,R.raw.grandson));
Numbers.add(new word("Niece","ભત્રીજી ",R.drawable.family_younger_sister,R.raw.niece));
wordAdapter itemsAdapter = new wordAdapter(this,Numbers,R.color.category_family);
ListView listView = (ListView) findViewById(R.id.list3);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
word word= Numbers.get(i);
releaseMediaPlayer();
int result = maudioManager.requestAudioFocus(monaudiofocuschange,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
nm = MediaPlayer.create(FamilyActivity.this, word.getaudio());
nm.start();
nm.setOnCompletionListener(mCompletionListener);
}
}
});
}
private void releaseMediaPlayer()
{
// If the media player is not null, then it may be currently playing a sound.
if (nm != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
nm.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
nm = null;
maudioManager.abandonAudioFocus(monaudiofocuschange);
}
}
}
| 44.576923 | 119 | 0.649267 |
42cd8d1486e03afda1ce9024e546210a7eeff437 | 319 | package com.starterkit.springboot.brs.repository.user;
import com.starterkit.springboot.brs.model.user.User;
import org.springframework.data.repository.CrudRepository;
/**
* Created by Arpit Khandelwal.
*/
public interface UserRepository extends CrudRepository<User, Long> {
User findByEmail(String email);
}
| 22.785714 | 68 | 0.789969 |
4432a0a476610aef3fde8115810a70065a30d12b | 2,489 | package models;
import models.*;
import java.io.Serializable;
import java.util.List;
public class Test implements Serializable {
int id;
String name;
String subject;
int autoCorrectedTest;
int totalTime;
int teacher_id;
List<Question> questions;
List<Student> students;
Teacher teacher;
public Test() {
}
public Test( String name, String subject, int autoCorrectedTest, int totalTime, int teacher_id) {
this.name = name;
this.subject = subject;
this.autoCorrectedTest = autoCorrectedTest;
this.totalTime = totalTime;
this.teacher_id = teacher_id;
}
public Test(int id, String name, String subject, int autoCorrectedTest, int totalTime, int teacher_id) {
System.out.println("new user");
this.id = id;
this.name = name;
this.subject = subject;
this.autoCorrectedTest = autoCorrectedTest;
this.totalTime = totalTime;
this.teacher_id = teacher_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public List<Question> getQuestions() {
return questions;
}
public int getAutoCorrectedTest() {
return autoCorrectedTest;
}
public void setAutoCorrectedTest(int autoCorrectedTest) {
this.autoCorrectedTest = autoCorrectedTest;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
public List<Student> getStudents() {
return students;
}
public int getTeacher_id() {
return teacher_id;
}
public void setTeacher_id(int teacher_id) {
this.teacher_id = teacher_id;
}
//
// public void setStudents(List<Student> students) {
// this.students = students;
// }
public int getTotalTime() {
return totalTime;
}
public void setTotalTime(int totalTime) {
this.totalTime = totalTime;
}
public void setTeacher(Teacher teacher){
this.teacher = teacher;
}
}
| 22.026549 | 109 | 0.586179 |
fff6801b9291ce1a3dbb2e5112560b194109286b | 724 | package org.osrs.api.wrappers.proxies;
import org.osrs.injection.bytescript.BClass;
import org.osrs.injection.bytescript.BField;
import org.osrs.injection.bytescript.BFunction;
import org.osrs.injection.bytescript.BMethod;
import org.osrs.injection.bytescript.BGetter;
import java.awt.event.MouseWheelEvent;
@BClass(name="MouseWheelListener")
public class MouseWheelListener implements org.osrs.api.wrappers.MouseWheelListener{
@BField
public int rotation;
@BGetter
@Override
public int rotation(){return rotation;}
@BMethod(name="mouseWheelMoved0")
public void mouseWheelMoved0(MouseWheelEvent var1) {}
@BFunction
@Override
public void mouseWheelMoved(MouseWheelEvent var1) {
mouseWheelMoved0(var1);
}
} | 26.814815 | 84 | 0.808011 |
23193648a2fbf3c1ea24ffbf62885c88d864bcd3 | 3,778 | // Copyright 2020 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.chrome.browser.tab.state;
import androidx.annotation.MainThread;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.Callback;
import org.chromium.base.supplier.Supplier;
import org.chromium.chrome.browser.profiles.Profile;
import java.util.Locale;
/**
* {@link LevelDBPersistedTabDataStorage} provides a level db backed implementation
* of {@link PersistedTabDataStorage}.
*/
public class LevelDBPersistedTabDataStorage implements PersistedTabDataStorage {
// In a mock environment, the native code will not be running so we should not
// make assertions about mNativePersistedStateDB
// LevelDBPersistedTabDataStorage needs to have an empty namespace for backwards compatibility.
// LevelDBPersitsedDataStorage is a generalization of the original
// LevelDBPersistedTabDataStorage which introduced namespaces to avoid collisions between
// clients.
private static String sNamespace = "";
private LevelDBPersistedDataStorage mPersistedDataStorage;
// Callback is only used for synchronization of save and delete in testing.
// Otherwise it is a no-op.
// TODO(crbug.com/1146799) Apply tricks like @CheckDiscard or @RemovableInRelease to improve
// performance
private boolean mIsDestroyed;
LevelDBPersistedTabDataStorage(Profile profile) {
assert !profile.isOffTheRecord()
: "LevelDBPersistedTabDataStorage is not supported for incognito profiles";
mPersistedDataStorage = new LevelDBPersistedDataStorage(profile, sNamespace);
}
@MainThread
@Override
public void save(int tabId, String dataId, Supplier<byte[]> dataSupplier) {
mPersistedDataStorage.save(getKey(tabId, dataId), dataSupplier.get());
}
@MainThread
public void saveForTesting(int tabId, String dataId, byte[] data, Runnable onComplete) {
mPersistedDataStorage.saveForTesting(getKey(tabId, dataId), data, onComplete); // IN-TEST
}
@MainThread
@Override
public void restore(int tabId, String dataId, Callback<byte[]> callback) {
mPersistedDataStorage.load(getKey(tabId, dataId), callback);
}
/**
* Synchronous restore was an exception provided for an edge case in
* {@link CriticalPersistedTabData} and is not typically part of the public API.
*/
@Deprecated
@MainThread
@Override
public byte[] restore(int tabId, String dataId) {
assert false : "Synchronous restore is not supported for LevelDBPersistedTabDataStorage";
return null;
}
@MainThread
@Override
public void delete(int tabId, String dataId) {
mPersistedDataStorage.delete(getKey(tabId, dataId));
}
@MainThread
public void deleteForTesting(int tabId, String dataId, Runnable onComplete) {
mPersistedDataStorage.deleteForTesting(getKey(tabId, dataId), onComplete); // IN-TEST
}
@Override
public String getUmaTag() {
return "LevelDB";
}
// TODO(crbug.com/1145785) Implement URL -> byte[] mapping rather
// than tab id -> byte[] mapping so we don't store the same data
// multiple times when the user has multiple tabs at the same URL.
private static final String getKey(int tabId, String dataId) {
return String.format(Locale.US, "%d-%s", tabId, dataId);
}
/**
* Destroy native instance of persisted_tab_state
*/
public void destroy() {
mPersistedDataStorage.destroy();
mIsDestroyed = true;
}
@VisibleForTesting
protected boolean isDestroyed() {
return mIsDestroyed;
}
}
| 35.308411 | 99 | 0.716517 |
9d5f7b2ba4b76f10dbf48d09816856939ddb6ed7 | 36,588 | package main.java;
// Imports
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.LinkedHashMap;
/*
* Peer Object
* Contains all the relevant information that is needed to
* manage the Peer-2-Peer network. This object contains each Peer's
* Server and Client sockets, the Peer ID, Hostname, and the pieces of
* theFile that the peer contains.
* The peer will also be responsible for handling and executing all the messages
*/
public class Peer {
int unchokeInterval;
int OptimisticUnchokeInterval;
int[] PreferredNeighbors;
int[] filesTranseredToPN;
int OptPeer;
int fileTransferedToOPN;
//Class Variables
private String hostName;
private int peerID;
private int listeningPort;
private boolean hasFile;
private boolean[] isChoked;
private boolean[] isInterested;
private boolean[][] hasPieces;
private byte[][] filePieces;
private int[] ReqPfromNeighbors;
private boolean wantToClose;
private Server server;
private Client[] clients;
private FileConverter fc;
private LinkedHashMap<Integer, String[]> AllPeers;
private LinkedHashMap<String, String> commonInfo;
private ArrayList<Integer> IndexOfPiecesMissing;
private int PieceSize;
private int fileSize;
String FileLocation;
String DirectoryLoc;
// This is the constructor of the class Peer
public Peer(int key, LinkedHashMap<Integer, String[]> peerInfo, LinkedHashMap<String,
String> cInfo, Server server, Client[] clients, String File) throws IOException {
//Sets all peer object variable to the info obtained from reading peerInfo.cfg and commonInfo.cfg
hostName = peerInfo.get(key)[0];
listeningPort = Integer.parseInt(peerInfo.get(key)[1]);
hasFile = Integer.parseInt(peerInfo.get(key)[2]) == 1;
peerID = key;
AllPeers = peerInfo;
//Sets all arrays of isChoked and isInterested to false
isChoked = new boolean[peerInfo.size()];
isInterested = new boolean[peerInfo.size()];
commonInfo = cInfo;
for (int i = 0; i < peerInfo.size(); i++) {
isChoked[i] = false;
isInterested[i] = false;
}
//Sets all other Peer object variables
wantToClose = false;
this.server = server;
this.clients = clients;
ReqPfromNeighbors = new int[Integer.parseInt(commonInfo.get("NumberOfPreferredNeighbors"))];
PreferredNeighbors = new int[Integer.parseInt(commonInfo.get("NumberOfPreferredNeighbors"))];
Arrays.fill(PreferredNeighbors, -1);
Arrays.fill(ReqPfromNeighbors, -1);
filesTranseredToPN = new int[PreferredNeighbors.length];
Arrays.fill(filesTranseredToPN, 0);
OptPeer = 0;
fileTransferedToOPN = 0;
OptimisticUnchokeInterval = Integer.parseInt(commonInfo.get("OptimisticUnchokingInterval"));
unchokeInterval = Integer.parseInt(commonInfo.get("UnchokingInterval"));
String test = new File("NetworkingProject\\src\\main\\java\\project_config_file_small\\project_config_file_small\\").getCanonicalPath();
if(File.equals(test)) {
DirectoryLoc = File+"\\"+peerID;
FileLocation = DirectoryLoc + "\\thefile";
}
else {
DirectoryLoc = File+"\\"+peerID;
FileLocation = DirectoryLoc + "\\tree.jpg";
}
setFilePieces(commonInfo, hasFile, key);
}
/*
* Parameter(s):
* fileSize- the file size as an integer
* pieceSize - the size of a piece within the file as an integer
*
* Function:
* Sets up the byte array with the correct number of columns using the number of pieces within a file
*/
public synchronized void setFilePieces(LinkedHashMap<String,
String> commonInfo, boolean hasFile, int key) throws IOException {
PieceSize = Integer.parseInt(commonInfo.get("PieceSize"));
fileSize = Integer.parseInt(commonInfo.get("FileSize"));
hasPieces = new boolean[AllPeers.size()][(int) Math.ceil((double) fileSize / PieceSize)];
IndexOfPiecesMissing = new ArrayList<>((int) Math.ceil((double) fileSize / PieceSize));
for (int i = 0; i < AllPeers.size(); i++) {
Arrays.fill(hasPieces[i], false);
}
if (hasFile) {
//filePieces = fc.fileToByte("src/main/java/project_config_file_small/project_config_file_small/"+key+"/thefile", commonInfo);
filePieces = fc.fileToByte(FileLocation, commonInfo);
for (int i = 0; i < (int) Math.ceil((double) fileSize / PieceSize); i++) {
hasPieces[getPeerID() - 1001][i] = true;
}
} else {
filePieces = new byte[(int) Math.ceil((double) fileSize / PieceSize)][PieceSize];
for (int i = 0; i < filePieces.length; i++)
IndexOfPiecesMissing.add(i, i);
}
}
// Sets Client Sockets
public synchronized void setClientSockets(Client[] clients) {
this.clients = clients;
}
// Sets Server Sockets
public synchronized void setServerSockets(Server server) {
this.server = server;
}
//*********************************** GET Functions ***********************************//
// Returns the array with all who is choked or not
public synchronized boolean[] getChokedPeer() {
return isChoked;
}
// Returns a boolean for if the peer wants to end its connections
public synchronized boolean getWantToClose() {
return wantToClose;
}
public synchronized ArrayList<Integer> getIndexOfPiecesMissing() {
return IndexOfPiecesMissing;
}
// Returns if the peer has the complete file or not
public synchronized boolean getHasFile() {
return hasFile;
}
public synchronized boolean[][] getHasPieces() {
return hasPieces;
}
// Get pieces of file
public synchronized byte[][] getFilePieces() {
return filePieces;
}
//Formats the Choke
public synchronized byte[] ChokeMsg() {
return new byte[]{0, 0, 0, 1, 0};
}
//Formats the UnChoke
public synchronized byte[] UnChokeMsg() {
return new byte[]{0, 0, 0, 1, 1};
}
//Formats the Interested
public synchronized byte[] InterestedMsg() {
return new byte[]{0, 0, 0, 1, 2};
}
//Formats the UnInterested
public synchronized byte[] UnInterestedMsg() {
return new byte[]{0, 0, 0, 1, 3};
}
//Formats the Have Message
public synchronized byte[] haveMsg(int hasIndex) {
byte[] mL = ByteBuffer.allocate(4).putInt(5).array();
byte mT = (byte) 4;
byte[] payload = ByteBuffer.allocate(4).putInt(hasIndex).array();
byte[] hasM = new byte[9];
for (int i = 0; i < 9; i++) {
if (i < 4)
hasM[i] = mL[i];
else if (i == 4)
hasM[i] = mT;
else
hasM[i] = payload[i - 5];
}
return hasM;
}
// Calculates the bitfield and formats the message
// 4 Bytes Length + 1 Byte Type + Variable Bytes for payload
public synchronized byte[] getBitFieldMessage() {
int b = (int) Math.ceil(Math.log((double) fileSize / PieceSize) / Math.log(2));
// BitSet bitSet = new BitSet((int) Math.pow(2, b));
BitSet bitSet = new BitSet((int) Math.ceil((double) fileSize / PieceSize));
for (int i = 0; i < hasPieces[peerID - 1001].length; i++) {
if (hasPieces[peerID - 1001][i]) {
//bitfield[(int) Math.floor((double) i / 8)] |= 1 << (7 - i % 8);
bitSet.set(i, true);
} else
bitSet.set(i, false);
}
//byte[] bitf = bitSet.toByteArray();
byte[] bitfield = bitSet.toByteArray();
if (bitfield.length == 0) {
bitfield = new byte[(int) Math.ceil((double) (fileSize / PieceSize) / 8)];
}
byte msgT = (byte) 5;
ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
lengthBuffer.putInt(1 + bitfield.length);
byte[] msgL = lengthBuffer.array();
byte[] bfmsg = new byte[5 + bitfield.length];
for (int i = 0; i < bfmsg.length; i++) {
if (i < 4) {
bfmsg[i] = msgL[i];
} else if (i == 4) {
bfmsg[i] = msgT;
} else {
bfmsg[i] = bitfield[i - 5];
}
}
return bfmsg;
}
//Creates the request message to be sent
public synchronized byte[] requestMessage(int pieceReq) {
byte[] mL = ByteBuffer.allocate(4).putInt(5).array();
byte mT = (byte) 6;
byte[] payload = ByteBuffer.allocate(4).putInt(pieceReq).array();
byte[] reqM = new byte[9];
for (int i = 0; i < 9; i++) {
if (i < 4)
reqM[i] = mL[i];
else if (i == 4)
reqM[i] = mT;
else
reqM[i] = payload[i - 5];
}
return reqM;
}
//Similar to request Message, but incorporates the entire piece into the bitfield
public synchronized byte[] pieceMessage(int pieceReq) {
byte mT = (byte) 7;
byte[] pieceData = filePieces[pieceReq];
byte[] Indexload = ByteBuffer.allocate(4).putInt(pieceReq).array();
byte[] mL = ByteBuffer.allocate(4).putInt(5 + pieceData.length).array();
byte[] reqM = new byte[9 + pieceData.length];
for (int i = 0; i < reqM.length; i++) {
if (i < 4)
reqM[i] = mL[i];
else if (i == 4)
reqM[i] = mT;
else if (i < 9)
reqM[i] = Indexload[i - 5];
else
reqM[i] = pieceData[i - 9];
}
return reqM;
}
// Returns the listing port of the peer
public synchronized int getListeningPort() {
return listeningPort;
}
// Returns the peer's ID number
public synchronized int getPeerID() {
return peerID;
}
// Return Peers host name
public synchronized String getHostName() {
return hostName;
}
//*********************************** Object Specific Functions ***********************************//
/*
* Parameters(s):
* messageType - This will be a byte the dictates the message to be printed
*
* Function:
* Takes in a message type and outputs the corresponding message
*/
public synchronized void interpretMessage(int OtherPeer, byte[] message) {
byte messageType = message[4];
switch (messageType) {
case 0:
// CHOKE - Set isChoked to true
if (!isChoked[OtherPeer - 1001]) {
isChoked[OtherPeer - 1001] = true;
writeLogMessage(OtherPeer, PreferredNeighbors, 0, 0, 5);
}
break;
case 1:
// UNCHOKE - Set isChoked to false
//If the peer correlates to a preferred neighbor
boolean preFNeighbor = false;
for (int i = 0; i < PreferredNeighbors.length; i++) {
if (OtherPeer == PreferredNeighbors[i]) {
preFNeighbor = true;
break;
}
}
if (preFNeighbor || OtherPeer == OptPeer) {
if (isChoked[OtherPeer - 1001]) {
isChoked[OtherPeer - 1001] = false;
writeLogMessage(OtherPeer, PreferredNeighbors, 0, 0, 4);
}
}
if (!hasFile) {
try {
int pieceReq;
if (peerID > OtherPeer) {
pieceReq = FindPieceToRequest(OtherPeer);
if (pieceReq != -1) {
clients[OtherPeer - 1001].sendRequest(requestMessage(pieceReq));
}
} else {
pieceReq = FindPieceToRequest(OtherPeer);
if (pieceReq != -1) {
clients[OtherPeer - 1002].sendRequest(requestMessage(pieceReq));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
break;
case 2:
// INTERESTED - Set isInterested to true
if (!isInterested[OtherPeer - 1001]) {
isInterested[OtherPeer - 1001] = true;
writeLogMessage(OtherPeer, PreferredNeighbors, 0, 0, 7);
}
break;
case 3:
// UNINTERESTED - Set isInterested to false
if (isInterested[OtherPeer - 1001]) {
isInterested[OtherPeer - 1001] = false;
writeLogMessage(OtherPeer, PreferredNeighbors, 0, 0, 8);
}
break;
case 4:
// HAVE
// TODO: IMPLEMENT HAVE
byte[] OPhave = new byte[4];
for (int i = 5; i < message.length; i++) {
OPhave[i - 5] = message[i];
}
int OPH = ByteBuffer.wrap(OPhave).getInt();
hasPieces[OtherPeer - 1001][OPH] = true;
boolean ThisPeerIsInterested = false;
for (int i = 0; i < hasPieces[peerID - 1001].length; i++) {
if (hasPieces[peerID - 1001][i] != hasPieces[OtherPeer - 1001][i] && hasPieces[OtherPeer - 1001][i]) {
ThisPeerIsInterested = true;
break;
}
}
try {
if (ThisPeerIsInterested) {
if (OtherPeer < getPeerID())
clients[OtherPeer - 1001].sendRequest(InterestedMsg());
else
clients[OtherPeer - 1002].sendRequest(InterestedMsg());
} else {
if (OtherPeer < getPeerID())
clients[OtherPeer - 1001].sendRequest(UnInterestedMsg());
else
clients[OtherPeer - 1002].sendRequest(UnInterestedMsg());
}
} catch (IOException e) {
e.printStackTrace();
}
//System.out.println("Have");
writeLogMessage(OtherPeer, PreferredNeighbors, OPH, 0, 6);
break;
case 5:
// BITFIELD
//As soon as a BitFieldRequest is sent
if (message.length > 5) {
byte[] bFieldResp = getBitFieldMessage();
boolean interestedINPeer = false;
//BitSet RecievedM = BitSet.valueOf(message);
//BitSet BitFiled = BitSet.valueOf(bFieldResp)
/* for (int i = 0; i <= (message.length - 1) * 8; i++) {
if (isSet(bFieldResp, i) != isSet(message, i)) {
interestedINPeer = true;
}
}*/
//The bitfield starts at byte 5 aka bit 40
for (int i = 40; i < 40 + hasPieces[OtherPeer - 1001].length; i++) {
if (isSet(message, i)) {
hasPieces[OtherPeer - 1001][i - 40] = true;
}
}
for (int i = 0; i < hasPieces[peerID - 1001].length; i++) {
if (hasPieces[peerID - 1001][i] != hasPieces[OtherPeer - 1001][i] && hasPieces[OtherPeer - 1001][i]) {
interestedINPeer = true;
break;
}
}
isInterested[OtherPeer - 1001] = interestedINPeer;
try {
if (interestedINPeer) {
if (OtherPeer < getPeerID())
clients[OtherPeer - 1001].sendRequest(InterestedMsg());
else
clients[OtherPeer - 1002].sendRequest(InterestedMsg());
} else {
if (OtherPeer < getPeerID())
clients[OtherPeer - 1001].sendRequest(UnInterestedMsg());
else
clients[OtherPeer - 1002].sendRequest(UnInterestedMsg());
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Bitfield");
}
break;
case 6:
// REQUEST
// After initial BITFIELD you need to request the pieces that are needed
// Check for any preferred neighbors
if (!isChoked[OtherPeer - 1001]) {
boolean isPreferred = false;
for (int i = 0; i < PreferredNeighbors.length; i++) {
if (PreferredNeighbors[i] == OtherPeer) {
filesTranseredToPN[i]++;
isPreferred = true;
break;
}
}
if (isPreferred || OtherPeer == OptPeer) {
if (OtherPeer == OptPeer)
fileTransferedToOPN++;
byte[] OPReq = new byte[4];
for (int i = 5; i < message.length; i++) {
OPReq[i - 5] = message[i];
}
int OPReqed = ByteBuffer.wrap(OPReq).getInt();
try {
if (OtherPeer < getPeerID())
clients[OtherPeer - 1001].sendRequest(pieceMessage(OPReqed));
else
clients[OtherPeer - 1002].sendRequest(pieceMessage(OPReqed));
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
case 7:
// PIECE
// TODO: IMPLEMENT PIECE
if (!hasFile) {
byte[] pieceIndex = new byte[4];
byte[] pieceReceived = new byte[PieceSize];
for (int i = 5; i < message.length; i++) {
if (i < 9)
pieceIndex[i - 5] = message[i];
else
pieceReceived[i - 9] = message[i];
}
int pIndex = ByteBuffer.wrap(pieceIndex).getInt();
boolean badPayload = true;
for (int p = 0; p < pieceReceived.length; p++) {
if (pieceReceived[p] != 0) {
badPayload = false;
break;
}
}
if (!badPayload && !hasPieces[peerID - 1001][pIndex]) {
filePieces[pIndex] = pieceReceived;
hasPieces[peerID - 1001][pIndex] = true;
for (int i = 0; i < ReqPfromNeighbors.length; i++)
if (ReqPfromNeighbors[i] == pIndex) {
ReqPfromNeighbors[i] = -1;
}
for (int i = 0; i < IndexOfPiecesMissing.size(); i++) {
if (IndexOfPiecesMissing.get(i) == pIndex) {
IndexOfPiecesMissing.remove(i);
IndexOfPiecesMissing.trimToSize();
}
}
int numberOfPieces = 0;
for (int i = 0; i < hasPieces[peerID - 1001].length; i++) {
if (hasPieces[peerID - 1001][i]) {
numberOfPieces++;
}
}
writeLogMessage(OtherPeer, PreferredNeighbors, pIndex, numberOfPieces, 9);
if (!hasFile) {
boolean check = true;
for (int i = 0; i < hasPieces[peerID - 1001].length; i++) {
if (!hasPieces[peerID - 1001][i]) {
check = false;
break;
}
}
hasFile = check;
if (hasFile) {
writeLogMessage(0, null, 0, 0, 10);
}
}
// Once 'receive' a piece send HAVE to all the other Peers
try {
for (int i = 0; i < clients.length; i++) {
clients[i].sendRequest(haveMsg(pIndex));
}
} catch (IOException e) {
System.err.println("IOEX in Piece recieved");
}
/* uwu */
}
if (!hasFile) {
try {
int pieceReq;
if (peerID > OtherPeer) {
pieceReq = FindPieceToRequest(OtherPeer);
if (pieceReq != -1) {
clients[OtherPeer - 1001].sendRequest(requestMessage(pieceReq));
}
} else {
pieceReq = FindPieceToRequest(OtherPeer);
if (pieceReq != -1) {
clients[OtherPeer - 1002].sendRequest(requestMessage(pieceReq));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
}
}
//Determines the preferred neighbors during the unchoked interval
public synchronized void determinePreferredNeighbors() {
//If requested has values inside store because messages could be lost
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
if (ReqPfromNeighbors[i] != -1) {
ReqPfromNeighbors[i] = -1;
}
}
// -1 signifies a lack of neighbor
boolean PreferredEmpty = false;
for (int i = 0; i < PreferredNeighbors.length; i++) {
if (PreferredNeighbors[i] == -1) {
PreferredEmpty = true;
break;
}
}
// If there are neighbors (i.e., this is not at the server start), continue
if (!PreferredEmpty) {
int[] downLoadRateResults = new int[PreferredNeighbors.length];
for (int i = 0; i < PreferredNeighbors.length; i++) {
downLoadRateResults[i] = filesTranseredToPN[i] / unchokeInterval;
filesTranseredToPN[i] = 0;
}
//Determines if Optimistic is better than one of than one preferred neighbors
int downLoadRateForOp = fileTransferedToOPN / unchokeInterval;
fileTransferedToOPN = 0;
//check if OP is one of the preferred neighbors
boolean OPisNotaPreferred = false;
for (int preferredNeighbor : PreferredNeighbors) {
if (OptPeer == preferredNeighbor) {
OPisNotaPreferred = true;
break;
}
}
//If OP is not a preferred Neighbor check to see if it is better than other preferred neighbors
if (!OPisNotaPreferred) {
for (int i = 0; i < PreferredNeighbors.length; i++) {
if (downLoadRateForOp > downLoadRateResults[i]) {
PreferredNeighbors[i] = OptPeer;
break;
}
}
}
}
// This is the start of the network, select random neighbors!
else {
// Not going to look at interested to start since there will be peers with nothing
ArrayList<Integer> interested = new ArrayList<Integer>(isInterested.length) {
};
for (int i = 0; i < isInterested.length; i++) {
if(peerID-1001 != i) {
interested.add(1001 + i);
}
}
// Randomly remove from the list, thus randomly selecting peers.
for (int n = 0; n < PreferredNeighbors.length; n++) {
int randPeer = (int) (Math.random() * interested.size());
PreferredNeighbors[n] = interested.get(randPeer);
interested.remove(randPeer);
}
writeLogMessage(0, PreferredNeighbors, 0, 0, 2);
}
}
//Determines the optimistic neighbors during the unchoked interval
public synchronized void determineOpNeighbors() {
//Checking any peers are interested in this peer
boolean thereArePeersInterested = false;
for (int i = 0; i < isInterested.length; i++) {
for (int j = 0; j < PreferredNeighbors.length; j++) {
if (isInterested[i] && PreferredNeighbors[j] != 1001 + j) {
thereArePeersInterested = true;
} else {
thereArePeersInterested = false;
break;
}
}
}
if (thereArePeersInterested) {
// What is interested and not a preferred neighbor already?
ArrayList<Integer> interested = new ArrayList<>() {
};
for (int i = 0; i < isInterested.length; i++) {
if (isInterested[i]) {
boolean isAlreadyPreferred = false;
for (int preferredNeighbor : PreferredNeighbors) {
if (preferredNeighbor == 1001 + i) {
isAlreadyPreferred = true;
break;
}
}
if (!isAlreadyPreferred)
interested.add(i + 1001);
}
}
int randP = (int) (Math.random() * interested.size());
if (interested.size() > 0)
OptPeer = interested.get(randP);
fileTransferedToOPN = 0;
} else {
ArrayList<Integer> chokedNeighbors = new ArrayList<>();
for (int i = 0; i < isChoked.length; i++) {
for (int j = 0; j < PreferredNeighbors.length; j++) {
if (isChoked[i] && PreferredNeighbors[j] == 1001 + i) {
break;
}
}
chokedNeighbors.add(i, i + 1001);
}
int randP = (int) (Math.random() * chokedNeighbors.size());
OptPeer = chokedNeighbors.get(randP);
}
writeLogMessage(OptPeer, null, 0, 0, 3);
}
// Check for whether a peer has a desired file piece.
public synchronized int FindPieceToRequest(int OtherPeer) {
//boolean dNHTFile = !hasFile;
//for (int i = 0; i < hasPieces[peerID-1001].length; i++)
//if (!hasPieces[peerID - 1001][i])
//dNHTFile = true;
boolean reqIsfull = true;
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
if (ReqPfromNeighbors[i] == -1) {
reqIsfull = false;
break;
}
}
if (reqIsfull) {
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
IndexOfPiecesMissing.add(ReqPfromNeighbors[i]);
ReqPfromNeighbors[i] = -1;
}
}
if (isChoked[OtherPeer - 1001]) {
// Making sure that we are not requesting what is already requested
boolean hasPieceNReq = false;
if (!hasFile) { // This peer doesn't have the file
for (int i = 0; i < IndexOfPiecesMissing.size(); i++) {//Looking through the OtherPeer for pieces we need
for (int j = 0; j < ReqPfromNeighbors.length; j++) {// Looking through what has been requested
if (hasPieces[OtherPeer - 1001][IndexOfPiecesMissing.get(i)] && ReqPfromNeighbors[j] != IndexOfPiecesMissing.get(i)) {// Has a piece we need and not requested yet
hasPieceNReq = true;
} else {
hasPieceNReq = false;
break;
}
}
}
}
if (!hasFile && hasPieceNReq) {
int randP = (int) (Math.random() * IndexOfPiecesMissing.size());
boolean ReqAlready = false;
// While the Other peers has a piece not already requested
do {
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
if (ReqPfromNeighbors[i] != IndexOfPiecesMissing.get(randP) && hasPieces[OtherPeer - 1001][IndexOfPiecesMissing.get(randP)]) {
ReqAlready = false;
} else {
ReqAlready = true;
randP = (int) (Math.random() * IndexOfPiecesMissing.size());
break;
}
}
} while (ReqAlready);
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
if (ReqPfromNeighbors[i] == -1) {
ReqPfromNeighbors[i] = IndexOfPiecesMissing.get(randP);
break;
}
}
return IndexOfPiecesMissing.get(randP);
} else {
for (int i = 0; i < ReqPfromNeighbors.length; i++) {
if (ReqPfromNeighbors[i] != -1) {
return ReqPfromNeighbors[i];
}
}
}
}
return -1;
}
// Sets bits, good for comparison
public synchronized boolean isSet(byte[] bitArr, int bit) {
int i = (int) Math.floor((double) bit / 8);
int bitPos = bit % 8;
if (i >= bitArr.length) {
return false;
}
return (bitArr[i] >> bitPos & 1) == 1;
}
/*
* writeLogMessage:
* Appends a log message at the time of calling
*
* msgType guide:
* [0] - Peer1 makes a TCP connection to Peer2
* [1] - Peer2 makes a TCP connection to Peer1
* [2] - Peer1 makes a change of preferred neighbors
* [3] - Peer1 optimistically unchokes a neighbor
* [4] - Peer1 is unchoked by Peer2
* [5] - Peer1 is choked by a neighbor
* [6] - Peer1 receives a 'have' message from Peer2
* [7] - Peer1 receives an 'interested' message from Peer2
* [8] - Peer1 receives a 'not interested' message from Peer2
* [9] - Peer1 finishes downloading a piece from Peer2
* [10] - Peer1 has downloaded the complete file
*/
public synchronized void writeLogMessage(int Peer2, int[] prefNeighbors, int pieceIndex, int numPieces, int msgType) {
try {
int peer2ID = Peer2;
String path = "/log_peer_" + peerID + ".log";
File f1 = new File(path);
FileWriter fileWriter = new FileWriter(f1.getName(), true);
BufferedWriter bw = new BufferedWriter(fileWriter);
String data = "";
LocalTime time = LocalTime.now();
switch (msgType) {
case 0:
data = time + ": Peer " + peerID + " makes a connection to Peer " + peer2ID + ".\n";
break;
case 1:
data = time + ": Peer " + peerID + " is connected from Peer " + peer2ID + ".\n";
break;
case 2:
data = time + ": Peer " + peerID + " has the preferred neighbors " + Arrays.toString(prefNeighbors) + ".\n";
break;
case 3:
data = time + ": Peer " + peerID + " has optimistically unchoked neighbor " + peer2ID + ".\n";
break;
case 4:
data = time + ": Peer " + peerID + " is unchoked by Peer " + peer2ID + ".\n";
break;
case 5:
data = time + ": Peer " + peerID + " is choked by Peer " + peer2ID + ".\n";
break;
case 6:
data = time + ": Peer " + peerID + " received the 'have' message from " + peer2ID + " for the piece " + pieceIndex + ".\n";
break;
case 7:
data = time + ": Peer " + peerID + " received the 'interested' message from " + peer2ID + ".\n";
break;
case 8:
data = time + ": Peer " + peerID + " received the 'not interested' message from " + peer2ID + ".\n";
break;
case 9:
data = time + ": Peer " + peerID + " has downloaded the piece " + pieceIndex + " from " + peer2ID + ". Now the number of pieces it has is " + numPieces + ".\n";
if (numPieces == (int) Math.ceil((double) fileSize / PieceSize)) {
System.out.println("Peer " + peerID + " is done!");
}
break;
case 10:
data = time + ": Peer " + peerID + " has downloaded the complete file.\n";
break;
default:
System.err.println("Error! Incorrect message type code!");
break;
}
bw.write(data);
bw.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void savePiecesAsFile() {
fc = new FileConverter();
try {
fc.byteToFile(filePieces, DirectoryLoc, FileLocation, commonInfo);
} catch (IOException e) {
e.printStackTrace();
}
}
// Print the Peer details
public synchronized void printPeerInfo() {
System.out.println("*******Peer Information*******");
System.out.println("Peer ID:" + peerID);
System.out.println("Hostname:" + hostName);
System.out.println("The Listening Port:" + listeningPort);
System.out.println("Has File:" + hasFile);
}
} | 39.683297 | 187 | 0.46589 |
a0e6c37c12f440afb03ed8ba521a2191baba80a6 | 738 | package Model;
import java.sql.Date;
public class UsuarioModel {
//Atributos
private String cpf;
private String nome;
private String email;
private String senha;
//Métodos Especiais
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
| 18.923077 | 40 | 0.574526 |
0cd0fda2d2f612a90366c7b38384c2309598c9f2 | 2,319 | package com.jwhh.androidbooks;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity implements OnSelectedBookChangeListener {
boolean mCreating = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
mCreating = false;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSelectedBookChanged(int bookIndex) {
// Access the FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// Get the book description fragment
BookDescFragment bookDescFragment = (BookDescFragment)
fragmentManager.findFragmentById
(R.id.fragmentDescription);
// Check validity of fragment reference
if(bookDescFragment == null || !bookDescFragment.isVisible()){
// Use activity to display description
if(!mCreating) {
Intent intent = new Intent(this, BookDescActivity.class);
intent.putExtra("bookIndex", bookIndex);
startActivity(intent);
}
}
else {
// Use contained fragment to display description
bookDescFragment.setBook(bookIndex);
}
}
}
| 32.661972 | 85 | 0.628719 |
f936243774bbf934b697e7eb81beafd9380c1ac6 | 20,422 | package uk.gov.defra.datareturns.tests.integration;
import io.restassured.http.ContentType;
import org.hamcrest.Matchers;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import uk.gov.defra.datareturns.exceptions.ApplicationExceptionType;
import uk.gov.defra.datareturns.testcommons.framework.WebIntegrationTest;
import uk.gov.defra.datareturns.testcommons.restassured.RestAssuredRule;
import javax.inject.Inject;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static uk.gov.defra.datareturns.testutils.EcmTestUtils.runMultipartUploadTest;
/**
* CSV Upload integration tests.
*
* @author Sam Gardner-Dell
*/
@RunWith(SpringRunner.class)
@WebIntegrationTest
public class CsvUploadIT {
@Inject
@Rule
public RestAssuredRule restAssuredRule;
@Test
public void testSimpleUpload() {
runMultipartUploadTest("/data/csv-uploads/success.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testBinaryExe() {
runMultipartUploadTest("/data/csv-uploads/binary.exe", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.FILE_TYPE_UNSUPPORTED.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.FILE_TYPE_UNSUPPORTED.getReason()));
r.body("errors[0].line_number", nullValue());
});
}
@Test
public void testBinaryCsv() {
runMultipartUploadTest("/data/csv-uploads/binary.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getReason()));
r.body("errors[0].line_number", equalTo(1));
});
}
@Test
public void testBinaryCsvWithHeaders() {
runMultipartUploadTest("/data/csv-uploads/binary-with-valid-headers.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getReason()));
r.body("errors[0].line_number", equalTo(2));
});
}
@Test
public void testEmptyFile() {
runMultipartUploadTest("/data/csv-uploads/empty.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.FILE_EMPTY.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.FILE_EMPTY.getReason()));
});
}
/**
* Tests that the backend will load a csv file which only contains the
* mandatory fields.
*/
@Test
public void testRequiredFieldsOnly() {
runMultipartUploadTest("/data/csv-uploads/required-fields-only.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", Matchers.nullValue());
});
}
/**
* Tests that the backend won't load a csv file that does not include all mandatory fields.
*/
@Test
public void testRequiredFieldsMissing() {
runMultipartUploadTest("/data/csv-uploads/required-fields-missing.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.HEADER_MANDATORY_FIELD_MISSING.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.HEADER_MANDATORY_FIELD_MISSING.getReason()));
r.body("errors[0].line_number", equalTo(1));
});
}
/**
* Tests that the backend will throw out CSV files which contain headings
* that we do not need
*/
@Test
public void testUnrecognisedFieldFound() {
runMultipartUploadTest("/data/csv-uploads/unrecognised-field-found.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.HEADER_UNRECOGNISED_FIELD_FOUND.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.HEADER_UNRECOGNISED_FIELD_FOUND.getReason()));
r.body("errors[0].line_number", equalTo(1));
});
}
/**
* Tests that the backend will throw out CSV files which contain rows with inconsistent number of fields with respect to headers
*/
@Test
public void testInconsistentRows() {
runMultipartUploadTest("/data/csv-uploads/inconsistent-rows.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getAppStatusCode()));
r.body("errors[0].message", equalTo(ApplicationExceptionType.FILE_STRUCTURE_EXCEPTION.getReason()));
r.body("errors[0].line_number", equalTo(4));
});
}
/**
* Tests that the backend will load a csv file with all supported date formats.
*/
@Test
public void testDateFormats() {
runMultipartUploadTest("/data/csv-uploads/date-format-test.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
/**
* Tests that the backend will load a csv file with all supported date formats.
*/
@Test
public void testDateFormatsInvalid() {
runMultipartUploadTest("/data/csv-uploads/date-format-invalid-test.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(2));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9020-Missing"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Mon_Date", equalTo(""));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
r.body("errors[1].error_class", equalTo("DR9020-Incorrect"));
r.body("errors[1].instances.size()", is(4));
r.body("errors[1].instances[0].invalid_values.Mon_Date", equalTo("16-04-15"));
r.body("errors[1].instances[0].line_numbers", hasItems(3));
r.body("errors[1].instances[1].invalid_values.Mon_Date", equalTo("15/04/16"));
r.body("errors[1].instances[1].line_numbers", hasItems(4));
r.body("errors[1].instances[2].invalid_values.Mon_Date", equalTo("32/01/2016"));
r.body("errors[1].instances[2].line_numbers", hasItems(5));
r.body("errors[1].instances[3].invalid_values.Mon_Date", equalTo("17-04-2016T9:4:59"));
r.body("errors[1].instances[3].line_numbers", hasItems(6));
});
}
@Test
public void testMutiplePermits() {
final String resource = "/data/csv-uploads/multiple_permits.csv";
runMultipartUploadTest(resource, (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("filename", equalTo(resource));
r.body("errors", nullValue());
// Check we have 2 datasets associated with the upload.
final String datasetsCollectionHref = r.extract().jsonPath().getString("_links.datasets.href");
given()
.contentType(ContentType.JSON)
.when()
.get(datasetsCollectionHref)
.then()
.body("_embedded.datasets.size()", is(2));
});
}
@Test
public void testInvalidPermitNumber() {
runMultipartUploadTest("/data/csv-uploads/invalid-permit-no.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(2));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9000-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.EA_ID", equalTo("An invalid permit number"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
r.body("errors[1].error_class", equalTo("DR9000-Missing"));
r.body("errors[1].instances.size()", is(1));
r.body("errors[1].instances[0].invalid_values.EA_ID", equalTo(""));
r.body("errors[1].instances[0].line_numbers", hasItems(3));
});
}
@Test
public void testPermitSiteMismatch() {
runMultipartUploadTest("/data/csv-uploads/permit-site-mismatch.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9110-Conflict"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.EA_ID", equalTo("AP3533LF"));
r.body("errors[0].instances[0].invalid_values.Site_Name", equalTo("Not the right site name for AP3533LF"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testAcceptableValueFieldChars() {
runMultipartUploadTest("/data/csv-uploads/valid-value-field-chars.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testUnacceptableValueFieldChars() {
runMultipartUploadTest("/data/csv-uploads/invalid-value-field-chars.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(2));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9999-Missing"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Value", equalTo(""));
r.body("errors[0].instances[0].invalid_values.Txt_Value", equalTo(""));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
r.body("errors[1].error_class", equalTo("DR9040-Incorrect"));
r.body("errors[1].instances.size()", is(3));
r.body("errors[1].instances[0].invalid_values.Value", equalTo("<"));
r.body("errors[1].instances[0].line_numbers", hasItems(3));
r.body("errors[1].instances[1].invalid_values.Value", equalTo(">"));
r.body("errors[1].instances[1].line_numbers", hasItems(4));
r.body("errors[1].instances[2].invalid_values.Value", equalTo("<-.1"));
r.body("errors[1].instances[2].line_numbers", hasItems(5));
});
}
@Test
public void testEmbeddedSeparators() {
runMultipartUploadTest("/data/csv-uploads/embedded-commas.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testMethStandValid() {
runMultipartUploadTest("/data/csv-uploads/testMethStand.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testMethStandInvalid() {
runMultipartUploadTest("/data/csv-uploads/testMethStandInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9100-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Meth_Stand", equalTo("Invalid Meth_Stand"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testReturnTypeValid() {
runMultipartUploadTest("/data/csv-uploads/testReturnType.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testReturnTypeInvalid() {
runMultipartUploadTest("/data/csv-uploads/testReturnTypeInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9010-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Rtn_Type", equalTo("Invalid Return Type"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testRefPeriodValid() {
runMultipartUploadTest("/data/csv-uploads/testRefPeriod.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testRefPeriodInvalid() {
runMultipartUploadTest("/data/csv-uploads/testRefPeriodInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9090-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Ref_Period", equalTo("Invalid Reference Period"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testUnitsValid() {
runMultipartUploadTest("/data/csv-uploads/testUnits.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testUnitsInvalid() {
runMultipartUploadTest("/data/csv-uploads/testUnitsInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9050-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Unit", equalTo("Invalid Unit"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testQualifiersValid() {
runMultipartUploadTest("/data/csv-uploads/testQualifier.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testQualifiersInvalid() {
runMultipartUploadTest("/data/csv-uploads/testQualifierInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9180-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Qualifier", equalTo("Invalid Qualifier"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
@Test
public void testReturnPeriodValid() {
runMultipartUploadTest("/data/csv-uploads/testReturnPeriod.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testReturnPeriodInvalid() {
runMultipartUploadTest("/data/csv-uploads/testReturnPeriodInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9070-Incorrect"));
r.body("errors[0].instances.size()", is(6));
r.body("errors[0].instances[0].invalid_values.Rtn_Period", equalTo("Week 99"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
r.body("errors[0].instances[1].invalid_values.Rtn_Period", equalTo("Spurs 2017"));
r.body("errors[0].instances[1].line_numbers", hasItems(3));
r.body("errors[0].instances[2].invalid_values.Rtn_Period", equalTo("Qtr 5 2017"));
r.body("errors[0].instances[2].line_numbers", hasItems(4));
r.body("errors[0].instances[3].invalid_values.Rtn_Period", equalTo("2017a"));
r.body("errors[0].instances[3].line_numbers", hasItems(5));
r.body("errors[0].instances[4].invalid_values.Rtn_Period", equalTo("2016-2017"));
r.body("errors[0].instances[4].line_numbers", hasItems(6));
r.body("errors[0].instances[5].invalid_values.Rtn_Period", equalTo("Tottenham Hotsyear 1963"));
r.body("errors[0].instances[5].line_numbers", hasItems(7));
});
}
@Test
public void testParameterValid() {
runMultipartUploadTest("/data/csv-uploads/testParameter.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testParameterInvalid() {
runMultipartUploadTest("/data/csv-uploads/testParameterInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(2));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9030-Missing"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Parameter", equalTo(""));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
r.body("errors[1].error_class", equalTo("DR9030-Incorrect"));
r.body("errors[1].instances.size()", is(1));
r.body("errors[1].instances[0].invalid_values.Parameter", equalTo("Unknown Parameter"));
r.body("errors[1].instances[0].line_numbers", hasItems(3));
});
}
@Test
public void testTextValueValid() {
runMultipartUploadTest("/data/csv-uploads/testTextValue.csv", (r) -> {
r.statusCode(HttpStatus.CREATED.value());
r.body("errors", nullValue());
});
}
@Test
public void testTextValueInvalid() {
runMultipartUploadTest("/data/csv-uploads/testTextValueInvalid.csv", (r) -> {
r.statusCode(HttpStatus.BAD_REQUEST.value());
r.body("errors.size()", is(1));
r.body("error_code", equalTo(ApplicationExceptionType.VALIDATION_ERRORS.getAppStatusCode()));
r.body("errors[0].error_class", equalTo("DR9080-Incorrect"));
r.body("errors[0].instances.size()", is(1));
r.body("errors[0].instances[0].invalid_values.Txt_Value", equalTo("Invalid Text Value"));
r.body("errors[0].instances[0].line_numbers", hasItems(2));
});
}
}
| 44.395652 | 132 | 0.619087 |
a005ccd337168111b6685bf5671cd7cbf76999c9 | 617 | package com.skytala.eCommerce.domain.product.relations.product.event.categoryLink;
import java.util.List;
import com.skytala.eCommerce.framework.pubsub.Event;
import com.skytala.eCommerce.domain.product.relations.product.model.categoryLink.ProductCategoryLink;
public class ProductCategoryLinkFound implements Event{
private List<ProductCategoryLink> productCategoryLinks;
public ProductCategoryLinkFound(List<ProductCategoryLink> productCategoryLinks) {
this.productCategoryLinks = productCategoryLinks;
}
public List<ProductCategoryLink> getProductCategoryLinks() {
return productCategoryLinks;
}
}
| 29.380952 | 101 | 0.842788 |
c3cb71c6ae7f8bc5bf488da0914866c6f941ff8c | 1,709 | package com.robrua.orianna.type.core.match;
import com.robrua.orianna.api.core.RiotAPI;
import com.robrua.orianna.type.core.OriannaObject;
import com.robrua.orianna.type.core.staticdata.Rune;
import com.robrua.orianna.type.exception.MissingDataException;
public class ParticipantRune extends OriannaObject<com.robrua.orianna.type.dto.match.Rune> {
private static final long serialVersionUID = -8028177856067862738L;
private Rune rune;
/**
* @param data
* the underlying dto
*/
public ParticipantRune(final com.robrua.orianna.type.dto.match.Rune data) {
super(data, com.robrua.orianna.type.dto.match.Rune.class);
}
/**
* Rune count
*
* @return rune count
*/
public long getCount() {
return super.getLong(data.getRank());
}
/**
* The rune this holds count for
*
* @return the rune this holds count for
*/
public Rune getRune() {
if(rune != null) {
return rune;
}
final Long l = data.getRuneId();
if(l == null) {
throw new MissingDataException("Rune ID is null.");
}
rune = RiotAPI.getRune(l.longValue());
return rune;
}
/**
* The ID of the rune this holds count for
*
* @return the ID of the rune this holds count for
*/
public long getRuneID() {
return super.getLong(data.getRuneId());
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "ParticipantRune (" + getRune() + "x" + getCount() + ")";
}
}
| 25.893939 | 93 | 0.576946 |
dcdf1c9afb779c558a8934d353cc5842c73b17ad | 1,624 | package net.java_school.controller;
import static com.googlecode.objectify.ObjectifyService.ofy;
import java.util.List;
import java.util.Locale;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.googlecode.objectify.Key;
import net.java_school.blog.Article;
import net.java_school.blog.Category;
import net.java_school.blog.Lang;
@Controller
public class DatastoreBlogController {
@RequestMapping(value="datastore/{category}/{id}", method=RequestMethod.GET)
public String blog(@PathVariable("category") String category, @PathVariable("id") String id, Locale locale, Model model) {
String lang = locale.getLanguage();
Key<Lang> theLang = Key.create(Lang.class, lang);
Key<Category> categoryKey = Key.create(theLang, Category.class, category);
Key<Article> articleKey = Key.create(categoryKey, Article.class, id);
Article article = ofy().load().key(articleKey).now();
if (article == null) return "redirect:/";
model.addAttribute("title", article.title);
model.addAttribute("keywords", article.keywords);
model.addAttribute("description", article.description);
model.addAttribute("content", article.content);
List<Article> articles = ofy()
.load()
.type(Article.class)
.ancestor(categoryKey)
.project("title")
.order("date")
.list();
model.addAttribute("articles", articles);
return "datastore/" + category + "/" + id;
}
} | 31.230769 | 123 | 0.751847 |
0d3d2211bf1123f288123b78e168436f437d3352 | 118 | package com.github.poad.examples.webauthn.exception;
public class UserNotFoundException extends RuntimeException {
}
| 23.6 | 61 | 0.847458 |
403901fd6993fb1d36ea956244b0db678cdbad00 | 5,577 | import android.graphics.Bitmap;
import com.qualcomm.hardware.modernrobotics.ModernRoboticsI2cGyro;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
//@TeleOp(name="WilTeleReverse", group = "myGroup")
/**
* Created Jan 17, 2017 by Wil Orlando
*
* Normal teleop, but reversed controls (so that the collector is the "front" while driving)
*
*/
public class WilTeleReverse extends OpMode {
// Declare motors, servos, and variables
DcMotor frontRight, frontLeft, backRight, backLeft, flicker, collector;
Servo gate;
ModernRoboticsI2cGyro gyro;
String gateState = "";
boolean targetSet = false;
int encVal, targetVal;
int FLICKER_ERROR = 184; // Number of encoder ticks the physical flicker runs past the target value; last measured as between 104 and 181
public ElapsedTime runTime = new ElapsedTime();
double timeMark = 0;
// Initialize robot before match starts
public void init() {
// Map this program's names for motors to the RC Phone's config file
frontRight = hardwareMap.dcMotor.get ("frontRight");
frontLeft = hardwareMap.dcMotor.get ("frontLeft");
backRight = hardwareMap.dcMotor.get("backRight");
backLeft = hardwareMap.dcMotor. get("backLeft");
flicker = hardwareMap.dcMotor.get("flicker");
collector = hardwareMap.dcMotor.get("collector");
gate = hardwareMap.servo.get("gate");
gyro = (ModernRoboticsI2cGyro)hardwareMap.gyroSensor.get("gyro");
// Reverse motors that are physically reversed on bot (so that setPower(1) means "forward" for every motor)
frontRight.setDirection(DcMotor.Direction.REVERSE);
backRight.setDirection(DcMotor.Direction.REVERSE);
frontLeft.setDirection(DcMotor.Direction.FORWARD);
backLeft.setDirection(DcMotor.Direction.FORWARD);
// Make sure that drive motors are using encoders
setModeAll(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
setModeAll(DcMotor.RunMode.RUN_WITHOUT_ENCODER);
// Reset flicker encoder to 0, then set it to run using encoders
flicker.setDirection(DcMotor.Direction.REVERSE);
flicker.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
flicker.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// Initialize flicker's target value for one rotation to be its current position, so that it doesn't start flicking if the reset failed (for some reason)
targetVal = flicker.getCurrentPosition();
// Calibrate gyro to take initial bearings as references for axes
gyro.calibrate();
// POTENTIAL TROUBLE! EMPTY LOOP MAY NOT SYNCHRONIZE
while (gyro.getIntegratedZValue() != 0 && (runTime.time() - timeMark) < 1.5) {
}
telemetry.addLine("Fully Initialized!");
}
public void loop() {
telemetry.addData(">", "Robot Heading Z = %d", gyro.getIntegratedZValue());
// Drive Controls //
// Normal tank drive, binding the left wheels to the left joystick and right wheels to right
frontLeft.setPower(gamepad1.right_stick_y);
backLeft.setPower(gamepad1.right_stick_y);
frontRight.setPower(gamepad1.left_stick_y);
backRight.setPower(gamepad1.left_stick_y);
// Gate Controls //
// Opens gate when x is pressed
if (gamepad2.x) {
gate.setPosition(.3); // Last set at .3
gateState = "Open";
}
// Closes gate by default
else {
gate.setPosition(0); // Last set at 0
gateState = "Closed";
}
telemetry.addData("Gate: ", gateState);
// Collector Controls //
// Collector out when dpad_up is pressed
if (gamepad2.dpad_up) {
collector.setPower(1);
}
// Collector in when dpad_down is pressed
else if (gamepad2.dpad_down) {
collector.setPower(-1);
}
// Collector off by default
else {
collector.setPower(0);
}
// Flicker Controls //
//Working note: flicker.setPower(1) is the right direction
if (gamepad2.y && flicker.getPower() == 0) {
encVal = Math.abs(flicker.getCurrentPosition());
targetVal = encVal + 3360;
flicker.setTargetPosition((targetVal - FLICKER_ERROR));
timeMark = runTime.time();
flicker.setPower(1);
}
// Manual reset, in case the flicker gets stuck, to rotate it a third of a rotation
else if (gamepad2.right_bumper && flicker.getPower() == 0) {
encVal = Math.abs(flicker.getCurrentPosition());
targetVal = encVal + 3360/3;
flicker.setTargetPosition((targetVal - FLICKER_ERROR));
timeMark = runTime.time();
flicker.setPower(1);
}
if ((runTime.time() - timeMark) >= 2) {
flicker.setPower(0);
}
telemetry.addData("Flicker Enc: ", flicker.getCurrentPosition());
telemetry.addData("Flicker Power: ", flicker.getPower());
}
// Sets all drive motors to a specified RunMode
public void setModeAll(DcMotor.RunMode mode) {
frontLeft.setMode(mode);
frontRight.setMode(mode);
backLeft.setMode(mode);
backRight.setMode(mode);
}
}
| 34.006098 | 161 | 0.647839 |
901cced692c6e5c94e9bd6c8fb6a712a9ea357b2 | 39,077 | /**
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
*
* The Apereo Foundation licenses this file to you under the Educational
* Community 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://opensource.org/licenses/ecl2.txt
*
* 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.opencastproject.workflow.handler.videogrid;
import static java.lang.String.format;
import org.opencastproject.composer.api.ComposerService;
import org.opencastproject.composer.api.EncoderException;
import org.opencastproject.composer.api.EncodingProfile;
import org.opencastproject.composer.layout.Dimension;
import org.opencastproject.inspection.api.MediaInspectionException;
import org.opencastproject.inspection.api.MediaInspectionService;
import org.opencastproject.job.api.Job;
import org.opencastproject.job.api.JobContext;
import org.opencastproject.mediapackage.MediaPackage;
import org.opencastproject.mediapackage.MediaPackageElementFlavor;
import org.opencastproject.mediapackage.MediaPackageElementParser;
import org.opencastproject.mediapackage.MediaPackageException;
import org.opencastproject.mediapackage.Track;
import org.opencastproject.mediapackage.TrackSupport;
import org.opencastproject.mediapackage.VideoStream;
import org.opencastproject.mediapackage.selector.TrackSelector;
import org.opencastproject.mediapackage.track.TrackImpl;
import org.opencastproject.serviceregistry.api.ServiceRegistry;
import org.opencastproject.smil.api.util.SmilUtil;
import org.opencastproject.util.NotFoundException;
import org.opencastproject.util.data.Tuple;
import org.opencastproject.videogrid.api.VideoGridService;
import org.opencastproject.videogrid.api.VideoGridServiceException;
import org.opencastproject.workflow.api.AbstractWorkflowOperationHandler;
import org.opencastproject.workflow.api.ConfiguredTagsAndFlavors;
import org.opencastproject.workflow.api.WorkflowInstance;
import org.opencastproject.workflow.api.WorkflowOperationException;
import org.opencastproject.workflow.api.WorkflowOperationHandler;
import org.opencastproject.workflow.api.WorkflowOperationInstance;
import org.opencastproject.workflow.api.WorkflowOperationResult;
import org.opencastproject.workspace.api.Workspace;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.smil.SMILDocument;
import org.w3c.dom.smil.SMILElement;
import org.w3c.dom.smil.SMILMediaElement;
import org.w3c.dom.smil.SMILParElement;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* The workflow definition for handling multiple videos that have overlapping playtime, e.g. webcam videos from
* a video conference call.
* Checks which videos are currently playing and dynamically scales them to fit in a single video.
*
* Relies on a smil with videoBegin and duration times, as is created by ingest through addPartialTrack.
* Will pad sections where no video is playing with a background color. This includes beginning and end.
*
* Returns the final video to the target flavor
*/
@Component(
immediate = true,
service = WorkflowOperationHandler.class,
property = {
"service.description=Video Grid Workflow Operation Handler",
"workflow.operation=videogrid"
}
)
public class VideoGridWorkflowOperationHandler extends AbstractWorkflowOperationHandler {
/** Workflow configuration keys */
private static final String SOURCE_FLAVORS = "source-flavors";
private static final String SOURCE_SMIL_FLAVOR = "source-smil-flavor";
private static final String CONCAT_ENCODING_PROFILE = "concat-encoding-profile";
private static final String OPT_RESOLUTION = "resolution";
private static final String OPT_BACKGROUND_COLOR = "background-color";
/** The logging facility */
private static final Logger logger = LoggerFactory.getLogger(VideoGridWorkflowOperationHandler.class);
/** Constants */
private static final String NODE_TYPE_VIDEO = "video";
// TODO: Make ffmpeg commands more "opencasty"
private static final String[] FFMPEG = {"ffmpeg", "-y", "-v", "warning", "-nostats", "-max_error_rate", "1.0"};
private static final String FFMPEG_WF_CODEC = "h264"; //"mpeg2video";
private static final int FFMPEG_WF_FRAMERATE = 24;
private static final String[] FFMPEG_WF_ARGS = {
"-an", "-codec", FFMPEG_WF_CODEC,
"-q:v", "2",
"-g", Integer.toString(FFMPEG_WF_FRAMERATE * 10),
"-pix_fmt", "yuv420p",
"-r", Integer.toString(FFMPEG_WF_FRAMERATE)
};
/** Services */
private Workspace workspace = null;
private VideoGridService videoGridService = null;
private MediaInspectionService inspectionService = null;
private ComposerService composerService = null;
/** Service Callbacks **/
@Reference
public void setWorkspace(Workspace workspace) {
this.workspace = workspace;
}
@Reference
public void setVideoGridService(VideoGridService videoGridService) {
this.videoGridService = videoGridService;
}
@Reference
protected void setMediaInspectionService(MediaInspectionService inspectionService) {
this.inspectionService = inspectionService;
}
@Reference
public void setComposerService(ComposerService composerService) {
this.composerService = composerService;
}
@Reference
@Override
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
super.setServiceRegistry(serviceRegistry);
}
/** Structs to store data and make code more readable **/
/**
* Holds basic information on the final video, which is for example used to appropriately place and scale
* individual videos.
*/
class LayoutArea {
private int x = 0;
private int y = 0;
private int width = 1920;
private int height = 1080;
private String name = "webcam";
private String bgColor = "0xFFFFFF";
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBgColor() {
return bgColor;
}
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
LayoutArea(int width, int height) {
this.width = width;
this.height = height;
}
LayoutArea(String name, int x, int y, int width, int height, String bgColor) {
this(width, height);
this.name = name;
this.x = x;
this.y = y;
this.bgColor = bgColor;
}
}
/**
* Holds information on a single video beyond what is usually stored in a Track
*/
class VideoInfo {
private int aspectRatioWidth = 16;
private int aspectRatioHeight = 9;
private long startTime = 0;
private long duration = 0;
private Track video;
public int getAspectRatioWidth() {
return aspectRatioWidth;
}
public void setAspectRatioWidth(int aspectRatioWidth) {
this.aspectRatioWidth = aspectRatioWidth;
}
public int getAspectRatioHeight() {
return aspectRatioHeight;
}
public void setAspectRatioHeight(int aspectRatioHeight) {
this.aspectRatioHeight = aspectRatioHeight;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public Track getVideo() {
return video;
}
public void setVideo(Track video) {
this.video = video;
}
VideoInfo() {
}
VideoInfo(int height, int width) {
aspectRatioWidth = width;
aspectRatioHeight = height;
}
VideoInfo(Track video, long timeStamp, int aspectRatioHeight, int aspectRatioWidth, long startTime) {
this(aspectRatioHeight, aspectRatioWidth);
this.video = video;
this.startTime = startTime;
}
}
/**
* Pair class for readability
*/
class Offset {
private int x = 16;
private int y = 9;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
Offset(int x, int y) {
this.x = x;
this.y = y;
}
}
/**
* A section of the complete edit decision list.
* A new section is defined whenever a video becomes active or inactive.
* Therefore it contains information on the timing as well as all currently active videos in the section.
*/
class EditDecisionListSection {
private long timeStamp = 0;
private long nextTimeStamp = 0;
private List<VideoInfo> areas;
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public long getNextTimeStamp() {
return nextTimeStamp;
}
public void setNextTimeStamp(long nextTimeStamp) {
this.nextTimeStamp = nextTimeStamp;
}
public List<VideoInfo> getAreas() {
return areas;
}
public void setAreas(List<VideoInfo> areas) {
this.areas = areas;
}
EditDecisionListSection() {
areas = new ArrayList<VideoInfo>();
}
}
/**
* Stores relevant information from the source SMIL
*/
class StartStopEvent implements Comparable<StartStopEvent> {
private boolean start;
private long timeStamp;
private Track video;
private VideoInfo videoInfo;
public boolean isStart() {
return start;
}
public void setStart(boolean start) {
this.start = start;
}
public long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(long timeStamp) {
this.timeStamp = timeStamp;
}
public VideoInfo getVideoInfo() {
return videoInfo;
}
public void setVideoInfo(VideoInfo videoInfo) {
this.videoInfo = videoInfo;
}
StartStopEvent(boolean start, Track video, long timeStamp, VideoInfo videoInfo) {
this.start = start;
this.timeStamp = timeStamp;
this.video = video;
this.videoInfo = videoInfo;
}
@Override
public int compareTo(StartStopEvent o) {
return Long.compare(this.timeStamp, o.timeStamp);
}
}
@Override
public WorkflowOperationResult start(final WorkflowInstance workflowInstance, JobContext context)
throws WorkflowOperationException {
logger.debug("Running videogrid workflow operation on workflow {}", workflowInstance.getId());
final MediaPackage mediaPackage = (MediaPackage) workflowInstance.getMediaPackage().clone();
ConfiguredTagsAndFlavors tagsAndFlavors = getTagsAndFlavors(workflowInstance,
Configuration.none, Configuration.many, Configuration.many, Configuration.one);
// Read config options
WorkflowOperationInstance operation = workflowInstance.getCurrentOperation();
final MediaPackageElementFlavor smilFlavor = MediaPackageElementFlavor.parseFlavor(
getConfig(operation, SOURCE_SMIL_FLAVOR));
final MediaPackageElementFlavor targetPresenterFlavor = tagsAndFlavors.getSingleTargetFlavor();
String concatEncodingProfile = StringUtils.trimToNull(operation.getConfiguration(CONCAT_ENCODING_PROFILE));
// Get source flavors
final List<MediaPackageElementFlavor> sourceFlavors = tagsAndFlavors.getSrcFlavors();
// Get tracks from flavor
final List<Track> sourceTracks = new ArrayList<>();
for (MediaPackageElementFlavor sourceFlavor: sourceFlavors) {
TrackSelector trackSelector = new TrackSelector();
trackSelector.addFlavor(sourceFlavor);
sourceTracks.addAll(trackSelector.select(mediaPackage, false));
}
// No tracks? Skip
if (sourceTracks.isEmpty()) {
logger.warn("No tracks in source flavors, skipping ...");
return createResult(mediaPackage, WorkflowOperationResult.Action.SKIP);
}
// No concat encoding profile? Fail
if (concatEncodingProfile == null) {
throw new WorkflowOperationException("Encoding profile must be set!");
}
EncodingProfile profile = composerService.getProfile(concatEncodingProfile);
if (profile == null) {
throw new WorkflowOperationException("Encoding profile '" + concatEncodingProfile + "' was not found");
}
// Define a general Layout for the final video
ImmutablePair<Integer, Integer> resolution;
try {
resolution = getResolution(getConfig(workflowInstance, OPT_RESOLUTION, "1280x720"));
} catch (IllegalArgumentException e) {
logger.warn("Given resolution was not well formatted!");
throw new WorkflowOperationException(e);
}
logger.info("The resolution of the final video: {}/{}", resolution.getLeft(), resolution.getRight());
// Define a bg color for the final video
String bgColor = getConfig(workflowInstance, OPT_BACKGROUND_COLOR, "0xFFFFFF");
final Pattern pattern = Pattern.compile("0x[A-Fa-f0-9]{6}");
if (!pattern.matcher(bgColor).matches()) {
logger.warn("Given color {} was not well formatted!", bgColor);
throw new WorkflowOperationException("Given color was not well formatted!");
}
logger.info("The background color of the final video: {}", bgColor);
// Target tags
List<String> targetTags = tagsAndFlavors.getTargetTags();
// Define general layout for the final video
LayoutArea layoutArea = new LayoutArea("webcam", 0, 0, resolution.getLeft(), resolution.getRight(),
bgColor);
// Get SMIL catalog
final SMILDocument smilDocument;
try {
smilDocument = SmilUtil.getSmilDocumentFromMediaPackage(mediaPackage, smilFlavor, workspace);
} catch (SAXException e) {
throw new WorkflowOperationException("SMIL is not well formatted", e);
} catch (IOException | NotFoundException e) {
throw new WorkflowOperationException("SMIL could not be found", e);
}
final SMILParElement parallel = (SMILParElement) smilDocument.getBody().getChildNodes().item(0);
final NodeList sequences = parallel.getTimeChildren();
final float trackDurationInSeconds = parallel.getDur();
final long trackDurationInMs = Math.round(trackDurationInSeconds * 1000f);
// Get Start- and endtime of the final video from SMIL
long finalStartTime = 0;
long finalEndTime = trackDurationInMs;
// Create a list of start and stop events, i.e. every time a new video begins or an old one ends
// Create list from SMIL from partial ingests
List<StartStopEvent> events = new ArrayList<>();
List<Track> videoSourceTracks = new ArrayList<>();
for (int i = 0; i < sequences.getLength(); i++) {
final SMILElement item = (SMILElement) sequences.item(i);
NodeList children = item.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node node = children.item(j);
SMILMediaElement e = (SMILMediaElement) node;
// Avoid any element that is not a video or of the source type
if (NODE_TYPE_VIDEO.equals(e.getNodeName())) {
Track track;
try {
track = getTrackByID(e.getId(), sourceTracks);
} catch (IllegalStateException ex) {
logger.info("No track corresponding to SMIL ID found, skipping SMIL ID {}", e.getId());
continue;
}
videoSourceTracks.add(track);
double beginInSeconds = e.getBegin().item(0).getResolvedOffset();
long beginInMs = Math.round(beginInSeconds * 1000d);
double durationInSeconds = e.getDur();
long durationInMs = Math.round(durationInSeconds * 1000d);
// Gather video information
VideoInfo videoInfo = new VideoInfo();
// Aspect Ratio, e.g. 16:9
List<Track> tmpList = new ArrayList<Track>();
tmpList.add(track);
LayoutArea trackDimension = determineDimension(tmpList, true);
if (trackDimension == null) {
throw new WorkflowOperationException("One of the source video tracks did not contain "
+ "a valid video stream or dimension");
}
videoInfo.aspectRatioHeight = trackDimension.getHeight();
videoInfo.aspectRatioWidth = trackDimension.getWidth();
// "StartTime" is calculated later. It describes how far into the video the next section starts.
// (E.g. If webcam2 is started 10 seconds after webcam1, the startTime for webcam1 in the next section is 10)
videoInfo.startTime = 0;
logger.info("Video information: Width: {}, Height {}, StartTime: {}", videoInfo.aspectRatioWidth,
videoInfo.aspectRatioHeight, videoInfo.startTime);
events.add(new StartStopEvent(true, track, beginInMs, videoInfo));
events.add(new StartStopEvent(false, track, beginInMs + durationInMs, videoInfo));
}
}
}
// No events? Skip
if (events.isEmpty()) {
logger.warn("Could not generate sections from given SMIL catalogue for tracks in given flavor, skipping ...");
return createResult(mediaPackage, WorkflowOperationResult.Action.SKIP);
}
// Sort by timestamps ascending
Collections.sort(events);
// Create an edit decision list
List<EditDecisionListSection> videoEdl = new ArrayList<EditDecisionListSection>();
HashMap<Track, StartStopEvent> activeVideos = new HashMap<>(); // Currently running videos
// Define starting point
EditDecisionListSection start = new EditDecisionListSection();
start.timeStamp = finalStartTime;
videoEdl.add(start);
// Define mid-points
for (StartStopEvent event : events) {
if (event.start) {
logger.info("Add start event at {}", event.timeStamp);
activeVideos.put(event.video, event);
} else {
logger.info("Add stop event at {}", event);
activeVideos.remove(event.video);
}
videoEdl.add(createEditDecisionList(event, activeVideos));
}
// Define ending point
EditDecisionListSection endVideo = new EditDecisionListSection();
endVideo.timeStamp = finalEndTime;
endVideo.nextTimeStamp = finalEndTime;
videoEdl.add(endVideo);
// Pre processing EDL
for (int i = 0; i < videoEdl.size() - 1; i++) {
// For calculating cut lengths
videoEdl.get(i).nextTimeStamp = videoEdl.get(i + 1).timeStamp;
}
// Create ffmpeg command for each section
List<List<String>> commands = new ArrayList<>(); // FFmpeg command
List<List<Track>> tracksForCommands = new ArrayList<>(); // Tracks used in the FFmpeg command
for (EditDecisionListSection edl : videoEdl) {
// A too small duration will result in ffmpeg producing a faulty video, so avoid any section smaller than 50ms
if (edl.nextTimeStamp - edl.timeStamp < 50) {
logger.info("Skipping {}-length edl entry", edl.nextTimeStamp - edl.timeStamp);
continue;
}
// Create command for section
commands.add(compositeSection(layoutArea, edl));
tracksForCommands.add(edl.getAreas().stream().map(m -> m.getVideo()).collect(Collectors.toList()));
}
// Create video tracks for each section
List<URI> uris = new ArrayList<>();
for (int i = 0; i < commands.size(); i++) {
logger.info("Sending command {} of {} to service. Command: {}", i + 1, commands.size(), commands.get(i));
Job job;
try {
job = videoGridService.createPartialTrack(
commands.get(i),
tracksForCommands.get(i).toArray(new Track[tracksForCommands.get(i).size()])
);
} catch (VideoGridServiceException | org.apache.commons.codec.EncoderException | MediaPackageException e) {
throw new WorkflowOperationException(e);
}
if (!waitForStatus(job).isSuccess()) {
throw new WorkflowOperationException(
String.format("VideoGrid job for media package '%s' failed", mediaPackage));
}
Gson gson = new Gson();
uris.add(gson.fromJson(job.getPayload(), new TypeToken<URI>() { }.getType()));
}
// Parse uris into tracks and enrich them with metadata
List<Track> tracks = new ArrayList<>();
for (URI uri : uris) {
TrackImpl track = new TrackImpl();
track.setFlavor(targetPresenterFlavor);
track.setURI(uri);
Job inspection = null;
try {
inspection = inspectionService.enrich(track, true);
} catch (MediaInspectionException | MediaPackageException e) {
throw new WorkflowOperationException("Inspection service could not enrich track", e);
}
if (!waitForStatus(inspection).isSuccess()) {
throw new WorkflowOperationException(String.format("Failed to add metadata to track."));
}
try {
tracks.add((TrackImpl) MediaPackageElementParser.getFromXml(inspection.getPayload()));
} catch (MediaPackageException e) {
throw new WorkflowOperationException("Could not parse track returned by inspection service", e);
}
}
// Concatenate sections
Job concatJob = null;
try {
concatJob = composerService.concat(composerService.getProfile(concatEncodingProfile).getIdentifier(),
new Dimension(layoutArea.width,layoutArea.height) , true, tracks.toArray(new Track[tracks.size()]));
} catch (EncoderException | MediaPackageException e) {
throw new WorkflowOperationException("The concat job failed", e);
}
if (!waitForStatus(concatJob).isSuccess()) {
throw new WorkflowOperationException("The concat job did not complete successfully.");
}
// Add to mediapackage
if (concatJob.getPayload().length() > 0) {
Track concatTrack;
try {
concatTrack = (Track) MediaPackageElementParser.getFromXml(concatJob.getPayload());
} catch (MediaPackageException e) {
throw new WorkflowOperationException("Could not parse track returned by concat service", e);
}
concatTrack.setFlavor(targetPresenterFlavor);
concatTrack.setURI(concatTrack.getURI());
for (String tag : targetTags) {
concatTrack.addTag(tag);
}
mediaPackage.add(concatTrack);
} else {
throw new WorkflowOperationException("Concat operation unsuccessful, no payload returned.");
}
try {
workspace.cleanup(mediaPackage.getIdentifier());
} catch (IOException e) {
throw new WorkflowOperationException(e);
}
final WorkflowOperationResult result = createResult(mediaPackage, WorkflowOperationResult.Action.CONTINUE);
logger.debug("Video Grid operation completed");
return result;
}
/**
* Create a ffmpeg command that generates a video for the given section
*
* The videos passed as part of <code>videoEdl</code> are arranged in a grid layout.
* The grid layout is calculated in a way that maximizes area usage (i.e. minimizes the areas where the background
* color has to be shown) by checking the area usage for each combination of vertical and horizontal rows, based
* on the resolution of the layout area. The number of tiles per row/column is then used to genrate a complex
* ffmpeg filter.
*
*
* @param layoutArea
* General layout information for the video
* @param videoEdl
* The edit decision list for the current cut
* @return A command line ready ffmpeg command
*/
private List<String> compositeSection(LayoutArea layoutArea, EditDecisionListSection videoEdl) {
// Duration for this cut
long duration = videoEdl.nextTimeStamp - videoEdl.timeStamp;
logger.info("Cut timeStamp {}, duration {}", videoEdl.timeStamp, duration);
// Declare ffmpeg command
String ffmpegFilter = String.format("color=c=%s:s=%dx%d:r=24", layoutArea.bgColor,
layoutArea.width, layoutArea.height);
List<VideoInfo> videos = videoEdl.areas;
int videoCount = videoEdl.areas.size();
logger.info("Laying out {} videos in {}", videoCount, layoutArea.name);
if (videoCount > 0) {
int tilesH = 0;
int tilesV = 0;
int tileWidth = 0;
int tileHeight = 0;
int totalArea = 0;
// Do and exhaustive search to maximize video areas
for (int tmpTilesV = 1; tmpTilesV < videoCount + 1; tmpTilesV++) {
int tmpTilesH = (int) Math.ceil((videoCount / (float)tmpTilesV));
int tmpTileWidth = (int) (2 * Math.floor((float)layoutArea.width / tmpTilesH / 2));
int tmpTileHeight = (int) (2 * Math.floor((float)layoutArea.height / tmpTilesV / 2));
if (tmpTileWidth <= 0 || tmpTileHeight <= 0) {
continue;
}
int tmpTotalArea = 0;
for (VideoInfo video: videos) {
int videoWidth = video.aspectRatioWidth;
int videoHeight = video.aspectRatioHeight;
VideoInfo videoScaled = aspectScale(videoWidth, videoHeight, tmpTileWidth, tmpTileHeight);
tmpTotalArea += videoScaled.aspectRatioWidth * videoScaled.aspectRatioHeight;
}
if (tmpTotalArea > totalArea) {
tilesH = tmpTilesH;
tilesV = tmpTilesV;
tileWidth = tmpTileWidth;
tileHeight = tmpTileHeight;
totalArea = tmpTotalArea;
}
}
int tileX = 0;
int tileY = 0;
logger.info("Tiling in a {}x{} grid", tilesH, tilesV);
ffmpegFilter += String.format("[%s_in];", layoutArea.name);
for (VideoInfo video : videos) {
//Get videoinfo
logger.info("tile location ({}, {})", tileX, tileY);
int videoWidth = video.aspectRatioWidth;
int videoHeight = video.aspectRatioHeight;
logger.info("original aspect: {}x{}", videoWidth, videoHeight);
VideoInfo videoScaled = aspectScale(videoWidth, videoHeight, tileWidth, tileHeight);
logger.info("scaled size: {}x{}", videoScaled.aspectRatioWidth, videoScaled.aspectRatioHeight);
Offset offset = padOffset(videoScaled.aspectRatioWidth, videoScaled.aspectRatioHeight, tileWidth, tileHeight);
logger.info("offset: left: {}, top: {}", offset.x, offset.y);
// TODO: Get a proper value instead of the badly hardcoded 0
// Offset in case the pts is greater than 0
long seekOffset = 0;
logger.info("seek offset: {}", seekOffset);
// Webcam videos are variable, low fps; it might be that there's
// no frame until some time after the seek point. Start decoding
// 10s before the desired point to avoid this issue.
long seek = video.startTime - 10000;
if (seek < 0) {
seek = 0;
}
String padName = String.format("%s_x%d_y%d", layoutArea.name, tileX, tileY);
// Apply the video start time offset to seek to the correct point.
// Only actually apply the offset if we're already seeking so we
// don't start seeking in a file where we've overridden the seek
// behaviour.
if (seek > 0) {
seek = seek + seekOffset;
}
// Instead of adding the filepath here, we put a placeholder.
// This is so that the videogrid service can later replace it, after it put the files in it's workspace
ffmpegFilter += String.format("movie=%s:sp=%s", "#{" + video.getVideo().getIdentifier() + "}", msToS(seek));
// Subtract away the offset from the timestamps, so the trimming
// in the fps filter is accurate
ffmpegFilter += String.format(",setpts=PTS-%s/TB", msToS(seekOffset));
// fps filter fills in frames up to the desired start point, and
// cuts the video there
ffmpegFilter += String.format(",fps=%d:start_time=%s", FFMPEG_WF_FRAMERATE, msToS(video.startTime));
// Reset the timestamps to start at 0 so that everything is synced
// for the video tiling, and scale to the desired size.
ffmpegFilter += String.format(",setpts=PTS-STARTPTS,scale=%d:%d,setsar=1",
videoScaled.aspectRatioWidth, videoScaled.aspectRatioHeight);
// And finally, pad the video to the desired aspect ratio
ffmpegFilter += String.format(",pad=w=%d:h=%d:x=%d:y=%d:color=%s", tileWidth, tileHeight,
offset.x, offset.y, layoutArea.bgColor);
ffmpegFilter += String.format("[%s_movie];", padName);
// In case the video was shorter than expected, we might have to pad
// it to length. do that by concatenating a video generated by the
// color filter. (It would be nice to repeat the last frame instead,
// but there's no easy way to do that.)
ffmpegFilter += String.format("color=c=%s:s=%dx%d:r=%d", layoutArea.bgColor, tileWidth,
tileHeight, FFMPEG_WF_FRAMERATE);
ffmpegFilter += String.format("[%s_pad];", padName);
ffmpegFilter += String.format("[%s_movie][%s_pad]concat=n=2:v=1:a=0[%s];", padName, padName, padName);
tileX += 1;
if (tileX >= tilesH) {
tileX = 0;
tileY += 1;
}
}
// Create the video rows
int remaining = videoCount;
for (tileY = 0; tileY < tilesV; tileY++) {
int thisTilesH = Math.min(tilesH, remaining);
remaining -= thisTilesH;
for (tileX = 0; tileX < thisTilesH; tileX++) {
ffmpegFilter += String.format("[%s_x%d_y%d]", layoutArea.name, tileX, tileY);
}
if (thisTilesH > 1) {
ffmpegFilter += String.format("hstack=inputs=%d,", thisTilesH);
}
ffmpegFilter += String.format("pad=w=%d:h=%d:color=%s", layoutArea.width, tileHeight, layoutArea.bgColor);
ffmpegFilter += String.format("[%s_y%d];", layoutArea.name, tileY);
}
// Stack the video rows
for (tileY = 0; tileY < tilesV; tileY++) {
ffmpegFilter += String.format("[%s_y%d]", layoutArea.name, tileY);
}
if (tilesV > 1) {
ffmpegFilter += String.format("vstack=inputs=%d,", tilesV);
}
ffmpegFilter += String.format("pad=w=%d:h=%d:color=%s", layoutArea.width, layoutArea.height, layoutArea.bgColor);
ffmpegFilter += String.format("[%s];", layoutArea.name);
ffmpegFilter += String.format("[%s_in][%s]overlay=x=%d:y=%d", layoutArea.name,
layoutArea.name, layoutArea.x, layoutArea.y);
// Here would be the end of the layoutArea Loop
}
ffmpegFilter += String.format(",trim=end=%s", msToS(duration));
List<String> ffmpegCmd = new ArrayList<String>(Arrays.asList(FFMPEG));
ffmpegCmd.add("-filter_complex");
ffmpegCmd.add(ffmpegFilter);
ffmpegCmd.addAll(Arrays.asList(FFMPEG_WF_ARGS));
logger.info("Final command:");
logger.info(String.join(" ", ffmpegCmd));
return ffmpegCmd;
}
/**
* Scale the video resolution to fit the new resolution while maintaining aspect ratio
* @param oldWidth
* Width of the video
* @param oldHeight
* Height of the video
* @param newWidth
* Intended new width of the video
* @param newHeight
* Intended new height of the video
* @return
* Actual new width and height of the video, guaranteed to be the same or smaller as the intended values
*/
private VideoInfo aspectScale(int oldWidth, int oldHeight, int newWidth, int newHeight) {
if ((float)oldWidth / oldHeight > (float)newWidth / newHeight) {
newHeight = (int) (2 * Math.round((float)oldHeight * newWidth / oldWidth / 2));
} else {
newWidth = (int) (2 * Math.round((float)oldWidth * newHeight / oldHeight / 2));
}
return new VideoInfo(newHeight, newWidth);
}
/**
* Calculate video offset from borders for ffmpeg pad operation
* @param videoWidth
* Width of the video
* @param videoHeight
* Height of the video
* @param areaWidth
* Width of the area
* @param areaHeight
* Width of the area
* @return
* The position of the video within the padded area
*/
private Offset padOffset(int videoWidth, int videoHeight, int areaWidth, int areaHeight) {
int padX = (int) (2 * Math.round((float)(areaWidth - videoWidth) / 4));
int padY = (int) (2 * Math.round((float)(areaHeight - videoHeight) / 4));
return new Offset(padX, padY);
}
/**
* Converts milliseconds to seconds and to string
* @param timestamp
* Time in milliseconds, e.g. 12567
* @return
* Time in seconds, e.g. "12.567"
*/
private String msToS(long timestamp) {
double s = (double)timestamp / 1000;
return String.format(Locale.US, "%.3f", s); // Locale.US to get a . instead of a ,
}
/**
* Finds and returns the first track matching the given id in a list of tracks
* @param trackId
* The id of the track we're looking for
* @param tracks
* The collection of tracks we're looking in
* @return
* The first track with the given trackId
*/
private Track getTrackByID(String trackId, List<Track> tracks) {
for (Track t : tracks) {
if (t.getIdentifier().contains(trackId)) {
logger.debug("Track-Id from smil found in Mediapackage ID: " + t.getIdentifier());
return t;
}
}
throw new IllegalStateException("No track matching smil Track-id: " + trackId);
}
/**
* Determine the largest dimension of the given list of tracks
*
* @param tracks
* the list of tracks
* @param forceDivisible
* Whether to enforce the track's dimension to be divisible by two
* @return the largest dimension from the list of track
*/
private LayoutArea determineDimension(List<Track> tracks, boolean forceDivisible) {
Tuple<Track, LayoutArea> trackDimension = getLargestTrack(tracks);
if (trackDimension == null) {
return null;
}
if (forceDivisible && (trackDimension.getB().getHeight() % 2 != 0 || trackDimension.getB().getWidth() % 2 != 0)) {
LayoutArea scaledDimension = new LayoutArea((trackDimension.getB().getWidth() / 2) * 2, (trackDimension
.getB().getHeight() / 2) * 2);
logger.info("Determined output dimension {} scaled down from {} for track {}", scaledDimension,
trackDimension.getB(), trackDimension.getA());
return scaledDimension;
} else {
logger.info("Determined output dimension {} for track {}", trackDimension.getB(), trackDimension.getA());
return trackDimension.getB();
}
}
/**
* Returns the track with the largest resolution from the list of tracks
*
* @param tracks
* the list of tracks
* @return a {@link Tuple} with the largest track and it's dimension
*/
private Tuple<Track, LayoutArea> getLargestTrack(List<Track> tracks) {
Track track = null;
LayoutArea dimension = null;
for (Track t : tracks) {
if (!t.hasVideo()) {
continue;
}
VideoStream[] videoStreams = TrackSupport.byType(t.getStreams(), VideoStream.class);
int frameWidth = videoStreams[0].getFrameWidth();
int frameHeight = videoStreams[0].getFrameHeight();
if (dimension == null || (frameWidth * frameHeight) > (dimension.getWidth() * dimension.getHeight())) {
dimension = new LayoutArea(frameWidth, frameHeight);
track = t;
}
}
if (track == null || dimension == null) {
return null;
}
return Tuple.tuple(track, dimension);
}
/**
* Returns the absolute path of the track
*
* @param track
* Track whose path you want
* @return {@String} containing the absolute path of the given track
* @throws WorkflowOperationException
*/
private String getTrackPath(Track track) throws WorkflowOperationException {
File mediaFile;
try {
mediaFile = workspace.get(track.getURI());
} catch (NotFoundException e) {
throw new WorkflowOperationException(
"Error finding the media file in the workspace", e);
} catch (IOException e) {
throw new WorkflowOperationException(
"Error reading the media file in the workspace", e);
}
return mediaFile.getAbsolutePath();
}
/**
* Collects the info for the next section of the final video into an object
* @param event
* Event detailing the time a video has become active/inactive
* @param activeVideos
* Currently active videos
* @return
*/
private EditDecisionListSection createEditDecisionList(
StartStopEvent event,
HashMap<Track, StartStopEvent> activeVideos
) {
EditDecisionListSection nextEdl = new EditDecisionListSection();
nextEdl.timeStamp = event.timeStamp;
for (Map.Entry<Track, StartStopEvent> activeVideo : activeVideos.entrySet()) {
nextEdl.areas.add(new VideoInfo(activeVideo.getKey(), event.timeStamp,
activeVideo.getValue().videoInfo.aspectRatioHeight,
activeVideo.getValue().videoInfo.aspectRatioWidth,
event.timeStamp - activeVideo.getValue().timeStamp));
}
return nextEdl;
}
/**
* Parses a string detailing a resolution into two integers
* @param s
* String of the form "AxB"
* @return
* The width and height
* @throws IllegalArgumentException
*/
private ImmutablePair<Integer, Integer> getResolution(String s) throws IllegalArgumentException {
String[] parts = s.split("x");
if (parts.length != 2) {
throw new IllegalArgumentException(format("Unable to create resolution from \"%s\"", s));
}
return new ImmutablePair<Integer, Integer>(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
}
}
| 37.074953 | 119 | 0.674463 |
75eeb30b9c35543c01ddfed59308e75709370465 | 1,048 | /*
* Copyright 2011-2018 ijym-lee
*
* 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.
*/
/**
* <p><a href="https://zeroturnaround.com/software/jrebel/download/#!/have-license">JRebel</a>介绍</p>
*
* <p>IDEA上原生是不支持热部署的,一般更新了 Java 文件后要手动重启 Tomcat 服务器,才能生效,浪费时间。</p>
* <p>JRebel-IntelliJ 是 JDEA 的热部署插件。这个类实现修改字节码的方式破解JRebel插件。</p>
*
* <p>因为这种方式稍有瑕疵(发现有时候会失效),且我已经转为使用 Spring-Boot,“spring-boot-devtools” 支持热部署,故 JRebel 已经不使用了。保留这个类是为了记录历史。</p>
*
* @author liym
* @since 2018-09-18 10:22 新建
*/
package me.ijleex.test.jrebel.activation;
| 36.137931 | 110 | 0.727099 |
fbc112f460681abd98f417f688efb6f325aa1895 | 1,334 | package blackbeard.patches;
import com.evacipated.cardcrawl.modthespire.lib.*;
import com.evacipated.cardcrawl.modthespire.patcher.PatchingException;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.events.beyond.SensoryStone;
import com.megacrit.cardcrawl.localization.EventStrings;
import javassist.CannotCompileException;
import javassist.CtBehavior;
import java.util.ArrayList;
import java.util.Collections;
@SpirePatch(clz = SensoryStone.class, method = "getRandomMemory")
public class SensoryStonePatch {
public static final String EVENT_ID = "blackbeard:SensoryStone";
public static EventStrings eventStrings = CardCrawlGame.languagePack.getEventString(EVENT_ID);
public static String[] DESCRIPTIONS = eventStrings.DESCRIPTIONS;
@SpireInsertPatch(locator = Locator.class, localvars = {"memories"})
public static void Insert(SensoryStone sensoryStone, ArrayList<String> memories) {
memories.add(DESCRIPTIONS[0]);
}
public static class Locator extends SpireInsertLocator {
public int[] Locate(CtBehavior ctMethodToPatch) throws CannotCompileException, PatchingException {
Matcher matcher = new Matcher.MethodCallMatcher(Collections.class, "shuffle");
return LineFinder.findInOrder(ctMethodToPatch, matcher);
}
}
} | 43.032258 | 106 | 0.781859 |
7a59bff3d30761bff2ee76352dd713291c548942 | 2,283 | package org.jgroups.protocols;
import org.jgroups.Global;
import org.jgroups.Header;
import urv.olsr.data.OLSRNode;
import java.io.*;
import java.net.InetAddress;
import java.util.function.Supplier;
public class OLSRHeader extends Header {
public static final int CONTROL = 0;
public static final int DATA = 1;
public int type;
public OLSRNode dest;
public String mcastAddress;
public OLSRHeader() {
}
@Override
public short getMagicId() {
return Constants.OLSR_ID;
}
/**
* @return the dest
*/
public OLSRNode getDest() {
return dest;
}
/**
* @return Returns the mcastAddress.
*/
public String getMcastAddress() {
return mcastAddress;
}
/**
* @return the type
*/
public int getType() {
return type;
}
@Override
public Supplier<? extends Header> create() {
return OLSRHeader::new;
}
@Override
public int serializedSize() {
int retval=Global.BYTE_SIZE; // type;
if(type == DATA)
retval+=dest.serializedSize() + Global.INT_SIZE;
return retval;
}
@Override
public void readFrom(DataInput in) throws Exception {
type = in.readByte();
if (type==DATA){
dest = new OLSRNode();
dest.readFrom(in);
byte[] addr = new byte[4];
for(int i=0;i<4;i++){
addr[i]=in.readByte();
}
mcastAddress = InetAddress.getByAddress(addr).getHostAddress();
}
}
@Override
public void writeTo(DataOutput out) throws Exception {
out.writeByte(type);
if (type==DATA){
dest.writeTo(out);
byte[] addr = InetAddress.getByName(mcastAddress).getAddress();
for(int i=0;i<addr.length;i++){
out.writeByte(addr[i]);
}
}
}
/**
* @param dest the dest to set
*/
public void setDest(OLSRNode dest) {
this.dest = dest;
}
/**
* @param mcastAddress The mcastAddress to set.
*/
public void setMcastAddress(String mcastAddress) {
this.mcastAddress = mcastAddress;
}
/**
* @param type the type to set
*/
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "[OLSR: <variables> ]";
}
}
| 19.025 | 75 | 0.595269 |
e00ce8f6aac1aed90655b3dd638b035805a2b5b6 | 803 | /*----------------------------------------------------------------------------*/
/* Copyright (c) 2020 FRC Team 2077. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. */
/*----------------------------------------------------------------------------*/
package org.usfirst.frc.team2077.commands;
import edu.wpi.first.wpilibj2.command.CommandBase;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
/**
* A command that's intended to be bound to some {@link JoystickButton Joystick button}
*/
public abstract class BindableCommand extends CommandBase {
/**
* Bind this command to a given joystick button
* @param button a joystick button
*/
public abstract void bind(JoystickButton button);
}
| 34.913043 | 87 | 0.557908 |
5bf0cdb7c7315dd7a8b4443e4c73a0e62955d198 | 391 | package dao.Interface;
import model.Gestore;
import model.Zona;
import java.sql.SQLException;
import java.util.ArrayList;
public interface ZonaDaoInterface {
ArrayList<Zona> LoadZona(ArrayList<Zona> zonal) throws SQLException;
ArrayList<Zona> LoadZonaGest(ArrayList<Zona> zonal, ArrayList<Gestore> gest) throws SQLException;
Integer NewZona(Zona zonal) throws SQLException;
}
| 27.928571 | 101 | 0.792839 |
7fd259ab64dcd9580ea556053536ed5501f825e5 | 3,339 | package com.bunchofstring.test.capture;
import com.bunchofstring.test.CoreUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Capture {
private static final Logger LOGGER = Logger.getLogger(Capture.class.getSimpleName());
private static final String VIDEO_SUFFIX = ".mp4";
private static final String IMAGE_SUFFIX = ".png";
public static boolean screenshot(final String fileName){
return screenshot("./", fileName);
}
public static boolean screenshot(final String subDirName, final String fileName){
LOGGER.log(Level.INFO, "Attempting screenshot...");
final File dir = DeviceStoragePreparer.getDeviceSubDir(subDirName);
try {
DeviceStoragePreparer.grantPermissions();
DeviceStoragePreparer.ensureDeviceDirExists(dir);
doScreenshot(dir, fileName);
return true;
} catch (Throwable throwable) {
LOGGER.log(Level.WARNING, "Unable to capture screenshot", throwable);
return false;
}
}
public static RecordingInProgress newVideoRecording(final String fileName) throws CaptureException {
return newVideoRecording("./", fileName);
}
public static RecordingInProgress newVideoRecording(final String subDirName, final String fileName) throws CaptureException {
LOGGER.log(Level.INFO, "Attempting video recording...");
final File dir = DeviceStoragePreparer.getDeviceSubDir(subDirName);
try {
DeviceStoragePreparer.grantPermissions();
DeviceStoragePreparer.ensureDeviceDirExists(dir);
return doScreenRecord(dir, fileName);
} catch (Throwable throwable) {
/*
Not recoverable during during test execution, but a caller should anticipate this
situation - because it directly affects the effectiveness of the tests. A runtime error
in Capture should not affect the test - unless the caller wants it to.
1. Force the caller to handle the Throwable. Test can decide what to do - in the moment :D
2. Log the Throwable and swallow it. Test continues unaware :)
3. Throw an unchecked exception. Test fails. Test can decide what to do - in the moment -
but that would require catching an unchecked exception - which would be a bad code smell :|
*/
throw new CaptureException("Unable to capture video recording", throwable);
}
}
private static RecordingInProgress doScreenRecord(final File dir, final String fileName) throws IOException {
final Path path = Files.createTempFile(dir.toPath(), fileName + "_", VIDEO_SUFFIX);
return new RecordingInProgress(path.toFile());
}
private static void doScreenshot(final File dir, final String fileName) throws IOException {
final File file = File.createTempFile(fileName + "_", IMAGE_SUFFIX, dir);
if (CoreUtils.getDevice().takeScreenshot(file)) {
LOGGER.log(Level.INFO, "Captured screenshot at " + file.getAbsolutePath());
} else {
throw new RuntimeException("Screenshot capture operation failed");
}
}
}
| 43.363636 | 129 | 0.683438 |
4868e019cdc7de8ac702c384945c9178b26d5792 | 3,331 | package nz.ac.vuw.engr300.weather.model;
/**
* Enum to represent WindDirection from the loaded data. Can provide an angle
* and retrieve the direction that matches the angle.
*
* @author Nathan Duckett
*
*/
public enum WindDirection {
NORTHWEST, NORTH, NORTHEAST, EAST, SOUTHEAST, SOUTH, SOUTHWEST, WEST;
@Override
public String toString() {
// Switch the state of this WindDirection to get a printable value.
switch (this) {
case NORTHWEST:
return "NW";
case NORTH:
return "N";
case NORTHEAST:
return "NE";
case EAST:
return "E";
case SOUTHEAST:
return "SE";
case SOUTH:
return "S";
case SOUTHWEST:
return "SW";
// Default to WEST direction
default:
return "W";
}
}
/**
* The following static values are set out in this document to determine the
* angles of the wind.
*
* @see <a href=
* "http://snowfence.umn.edu/Components/winddirectionanddegrees.htm">Weather
* angles</a>
*/
private static final double Right_NORTH = 11.25;
private static final double Right_NORTHEAST = 56.25;
private static final double Right_EAST = 101.75;
private static final double Right_SOUTHEAST = 146.25;
private static final double Right_SOUTH = 191.25;
private static final double Right_SOUTHWEST = 236.25;
private static final double Right_WEST = 281.25;
private static final double Right_NORTHWEST = 326.25;
/**
* Get a WindDirection object based on the provided wind angle value.
*
* @param windAngle double value of the wind angle extracted in the WeatherData.
* @return WindDirection object representing the direction of the angle.
*/
public static WindDirection getFromWindAngle(double windAngle) {
// Check each direction if the wind angle is within the range.
if (checkRange(windAngle, Right_NORTH, Right_NORTHEAST)) {
return NORTHEAST;
} else if (checkRange(windAngle, Right_NORTHEAST, Right_EAST)) {
return EAST;
} else if (checkRange(windAngle, Right_EAST, Right_SOUTHEAST)) {
return SOUTHEAST;
} else if (checkRange(windAngle, Right_SOUTHEAST, Right_SOUTH)) {
return SOUTH;
} else if (checkRange(windAngle, Right_SOUTH, Right_SOUTHWEST)) {
return SOUTHWEST;
} else if (checkRange(windAngle, Right_SOUTHWEST, Right_WEST)) {
return WEST;
} else if (checkRange(windAngle, Right_WEST, Right_NORTHWEST)) {
return NORTHWEST;
} else {
return NORTH;
}
}
/**
* Check if the windAngle is within the specified range.
*
* @param windAngle Extracted windAngle from the WeatherData.
* @param leftSide Left bound of the direction range.
* @param rightSide Right bound of the direction range.
* @return Boolean indicating if the windAngle is within the bounds;
*/
private static boolean checkRange(double windAngle, double leftSide, double rightSide) {
return windAngle >= leftSide && windAngle < rightSide;
}
}
| 35.43617 | 92 | 0.618433 |
55db03f4fab572a518a7aaca2fd7c3084557e528 | 3,235 | package stepdefs;
import config.EndpointURLs;
import config.EnvGlobals;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import general.ReusableFunctions;
import payloads.EncounterPayload;
import static stepdefs.Hooks.RequestPayLoad;
import static stepdefs.Hooks.endPoint;
public class Encounter {
@Given("I Set POST Encounter service api endpoint")
public void i_Set_POST_Encounter_service_api_endpoint() {
endPoint = EndpointURLs.ENCOUNTER_URL;
RequestPayLoad = EncounterPayload.createEncounter(EnvGlobals.patientId);
}
@Then("I receive valid Response for POST Encounter service")
public void i_receive_valid_Response_for_POST_Encounter_service() {
ReusableFunctions.thenFunction(Hooks.HTTP_RESPONSE_CREATED);
EnvGlobals.encounterId = ReusableFunctions.getResponsePath("id");
validation.Encounter.validatePostResponse(EnvGlobals.patientId);
}
@Given("I Set GET Encounter api endpoint")
public void i_Set_GET_Encounter_api_endpoint() {
endPoint = EndpointURLs.GET_ENCOUNTER_URL;
endPoint = String.format(endPoint, EnvGlobals.encounterId);
}
@Then("I receive valid Response for GET Encounter service")
public void i_receive_valid_Response_for_GET_Encounter_service() {
ReusableFunctions.thenFunction(Hooks.HTTP_RESPONSE_SUCCESS);
validation.Encounter.validatePostResponse(EnvGlobals.patientId);
validation.Encounter.validateEncounterId(EnvGlobals.encounterId);
}
@Then("I receive valid Response for GET Encounter service for specific Patient")
public void i_receive_valid_Response_for_GET_Encounter_service_patient() {
ReusableFunctions.thenFunction(Hooks.HTTP_RESPONSE_SUCCESS);
validation.Encounter.validatePatient(EnvGlobals.patientId);
}
@Given("I Set GET Encounter api endpoint for specific Patient")
public void i_Set_GET_Encounter_api_endpoint_for_specific_Patient() {
endPoint = EndpointURLs.GET_ENCOUNTER_BY_PATIENT_URL;
endPoint= String.format(endPoint, EnvGlobals.patientId);
}
@Given("I Set PUT Encounter api endpoint")
public void i_Set_PUT_Facility_Encounter_api_endpoint() {
endPoint = EndpointURLs.GET_ENCOUNTER_URL;
endPoint= String.format(endPoint, EnvGlobals.encounterId);
RequestPayLoad = EncounterPayload.updateEncounter(EnvGlobals.patientId,EnvGlobals.encounterId);
}
@Then("I receive valid Response for PUT Encounter service")
public void i_receive_valid_Response_for_PUT_Encounter_service() {
ReusableFunctions.thenFunction(Hooks.HTTP_RESPONSE_SUCCESS);
validation.Encounter.validateEncounterId(EnvGlobals.encounterId);
validation.Encounter.validateStatus();
}
@Given("I Set GET Encounter api endpoint with invalid id")
public void i_Set_GET_Encounter_api_endpoint_with_invalid_id() {
endPoint = EndpointURLs.GET_ENCOUNTER_URL;
endPoint = String.format(endPoint, "000");
}
@Then("I receive Invalid Response for GET Encounter service")
public void i_receive_Invalid_Response_for_GET_Encounter_service() {
ReusableFunctions.thenFunction(Hooks.HTTP_RESPONSE_NOT_FOUND);
}
}
| 39.938272 | 103 | 0.762906 |
caf334af169a77550de98415c4fee89f0fefae20 | 730 | /*
* Copyright (C) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
*/
package com.huawei.example.demo.service;
/**
* 名称匹配的示例被拦截点
*
* @author HapThorin
* @version 1.0.0
* @since 2021/10/25
*/
public class DemoNameService {
/**
* 被拦截的构造函数
*/
public DemoNameService() {
System.out.println("DemoNameEntity: constructor");
}
/**
* 被拦截的实例方法
*/
public void instFunc() {
System.out.println("DemoNameEntity: instFunc");
}
/**
* 被拦截的静态方法
*/
public static void staticFunc() {
System.out.println("DemoNameEntity: staticFunc");
}
@Override
public String toString() {
return getClass().getSimpleName();
}
}
| 17.804878 | 78 | 0.589041 |
886ffa38afdb9e8d38c1aac9add646690171e53d | 350 | package com.sgrailways.giftidea.wiring;
import android.app.Fragment;
import android.os.Bundle;
public class BaseFragment extends Fragment {
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BaseActivity activity = (BaseActivity)getActivity();
activity.inject(this);
}
}
| 26.923077 | 63 | 0.74 |
d4f77ab9f55b28db870706a4ea4d36f2364df889 | 3,689 | /**
* Copyright (C) 2014 The SciGraph 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 io.scigraph.owlapi.loader;
import io.scigraph.owlapi.loader.OWLCompositeObject;
import io.scigraph.owlapi.loader.OwlOntologyProducer;
import io.scigraph.owlapi.loader.OwlLoadConfiguration.OntologySetup;
import io.scigraph.util.GraphTestBase;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntologyManager;
public class OwlOntologyProducerFailFastTest extends GraphTestBase {
static Server server = new Server(10000);
static OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
server.setStopAtShutdown(true);
ResourceHandler handler = new ResourceHandler();
handler.setBaseResource(Resource.newClassPathResource("/ontologies/bad/"));
server.setHandler(handler);
server.start();
}
@AfterClass
public static void teardown() throws Exception {
server.stop();
server.join();
}
@Test(timeout = 11000)
public void fail_fast() throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newFixedThreadPool(2);
CompletionService<Long> completionService = new ExecutorCompletionService<Long>(executorService);
BlockingQueue<OWLCompositeObject> queue = new LinkedBlockingQueue<OWLCompositeObject>();
BlockingQueue<OntologySetup> ontologyQueue = new LinkedBlockingQueue<OntologySetup>();
OwlOntologyProducer producer =
new OwlOntologyProducer(queue, ontologyQueue, new AtomicInteger(), graph);
OntologySetup ontologyConfig = new OntologySetup();
ontologyConfig.setUrl("http://localhost:10000/foo.owl");
List<Future<?>> futures = new ArrayList<>();
futures.add(completionService.submit(producer));
futures.add(completionService.submit(producer));
Thread.sleep(1000);
ontologyQueue.put(ontologyConfig);
expectedException.expect(ExecutionException.class);
while (futures.size() > 0) {
Future<?> completedFuture = completionService.take();
futures.remove(completedFuture);
completedFuture.get();
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
}
}
| 36.89 | 101 | 0.778802 |
115a73e5abce4f05ae4b0d1cb91f1626d1cdf77b | 263 | package com.csr.iticket.services;
import java.util.List;
import com.csr.iticket.dto.mongo.AgentDto;
public interface AgentService {
AgentDto getAgent(int agentId);
List<AgentDto> getAllAgents();
AgentDto validateLogin(String username,String password);
}
| 18.785714 | 57 | 0.787072 |
84fa2316c3733856f8691b32da68491245514c62 | 1,895 | /*MIT License
Copyright (c) 2020 Lucas Mendes,Marcela Cardoso,Luciano Jr.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
package br.edu.ifpe.model.negocio;
import br.edu.ifpe.model.classes.Endereco;
import br.edu.ifpe.model.dao.EnderecoDAO;
import java.util.List;
/**
*
* @author Luciano
*/
public class EnderecoNegocio {
EnderecoDAO enderecoJDBC = new EnderecoDAO();
public void inserirEndereco (Endereco endereco){
enderecoJDBC.inserir(endereco);
}
public void alterarEndereco (Endereco endereco){
enderecoJDBC.alterar(endereco);
}
public Endereco recuperarEndereco (int codigo){
return enderecoJDBC.recuperar(codigo);
}
public void deletarEndereco (Endereco endereco){
enderecoJDBC.deletar(endereco);
}
public List<Endereco> listarTodosEnderecos(){
return enderecoJDBC.listarTodos();
}
}
| 33.245614 | 78 | 0.748813 |
189a84a5aabfe1df55b94c6c720350effb78b258 | 141 | /**
* FileName: package-info
* Author: Rust
* Date: 2018/6/21
* Description: netty heartbeat
*/
package com.rust.netty.heartbeat;
| 17.625 | 33 | 0.659574 |
7ec4654169e5ca16276d0b4a16d4f268bd3a0503 | 368 | package edt.texteditor;
import java.io.Serializable;
public abstract class TextElement implements Serializable {
private String _id = "";
public TextElement(){}
public TextElement(String id){
_id = id;
}
public String get_id(){
return _id;
}
public void set_id(String id){
_id = id;
}
public abstract String showContent();
} | 17.52381 | 60 | 0.668478 |
308cc85dc7441e38b21daf5029e5b23dd3c803ed | 754 | package cn.hutool.http;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Http拦截器接口,通过实现此接口,完成请求发起前对请求的编辑工作
*
* @author looly
* @since 5.7.16
*/
@FunctionalInterface
public interface HttpInterceptor {
/**
* 处理请求
*
* @param request 请求
*/
void process(HttpRequest request);
/**
* 拦截器链
*
* @author looly
* @since 5.7.16
*/
class Chain implements cn.hutool.core.lang.Chain<HttpInterceptor, Chain> {
private final List<HttpInterceptor> interceptors = new LinkedList<>();
@Override
public Chain addChain(HttpInterceptor element) {
interceptors.add(element);
return this;
}
@Override
public Iterator<HttpInterceptor> iterator() {
return interceptors.iterator();
}
}
}
| 16.755556 | 75 | 0.693634 |
64651eb4b1005debbe4784d6bdc955ba07bd779f | 4,449 | /**
* Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* 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.commonjava.indy.core.expire;
import org.commonjava.indy.model.core.StoreKey;
import org.commonjava.indy.model.core.StoreType;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Indexed;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
import java.util.Objects;
@Indexed
public class ScheduleKey implements Externalizable, Serializable
{
@Field( index = Index.YES, analyze = Analyze.NO )
private StoreKey storeKey;
@Field( index = Index.YES, analyze = Analyze.NO )
private String type;
@Field( index = Index.YES, analyze = Analyze.NO )
private String name;
@Field( index = Index.YES, analyze = Analyze.NO )
private String groupName;
public ScheduleKey()
{
}
public ScheduleKey( final StoreKey storeKey, final String type, final String name )
{
this.storeKey = storeKey;
this.type = type;
this.name = name;
this.groupName = ScheduleManager.groupName( this.storeKey, this.type );
}
public StoreKey getStoreKey()
{
return storeKey;
}
public String getType()
{
return type;
}
public String getName()
{
return name;
}
public String getGroupName()
{
return groupName;
}
public static ScheduleKey fromGroupWithName( final String group, final String name )
{
final String[] splits = group.split( "#" );
return new ScheduleKey( StoreKey.fromString( splits[0] ), splits[1], name );
}
@Override
public boolean equals( Object obj )
{
if ( !( obj instanceof ScheduleKey ) )
{
return false;
}
final ScheduleKey that = (ScheduleKey) obj;
return Objects.equals( this.storeKey, that.storeKey ) && Objects.equals( this.type, that.type )
&& Objects.equals( this.name, that.name );
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ( ( storeKey == null ) ? 0 : storeKey.hashCode() );
result = prime * result + ( ( type == null ) ? 0 : type.hashCode() );
result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
return result;
}
public String toStringKey()
{
return ( storeKey != null ? storeKey.toString() : "" ) + "#" + type + "#" + name;
}
public String toString()
{
return toStringKey();
}
public boolean exists()
{
return this.storeKey != null && this.type != null;
}
@Override
public void writeExternal( ObjectOutput out )
throws IOException
{
out.writeObject( storeKey.getName() );
out.writeObject( storeKey.getType().name() );
out.writeObject( storeKey.getPackageType() );
out.writeObject( type );
out.writeObject( name );
}
@Override
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException
{
final String storeKeyName = (String) in.readObject();
final StoreType storeType = StoreType.get( (String) in.readObject() );
final String packageType = (String)in.readObject();
storeKey = new StoreKey( packageType, storeType, storeKeyName );
final String typeStr = (String) in.readObject();
type = "".equals( typeStr ) ? null : typeStr;
final String nameStr = (String) in.readObject();
name = "".equals( nameStr ) ? null : nameStr;
groupName = ScheduleManager.groupName( storeKey, type );
}
}
| 29.078431 | 103 | 0.636323 |
6be83b8f7a3a8c55ea782f55a037def6e0876051 | 2,735 | /*
120
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
Note:
Bonus point if you are able to do this using only O(n) extra space,
where n is the total number of rows in the triangle.
*/
import java.util.List;
public class Triangle {
public int minimumTotal0(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int[][] DP = new int[triangle.size()][triangle.size()];
List<Integer> bottom = triangle.get(triangle.size() - 1);
for (int index = 0; index < bottom.size(); index++) {
DP[triangle.size() - 1][index] = bottom.get(index);
}
for (int row = triangle.size() - 2; row >= 0; row--) {
for (int column = 0; column < triangle.get(row).size(); column++) {
DP[row][column] = Math.min(DP[row + 1][column], DP[row + 1][column + 1]) + triangle.get(row).get(column);
}
}
return DP[0][0];
}
public int minimumTotal1(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int[][] DP = new int[triangle.size() + 1][triangle.size() + 1];
for (int row = triangle.size() - 1; row >= 0; row--) {
List<Integer> current = triangle.get(row);
for (int column = 0; column < triangle.get(row).size(); column++) {
DP[row][column] = Math.min(DP[row + 1][column], DP[row + 1][column + 1]) + triangle.get(row).get(column);
}
}
return DP[0][0];
}
public int minimumTotal2(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int[] dp = new int[triangle.get(triangle.size() - 1).size() + 1];
for (int row = triangle.size() - 1; row >= 0; row--) {
for (int column = 0; column < triangle.get(row).size(); column++) {
dp[column] = Math.min(dp[column], dp[column + 1]) + triangle.get(row).get(column);
}
}
return dp[0];
}
public int minimumTotal3(List<List<Integer>> triangle) {
if (triangle == null || triangle.size() == 0) {
return 0;
}
int rows = triangle.size();
for (int row = rows - 2; row >= 0; row--) {
for (int column = 0; column < triangle.get(row).size(); column++) {
int temp = Math.min(triangle.get(rows - 1).get(column), triangle.get(rows - 1).get(column + 1)) + triangle.get(row).get(column);
triangle.get(rows - 1).set(column, temp);
}
}
return triangle.get(rows - 1).get(0);
}
}
| 29.095745 | 136 | 0.565996 |
06c4b533467f8f2d558607b5c261812dcd881b7f | 169 | package com.web.common.web.common.study.code;
/**
* @author: [email protected]
* @date: 2016年6月8日 下午5:41:56
*/
public class ConcurrentLinkQueue {
}
| 16.9 | 46 | 0.674556 |
e7d789b90fbda5c9e7376d99fac86eaed50ba790 | 6,733 | /*
* Copyright (c) 2016 Martin Davis.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License 2.0
* and Eclipse Distribution License v. 1.0 which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
*
* http://www.eclipse.org/org/documents/edl-v10.php.
*/
package org.locationtech.jts.math;
import org.locationtech.jts.geom.Coordinate;
/**
* Represents a vector in 3-dimensional Cartesian space.
*
* @author mdavis
*
*/
public class Vector3D {
/**
* Computes the dot product of the 3D vectors AB and CD.
*
* @param A the start point of the first vector
* @param B the end point of the first vector
* @param C the start point of the second vector
* @param D the end point of the second vector
* @return the dot product
*/
public static double dot(Coordinate A, Coordinate B, Coordinate C, Coordinate D)
{
double ABx = B.x - A.x;
double ABy = B.y - A.y;
double ABz = B.getZ() - A.getZ();
double CDx = D.x - C.x;
double CDy = D.y - C.y;
double CDz = D.getZ() - C.getZ();
return ABx*CDx + ABy*CDy + ABz*CDz;
}
/**
* Creates a new vector with given X, Y and Z components.
*
* @param x the X component
* @param y the Y component
* @param z the Z component
* @return a new vector
*/
public static Vector3D create(double x, double y, double z) {
return new Vector3D(x, y, z);
}
/**
* Creates a vector from a 3D {@link Coordinate}.
* The coordinate should have the
* X,Y and Z ordinates specified.
*
* @param coord the Coordinate to copy
* @return a new vector
*/
public static Vector3D create(Coordinate coord) {
return new Vector3D(coord);
}
/**
* Computes the 3D dot-product of two {@link Coordinate}s.
*
* @param v1 the first vector
* @param v2 the second vector
* @return the dot product of the vectors
*/
public static double dot(Coordinate v1, Coordinate v2) {
return v1.x * v2.x + v1.y * v2.y + v1.getZ() * v2.getZ();
}
private double x;
private double y;
private double z;
/**
* Creates a new 3D vector from a {@link Coordinate}. The coordinate should have
* the X,Y and Z ordinates specified.
*
* @param v the Coordinate to copy
*/
public Vector3D(Coordinate v) {
x = v.x;
y = v.y;
z = v.getZ();
}
/**
* Creates a new vector with the direction and magnitude
* of the difference between the
* <tt>to</tt> and <tt>from</tt> {@link Coordinate}s.
*
* @param from the origin Coordinate
* @param to the destination Coordinate
*/
public Vector3D(Coordinate from, Coordinate to) {
x = to.x - from.x;
y = to.y - from.y;
z = to.getZ() - from.getZ();
}
/**
* Creates a vector with the givne components.
*
* @param x the X component
* @param y the Y component
* @param z the Z component
*/
public Vector3D(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Gets the X component of this vector.
*
* @return the value of the X component
*/
public double getX() {
return x;
}
/**
* Gets the Y component of this vector.
*
* @return the value of the Y component
*/
public double getY() {
return y;
}
/**
* Gets the Z component of this vector.
*
* @return the value of the Z component
*/
public double getZ() {
return z;
}
/**
* Computes a vector which is the sum
* of this vector and the given vector.
*
* @param v the vector to add
* @return the sum of this and <code>v</code>
*/
public Vector3D add(Vector3D v) {
return create(x + v.x, y + v.y, z + v.z);
}
/**
* Computes a vector which is the difference
* of this vector and the given vector.
*
* @param v the vector to subtract
* @return the difference of this and <code>v</code>
*/
public Vector3D subtract(Vector3D v) {
return create(x - v.x, y - v.y, z - v.z);
}
/**
* Creates a new vector which has the same direction
* and with length equals to the length of this vector
* divided by the scalar value <code>d</code>.
*
* @param d the scalar divisor
* @return a new vector with divided length
*/
public Vector3D divide(double d) {
return create(x / d, y / d, z / d);
}
/**
* Computes the dot-product of two vectors
*
* @param v a vector
* @return the dot product of the vectors
*/
public double dot(Vector3D v) {
return x * v.x + y * v.y + z * v.z;
}
/**
* Computes the length of this vector.
*
* @return the length of the vector
*/
public double length() {
return Math.sqrt(x * x + y * y + z * z);
}
/**
* Computes the length of a vector.
*
* @param v a coordinate representing a 3D vector
* @return the length of the vector
*/
public static double length(Coordinate v) {
return Math.sqrt(v.x * v.x + v.y * v.y + v.getZ() * v.getZ());
}
/**
* Computes a vector having identical direction
* but normalized to have length 1.
*
* @return a new normalized vector
*/
public Vector3D normalize() {
double length = length();
if (length > 0.0)
return divide(length());
return create(0.0, 0.0, 0.0);
}
/**
* Computes a vector having identical direction
* but normalized to have length 1.
*
* @param v a coordinate representing a 3D vector
* @return a coordinate representing the normalized vector
*/
public static Coordinate normalize(Coordinate v) {
double len = length(v);
return new Coordinate(v.x / len, v.y / len, v.getZ() / len);
}
/**
* Gets a string representation of this vector
*
* @return a string representing this vector
*/
public String toString() {
return "[" + x + ", " + y + ", " + z + "]";
}
/**
* Tests if a vector <tt>o</tt> has the same values for the components.
*
* @param o a <tt>Vector3D</tt> with which to do the comparison.
* @return true if <tt>other</tt> is a <tt>Vector3D</tt> with the same values
* for the x and y components.
*/
public boolean equals(Object o) {
if ( !(o instanceof Vector3D) ) {
return false;
}
Vector3D v = (Vector3D) o;
return x == v.x && y == v.y && z == v.z;
}
/**
* Gets a hashcode for this vector.
*
* @return a hashcode for this vector
*/
public int hashCode() {
// Algorithm from Effective Java by Joshua Bloch
int result = 17;
result = 37 * result + Coordinate.hashCode(x);
result = 37 * result + Coordinate.hashCode(y);
result = 37 * result + Coordinate.hashCode(z);
return result;
}
}
| 24.306859 | 87 | 0.621565 |
416a4cb4dfa596aeebdda89f46f8e9e113c773d1 | 8,447 | /*
* Copyright 2019 Monotonic Ltd.
*
* 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
*
* https://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 uk.co.real_logic.artio.system_tests;
import org.agrona.CloseHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.co.real_logic.artio.Reply;
import uk.co.real_logic.artio.builder.AbstractLogonEncoder;
import uk.co.real_logic.artio.builder.AbstractLogoutEncoder;
import uk.co.real_logic.artio.engine.EngineConfiguration;
import uk.co.real_logic.artio.engine.FixEngine;
import uk.co.real_logic.artio.engine.LowResourceEngineScheduler;
import uk.co.real_logic.artio.fixt.ApplVerID;
import uk.co.real_logic.artio.fixt.FixDictionaryImpl;
import uk.co.real_logic.artio.fixt.builder.LogonEncoder;
import uk.co.real_logic.artio.library.FixLibrary;
import uk.co.real_logic.artio.library.LibraryConfiguration;
import uk.co.real_logic.artio.library.SessionConfiguration;
import uk.co.real_logic.artio.session.Session;
import uk.co.real_logic.artio.session.SessionCustomisationStrategy;
import uk.co.real_logic.artio.validation.AuthenticationStrategy;
import uk.co.real_logic.artio.validation.MessageValidationStrategy;
import static io.aeron.CommonContext.IPC_CHANNEL;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static uk.co.real_logic.artio.TestFixtures.launchMediaDriver;
import static uk.co.real_logic.artio.TestFixtures.unusedPort;
import static uk.co.real_logic.artio.fixt.ApplVerID.FIX50;
import static uk.co.real_logic.artio.system_tests.SystemTestUtil.*;
public class MultipleFixVersionInitiatorSystemTest extends AbstractGatewayToGatewaySystemTest
{
private static final String FIXT_ACCEPTOR_LOGS = "fixt-acceptor-logs";
private static final String FIXT_ACCEPTOR_ID = "fixt-acceptor";
private static final int FIXT_INBOUND_LIBRARY_STREAM = 11;
private static final int FIXT_OUTBOUND_LIBRARY_STREAM = 12;
private static final int FIXT_OUTBOUND_REPLAY_STREAM = 13;
private static final int FIXT_ARCHIVE_REPLAY_STREAM = 14;
private int fixtPort = unusedPort();
private FixEngine fixtAcceptingEngine;
private FixLibrary fixtAcceptingLibrary;
private FakeOtfAcceptor fixtAcceptingOtfAcceptor = new FakeOtfAcceptor();
private FakeHandler fixtAcceptingHandler = new FakeHandler(fixtAcceptingOtfAcceptor);
private Session fixtInitiatingSession;
@Before
public void launch()
{
deleteLogs();
delete(FIXT_ACCEPTOR_LOGS);
mediaDriver = launchMediaDriver();
launchAcceptingEngine();
launchFixTAcceptingEngine();
initiatingEngine = launchInitiatingEngine(libraryAeronPort);
acceptingLibrary = connect(acceptingLibraryConfig(acceptingHandler));
connectFixTAcceptingLibrary();
final LibraryConfiguration configuration = initiatingLibraryConfig(libraryAeronPort, initiatingHandler);
configuration.sessionCustomisationStrategy(new FixTSessionCustomisationStrategy(FIX50));
initiatingLibrary = connect(configuration);
testSystem = new TestSystem(acceptingLibrary, fixtAcceptingLibrary, initiatingLibrary);
}
@After
public void closeFixT()
{
CloseHelper.close(fixtAcceptingLibrary);
CloseHelper.close(fixtAcceptingEngine);
}
private void connectFixTAcceptingLibrary()
{
final LibraryConfiguration configuration = new LibraryConfiguration();
setupCommonConfig(FIXT_ACCEPTOR_ID, INITIATOR_ID, configuration);
configuration
.sessionExistsHandler(fixtAcceptingHandler)
.sessionAcquireHandler(fixtAcceptingHandler)
.sentPositionHandler(fixtAcceptingHandler)
.libraryAeronChannels(singletonList(IPC_CHANNEL))
.libraryName("fixtAccepting")
.inboundLibraryStream(FIXT_INBOUND_LIBRARY_STREAM)
.outboundLibraryStream(FIXT_OUTBOUND_LIBRARY_STREAM)
.sessionCustomisationStrategy(new FixTSessionCustomisationStrategy(FIX50));
fixtAcceptingLibrary = connect(configuration);
}
private void launchFixTAcceptingEngine()
{
final EngineConfiguration configuration = new EngineConfiguration();
final MessageValidationStrategy validationStrategy = setupCommonConfig(
FIXT_ACCEPTOR_ID,
INITIATOR_ID, configuration);
final AuthenticationStrategy authenticationStrategy = AuthenticationStrategy.of(validationStrategy);
configuration.authenticationStrategy(authenticationStrategy);
final EngineConfiguration fixtAcceptingConfiguration = configuration
.bindTo("localhost", fixtPort)
.libraryAeronChannel(IPC_CHANNEL)
.monitoringFile(acceptorMonitoringFile("fixtEngineCounters"))
.inboundLibraryStream(FIXT_INBOUND_LIBRARY_STREAM)
.outboundLibraryStream(FIXT_OUTBOUND_LIBRARY_STREAM)
.outboundReplayStream(FIXT_OUTBOUND_REPLAY_STREAM)
.archiveReplayStream(FIXT_ARCHIVE_REPLAY_STREAM)
.logFileDir(FIXT_ACCEPTOR_LOGS)
.scheduler(new LowResourceEngineScheduler());
fixtAcceptingConfiguration
.acceptorfixDictionary(FixDictionaryImpl.class)
.sessionCustomisationStrategy(new FixTSessionCustomisationStrategy(FIX50));
fixtAcceptingEngine = FixEngine.launch(fixtAcceptingConfiguration);
}
@Test
public void messagesCanBeSentFromInitiatorToBothAcceptors()
{
connectSessions();
connectFixTSessions();
bothSessionsCanExchangeMessages();
}
@Test
public void sessionsCanBeAcquired()
{
connectSessions();
acquireAcceptingSession();
connectFixTSessions();
acquireFixTSession();
bothSessionsCanExchangeMessages();
}
private void bothSessionsCanExchangeMessages()
{
messagesCanBeExchanged();
final FixDictionaryImpl fixtDictionary = new FixDictionaryImpl();
final String testReqID = testReqId();
sendTestRequest(fixtInitiatingSession, testReqID, fixtDictionary);
assertReceivedSingleHeartbeat(testSystem, initiatingOtfAcceptor, testReqID);
}
private void acquireFixTSession()
{
final long sessionId = fixtAcceptingHandler.awaitSessionId(testSystem::poll);
final Session fixtAcceptingSession = acquireSession(
fixtAcceptingHandler, fixtAcceptingLibrary, sessionId, testSystem);
assertEquals(INITIATOR_ID, fixtAcceptingHandler.lastInitiatorCompId());
assertEquals(FIXT_ACCEPTOR_ID, fixtAcceptingHandler.lastAcceptorCompId());
assertNotNull("unable to acquire accepting session", fixtAcceptingSession);
}
private void connectFixTSessions()
{
final SessionConfiguration config = SessionConfiguration.builder()
.address("localhost", fixtPort)
.credentials(USERNAME, PASSWORD)
.senderCompId(INITIATOR_ID)
.targetCompId(FIXT_ACCEPTOR_ID)
.fixDictionary(FixDictionaryImpl.class)
.build();
final Reply<Session> reply = initiatingLibrary.initiate(config);
fixtInitiatingSession = completeConnectSessions(reply);
}
}
class FixTSessionCustomisationStrategy implements SessionCustomisationStrategy
{
private final ApplVerID applVerID;
FixTSessionCustomisationStrategy(final ApplVerID applVerID)
{
this.applVerID = applVerID;
}
public void configureLogon(final AbstractLogonEncoder abstractLogon, final long sessionId)
{
if (abstractLogon instanceof LogonEncoder)
{
final LogonEncoder logon = (LogonEncoder)abstractLogon;
logon.defaultApplVerID(applVerID.representation());
}
}
public void configureLogout(final AbstractLogoutEncoder logout, final long sessionId)
{
}
}
| 38.04955 | 112 | 0.747721 |
5e9fa64e70ddb32f3caa6501cd23d8d5e2663913 | 459 | package org.opencds.cqf.cds.hooks;
import org.opencds.cqf.cds.request.JsonHelper;
import org.opencds.cqf.cds.request.Request;
import com.google.gson.JsonElement;
public class OrderSelectHook extends Hook {
public OrderSelectHook(Request request) {
super(request);
}
@Override
public JsonElement getContextResources() {
return JsonHelper.getObjectRequired(getRequest().getContext().getContextJson(), "draftOrders");
}
}
| 25.5 | 103 | 0.738562 |
33a6eba967bb5ba979f6fe880776d66690818a63 | 465 | package com.web.project.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.NoArgsConstructor;
@Entity
@NoArgsConstructor
@Table(name = "publicacoes")
public class Publicacao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private byte[] metadados;
private TipoPublicacao tipo;
}
| 18.6 | 52 | 0.804301 |
41446a20c746a11245db379380006af30e81db95 | 963 | package com.wizzardo.http.framework.template.taglib.g;
import com.wizzardo.http.framework.template.Body;
import com.wizzardo.http.framework.template.ExpressionHolder;
import com.wizzardo.http.framework.template.RenderResult;
import com.wizzardo.http.framework.template.Tag;
import com.wizzardo.tools.evaluation.AsBooleanExpression;
import java.util.Collection;
import java.util.Map;
/**
* Created by wizzardo on 16.05.15.
*/
public class While extends Tag {
public Tag init(Map<String, String> attrs, Body body, String offset) {
ExpressionHolder<Collection> raw = asExpression(attrs, "test", false, true);
add((model, result) -> {
while (AsBooleanExpression.toBoolean(raw.getRaw(model))) {
body.get(model, result);
}
return result;
});
return this;
}
@Override
protected String getBodyOffset(String offset, String padding) {
return offset;
}
}
| 29.181818 | 84 | 0.687435 |
08d482d4a0aa21efce399f64df635b007025075b | 3,361 | /*
* Copyright 2016 org.NLP4L
*
* 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.nlp4l.solr.ltr;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.Weight;
public final class LinearWeightQuery extends AbstractLTRQuery {
public LinearWeightQuery(List<FieldFeatureExtractorFactory> featuresSpec, List<Float> weights){
super(featuresSpec, weights);
}
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException {
return new LinearWeight(this);
}
@Override
public int hashCode() {
final int prime = 61;
return super.hashCode(prime);
}
public final class LinearWeight extends Weight {
protected LinearWeight(Query query) {
super(query);
}
/**
* Expert: adds all terms occurring in this query to the terms set. If the
* {@link Weight} was created with {@code needsScores == true} then this
* method will only extract terms which are used for scoring, otherwise it
* will extract all terms which are used for matching.
*/
@Override
public void extractTerms(Set<Term> set) {
for(FieldFeatureExtractorFactory factory: featuresSpec){
// TODO: need to remove redundant terms...
for(Term term: factory.getTerms()){
set.add(term);
}
}
}
@Override
public Explanation explain(LeafReaderContext leafReaderContext, int doc) throws IOException {
LinearWeightScorer scorer = (LinearWeightScorer)scorer(leafReaderContext);
if(scorer != null){
int newDoc = scorer.iterator().advance(doc);
if (newDoc == doc) {
return Explanation.match(scorer.score(), "sum of:", scorer.subExplanations(doc));
}
}
return Explanation.noMatch("no matching terms");
}
@Override
public Scorer scorer(LeafReaderContext context) throws IOException {
List<FieldFeatureExtractor[]> spec = new ArrayList<FieldFeatureExtractor[]>();
Set<Integer> allDocs = new HashSet<Integer>();
for(FieldFeatureExtractorFactory factory: featuresSpec){
FieldFeatureExtractor[] extractors = factory.create(context, allDocs);
spec.add(extractors);
}
if(allDocs.size() == 0) return null;
else{
return new LinearWeightScorer(this, spec, weights, getIterator(allDocs));
}
}
@Override
public boolean isCacheable(LeafReaderContext leafReaderContext) {
return false;
}
}
}
| 32.009524 | 107 | 0.705147 |
f46e0760f9304e8efcb6df9eb71f8112fe063b19 | 2,961 | package com.tongji.meeting.service;
import com.tongji.meeting.dao.CalendarDao;
import com.tongji.meeting.dao.EventDao;
import com.tongji.meeting.dao.UserCalendarDao;
import com.tongji.meeting.model.Calendar;
import com.tongji.meeting.model.UserCalendar;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
@Service
public class CalendarService {
@Autowired
private CalendarDao calendarDao;
@Autowired
private UserCalendarDao userCalendarDao;
@Autowired
private EventDao eventDao;
public void createCalendar(Calendar calendar){
calendarDao.createCalendar(calendar);
}
public void disbandCalendar(Integer calendarId){calendarDao.disbandCalendar(calendarId);}
public Hashtable<String,Object> getCreatedCalendar(Integer userId){
List<Calendar> calendarList=calendarDao.getCreatedCalendar(userId);
List<Integer> memberNum=new ArrayList<>();
List<Integer> eventNum=new ArrayList<>();
List<Boolean> disturbModes=new ArrayList<>();
int calendarId;
for(Calendar calendar:calendarList){
calendarId=calendar.getCalendarId();
memberNum.add(userCalendarDao.getMemberNum(calendarId));
eventNum.add(eventDao.getEventNum(calendarId));
disturbModes.add(userCalendarDao.getDisturbStatus(userId,calendarId));
}
Hashtable<String,Object> createdCalendar = new Hashtable<>();
createdCalendar.put("calendarList",calendarList);
createdCalendar.put("memberNum",memberNum);
createdCalendar.put("eventNum",eventNum);
createdCalendar.put("disturbModes",disturbModes);
return createdCalendar;
}
public Hashtable<String,Object> getParticipantCalendar(Integer userId){
List<Calendar> calendarList=calendarDao.getParticipantCalendar(userId);
List<Integer> memberNum=new ArrayList<>();
List<Integer> eventNum=new ArrayList<>();
List<Boolean> disturbModes=new ArrayList<>();
int calendarId;
for(Calendar calendar:calendarList){
calendarId=calendar.getCalendarId();
memberNum.add(userCalendarDao.getMemberNum(calendarId));
eventNum.add(eventDao.getEventNum(calendarId));
disturbModes.add(userCalendarDao.getDisturbStatus(userId,calendarId));
}
Hashtable<String,Object> participantCalendar = new Hashtable<>();
participantCalendar.put("calendarList",calendarList);
participantCalendar.put("memberNum",memberNum);
participantCalendar.put("eventNum",eventNum);
participantCalendar.put("disturbModes",disturbModes);
return participantCalendar;
}
public Calendar getMyCalendar(Integer userId){
return calendarDao.getMyCalendar(userId);
}
}
| 38.454545 | 93 | 0.721378 |
b5aa7c189868fc5f7f344944b85ee2575bd347b3 | 1,198 | package org.zstack.header.network.service;
import org.zstack.header.message.APIEvent;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.rest.RestResponse;
import java.util.Arrays;
/**
* Created by frank on 1/4/2016.
*/
@RestResponse(allTo = "inventory")
public class APIDetachNetworkServiceFromL3NetworkEvent extends APIEvent {
private L3NetworkInventory inventory;
public APIDetachNetworkServiceFromL3NetworkEvent() {
}
public APIDetachNetworkServiceFromL3NetworkEvent(String apiId) {
super(apiId);
}
public L3NetworkInventory getInventory() {
return inventory;
}
public void setInventory(L3NetworkInventory inventory) {
this.inventory = inventory;
}
public static APIDetachNetworkServiceFromL3NetworkEvent __example__() {
APIDetachNetworkServiceFromL3NetworkEvent event = new APIDetachNetworkServiceFromL3NetworkEvent();
L3NetworkInventory l3 = new L3NetworkInventory();
NetworkServiceL3NetworkRefInventory ns = new NetworkServiceL3NetworkRefInventory();
l3.setUuid(uuid());
l3.setNetworkServices(Arrays.asList(ns));
return event;
}
}
| 27.860465 | 106 | 0.74374 |
336f463113405e0dc5a3d952ce08d1adb446996c | 2,403 | /*
* Copyright 2013, Unitils.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.unitils.core;
import org.junit.Before;
import org.junit.Test;
import org.unitils.core.reflect.ClassWrapper;
import java.lang.reflect.Method;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
/**
* @author Tim Ducheyne
*/
public class TestInstanceTest {
/* Tested object */
private TestInstance testInstance;
private ClassWrapper classWrapper;
private Object testObject;
private Method testMethod;
@Before
public void initialize() throws Exception {
testMethod = MyClass.class.getMethod("method");
classWrapper = new ClassWrapper(MyClass.class);
testObject = new MyClass();
}
@Test
public void getTestClass() {
testInstance = new TestInstance(classWrapper, testObject, testMethod);
ClassWrapper result = testInstance.getClassWrapper();
assertSame(classWrapper, result);
}
@Test
public void getTestMethod() {
testInstance = new TestInstance(classWrapper, testObject, testMethod);
Method result = testInstance.getTestMethod();
assertSame(testMethod, result);
}
@Test
public void getTestObject() {
testInstance = new TestInstance(classWrapper, testObject, testMethod);
Object result = testInstance.getTestObject();
assertSame(testObject, result);
}
@Test
public void getName() {
testInstance = new TestInstance(classWrapper, testObject, testMethod);
String result = testInstance.getName();
assertEquals("org.unitils.core.TestInstanceTest$MyClass.method", result);
}
private static class MyClass {
public void method() {
}
}
}
| 27.306818 | 82 | 0.669164 |
eefbb3bd5ea568e3e759a788ae7f7d05b659acd5 | 10,584 | /*
* Copyright 2020 The Error Prone 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 com.google.errorprone.bugpatterns;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.Iterables.getLast;
import static com.google.errorprone.matchers.ChildMultiMatcher.MatchType.AT_LEAST_ONE;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.Matchers.annotations;
import static com.google.errorprone.util.ASTHelpers.getStartPosition;
import static com.google.errorprone.util.ASTHelpers.getSymbol;
import static com.google.errorprone.util.FindIdentifiers.findIdent;
import com.google.common.base.Ascii;
import com.google.common.base.Splitter;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Table;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.BugPattern.StandardTags;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.MultiMatcher;
import com.sun.source.tree.AnnotatedTypeTree;
import com.sun.source.tree.AnnotationTree;
import com.sun.source.tree.CaseTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.util.Position;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Discourages using multiple names to refer to the same type within a file (e.g. both {@code
* OuterClass.InnerClass} and {@code InnerClass}).
*/
@BugPattern(
name = "DifferentNameButSame",
severity = SeverityLevel.WARNING,
summary =
"This type is referred to in different ways within this file, which may be confusing.",
tags = StandardTags.STYLE)
public final class DifferentNameButSame extends BugChecker implements CompilationUnitTreeMatcher {
@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
Table<Symbol, String, List<TreePath>> names = HashBasedTable.create();
new TreePathScanner<Void, Void>() {
@Override
public Void visitImport(ImportTree importTree, Void unused) {
return null;
}
@Override
public Void visitCase(CaseTree caseTree, Void unused) {
return null;
}
@Override
public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
if (getCurrentPath().getParentPath().getLeaf() instanceof MemberSelectTree) {
MemberSelectTree tree = (MemberSelectTree) getCurrentPath().getParentPath().getLeaf();
Symbol superSymbol = getSymbol(tree);
if (superSymbol instanceof ClassSymbol) {
return super.visitMemberSelect(memberSelectTree, null);
}
}
handle(memberSelectTree);
return super.visitMemberSelect(memberSelectTree, null);
}
@Override
public Void visitIdentifier(IdentifierTree identifierTree, Void unused) {
handle(identifierTree);
return super.visitIdentifier(identifierTree, null);
}
private void handle(Tree tree) {
if (state.getEndPosition(tree) == Position.NOPOS) {
return;
}
Symbol symbol = getSymbol(tree);
if (!(symbol instanceof ClassSymbol)) {
return;
}
String name = tree.toString();
List<TreePath> treePaths = names.get(symbol, name);
if (treePaths == null) {
treePaths = new ArrayList<>();
names.put(symbol, name, treePaths);
}
treePaths.add(getCurrentPath());
}
}.scan(tree, null);
for (Map.Entry<Symbol, Map<String, List<TreePath>>> entry : names.rowMap().entrySet()) {
Symbol symbol = entry.getKey();
// Skip generic symbols; we need to do a lot more work to check the type parameters match at
// each level.
if (isGeneric(symbol)) {
continue;
}
if (isDefinedInThisFile(symbol, tree)) {
continue;
}
Map<String, List<TreePath>> references = entry.getValue();
if (references.size() == 1) {
continue;
}
// Skip if any look to be fully qualified: this will be mentioned by a different check.
if (references.keySet().stream().anyMatch(n -> Ascii.isLowerCase(n.charAt(0)))) {
continue;
}
ImmutableList<String> namesByPreference =
references.entrySet().stream()
.sorted(REPLACEMENT_PREFERENCE)
.map(Map.Entry::getKey)
.collect(toImmutableList());
for (String name : namesByPreference) {
ImmutableList<TreePath> sites =
references.entrySet().stream()
.filter(e -> !e.getKey().equals(name))
.map(Map.Entry::getValue)
.flatMap(Collection::stream)
.collect(toImmutableList());
if (!(symbol instanceof MethodSymbol) && !visibleAndReferToSameThing(name, sites, state)) {
continue;
}
if (BadImport.BAD_NESTED_CLASSES.contains(name)) {
continue;
}
List<String> components = DOT_SPLITTER.splitToList(name);
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
for (TreePath site : sites) {
fixBuilder.merge(createFix(site, components, state));
}
SuggestedFix fix = fixBuilder.build();
for (TreePath path : sites) {
state.reportMatch(describeMatch(path.getLeaf(), fix));
}
break;
}
}
return NO_MATCH;
}
private boolean isDefinedInThisFile(Symbol symbol, CompilationUnitTree tree) {
return tree.getTypeDecls().stream()
.anyMatch(
t -> {
Symbol topLevelClass = getSymbol(t);
return topLevelClass instanceof ClassSymbol
&& symbol.isEnclosedBy((ClassSymbol) topLevelClass);
});
}
private static boolean isGeneric(Symbol symbol) {
for (Symbol s = symbol; s != null; s = s.owner) {
if (!s.getTypeParameters().isEmpty()) {
return true;
}
}
return false;
}
private static SuggestedFix createFix(
TreePath path, List<String> components, VisitorState state) {
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
StringBuilder stringBuilder = new StringBuilder();
components.stream()
.limit(components.size() - 1)
.forEachOrdered(c -> stringBuilder.append(c).append("."));
Tree site = path.getLeaf();
Tree parent = path.getParentPath().getLeaf();
if (canHaveTypeUseAnnotations(parent)) {
for (AnnotationTree annotation :
HAS_TYPE_USE_ANNOTATION.multiMatchResult(parent, state).matchingNodes()) {
if (state.getEndPosition(annotation) < getStartPosition(site)) {
fixBuilder.delete(annotation);
}
stringBuilder.append(state.getSourceForNode(annotation)).append(" ");
}
}
stringBuilder.append(getLast(components));
return fixBuilder.replace(site, stringBuilder.toString()).build();
}
private static boolean canHaveTypeUseAnnotations(Tree tree) {
return tree instanceof AnnotatedTypeTree
|| tree instanceof MethodTree
|| tree instanceof VariableTree;
}
/**
* Checks whether the symbol with {@code name} is visible from the position encoded in {@code
* state}.
*
* <p>This is not fool-proof by any means: it doesn't check that the symbol actually has the same
* meaning.
*/
private static boolean visibleAndReferToSameThing(
String name, ImmutableList<TreePath> locations, VisitorState state) {
String firstComponent = name.contains(".") ? name.substring(0, name.indexOf(".")) : name;
Set<Symbol> idents = new HashSet<>();
for (TreePath path : locations) {
VisitorState stateWithPath = state.withPath(path);
if (findIdent(firstComponent, stateWithPath, KindSelector.VAR) != null) {
return false;
}
Symbol symbol = findIdent(firstComponent, stateWithPath, KindSelector.VAL_TYP_PCK);
if (symbol == null) {
return false;
}
idents.add(symbol);
}
return idents.size() == 1;
}
private static final Comparator<Map.Entry<String, List<TreePath>>> REPLACEMENT_PREFERENCE =
Comparator.<Map.Entry<String, List<TreePath>>>comparingInt(e -> e.getKey().length())
.thenComparing(Map.Entry::getKey);
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private static final MultiMatcher<Tree, AnnotationTree> HAS_TYPE_USE_ANNOTATION =
annotations(AT_LEAST_ONE, (t, state) -> isTypeAnnotation(t));
private static boolean isTypeAnnotation(AnnotationTree t) {
Symbol annotationSymbol = getSymbol(t.getAnnotationType());
if (annotationSymbol == null) {
return false;
}
Target target = annotationSymbol.getAnnotation(Target.class);
if (target == null) {
return false;
}
List<ElementType> value = Arrays.asList(target.value());
return value.contains(ElementType.TYPE_USE) || value.contains(ElementType.TYPE_PARAMETER);
}
}
| 38.209386 | 99 | 0.691893 |
b873b6531ecd850a568115a5f3ef8f965ee45a4f | 1,157 | package io.hilamg.imservice.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.github.yuweiguocn.library.greendao.MigrationHelper;
import io.hilamg.imservice.bean.DaoMaster;
import io.hilamg.imservice.bean.SlowModeLocalBeanDao;
import org.greenrobot.greendao.database.Database;
public class OpenHelper extends DaoMaster.OpenHelper {
public OpenHelper(Context context, String name) {
super(context, name);
}
public OpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
@Override
public void onCreateAllTables(Database db, boolean ifNotExists) {
DaoMaster.createAllTables(db, true);
}
@Override
public void onDropAllTables(Database db, boolean ifExists) {
DaoMaster.dropAllTables(db, true);
}
}, SlowModeLocalBeanDao.class);
}
}
| 32.138889 | 91 | 0.698358 |
a515df12721f8420fb63f234a25d2a3b068a452f | 21,453 | /*
* Copyright 2001-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.tools.ant.taskdefs.optional.sitraka;
import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.optional.sitraka.bytecode.ClassFile;
import org.apache.tools.ant.taskdefs.optional.sitraka.bytecode.ClassPathLoader;
import org.apache.tools.ant.taskdefs.optional.sitraka.bytecode.MethodInfo;
import org.apache.tools.ant.taskdefs.optional.sitraka.bytecode.Utils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* Little hack to process XML report from JProbe. It will fix
* some reporting errors from JProbe 3.0 and makes use of a reference
* classpath to add classes/methods that were not reported by JProbe
* as being used (ie loaded)
*
*/
public class XMLReport {
/** task caller, can be null, used for logging purpose */
private Task task;
/** the XML file to process just from CovReport */
private File file;
/** jprobe home path. It is used to get the DTD */
private File jprobeHome;
/** parsed document */
private Document report;
/**
* mapping of class names to <code>ClassFile</code>s from the reference
* classpath. It is used to filter the JProbe report.
*/
private Hashtable classFiles;
/** mapping package name / package node for faster access */
private Hashtable pkgMap;
/** mapping classname / class node for faster access */
private Hashtable classMap;
/** method filters */
private ReportFilters filters;
/** create a new XML report, logging will be on stdout */
public XMLReport(File file) {
this(null, file);
}
/** create a new XML report, logging done on the task */
public XMLReport(Task task, File file) {
this.file = file;
this.task = task;
}
/** set the JProbe home path. Used to get the DTD */
public void setJProbehome(File home) {
jprobeHome = home;
}
/** set the */
public void setReportFilters(ReportFilters filters) {
this.filters = filters;
}
/** create node maps so that we can access node faster by their name */
protected void createNodeMaps() {
pkgMap = new Hashtable();
classMap = new Hashtable();
// create a map index of all packages by their name
// @todo can be done faster by direct access.
NodeList packages = report.getElementsByTagName("package");
final int pkglen = packages.getLength();
log("Indexing " + pkglen + " packages");
for (int i = pkglen - 1; i > -1; i--) {
Element pkg = (Element) packages.item(i);
String pkgname = pkg.getAttribute("name");
int nbclasses = 0;
// create a map index of all classes by their fully
// qualified name.
NodeList classes = pkg.getElementsByTagName("class");
final int classlen = classes.getLength();
log("Indexing " + classlen + " classes in package " + pkgname);
for (int j = classlen - 1; j > -1; j--) {
Element clazz = (Element) classes.item(j);
String classname = clazz.getAttribute("name");
if (pkgname != null && pkgname.length() != 0) {
classname = pkgname + "." + classname;
}
int nbmethods = 0;
NodeList methods = clazz.getElementsByTagName("method");
final int methodlen = methods.getLength();
for (int k = methodlen - 1; k > -1; k--) {
Element meth = (Element) methods.item(k);
StringBuffer methodname = new StringBuffer(meth.getAttribute("name"));
methodname.delete(methodname.toString().indexOf("("),
methodname.toString().length());
String signature = classname + "." + methodname + "()";
if (filters.accept(signature)) {
log("kept method:" + signature);
nbmethods++;
} else {
clazz.removeChild(meth);
}
}
// if we don't keep any method, we don't keep the class
if (nbmethods != 0 && classFiles.containsKey(classname)) {
log("Adding class '" + classname + "'");
classMap.put(classname, clazz);
nbclasses++;
} else {
pkg.removeChild(clazz);
}
}
if (nbclasses != 0) {
log("Adding package '" + pkgname + "'");
pkgMap.put(pkgname, pkg);
} else {
pkg.getParentNode().removeChild(pkg);
}
}
log("Indexed " + classMap.size() + " classes in " + pkgMap.size() + " packages");
}
/** create the whole new document */
public Document createDocument(String[] classPath) throws Exception {
// Iterate over the classpath to identify reference classes
classFiles = new Hashtable();
ClassPathLoader cpl = new ClassPathLoader(classPath);
Enumeration e = cpl.loaders();
while (e.hasMoreElements()) {
ClassPathLoader.FileLoader fl = (ClassPathLoader.FileLoader) e.nextElement();
ClassFile[] classes = fl.getClasses();
log("Processing " + classes.length + " classes in " + fl.getFile());
// process all classes
for (int i = 0; i < classes.length; i++) {
classFiles.put(classes[i].getFullName(), classes[i]);
}
}
// Load the JProbe coverage XML report
DocumentBuilder dbuilder = newBuilder();
InputSource is = new InputSource(new FileInputStream(file));
if (jprobeHome != null) {
File dtdDir = new File(jprobeHome, "dtd");
is.setSystemId("file:///" + dtdDir.getAbsolutePath() + "/");
}
report = dbuilder.parse(is);
report.normalize();
// create maps for faster node access (also filters out unwanted nodes)
createNodeMaps();
// Make sure each class from the reference path ends up in the report
Enumeration classes = classFiles.elements();
while (classes.hasMoreElements()) {
ClassFile cf = (ClassFile) classes.nextElement();
serializeClass(cf);
}
// update the document with the stats
update();
return report;
}
/**
* JProbe does not put the java.lang prefix for classes
* in this package, so used this nice method so that
* I have the same signature for methods
*/
protected String getMethodSignature(MethodInfo method) {
StringBuffer buf = new StringBuffer(method.getName());
buf.append("(");
String[] params = method.getParametersType();
for (int i = 0; i < params.length; i++) {
String type = params[i];
int pos = type.lastIndexOf('.');
if (pos != -1) {
String pkg = type.substring(0, pos);
if ("java.lang".equals(pkg)) {
params[i] = type.substring(pos + 1);
}
}
buf.append(params[i]);
if (i != params.length - 1) {
buf.append(", ");
}
}
buf.append(")");
return buf.toString();
}
/**
* Convert to a CovReport-like signature - <classname>.<method>().
*/
protected String getMethodSignature(ClassFile clazz, MethodInfo method) {
StringBuffer buf = new StringBuffer(clazz.getFullName());
buf.append(".");
buf.append(method.getName());
buf.append("()");
return buf.toString();
}
/**
* Do additional work on an element to remove abstract methods that
* are reported by JProbe 3.0
*/
protected void removeAbstractMethods(ClassFile classFile, Element classNode) {
MethodInfo[] methods = classFile.getMethods();
Hashtable methodNodeList = getMethods(classNode);
// assert xmlMethods.size() == methods.length()
final int size = methods.length;
for (int i = 0; i < size; i++) {
MethodInfo method = methods[i];
String methodSig = getMethodSignature(method);
Element methodNode = (Element) methodNodeList.get(methodSig);
if (methodNode != null
&& Utils.isAbstract(method.getAccessFlags())) {
log("\tRemoving abstract method " + methodSig);
classNode.removeChild(methodNode);
}
}
}
/** create an empty method element with its cov.data values */
protected Element createMethodElement(MethodInfo method) {
String methodsig = getMethodSignature(method);
Element methodElem = report.createElement("method");
methodElem.setAttribute("name", methodsig);
// create the method cov.data element
Element methodData = report.createElement("cov.data");
methodElem.appendChild(methodData);
methodData.setAttribute("calls", "0");
methodData.setAttribute("hit_lines", "0");
methodData.setAttribute("total_lines", String.valueOf(method.getNumberOfLines()));
return methodElem;
}
/** create an empty package element with its default cov.data (0) */
protected Element createPackageElement(String pkgname) {
Element pkgElem = report.createElement("package");
pkgElem.setAttribute("name", pkgname);
// create the package cov.data element / default
// must be updated at the end of the whole process
Element pkgData = report.createElement("cov.data");
pkgElem.appendChild(pkgData);
pkgData.setAttribute("calls", "0");
pkgData.setAttribute("hit_methods", "0");
pkgData.setAttribute("total_methods", "0");
pkgData.setAttribute("hit_lines", "0");
pkgData.setAttribute("total_lines", "0");
return pkgElem;
}
/** create an empty class element with its default cov.data (0) */
protected Element createClassElement(ClassFile classFile) {
// create the class element
Element classElem = report.createElement("class");
classElem.setAttribute("name", classFile.getName());
// source file possibly does not exist in the bytecode
if (null != classFile.getSourceFile()) {
classElem.setAttribute("source", classFile.getSourceFile());
}
// create the cov.data elem
Element classData = report.createElement("cov.data");
classElem.appendChild(classData);
// create the class cov.data element
classData.setAttribute("calls", "0");
classData.setAttribute("hit_methods", "0");
classData.setAttribute("total_methods", "0");
classData.setAttribute("hit_lines", "0");
classData.setAttribute("total_lines", "0");
return classElem;
}
/** serialize a classfile into XML */
protected void serializeClass(ClassFile classFile) {
// the class already is reported so ignore it
String fullclassname = classFile.getFullName();
log("Looking for '" + fullclassname + "'");
Element clazz = (Element) classMap.get(fullclassname);
// ignore classes that are already reported, all the information is
// already there.
if (clazz != null) {
log("Ignoring " + fullclassname);
removeAbstractMethods(classFile, clazz);
return;
}
// ignore interfaces files, there is no code in there to cover.
if (Utils.isInterface(classFile.getAccess())) {
return;
}
Vector methods = getFilteredMethods(classFile);
// no need to process, there are no methods to add for this class.
if (methods.size() == 0) {
return;
}
String pkgname = classFile.getPackage();
// System.out.println("Looking for package " + pkgname);
Element pkgElem = (Element) pkgMap.get(pkgname);
if (pkgElem == null) {
pkgElem = createPackageElement(pkgname);
report.getDocumentElement().appendChild(pkgElem);
pkgMap.put(pkgname, pkgElem); // add the pkg to the map
}
// this is a brand new class, so we have to create a new node
// create the class element
Element classElem = createClassElement(classFile);
pkgElem.appendChild(classElem);
int total_lines = 0;
int total_methods = 0;
final int count = methods.size();
for (int i = 0; i < count; i++) {
// create the method element
MethodInfo method = (MethodInfo) methods.elementAt(i);
if (Utils.isAbstract(method.getAccessFlags())) {
continue; // no need to report abstract methods
}
Element methodElem = createMethodElement(method);
classElem.appendChild(methodElem);
total_lines += method.getNumberOfLines();
total_methods++;
}
// create the class cov.data element
Element classData = getCovDataChild(classElem);
classData.setAttribute("total_methods", String.valueOf(total_methods));
classData.setAttribute("total_lines", String.valueOf(total_lines));
// add itself to the node map
classMap.put(fullclassname, classElem);
}
protected Vector getFilteredMethods(ClassFile classFile) {
MethodInfo[] methodlist = classFile.getMethods();
Vector methods = new Vector(methodlist.length);
for (int i = 0; i < methodlist.length; i++) {
MethodInfo method = methodlist[i];
String signature = getMethodSignature(classFile, method);
if (filters.accept(signature)) {
methods.addElement(method);
log("keeping " + signature);
} else {
// log("discarding " + signature);
}
}
return methods;
}
/** update the count of the XML, that is accumulate the stats on
* methods, classes and package so that the numbers are valid
* according to the info that was appended to the XML.
*/
protected void update() {
int calls = 0;
int hit_methods = 0;
int total_methods = 0;
int hit_lines = 0;
int total_lines = 0;
// use the map for access, all nodes should be there
Enumeration e = pkgMap.elements();
while (e.hasMoreElements()) {
Element pkgElem = (Element) e.nextElement();
String pkgname = pkgElem.getAttribute("name");
Element[] classes = getClasses(pkgElem);
int pkg_calls = 0;
int pkg_hit_methods = 0;
int pkg_total_methods = 0;
int pkg_hit_lines = 0;
int pkg_total_lines = 0;
//System.out.println("Processing package '" + pkgname + "': "
// + classes.length + " classes");
for (int j = 0; j < classes.length; j++) {
Element clazz = classes[j];
String classname = clazz.getAttribute("name");
if (pkgname != null && pkgname.length() != 0) {
classname = pkgname + "." + classname;
}
// there's only cov.data as a child so bet on it
Element covdata = getCovDataChild(clazz);
try {
pkg_calls += Integer.parseInt(covdata.getAttribute("calls"));
pkg_hit_methods += Integer.parseInt(covdata.getAttribute("hit_methods"));
pkg_total_methods += Integer.parseInt(covdata.getAttribute("total_methods"));
pkg_hit_lines += Integer.parseInt(covdata.getAttribute("hit_lines"));
pkg_total_lines += Integer.parseInt(covdata.getAttribute("total_lines"));
} catch (NumberFormatException ex) {
log("Error parsing '" + classname + "' (" + j + "/"
+ classes.length + ") in package '" + pkgname + "'");
throw ex;
}
}
Element covdata = getCovDataChild(pkgElem);
covdata.setAttribute("calls", String.valueOf(pkg_calls));
covdata.setAttribute("hit_methods", String.valueOf(pkg_hit_methods));
covdata.setAttribute("total_methods", String.valueOf(pkg_total_methods));
covdata.setAttribute("hit_lines", String.valueOf(pkg_hit_lines));
covdata.setAttribute("total_lines", String.valueOf(pkg_total_lines));
calls += pkg_calls;
hit_methods += pkg_hit_methods;
total_methods += pkg_total_methods;
hit_lines += pkg_hit_lines;
total_lines += pkg_total_lines;
}
Element covdata = getCovDataChild(report.getDocumentElement());
covdata.setAttribute("calls", String.valueOf(calls));
covdata.setAttribute("hit_methods", String.valueOf(hit_methods));
covdata.setAttribute("total_methods", String.valueOf(total_methods));
covdata.setAttribute("hit_lines", String.valueOf(hit_lines));
covdata.setAttribute("total_lines", String.valueOf(total_lines));
}
protected Element getCovDataChild(Element parent) {
NodeList children = parent.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) child;
if ("cov.data".equals(elem.getNodeName())) {
return elem;
}
}
}
throw new NoSuchElementException("Could not find 'cov.data' "
+ "element in parent '" + parent.getNodeName() + "'");
}
protected Hashtable getMethods(Element clazz) {
Hashtable map = new Hashtable();
NodeList children = clazz.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) child;
if ("method".equals(elem.getNodeName())) {
String name = elem.getAttribute("name");
map.put(name, elem);
}
}
}
return map;
}
protected Element[] getClasses(Element pkg) {
Vector v = new Vector();
NodeList children = pkg.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) child;
if ("class".equals(elem.getNodeName())) {
v.addElement(elem);
}
}
}
Element[] elems = new Element[v.size()];
v.copyInto(elems);
return elems;
}
protected Element[] getPackages(Element snapshot) {
Vector v = new Vector();
NodeList children = snapshot.getChildNodes();
int len = children.getLength();
for (int i = 0; i < len; i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element) child;
if ("package".equals(elem.getNodeName())) {
v.addElement(elem);
}
}
}
Element[] elems = new Element[v.size()];
v.copyInto(elems);
return elems;
}
private static DocumentBuilder newBuilder() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringComments(true);
factory.setValidating(false);
return factory.newDocumentBuilder();
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public void log(String message) {
if (task == null) {
//System.out.println(message);
} else {
task.log(message, Project.MSG_DEBUG);
}
}
}
| 39.508287 | 97 | 0.582622 |
69dd7dc2131a4079782c827d5caeb904123ffc5c | 10,414 | package de.metas.printing.api.impl;
import static org.adempiere.model.InterfaceWrapperHelper.create;
import static org.adempiere.model.InterfaceWrapperHelper.delete;
import static org.adempiere.model.InterfaceWrapperHelper.getCtx;
import static org.adempiere.model.InterfaceWrapperHelper.getTrxName;
import static org.adempiere.model.InterfaceWrapperHelper.load;
import static org.adempiere.model.InterfaceWrapperHelper.newInstance;
import static org.adempiere.model.InterfaceWrapperHelper.save;
/*
* #%L
* de.metas.printing.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (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/gpl-2.0.html>.
* #L%
*/
import java.util.List;
import java.util.Properties;
import javax.print.attribute.standard.MediaSize;
import de.metas.printing.HardwarePrinterId;
import de.metas.printing.LogicalPrinterId;
import de.metas.user.UserId;
import org.adempiere.model.PlainContextAware;
import com.google.common.annotations.VisibleForTesting;
import de.metas.printing.Printing_Constants;
import de.metas.printing.api.IPrinterBL;
import de.metas.printing.api.IPrintingDAO;
import de.metas.printing.model.I_AD_Printer;
import de.metas.printing.model.I_AD_PrinterHW;
import de.metas.printing.model.I_AD_PrinterHW_Calibration;
import de.metas.printing.model.I_AD_PrinterHW_MediaSize;
import de.metas.printing.model.I_AD_PrinterHW_MediaTray;
import de.metas.printing.model.I_AD_PrinterTray_Matching;
import de.metas.printing.model.I_AD_Printer_Config;
import de.metas.printing.model.I_AD_Printer_Matching;
import de.metas.printing.model.I_AD_Printer_Tray;
import de.metas.printing.model.X_AD_PrinterHW;
import de.metas.util.Check;
import de.metas.util.Services;
import lombok.NonNull;
public class PrinterBL implements IPrinterBL
{
@Override
public boolean createConfigAndDefaultPrinterMatching(@NonNull final I_AD_PrinterHW printerHW)
{
final Properties ctx = getCtx(printerHW);
final I_AD_Printer_Config printerConfig = createPrinterConfigIfNoneExists(printerHW);
final List<I_AD_Printer> printers = Services.get(IPrintingDAO.class).retrievePrinters(ctx, printerHW.getAD_Org_ID());
if (printers.isEmpty())
{
// no logical printer defined, nothing to match
return false;
}
boolean anythingCreated = false;
for (final I_AD_Printer printer : printers)
{
// Generate default matching
final I_AD_Printer_Matching printerMatchingOrNull = createPrinterMatchingIfNoneExists(printerConfig, printer, printerHW);
anythingCreated = anythingCreated || printerMatchingOrNull != null;
}
return anythingCreated;
}
/**
* If there is not yet any printer matching for the given <code>printerHW</code>'s host key, then this method creates one.
*/
private I_AD_Printer_Config createPrinterConfigIfNoneExists(final I_AD_PrinterHW printerHW)
{
final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class);
final I_AD_Printer_Config existientPrinterConfig = printingDAO.retrievePrinterConfig(
printerHW.getHostKey(),
UserId.ofRepoIdOrNull(printerHW.getUpdatedBy()));
if (existientPrinterConfig != null)
{
return existientPrinterConfig;
}
final I_AD_Printer_Config newPrinterConfig = newInstance(I_AD_Printer_Config.class, printerHW);
newPrinterConfig.setAD_Org_ID(printerHW.getAD_Org_ID());
newPrinterConfig.setConfigHostKey(printerHW.getHostKey());
newPrinterConfig.setIsSharedPrinterConfig(false); // not shared by default
newPrinterConfig.setAD_User_PrinterMatchingConfig_ID(printerHW.getUpdatedBy());
save(newPrinterConfig);
return newPrinterConfig;
}
@VisibleForTesting
I_AD_Printer_Matching createPrinterMatchingIfNoneExists(
final I_AD_Printer_Config config,
final I_AD_Printer printer,
final I_AD_PrinterHW printerHW)
{
// first search ; if one exists *for any hostkey*, then return null
final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class);
final I_AD_Printer_Matching existentMatching = printingDAO.retrievePrinterMatchingOrNull(
null,
UserId.ofRepoIdOrNull(printerHW.getUpdatedBy()),
printer);
if (existentMatching != null)
{
return null;
}
final I_AD_Printer_Matching matching = newInstance(I_AD_Printer_Matching.class);
matching.setAD_Printer_Config(config);
matching.setAD_Org_ID(printerHW.getAD_Org_ID());
matching.setAD_Printer_ID(printer.getAD_Printer_ID());
matching.setAD_PrinterHW(printerHW);
save(matching);
return matching;
}
@Override
public boolean createDefaultTrayMatching(@NonNull final I_AD_PrinterHW_MediaTray printerTrayHW)
{
final I_AD_PrinterHW printerHW = printerTrayHW.getAD_PrinterHW();
final List<I_AD_Printer_Matching> printerMatchings = //
Services.get(IPrintingDAO.class).retrievePrinterMatchings(printerHW);
if (printerMatchings.isEmpty())
{
// no printer matching was found for printerHW => nothing to match
return false;
}
boolean anythingCreated = false;
for (final I_AD_Printer_Matching printerMatching : printerMatchings)
{
final LogicalPrinterId printerId = LogicalPrinterId.ofRepoId(printerMatching.getAD_Printer_ID());
final List<I_AD_Printer_Tray> trays = Services.get(IPrintingDAO.class).retrieveTrays(printerId);
for (final I_AD_Printer_Tray tray : trays)
{
// Create tray matching
final I_AD_PrinterTray_Matching trayMatchingOrNull = createTrayMatchingIfNoneExists(printerMatching, tray, printerTrayHW);
anythingCreated = anythingCreated || trayMatchingOrNull != null;
}
}
return anythingCreated;
}
@VisibleForTesting
I_AD_PrinterTray_Matching createTrayMatchingIfNoneExists(
final I_AD_Printer_Matching printerMatching,
final I_AD_Printer_Tray tray,
final I_AD_PrinterHW_MediaTray printerTrayHW)
{
final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class);
// first search ; if exists return null
final I_AD_PrinterTray_Matching exitentTrayMatching = printingDAO.retrievePrinterTrayMatchingOrNull(printerMatching, tray.getAD_Printer_Tray_ID());
if (exitentTrayMatching != null)
{
return null;
}
final I_AD_PrinterTray_Matching trayMatching = newInstance(I_AD_PrinterTray_Matching.class);
trayMatching.setAD_Org_ID(printerTrayHW.getAD_Org_ID());
trayMatching.setAD_Printer_Matching(printerMatching);
trayMatching.setAD_Printer_Tray(tray);
trayMatching.setAD_PrinterHW_MediaTray(printerTrayHW);
save(trayMatching);
return trayMatching;
}
@Override
public I_AD_PrinterHW_Calibration createCalibrationIfNoneExists(final I_AD_PrinterTray_Matching printerTrayMatching)
{
final Properties ctx = getCtx(printerTrayMatching);
final String trxName = getTrxName(printerTrayMatching);
final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class);
final I_AD_PrinterHW printerHW = printerTrayMatching.getAD_Printer_Matching().getAD_PrinterHW();
final I_AD_PrinterHW_MediaSize hwMediaSize = printingDAO.retrieveMediaSize(printerHW, MediaSize.ISO.A4, true);
final I_AD_PrinterHW_MediaTray hwMediaTray = printerTrayMatching.getAD_PrinterHW_MediaTray();
final I_AD_PrinterHW_Calibration existingCalibration = printingDAO.retrieveCalibration(hwMediaSize, hwMediaTray);
if (existingCalibration != null)
{
return null; // nothing to do, calibration already exists
}
final I_AD_PrinterHW_Calibration cal = create(ctx, I_AD_PrinterHW_Calibration.class, trxName);
cal.setAD_PrinterHW(printerHW);
cal.setAD_PrinterHW_MediaSize(hwMediaSize);
cal.setAD_PrinterHW_MediaTray(hwMediaTray);
cal.setMeasurementX(Printing_Constants.AD_PrinterHW_Calibration_JASPER_REF_X_MM);
cal.setMeasurementY(Printing_Constants.AD_PrinterHW_Calibration_JASPER_REF_Y_MM);
save(cal);
return cal;
}
@Override
public void updatePrinterTrayMatching(@NonNull final I_AD_Printer_Matching printerMatching)
{
final IPrintingDAO dao = Services.get(IPrintingDAO.class);
final HardwarePrinterId printerID = HardwarePrinterId.ofRepoId(printerMatching.getAD_PrinterHW_ID());
final List<I_AD_PrinterHW_MediaTray> hwTrays = dao.retrieveMediaTrays(printerID);
final List<I_AD_PrinterTray_Matching> existingPrinterTrayMatchings = dao.retrievePrinterTrayMatchings(printerMatching);
final I_AD_PrinterHW_MediaTray defaultHWTray = hwTrays.isEmpty() ? null : hwTrays.get(0);
if (defaultHWTray == null)
{
// the new HW printer has no tray
// delete existing tray matchings;
for (final I_AD_PrinterTray_Matching trayMatching : existingPrinterTrayMatchings)
{
delete(trayMatching);
}
}
else if (existingPrinterTrayMatchings.isEmpty() && defaultHWTray != null)
{
// the old HW printer didn't have a tray, but the new one does
// create a new matching for every logical tray
final LogicalPrinterId printerId = LogicalPrinterId.ofRepoId(printerMatching.getAD_Printer_ID());
for (final I_AD_Printer_Tray logicalTray : dao.retrieveTrays(printerId))
{
final I_AD_PrinterTray_Matching trayMatching = newInstance(I_AD_PrinterTray_Matching.class, printerMatching);
trayMatching.setAD_Printer_Matching(printerMatching);
trayMatching.setAD_Printer_Tray(logicalTray);
trayMatching.setAD_PrinterHW_MediaTray(defaultHWTray);
save(trayMatching);
}
}
else
{
final I_AD_Printer printer = load(printerMatching.getAD_Printer_ID(), I_AD_Printer.class);
Check.assumeNotNull(defaultHWTray, "{} has at least one tray", printer);
Check.assume(!existingPrinterTrayMatchings.isEmpty(), "{} has at least one tray matching", printerMatching);
for (final I_AD_PrinterTray_Matching trayMatching : existingPrinterTrayMatchings)
{
trayMatching.setAD_PrinterHW_MediaTray(defaultHWTray);
save(trayMatching);
}
}
}
@Override
public boolean isAttachToPrintPackagePrinter(@NonNull final I_AD_PrinterHW printerHW)
{
return X_AD_PrinterHW.OUTPUTTYPE_Attach.equals(printerHW.getOutputType());
}
}
| 36.929078 | 149 | 0.798925 |
28f5886b59f0f97ad64ac905866d4de37b730b4f | 239 | package com.flys.bible.dao.db.ifaces;
import com.flys.bible.entities.AppConfig;
import com.flys.generictools.dao.IDao.GenericDao;
public interface AppConfigDao extends GenericDao<AppConfig,Long> {
public AppConfig getAppConfig();
}
| 26.555556 | 66 | 0.799163 |
e8baacb838d64638719f032da695d8506d8f51c5 | 168 | /**
* This package tests strict builder generations
*/
@Value.Style(strictBuilder = true)
package org.immutables.fixture.strict;
import org.immutables.value.Value;
| 18.666667 | 48 | 0.767857 |
2653f6356fffca64be25c3aa65b43da3f96f89a1 | 1,057 | package model.services;
import java.util.Calendar;
import java.util.Date;
import model.entities.Contract;
import model.entities.Installment;
public class ContractService {
private OnlinePaymentService onlinePaymentService;
public ContractService (OnlinePaymentService onlinePaymentService) {
this.onlinePaymentService = onlinePaymentService;
}
public void processContract(Contract contract, int month) {
Double basicQuota = contract.getTotalValue() / month;
//basicQuota = 200
for (int i = 1; i <= month; i++) {
Double updatedQuota = basicQuota + onlinePaymentService.interest(basicQuota, i);
//updatedQuota = 202
Double fullQuota = updatedQuota + onlinePaymentService.paymentFee(updatedQuota);
// fullQuota = 206.04
Date dueDate = addMonths(contract.getDate(), i);
contract.getInstallments().add(new Installment (dueDate, fullQuota));
}
}
private Date addMonths(Date date, int N) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, N);
return cal.getTime();
}
}
| 27.815789 | 83 | 0.740776 |
a1fff842ed4e420802da425bee6efea9409a9f5d | 542 | package spoon.test.filters;
class FooLine {
void simple() {
int x = 3;
int z = 0;
System.out.println(z);
}
void loopBlock() {
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
}
void loopNoBlock() {
for(int i = 0; i < 10; i++)
System.out.println(i);
}
void ifBlock() {
if (3 < 4) {
System.out.println("if");
}
}
void ifNoBlock() {
if (3 < 4)
System.out.println("if");
}
void switchBlock() {
switch ("test") {
case "test":
break;
default:
System.out.println("switch");
}
}
}
| 12.904762 | 32 | 0.54059 |
67ef36430df962258de113098ad888442a6c0a3f | 2,663 | /*
* Copyright 2017 Nemanja Zbiljić
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zbiljic.nodez;
import com.zbiljic.nodez.utils.CompletableFutures;
import com.zbiljic.nodez.utils.DeciderSupplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.concurrent.CompletableFuture;
/**
* Base class for nodes that transforms a node value, producing a new one.
*
* @param <SourceType> source node type
* @param <R> resulting node value type
* @see Node
*/
public abstract class BaseTransformNode<SourceType, R> extends Node<R> {
private static final Logger log = LoggerFactory.getLogger(BaseTransformNode.class);
protected final Node<SourceType> node;
protected BaseTransformNode(Node<SourceType> node,
@Nullable String name,
@Nullable DeciderSupplier deciderSupplier) {
this(node, name, deciderSupplier, false, false);
}
protected BaseTransformNode(Node<SourceType> node,
@Nullable String name,
@Nullable DeciderSupplier deciderSupplier,
boolean optional,
boolean canEmitNull) {
super(name != null ? name : String.format("Transform[%s]", node.getName()),
optional,
canEmitNull,
node);
this.node = node;
setDeciderSupplier(deciderSupplier);
}
@Override
public abstract String getResponseClassName();
@Override
protected CompletableFuture<R> evaluate() throws Exception {
SourceType source = node.emit();
CompletableFuture<R> response;
try {
response = transform(source);
} catch (Exception e) {
String msg = String.format(
"TransformNode [%s] on [%s] threw an exception while transforming (%s): %s",
getName(), node.getName(), e, String.valueOf(source));
log.error(msg, e);
return CompletableFutures.exceptionallyCompletedFuture(new RuntimeException(msg, e));
}
return response;
}
protected abstract CompletableFuture<R> transform(SourceType source);
}
| 32.47561 | 91 | 0.678558 |
9be6405228b394a7ba931836d23725b64e76ef65 | 2,103 | package com.littledudu.redis.watch;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import com.littledudu.redis.watch.util.ParamKeyConvertor;
public class InfoTest {
@Before
public void setUp() throws Exception {
}
@Test
public void test() {
Map<String, String> map = new HashMap<String, String>();
String[] lines = TEST_INFO_RESPONSE.split("\r\n");
for(String line : lines) {
if(line.startsWith("#"))
continue;
int pos = line.indexOf(':');
if(pos > -1) {
String key = line.substring(0, pos);
String value = line.substring(pos + 1);
map.put(key, value);
}
}
Info info = ParamKeyConvertor.setupByParamKey(map, Info.class);
assertNotNull(info);
assertNotNull(info.getRedisVersion());
assertTrue(info.getProcessId() > 0);
assertTrue(info.getPort() > 0);
System.out.println(info);
}
private static final String TEST_INFO_RESPONSE = "# Server\r\n" +
"redis_version:2.8.5\r\n" +
"process_id:8455\r\n" +
"tcp_port:6379\r\n" +
"uptime_in_seconds:999\r\n" +
"uptime_in_days:2\r\n" +
"# Clients\r\n" +
"connected_clients:6\r\n" +
"client_longest_output_list:0\r\n" +
"client_biggest_input_buf:0\r\n" +
"blocked_clients:0\r\n" +
"# Memory\r\n" +
"used_memory:167379432\r\n" +
"used_memory_human:159.63M\r\n" +
"used_memory_rss:174428160\r\n" +
"used_memory_peak:169314336\r\n" +
"used_memory_peak_human:161.47M\r\n" +
"used_memory_lua:33792\r\n" +
"mem_fragmentation_ratio:1.04\r\n" +
"mem_allocator:jemalloc-3.2.0\r\n" +
"# Stats\r\n" +
"total_connections_received:33\r\n" +
"total_commands_processed:48\r\n" +
"instantaneous_ops_per_sec:0\r\n" +
"rejected_connections:0\r\n" +
"sync_full:0\r\n" +
"sync_partial_ok:0\r\n" +
"sync_partial_err:0\r\n" +
"expired_keys:2\r\n" +
"evicted_keys:0\r\n" +
"keyspace_hits:7\r\n" +
"keyspace_misses:5\r\n" +
"pubsub_channels:0\r\n" +
"pubsub_patterns:0\r\n" +
"latest_fork_usec:0\r\n";
}
| 26.961538 | 69 | 0.652401 |
8eebafd8b437f374b4112a56afc8f1c2d87dfc3a | 21,521 | /* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.propagation.analytical;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.hipparchus.geometry.euclidean.threed.Rotation;
import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.ode.nonstiff.DormandPrince853Integrator;
import org.hipparchus.util.FastMath;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.attitudes.AttitudeProvider;
import org.orekit.attitudes.AttitudesSequence;
import org.orekit.attitudes.CelestialBodyPointed;
import org.orekit.attitudes.LofOffset;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.errors.TimeStampedCacheException;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.frames.LOFType;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.AdditionalStateProvider;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.DateDetector;
import org.orekit.propagation.events.handlers.ContinueOnEvent;
import org.orekit.propagation.numerical.NumericalPropagator;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.DateComponents;
import org.orekit.time.TimeComponents;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.AbsolutePVCoordinates;
import org.orekit.utils.AngularDerivativesFilter;
import org.orekit.utils.Constants;
import org.orekit.utils.PVCoordinates;
import org.orekit.utils.TimeStampedPVCoordinates;
public class EphemerisTest {
private AbsoluteDate initDate;
private AbsoluteDate finalDate;
private Frame inertialFrame;
private Propagator propagator;
@Test
public void testAttitudeOverride() throws IllegalArgumentException, OrekitException {
final double positionTolerance = 1e-6;
final double velocityTolerance = 1e-5;
final double attitudeTolerance = 1e-6;
int numberOfInterals = 1440;
double deltaT = finalDate.durationFrom(initDate)/((double)numberOfInterals);
propagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
List<SpacecraftState> states = new ArrayList<SpacecraftState>(numberOfInterals + 1);
for (int j = 0; j<= numberOfInterals; j++) {
states.add(propagator.propagate(initDate.shiftedBy((j * deltaT))));
}
int numInterpolationPoints = 2;
Ephemeris ephemPropagator = new Ephemeris(states, numInterpolationPoints);
Assert.assertEquals(0, ephemPropagator.getManagedAdditionalStates().length);
//First test that we got position, velocity and attitude nailed
int numberEphemTestIntervals = 2880;
deltaT = finalDate.durationFrom(initDate)/((double)numberEphemTestIntervals);
for (int j = 0; j <= numberEphemTestIntervals; j++) {
AbsoluteDate currentDate = initDate.shiftedBy(j * deltaT);
SpacecraftState ephemState = ephemPropagator.propagate(currentDate);
SpacecraftState keplerState = propagator.propagate(currentDate);
double positionDelta = calculatePositionDelta(ephemState, keplerState);
double velocityDelta = calculateVelocityDelta(ephemState, keplerState);
double attitudeDelta = calculateAttitudeDelta(ephemState, keplerState);
Assert.assertEquals("LVLH_CCSDS Unmatched Position at: " + currentDate, 0.0, positionDelta, positionTolerance);
Assert.assertEquals("LVLH_CCSDS Unmatched Velocity at: " + currentDate, 0.0, velocityDelta, velocityTolerance);
Assert.assertEquals("LVLH_CCSDS Unmatched Attitude at: " + currentDate, 0.0, attitudeDelta, attitudeTolerance);
}
//Now force an override on the attitude and check it against a Keplerian propagator
//setup identically to the first but with a different attitude
//If override isn't working this will fail.
propagator = new KeplerianPropagator(propagator.getInitialState().getOrbit());
propagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.QSW));
ephemPropagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.QSW));
for (int j = 0; j <= numberEphemTestIntervals; j++) {
AbsoluteDate currentDate = initDate.shiftedBy(j * deltaT);
SpacecraftState ephemState = ephemPropagator.propagate(currentDate);
SpacecraftState keplerState = propagator.propagate(currentDate);
double positionDelta = calculatePositionDelta(ephemState, keplerState);
double velocityDelta = calculateVelocityDelta(ephemState, keplerState);
double attitudeDelta = calculateAttitudeDelta(ephemState, keplerState);
Assert.assertEquals("QSW Unmatched Position at: " + currentDate, 0.0, positionDelta, positionTolerance);
Assert.assertEquals("QSW Unmatched Velocity at: " + currentDate, 0.0, velocityDelta, velocityTolerance);
Assert.assertEquals("QSW Unmatched Attitude at: " + currentDate, 0.0, attitudeDelta, attitudeTolerance);
}
}
@Test
public void testAttitudeSequenceTransition() {
// Initialize the orbit
final AbsoluteDate initialDate = new AbsoluteDate(2003, 01, 01, 0, 0, 00.000, TimeScalesFactory.getUTC());
final Vector3D position = new Vector3D(-39098981.4866597, -15784239.3610601, 78908.2289853595);
final Vector3D velocity = new Vector3D(1151.00321021175, -2851.14864755189, -2.02133248357321);
final Orbit initialOrbit = new KeplerianOrbit(new PVCoordinates(position, velocity),
FramesFactory.getGCRF(), initialDate,
Constants.WGS84_EARTH_MU);
final SpacecraftState initialState = new SpacecraftState(initialOrbit);
// Define attitude laws
AttitudeProvider before = new CelestialBodyPointed(FramesFactory.getICRF(), CelestialBodyFactory.getSun(), Vector3D.PLUS_K, Vector3D.PLUS_I, Vector3D.PLUS_K);
AttitudeProvider after = new CelestialBodyPointed(FramesFactory.getICRF(), CelestialBodyFactory.getEarth(), Vector3D.PLUS_K, Vector3D.PLUS_I, Vector3D.PLUS_K);
// Define attitude sequence
AbsoluteDate switchDate = initialDate.shiftedBy(86400.0);
double transitionTime = 600;
DateDetector switchDetector = new DateDetector(switchDate).withHandler(new ContinueOnEvent<DateDetector>());
AttitudesSequence attitudeSequence = new AttitudesSequence();
attitudeSequence.resetActiveProvider(before);
attitudeSequence.addSwitchingCondition(before, after, switchDetector, true, false, transitionTime, AngularDerivativesFilter.USE_RR, null);
NumericalPropagator propagator = new NumericalPropagator(new DormandPrince853Integrator(0.1, 500, 1e-9, 1e-9));
propagator.setInitialState(initialState);
// Propagate and build ephemeris
final List<SpacecraftState> propagatedStates = new ArrayList<>();
propagator.setStepHandler(60, currentState -> propagatedStates.add(currentState));
propagator.propagate(initialDate.shiftedBy(2*86400.0));
final Ephemeris ephemeris = new Ephemeris(propagatedStates, 8);
// Add attitude switch event to ephemeris
ephemeris.setAttitudeProvider(attitudeSequence);
attitudeSequence.registerSwitchEvents(ephemeris);
// Propagate with a step during the transition
AbsoluteDate endDate = initialDate.shiftedBy(2*86400.0);
SpacecraftState stateBefore = ephemeris.getInitialState();
ephemeris.propagate(switchDate.shiftedBy(transitionTime/2));
SpacecraftState stateAfter = ephemeris.propagate(endDate);
// Check that the attitudes are correct
Assert.assertEquals(before.getAttitude(stateBefore.getOrbit(), stateBefore.getDate(), stateBefore.getFrame()).getRotation().getQ0(),
stateBefore.getAttitude().getRotation().getQ0(),
1.0E-16);
Assert.assertEquals(before.getAttitude(stateBefore.getOrbit(), stateBefore.getDate(), stateBefore.getFrame()).getRotation().getQ1(),
stateBefore.getAttitude().getRotation().getQ1(),
1.0E-16);
Assert.assertEquals(before.getAttitude(stateBefore.getOrbit(), stateBefore.getDate(), stateBefore.getFrame()).getRotation().getQ2(),
stateBefore.getAttitude().getRotation().getQ2(),
1.0E-16);
Assert.assertEquals(before.getAttitude(stateBefore.getOrbit(), stateBefore.getDate(), stateBefore.getFrame()).getRotation().getQ3(),
stateBefore.getAttitude().getRotation().getQ3(),
1.0E-16);
Assert.assertEquals(after.getAttitude(stateAfter.getOrbit(), stateAfter.getDate(), stateAfter.getFrame()).getRotation().getQ0(),
stateAfter.getAttitude().getRotation().getQ0(),
1.0E-16);
Assert.assertEquals(after.getAttitude(stateAfter.getOrbit(), stateAfter.getDate(), stateAfter.getFrame()).getRotation().getQ1(),
stateAfter.getAttitude().getRotation().getQ1(),
1.0E-16);
Assert.assertEquals(after.getAttitude(stateAfter.getOrbit(), stateAfter.getDate(), stateAfter.getFrame()).getRotation().getQ2(),
stateAfter.getAttitude().getRotation().getQ2(),
1.0E-16);
Assert.assertEquals(after.getAttitude(stateAfter.getOrbit(), stateAfter.getDate(), stateAfter.getFrame()).getRotation().getQ3(),
stateAfter.getAttitude().getRotation().getQ3(),
1.0E-16);
}
@Test
public void testNonResettableState() {
try {
propagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
List<SpacecraftState> states = new ArrayList<SpacecraftState>();
for (double dt = 0; dt >= -1200; dt -= 60.0) {
states.add(propagator.propagate(initDate.shiftedBy(dt)));
}
new Ephemeris(states, 2).resetInitialState(propagator.getInitialState());
Assert.fail("an exception should have been thrown");
} catch (OrekitException oe) {
Assert.assertEquals(OrekitMessages.NON_RESETABLE_STATE, oe.getSpecifier());
}
}
@Test
public void testAdditionalStates() {
final String name1 = "dt0";
final String name2 = "dt1";
propagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
List<SpacecraftState> states = new ArrayList<SpacecraftState>();
for (double dt = 0; dt >= -1200; dt -= 60.0) {
final SpacecraftState original = propagator.propagate(initDate.shiftedBy(dt));
final SpacecraftState expanded = original.addAdditionalState(name2, original.getDate().durationFrom(finalDate));
states.add(expanded);
}
final Propagator ephem = new Ephemeris(states, 2);
ephem.addAdditionalStateProvider(new AdditionalStateProvider() {
public String getName() {
return name1;
}
public double[] getAdditionalState(SpacecraftState state) {
return new double[] { state.getDate().durationFrom(initDate) };
}
});
final String[] additional = ephem.getManagedAdditionalStates();
Arrays.sort(additional);
Assert.assertEquals(2, additional.length);
Assert.assertEquals(name1, ephem.getManagedAdditionalStates()[0]);
Assert.assertEquals(name2, ephem.getManagedAdditionalStates()[1]);
Assert.assertTrue(ephem.isAdditionalStateManaged(name1));
Assert.assertTrue(ephem.isAdditionalStateManaged(name2));
Assert.assertFalse(ephem.isAdditionalStateManaged("not managed"));
SpacecraftState s = ephem.propagate(initDate.shiftedBy(-270.0));
Assert.assertEquals(-270.0, s.getAdditionalState(name1)[0], 1.0e-15);
Assert.assertEquals(-86670.0, s.getAdditionalState(name2)[0], 1.0e-15);
}
@Test
public void testProtectedMethods()
throws SecurityException, NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
propagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
List<SpacecraftState> states = new ArrayList<SpacecraftState>();
for (double dt = 0; dt >= -1200; dt -= 60.0) {
final SpacecraftState original = propagator.propagate(initDate.shiftedBy(dt));
final SpacecraftState modified = new SpacecraftState(original.getOrbit(),
original.getAttitude(),
original.getMass() - 0.0625 * dt);
states.add(modified);
}
final Propagator ephem = new Ephemeris(states, 2);
Method propagateOrbit = Ephemeris.class.getDeclaredMethod("propagateOrbit", AbsoluteDate.class);
propagateOrbit.setAccessible(true);
Method getMass = Ephemeris.class.getDeclaredMethod("getMass", AbsoluteDate.class);
getMass.setAccessible(true);
SpacecraftState s = ephem.propagate(initDate.shiftedBy(-270.0));
Orbit o = (Orbit) propagateOrbit.invoke(ephem, s.getDate());
double m = ((Double) getMass.invoke(ephem, s.getDate())).doubleValue();
Assert.assertEquals(0.0,
Vector3D.distance(s.getPVCoordinates().getPosition(),
o.getPVCoordinates().getPosition()),
1.0e-15);
Assert.assertEquals(s.getMass(), m, 1.0e-15);
}
@Test
public void testExtrapolation() {
double dt = finalDate.durationFrom(initDate);
double timeStep = dt / 20.0;
List<SpacecraftState> states = new ArrayList<SpacecraftState>();
for(double t = 0 ; t <= dt; t+=timeStep) {
states.add(propagator.propagate(initDate.shiftedBy(t)));
}
final int interpolationPoints = 5;
Ephemeris ephemeris = new Ephemeris(states, interpolationPoints);
Assert.assertEquals(finalDate, ephemeris.getMaxDate());
double tolerance = ephemeris.getExtrapolationThreshold();
ephemeris.propagate(ephemeris.getMinDate());
ephemeris.propagate(ephemeris.getMaxDate());
ephemeris.propagate(ephemeris.getMinDate().shiftedBy(-tolerance / 2.0));
ephemeris.propagate(ephemeris.getMaxDate().shiftedBy(tolerance / 2.0));
try {
ephemeris.propagate(ephemeris.getMinDate().shiftedBy(-2.0 * tolerance));
Assert.fail("an exception should have been thrown");
} catch (TimeStampedCacheException e) {
//supposed to fail since out of bounds
}
try {
ephemeris.propagate(ephemeris.getMaxDate().shiftedBy(2.0 * tolerance));
Assert.fail("an exception should have been thrown");
} catch (TimeStampedCacheException e) {
//supposed to fail since out of bounds
}
}
@Test
public void testIssue662() {
// Input parameters
int numberOfInterals = 1440;
double deltaT = finalDate.durationFrom(initDate)/((double)numberOfInterals);
// Build the list of spacecraft states
String additionalName = "testValue";
double additionalValue = 1.0;
List<SpacecraftState> states = new ArrayList<SpacecraftState>(numberOfInterals + 1);
for (int j = 0; j<= numberOfInterals; j++) {
states.add(propagator.propagate(initDate.shiftedBy((j * deltaT))).addAdditionalState(additionalName, additionalValue));
}
// Build the epemeris propagator
Ephemeris ephemPropagator = new Ephemeris(states, 2);
// State before adding an attitude provider
SpacecraftState stateBefore = ephemPropagator.propagate(ephemPropagator.getMaxDate().shiftedBy(-60.0));
Assert.assertEquals(1, stateBefore.getAdditionalState(additionalName).length);
Assert.assertEquals(additionalValue, stateBefore.getAdditionalState(additionalName)[0], Double.MIN_VALUE);
// Set an attitude provider
ephemPropagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
// State after adding an attitude provider
SpacecraftState stateAfter = ephemPropagator.propagate(ephemPropagator.getMaxDate().shiftedBy(-60.0));
Assert.assertEquals(1, stateAfter.getAdditionalState(additionalName).length);
Assert.assertEquals(additionalValue, stateAfter.getAdditionalState(additionalName)[0], Double.MIN_VALUE);
}
@Test
public void testIssue680() {
// Initial PV coordinates
AbsolutePVCoordinates initPV = new AbsolutePVCoordinates(inertialFrame,
new TimeStampedPVCoordinates(initDate,
new PVCoordinates(new Vector3D(-29536113.0, 30329259.0, -100125.0),
new Vector3D(-2194.0, -2141.0, -8.0))));
// Input parameters
int numberOfInterals = 1440;
double deltaT = finalDate.durationFrom(initDate)/((double)numberOfInterals);
// Build the list of spacecraft states
List<SpacecraftState> states = new ArrayList<SpacecraftState>(numberOfInterals + 1);
for (int j = 0; j<= numberOfInterals; j++) {
states.add(new SpacecraftState(initPV).shiftedBy(j * deltaT));
}
// Build the epemeris propagator
Ephemeris ephemPropagator = new Ephemeris(states, 2);
// Get initial state without attitude provider
SpacecraftState withoutAttitudeProvider = ephemPropagator.getInitialState();
Assert.assertEquals(0.0, Vector3D.distance(withoutAttitudeProvider.getAbsPVA().getPosition(), initPV.getPosition()), 1.0e-10);
Assert.assertEquals(0.0, Vector3D.distance(withoutAttitudeProvider.getAbsPVA().getVelocity(), initPV.getVelocity()), 1.0e-10);
// Set an attitude provider
ephemPropagator.setAttitudeProvider(new LofOffset(inertialFrame, LOFType.LVLH_CCSDS));
// Get initial state with attitude provider
SpacecraftState withAttitudeProvider = ephemPropagator.getInitialState();
Assert.assertEquals(0.0, Vector3D.distance(withAttitudeProvider.getAbsPVA().getPosition(), initPV.getPosition()), 1.0e-10);
Assert.assertEquals(0.0, Vector3D.distance(withAttitudeProvider.getAbsPVA().getVelocity(), initPV.getVelocity()), 1.0e-10);
}
@Before
public void setUp() throws IllegalArgumentException, OrekitException {
Utils.setDataRoot("regular-data");
initDate = new AbsoluteDate(new DateComponents(2004, 01, 01),
TimeComponents.H00,
TimeScalesFactory.getUTC());
finalDate = new AbsoluteDate(new DateComponents(2004, 01, 02),
TimeComponents.H00,
TimeScalesFactory.getUTC());
double a = 7187990.1979844316;
double e = 0.5e-4;
double i = 1.7105407051081795;
double omega = 1.9674147913622104;
double OMEGA = FastMath.toRadians(261);
double lv = 0;
double mu = 3.9860047e14;
inertialFrame = FramesFactory.getEME2000();
Orbit initialState = new KeplerianOrbit(a, e, i, omega, OMEGA, lv, PositionAngle.TRUE,
inertialFrame, initDate, mu);
propagator = new KeplerianPropagator(initialState);
}
private double calculatePositionDelta(SpacecraftState state1, SpacecraftState state2) {
return Vector3D.distance(state1.getPVCoordinates().getPosition(), state2.getPVCoordinates().getPosition());
}
private double calculateVelocityDelta(SpacecraftState state1, SpacecraftState state2) {
return Vector3D.distance(state1.getPVCoordinates().getVelocity(), state2.getPVCoordinates().getVelocity());
}
private double calculateAttitudeDelta(SpacecraftState state1, SpacecraftState state2) {
return Rotation.distance(state1.getAttitude().getRotation(), state2.getAttitude().getRotation());
}
}
| 49.81713 | 167 | 0.68324 |
2e41bf6a853b04b66d18642439d1544dda900929 | 4,370 | package com.daviancorp.android.ui.detail;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.daviancorp.android.data.classes.ItemToSkillTree;
import com.daviancorp.android.data.database.ItemToSkillTreeCursor;
import com.daviancorp.android.loader.ItemToSkillTreeListCursorLoader;
import com.daviancorp.android.monsterhunter3udatabase.R;
public class ItemToSkillFragment extends ListFragment implements
LoaderCallbacks<Cursor> {
private static final String ARG_ITEM_TO_SKILL_ID = "ITEM_TO_SKILL_ID";
private static final String ARG_ITEM_TO_SKILL_FROM = "ITEM_TO_SKILL_FROM";
public static ItemToSkillFragment newInstance(long id, String from) {
Bundle args = new Bundle();
args.putLong(ARG_ITEM_TO_SKILL_ID, id);
args.putString(ARG_ITEM_TO_SKILL_FROM, from);
ItemToSkillFragment f = new ItemToSkillFragment();
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize the loader to load the list of runs
getLoaderManager().initLoader(R.id.item_to_skill_fragment, getArguments(), this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_decoration_skill_list, null);
return v;
}
@SuppressLint("NewApi")
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// You only ever load the runs, so assume this is the case
long mId = args.getLong(ARG_ITEM_TO_SKILL_ID, -1);
String mFrom = args.getString(ARG_ITEM_TO_SKILL_FROM);
return new ItemToSkillTreeListCursorLoader(getActivity(),
ItemToSkillTreeListCursorLoader.FROM_ITEM, mId, mFrom);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
// Create an adapter to point at this cursor
ItemToSkillTreeListCursorAdapter adapter = new ItemToSkillTreeListCursorAdapter(
getActivity(), (ItemToSkillTreeCursor) cursor);
setListAdapter(adapter);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
// Stop using the cursor (via the adapter)
setListAdapter(null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// The id argument will be the Monster ID; CursorAdapter gives us this
// for free
Intent i = new Intent(getActivity(), SkillTreeDetailActivity.class);
i.putExtra(SkillTreeDetailActivity.EXTRA_SKILLTREE_ID, (long) v.getTag());
startActivity(i);
}
private static class ItemToSkillTreeListCursorAdapter extends CursorAdapter {
private ItemToSkillTreeCursor mItemToSkillTreeCursor;
public ItemToSkillTreeListCursorAdapter(Context context,
ItemToSkillTreeCursor cursor) {
super(context, cursor, 0);
mItemToSkillTreeCursor = cursor;
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Use a layout inflater to get a row view
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return inflater.inflate(R.layout.fragment_decoration_skill,
parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// Get the item for the current row
ItemToSkillTree itemToSkillTree = mItemToSkillTreeCursor
.getItemToSkillTree();
// Set up the text view
LinearLayout itemLayout = (LinearLayout) view
.findViewById(R.id.listitem);
TextView skillTextView = (TextView) view
.findViewById(R.id.skill);
TextView pointTextView = (TextView) view
.findViewById(R.id.point);
String cellSkill = itemToSkillTree.getSkillTree().getName();
String cellPoints = "" + itemToSkillTree.getPoints();
skillTextView.setText(cellSkill);
pointTextView.setText(cellPoints);
itemLayout.setTag(itemToSkillTree.getSkillTree().getId());
}
}
}
| 33.106061 | 83 | 0.779176 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.