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
|
---|---|---|---|---|---|
6e1127d3bfabadad28a16fca73ef27ad206236a8 | 3,231 | package cn.edu.xmut.izhihu.pojo.entity;
import javax.persistence.*;
import java.util.Date;
@Table(name = "private_message")
public class PrivateMessage {
/**
* 私信Id
*/
@Id
@Column(name = "priv_mess_id")
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SELECT LAST_INSERT_ID()")
private String privMessId;
/**
* 接收私信用户Id
*/
@Column(name = "takeIn_user_id")
private String takeinUserId;
/**
* 发送私信用户Id
*/
@Column(name = "send_user_id")
private String sendUserId;
/**
* 发送时间
*/
@Column(name = "create_time")
private Date createTime;
/**
* 是否已读(0未读1已读)
*/
private Integer readed;
/**
* 是否已删除(1删除0未删除)
*/
private Integer del;
/**
* 私信内容
*/
@Column(name = "priv_mess_content")
private String privMessContent;
/**
* 获取私信Id
*
* @return priv_mess_id - 私信Id
*/
public String getPrivMessId() {
return privMessId;
}
/**
* 设置私信Id
*
* @param privMessId 私信Id
*/
public void setPrivMessId(String privMessId) {
this.privMessId = privMessId == null ? null : privMessId.trim();
}
/**
* 获取接收私信用户Id
*
* @return takeIn_user_id - 接收私信用户Id
*/
public String getTakeinUserId() {
return takeinUserId;
}
/**
* 设置接收私信用户Id
*
* @param takeinUserId 接收私信用户Id
*/
public void setTakeinUserId(String takeinUserId) {
this.takeinUserId = takeinUserId == null ? null : takeinUserId.trim();
}
/**
* 获取发送私信用户Id
*
* @return send_user_id - 发送私信用户Id
*/
public String getSendUserId() {
return sendUserId;
}
/**
* 设置发送私信用户Id
*
* @param sendUserId 发送私信用户Id
*/
public void setSendUserId(String sendUserId) {
this.sendUserId = sendUserId == null ? null : sendUserId.trim();
}
/**
* 获取发送时间
*
* @return create_time - 发送时间
*/
public Date getCreateTime() {
return createTime;
}
/**
* 设置发送时间
*
* @param createTime 发送时间
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/**
* 获取是否已读(0未读1已读)
*
* @return readed - 是否已读(0未读1已读)
*/
public Integer getReaded() {
return readed;
}
/**
* 设置是否已读(0未读1已读)
*
* @param readed 是否已读(0未读1已读)
*/
public void setReaded(Integer readed) {
this.readed = readed;
}
/**
* 获取是否已删除(1删除0未删除)
*
* @return del - 是否已删除(1删除0未删除)
*/
public Integer getDel() {
return del;
}
/**
* 设置是否已删除(1删除0未删除)
*
* @param del 是否已删除(1删除0未删除)
*/
public void setDel(Integer del) {
this.del = del;
}
/**
* 获取私信内容
*
* @return priv_mess_content - 私信内容
*/
public String getPrivMessContent() {
return privMessContent;
}
/**
* 设置私信内容
*
* @param privMessContent 私信内容
*/
public void setPrivMessContent(String privMessContent) {
this.privMessContent = privMessContent == null ? null : privMessContent.trim();
}
} | 18.462857 | 94 | 0.545961 |
07ae9d2221f664e9ba5fb05f65c12faec5b9dfca | 174 | package ru.javawebinar.basejava.storage;
public class ListStorageTest extends AbstractStorageTest {
public ListStorageTest() {
super(new ListStorage());
}
} | 21.75 | 58 | 0.729885 |
5301ea97fbcf1a8739888d766016cce854b55bb9 | 2,507 | /*
* JBoss, Home of Professional Open Source
*
* Copyright 2013 Red Hat, Inc. and/or its affiliates.
*
* 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.picketlink.idm.spi;
import org.picketlink.idm.IdGenerator;
import org.picketlink.idm.event.EventBridge;
import org.picketlink.idm.model.Partition;
import org.picketlink.idm.permission.acl.spi.PermissionHandlerPolicy;
/**
* Stores security related state for one or more identity management operations
*
* @author Shane Bryzak
*
*/
public interface IdentityContext {
/**
* <p>Name of the context parameter that provides a reference to an authenticated account. Useful if the identity store
* needs a reference to the authenticated account performing a specific operation.</p>
*/
String AUTHENTICATED_ACCOUNT = "AUTHENTICATED_ACCOUNT";
/**
* <p>Name of the context parameter that provides a reference to the credentials associated with the invocation context for a
* specific operation.</p>
*/
String CREDENTIALS = "CREDENTIALS";
/**
* Returns the parameter value with the specified name
*
* @return
*/
<P> P getParameter(String paramName);
/**
* Returns a boolean indicating whether the parameter with the specified name has been set
*
* @param paramName
* @return
*/
boolean isParameterSet(String paramName);
/**
* Sets a parameter value
*
* @param paramName
* @param value
*/
void setParameter(String paramName, Object value);
/**
*
* @return
*/
EventBridge getEventBridge();
/**
*
* @return
*/
IdGenerator getIdGenerator();
/**
* Return the active Partition for this context
*
* @return
*/
Partition getPartition();
/**
* Return the permission handler policy (used for permission related operations)
*
* @return
*/
PermissionHandlerPolicy getPermissionHandlerPolicy();
} | 26.956989 | 129 | 0.677702 |
5c6c97aaddc43cadc074660038caa927f1b4f19a | 3,442 | package qkbc.distribution;
import umontreal.ssj.probdist.ContinuousDistribution;
import util.Pair;
import java.util.Arrays;
import java.util.Comparator;
public class IntegralDistributionApproximator {
public static final int INTEGRAL_N_BINS = 1 << 16;
public static final double INVERSE_F_IGNORE_THRESHOLD = 1e-4;
public static final int MIDPOINT_RULE = 0, TRAPEZOID_RULE = 1, SIMPSON_RULE = 2;
private double[] binX, binDensity, binVolume;
private double binWidth;
private double[] cdf, pValue;
public IntegralDistributionApproximator(ContinuousDistribution d) {
this(d, MIDPOINT_RULE);
}
public IntegralDistributionApproximator(ContinuousDistribution d, int ruleCode) {
binX = new double[INTEGRAL_N_BINS];
binDensity = new double[INTEGRAL_N_BINS];
binVolume = new double[INTEGRAL_N_BINS];
double start = d.inverseF(INVERSE_F_IGNORE_THRESHOLD), end = d.inverseF(1 - INVERSE_F_IGNORE_THRESHOLD);
binWidth = (end - start) / INTEGRAL_N_BINS;
// Init density
for (int i = 0; i < INTEGRAL_N_BINS; ++i) {
binX[i] = start + binWidth * (i + 0.5);
binDensity[i] = d.density(binX[i]);
if (ruleCode == MIDPOINT_RULE) {
binVolume[i] = binDensity[i] * binWidth;
} else if (ruleCode == TRAPEZOID_RULE) {
binVolume[i] = (d.density(binX[i] - binWidth * 0.5) + d.density(binX[i] + binWidth * 0.5)) * binWidth / 2;
} else if (ruleCode == SIMPSON_RULE) {
binVolume[i] = (d.density(binX[i] - binWidth * 0.5) + 4 * d.density(binX[i]) + d.density(binX[i] + binWidth * 0.5)) * binWidth / 6;
} else {
throw new RuntimeException("Unknown rule code");
}
}
// Init cdf
cdf = new double[INTEGRAL_N_BINS];
for (int i = 0; i < INTEGRAL_N_BINS; ++i) {
cdf[i] = binVolume[i];
if (i > 0) {
cdf[i] += cdf[i - 1];
}
}
// init pValue
pValue = new double[INTEGRAL_N_BINS];
Pair<Integer, Double>[] pos = new Pair[INTEGRAL_N_BINS];
for (int i = 0; i < INTEGRAL_N_BINS; ++i) {
pos[i] = new Pair<>(i, binDensity[i]);
}
Arrays.sort(pos, Comparator.comparing(o -> o.second));
for (int i = 0; i < INTEGRAL_N_BINS; ++i) {
pValue[pos[i].first] = binVolume[pos[i].first];
if (i > 0) {
pValue[pos[i].first] += pValue[pos[i - 1].first];
}
}
}
private int getBin(double v) {
int l = -1, r = INTEGRAL_N_BINS;
while (l + 1 < r) {
int mid = (l + r) >> 1;
if (binX[mid] <= v) {
l = mid;
} else {
r = mid;
}
}
if (l == -1) {
return v >= binX[0] - binWidth * 0.5 ? 0 : -1;
}
return (v <= binX[l] + binWidth * 0.5) ? l : l + 1;
}
public double getEstimatedCdf(double v) {
int bin = getBin(v);
if (bin == -1) {
return 0;
}
if (bin == INTEGRAL_N_BINS) {
return 1;
}
return cdf[bin];
}
public double getEstimatedPValue(double v) {
int bin = getBin(v);
if (bin == -1 || bin == INTEGRAL_N_BINS) {
return 0;
}
return pValue[bin];
}
}
| 31.577982 | 147 | 0.528472 |
ffdb055ada67a0170438d0d94d722b4e2f5c252e | 5,046 | package org.apereo.cas.oidc.services;
import org.apereo.cas.oidc.AbstractOidcTests;
import org.apereo.cas.services.OidcRegisteredService;
import org.apereo.cas.services.PartialRegexRegisteredServiceMatchingStrategy;
import org.apereo.cas.services.RegexRegisteredService;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.services.ServicesManagerRegisteredServiceLocator;
import org.apereo.cas.support.oauth.OAuth20Constants;
import org.apereo.cas.util.CollectionUtils;
import lombok.val;
import org.apache.http.client.utils.URIBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.Ordered;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is {@link OidcServicesManagerRegisteredServiceLocatorTests}.
*
* @author Misagh Moayyed
* @since 6.3.0
*/
@Tag("OIDC")
public class OidcServicesManagerRegisteredServiceLocatorTests extends AbstractOidcTests {
@Autowired
@Qualifier("oidcServicesManagerRegisteredServiceLocator")
private ServicesManagerRegisteredServiceLocator oidcServicesManagerRegisteredServiceLocator;
@BeforeEach
public void setup() {
servicesManager.deleteAll();
}
@Test
public void verifyWithCallback() throws Exception {
val callbackUrl = "http://localhost:8443/cas"
+ OAuth20Constants.BASE_OAUTH20_URL + '/' + OAuth20Constants.CALLBACK_AUTHORIZE_URL;
val service0 = RegisteredServiceTestUtils.getRegisteredService(callbackUrl + ".*");
service0.setEvaluationOrder(0);
val service1 = getOidcRegisteredService("application1");
service1.setEvaluationOrder(100);
val service2 = getOidcRegisteredService("application-catch-all", ".*");
service2.setEvaluationOrder(1000);
val candidateServices = CollectionUtils.wrapList(service0, service1, service2);
servicesManager.save(candidateServices.toArray(new RegisteredService[0]));
Collections.sort(candidateServices);
val url = new URIBuilder(callbackUrl + '?' + OAuth20Constants.CLIENT_ID + "=application1");
val request = new MockHttpServletRequest();
request.setRequestURI(callbackUrl);
url.getQueryParams().forEach(param -> request.addParameter(param.getName(), param.getValue()));
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, new MockHttpServletResponse()));
val service = webApplicationServiceFactory.createService(url.toString());
val result = servicesManager.findServiceBy(service);
assertEquals(result, service1);
}
@Test
public void verifyOperation() {
assertNotNull(oidcServicesManagerRegisteredServiceLocator);
assertEquals(OidcServicesManagerRegisteredServiceLocator.DEFAULT_ORDER, oidcServicesManagerRegisteredServiceLocator.getOrder());
val clientId = UUID.randomUUID().toString();
val service = getOidcRegisteredService(clientId);
service.setMatchingStrategy(new PartialRegexRegisteredServiceMatchingStrategy());
val svc = webApplicationServiceFactory.createService(
String.format("https://oauth.example.org/whatever?%s=%s", OAuth20Constants.CLIENT_ID, clientId));
val result = oidcServicesManagerRegisteredServiceLocator.locate(List.of(service), svc);
assertNotNull(result);
}
@Test
public void verifyReverseOperation() {
val service1 = RegisteredServiceTestUtils.getRegisteredService(".+");
service1.setEvaluationOrder(5);
val oidcClientId = UUID.randomUUID().toString();
val service2 = getOidcRegisteredService(oidcClientId, ".+", false, false);
service2.setEvaluationOrder(10);
val oauthClientId = UUID.randomUUID().toString();
val service3 = getOAuthRegisteredService(oauthClientId, ".+");
service3.setEvaluationOrder(15);
servicesManager.save(service1, service2, service3);
var svc = webApplicationServiceFactory.createService(
String.format("https://app.example.org/whatever?%s=clientid", OAuth20Constants.CLIENT_ID));
var result = servicesManager.findServiceBy(svc);
assertTrue(result instanceof OidcRegisteredService);
svc = webApplicationServiceFactory.createService("https://app.example.org/whatever?hello=world");
result = servicesManager.findServiceBy(svc);
assertTrue(result instanceof RegexRegisteredService);
}
}
| 42.762712 | 136 | 0.757432 |
9c63222d6ef7b4ed83fc0b85de18c27c75e6f49a | 7,668 | package com.miemie.naming;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class NamingProvider extends ContentProvider {
private static final String TAG = NamingProvider.class.getSimpleName();
private SQLiteOpenHelper mOpenHelper;
private static final int CHARS = 1;
private static final int CHARS_ID = 2;
private static final int PINYINS = 3;
private static final int PINYINS_ID = 4;
private static final UriMatcher sURLMatcher = new UriMatcher(UriMatcher.NO_MATCH);
private static final String TABLE_NAME1 = "characters";
private static final String TABLE_NAME2 = "pinyin";
/**
* The content:// style URL for this table
*/
public static final Uri CONTENT_URI1 = Uri.parse("content://com.miemie.naming/" + TABLE_NAME1);
public static final Uri CONTENT_URI2 = Uri.parse("content://com.miemie.naming/" + TABLE_NAME2);
static {
sURLMatcher.addURI("com.miemie.naming", "characters", CHARS);
sURLMatcher.addURI("com.miemie.naming", "characters/#", CHARS_ID);
sURLMatcher.addURI("com.miemie.naming", "pinyin", PINYINS);
sURLMatcher.addURI("com.miemie.naming", "pinyin/#", PINYINS_ID);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pinyin.db";
private static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE characters (" + "_id INTEGER PRIMARY KEY," + "hanzi TEXT, "
+ "unicode INTEGER, " + "strokes INTEGER, " + "pinyin TEXT, " + "mostused INTEGER," + "tone INTEGER);");
db.execSQL("CREATE TABLE pinyin (" + "_id INTEGER PRIMARY KEY, " + "pinyin TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME2);
onCreate(db);
}
}
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
// Generate the body of the query
int match = sURLMatcher.match(uri);
switch (match) {
case CHARS:
qb.setTables(TABLE_NAME1);
break;
case CHARS_ID:
qb.setTables(TABLE_NAME1);
qb.appendWhere("_id=");
qb.appendWhere(uri.getPathSegments().get(1));
break;
case PINYINS:
qb.setTables(TABLE_NAME2);
break;
case PINYINS_ID:
qb.setTables(TABLE_NAME2);
qb.appendWhere("_id=");
qb.appendWhere(uri.getPathSegments().get(1));
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
SQLiteDatabase db = mOpenHelper.getReadableDatabase();
Cursor ret = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);
if (ret == null) {
Log.e(TAG, "query: failed");
} else {
ret.setNotificationUri(getContext().getContentResolver(), uri);
}
return ret;
}
@Override
public String getType(Uri uri) {
int match = sURLMatcher.match(uri);
switch (match) {
case CHARS:
return "vnd.android.cursor.dir/" + TABLE_NAME1;
case CHARS_ID:
return "vnd.android.cursor.item/" + TABLE_NAME1;
case PINYINS:
return "vnd.android.cursor.dir/" + TABLE_NAME2;
case PINYINS_ID:
return "vnd.android.cursor.item/" + TABLE_NAME2;
default:
throw new IllegalArgumentException("Unknown URI");
}
}
@Override
public Uri insert(Uri uri, ContentValues initialValues) {
String tableName = TABLE_NAME1;
Uri contentUri = CONTENT_URI1;
if (sURLMatcher.match(uri) == CHARS) {
tableName = TABLE_NAME1;
contentUri = CONTENT_URI1;
} else if (sURLMatcher.match(uri) == PINYINS) {
tableName = TABLE_NAME2;
contentUri = CONTENT_URI2;
} else {
throw new IllegalArgumentException("Cannot insert into URI: " + uri);
}
ContentValues values;
if (initialValues != null)
values = new ContentValues(initialValues);
else
values = new ContentValues();
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
long rowId = db.insert(tableName, null, values);
if (rowId < 0) {
throw new SQLException("Failed to insert row into " + uri);
}
Uri newUri = ContentUris.withAppendedId(contentUri, rowId);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count;
switch (sURLMatcher.match(uri)) {
case CHARS:
count = db.delete(TABLE_NAME1, where, whereArgs);
break;
case CHARS_ID: {
String segment = uri.getPathSegments().get(1);
if (TextUtils.isEmpty(where)) {
where = "_id=" + segment;
} else {
where = "_id=" + segment + " AND (" + where + ")";
}
count = db.delete(TABLE_NAME1, where, whereArgs);
}
break;
case PINYINS:
count = db.delete(TABLE_NAME2, where, whereArgs);
break;
case PINYINS_ID: {
String segment = uri.getPathSegments().get(1);
if (TextUtils.isEmpty(where)) {
where = "_id=" + segment;
} else {
where = "_id=" + segment + " AND (" + where + ")";
}
count = db.delete(TABLE_NAME2, where, whereArgs);
}
break;
default:
throw new IllegalArgumentException("Cannot delete from URI: " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
int count;
long rowId = 0;
int match = sURLMatcher.match(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
switch (match) {
case CHARS_ID: {
String segment = uri.getPathSegments().get(1);
rowId = Long.parseLong(segment);
try {
count = db.update(TABLE_NAME1, values, "_id=" + rowId, null);
} catch (SQLException e) {
Log.e(TAG, "update SQLException ", e);
return 0;
}
break;
}
case PINYINS_ID: {
String segment = uri.getPathSegments().get(1);
rowId = Long.parseLong(segment);
try {
count = db.update(TABLE_NAME2, values, "_id=" + rowId, null);
} catch (SQLException e) {
Log.e(TAG, "update SQLException ", e);
return 0;
}
break;
}
default: {
throw new UnsupportedOperationException("Cannot update URI: " + uri);
}
}
// Log.v(TAG, "*** notifyChange() rowId: " + rowId + " uri " + uri);
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
| 31.817427 | 114 | 0.641497 |
db0156a845b96b7a4cd8412cfe7d37626d362ce0 | 1,602 | package org.trimou.trimness.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.trimou.trimness.config.TrimnessKey.GLOBAL_JSON_FILE;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonStructure;
import javax.json.JsonValue.ValueType;
import org.jboss.weld.junit4.WeldInitiator;
import org.junit.Rule;
import org.junit.Test;
import org.trimou.trimness.DummyConfiguration;
/**
*
* @author Martin Kouba
*/
public class GlobalJsonModelProviderTest {
@Rule
public WeldInitiator weld = WeldInitiator.of(GlobalJsonModelProvider.class, DummyConfiguration.class);
@Test
public void testBasicOperations() {
DummyConfiguration configuration = weld.select(DummyConfiguration.class).get();
configuration.put(GLOBAL_JSON_FILE, "src/test/resources/global-data.json");
DummyModelRequest dummyModelRequest = new DummyModelRequest();
GlobalJsonModelProvider provider = weld.select(GlobalJsonModelProvider.class).get();
provider.handle(dummyModelRequest);
assertNotNull(dummyModelRequest.getResult());
JsonStructure model = (JsonStructure) dummyModelRequest.getResult();
assertEquals(ValueType.OBJECT, model.getValueType());
JsonObject modelObject = (JsonObject) model;
assertEquals(2, modelObject.size());
assertEquals("bar", modelObject.getString("foo"));
JsonArray array = modelObject.getJsonArray("array");
assertEquals(3, array.size());
assertEquals(1, array.getInt(0));
}
}
| 32.04 | 106 | 0.742821 |
2a5d00fa7000b97f0db6eebc31232ad2d05b3765 | 2,209 | package de.samply.fhir.valueset.gen;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.parser.IParser;
import de.samply.fhir.valueset.gen.icd.Extractor;
import org.hl7.fhir.r4.model.ValueSet;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
/**
* https://hapifhir.io/hapi-fhir/docs/model/parsers.html
*
* @param args source output
*/
public static void main(String[] args) throws IOException {
if (args.length < 2) throw new IllegalArgumentException("source file or output path not provided");
String inputPath = args[0];
String outputPath = args[1];
for (Reader inputFile : getInputFiles(inputPath)) {
Extractor extractor = new Extractor(inputFile);
writeValueSets(outputPath, extractor.generate());
}
}
private static List<Reader> getInputFiles(String inputPath) throws IOException {
System.out.println("Reading files: ");
List<Reader> listOfReaders = new ArrayList<>();
for (File file : new File(inputPath).listFiles()) {
if (file.isFile() && file.getName().endsWith(".json")) {
System.out.println(file.getName());
listOfReaders.add(new FileReader(file));
}
}
return listOfReaders;
}
private static void writeValueSets(String outputPath, List<ValueSet> valueSets) throws FileNotFoundException {
if (outputPath.charAt(outputPath.length() - 1) != File.separatorChar) {
outputPath += File.separator;
}
if (!new File(outputPath).isDirectory() || new File(outputPath).list().length != 0) {
System.out.println(outputPath + " is not empty or not exists");
return;
}
System.out.println("Writing " + valueSets.size() + " ValueSets to " + outputPath);
IParser parser = FhirContext.forR4().newJsonParser().setPrettyPrint(true);
for (ValueSet valueSet : valueSets) {
try (PrintWriter out = new PrintWriter(outputPath + valueSet.getName() + ".json")) {
out.println(parser.encodeResourceToString(valueSet));
}
}
}
}
| 37.440678 | 114 | 0.631055 |
a346a82cf34454a60e8149ba5f7d75c15abc17c2 | 227 | package com.rbkmoney.fraudo.model;
import lombok.Data;
@Data
public class BaseModel {
private String ip;
private String email;
private String fingerprint;
private Long amount;
private String currency;
}
| 15.133333 | 34 | 0.722467 |
70519665401c6ec0af4b40a8e43e8fb3985a687a | 137 | class T {
void f(String[] a) {
int k = 0;
while <caret>(k < a.length)
System.out.println(a[k++]);
}
} | 19.571429 | 39 | 0.430657 |
a421eb08cb9bf3ab62280deb024ca1e4dabeb691 | 848 | /*
* Copyright 2016-2017 Malcolm Reid Jr.
* 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.continuousassurance.swamp.eclipse;
import org.eclipse.ui.IStartup;
/** This class simply starts up the plug-in when Eclipse is started */
public class ActivationTriggerDummy implements IStartup {
@Override
public void earlyStartup() { }
}
| 36.869565 | 75 | 0.761792 |
72c2cb412ca418a16fa072eec44752943f04390f | 5,928 | package jkanvas;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.RectangularShape;
/**
* Paints and interacts with a Kanvas in canvas coordinates.
*
* @author Joschi <[email protected]>
*/
public interface KanvasInteraction {
/**
* Draw on a canvas. The panning and zooming of the canvas is transparent to
* this method and needs no further investigation.
*
* @param g The graphics context.
* @param ctx The canvas context.
*/
void draw(Graphics2D g, KanvasContext ctx);
/**
* Is called when the user clicks at the component and the HUD action does not
* consume the event. The coordinates are in the {@link KanvasPainter
* Painters} coordinate space and therefore suitable for clicks on objects on
* the canvas. This method is the second in the order of click processing and
* no dragging is performed, when this method returns <code>true</code>. In
* this method peers can be prevented to get processed by calling
* {@link Canvas#preventPeerInteraction()}. In contrast to returning
* <code>true</code> other interaction types still get processed.
*
* @param cam The camera on which the interaction happened.
* @param p The click position in canvas coordinates.
* @param e The original event.
* @return Whether the click was consumed.
* @see Canvas#preventPeerInteraction()
*/
boolean click(Camera cam, Point2D p, MouseEvent e);
/**
* Is called when the user performs a double click at the component and the
* HUD action does not consume the event. The coordinates are in the
* {@link KanvasPainter Painters} coordinate space and therefore suitable for
* clicks on the objects on the canvas. This method does not interfere with
* other clicks or drags. In this method peers can be prevented to get
* processed by calling {@link Canvas#preventPeerInteraction()}. In contrast
* to returning <code>true</code> other interaction types still get processed.
*
* @param cam The camera on which the interaction happened.
* @param p The double click position in canvas coordinates.
* @param e The original event.
* @return Whether the double click was consumed.
* @see Canvas#preventPeerInteraction()
*/
boolean doubleClick(Camera cam, Point2D p, MouseEvent e);
/**
* Is called when the user moves the mouse over the component and
* {@link HUDInteraction#getTooltipHUD(Point2D)} has returned
* <code>null</code>. This method returns the tool-tip that should be
* displayed at the given canvas position.
*
* @param p The mouse position in canvas coordinates.
* @return The tool-tip text or <code>null</code> if no tool-tip should be
* displayed.
*/
String getTooltip(Point2D p);
/**
* Is called when the user starts a dragging operation on the canvas. The
* coordinates are in the {@link KanvasPainter Painters} coordinate space and
* therefore suitable for dragging of objects on the canvas. In this method
* peers can be prevented to get processed by calling
* {@link Canvas#preventPeerInteraction()}. In contrast to returning
* <code>true</code> other interaction types still get processed.
*
* @param p The position where the drag starts in canvas coordinates.
* @param e The mouse event.
* @return Whether the drag is accepted and the dragging should start.
* @see Canvas#preventPeerInteraction()
*/
boolean acceptDrag(Point2D p, MouseEvent e);
/**
* Is called subsequently after {@link #acceptDrag(Point2D, MouseEvent)}
* returned <code>true</code> on every mouse movement until the user releases
* the mouse button.
*
* @param start The position where the drag started in canvas coordinates.
* @param cur The current drag position in canvas coordinates.
* @param dx The x distance of the drag in canvas coordinates.
* @param dy The y distance of the drag in canvas coordinates.
*/
void drag(Point2D start, Point2D cur, double dx, double dy);
/**
* Is called when the user releases the mouse in drag operation.
*
* @param start The position where the drag started in canvas coordinates.
* @param end The end position of the drag in canvas coordinates.
* @param dx The x distance of the drag in canvas coordinates.
* @param dy The y distance of the drag in canvas coordinates.
*/
// TODO #43 -- Java 8 simplification
void endDrag(Point2D start, Point2D end, double dx, double dy);
/**
* Is called when the mouse was moved. In this method peers can be prevented
* to get processed by calling {@link Canvas#preventPeerInteraction()}.
* Returning <code>true</code> on the other hand does not prevent peers from
* being executed in this method.
*
* @param cur The current position in canvas coordinates.
* @return Whether this event has affected the render pass.
* @see Canvas#preventPeerInteraction()
*/
boolean moveMouse(Point2D cur);
/**
* Calculates the bounding box of the canvas.
*
* @param bbox The rectangle where the bounding box is stored.
*/
void getBoundingBox(RectangularShape bbox);
/**
* Processes a message handed in via the {@link Canvas#postMessage(String)}
* method.
*
* @param ids A list of ids the message is for. Only objects with at least one
* of those ids should consume the message. Due to technical reasons
* the characters '<code>#</code>' and '<code> </code>' cannot be in
* ids. The list may be empty. Ids cannot be the empty string.
* @param msg The message to be processed. The message must be handed to all
* children even when consumed. Due to technical reasons the
* character '<code>#</code>' cannot be in messages. Messages cannot
* be the empty string.
*/
void processMessage(String[] ids, String msg);
}
| 41.166667 | 80 | 0.70614 |
2f48a04a440683e65aedc525a5e07b50e242d073 | 1,601 | package com.aoeai.spin.accelerator.generate.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileNotFoundException;
import static com.aoeai.spin.accelerator.generate.utils.FileTools.getMainResourcesFilePath;
/**
* 配置信息工具
* @author aoe
*/
@Slf4j
public class ConfigTools {
private ConfigTools() {
}
/**
* 从yaml文件中获取配置信息
* @param yamlName (resources目录下)yaml文件名
* @param clazz com.aoeai.spin.accelerator.generate.bean.config.JavaConfig 及其子类
* @param <T>
* @return
*/
public static <T>T getConfig(String yamlName, Class<T> clazz) {
String yamlPath = getMainResourcesFilePath(yamlName);
String configPath = yamlName.substring(0, yamlName.lastIndexOf("/")) + "/base-config.yaml";
configPath = StringUtils.replace(configPath,"/", File.separator);
configPath = getMainResourcesFilePath(configPath);
var configFile = new File(configPath);
boolean existsConfigFile = configFile.exists();
String yamlStr = null;
try {
if (existsConfigFile) {
yamlStr = YamlTools.mergeYaml(configPath, yamlPath);
yamlStr = YamlTools.removeElements(yamlStr, YamlTools.mergeYaml(configPath));
} else {
yamlStr = YamlTools.mergeYaml(yamlPath);
}
} catch (FileNotFoundException e) {
log.error("合并Yaml文件失败", e);
}
var yaml = new Yaml();
return yaml.loadAs(yamlStr, clazz);
}
}
| 30.207547 | 99 | 0.652092 |
0ebb89291ce8f4b690464a6e063eb2330a03cfce | 10,786 | package fr.inra.urgi.faidare.service.es;
import com.opencsv.CSVWriter;
import fr.inra.urgi.faidare.api.faidare.v1.GnpISGermplasmController;
import fr.inra.urgi.faidare.domain.criteria.FaidareGermplasmPOSTShearchCriteria;
import fr.inra.urgi.faidare.domain.criteria.GermplasmSearchCriteria;
import fr.inra.urgi.faidare.domain.data.germplasm.*;
import fr.inra.urgi.faidare.domain.datadiscovery.response.GermplasmSearchResponse;
import fr.inra.urgi.faidare.domain.response.PaginatedList;
import fr.inra.urgi.faidare.repository.es.GermplasmRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author cpommier, gcornut, jdestin
*/
@Service("germplasmService")
public class GermplasmServiceImpl implements GermplasmService {
private final static Logger LOGGER = LoggerFactory.getLogger(GnpISGermplasmController.class);
@Resource
GermplasmRepository germplasmRepository;
@Override
public File exportCSV(GermplasmSearchCriteria criteria) {
try {
Iterator<GermplasmVO> allGermplasm = germplasmRepository.scrollAll(criteria);
Path tmpDirPath = Files.createTempDirectory("germplasm");
Path tmpFile = Files.createTempFile(tmpDirPath, "germplasm_", ".csv");
writeToCSV(tmpFile, allGermplasm);
return tmpFile.toFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public File exportListGermplasmCSV(FaidareGermplasmPOSTShearchCriteria criteria) {
try {
Iterator<GermplasmVO> allGermplasm = germplasmRepository.scrollAllGermplasm(criteria);
Path tmpDirPath = Files.createTempDirectory("germplasm");
Path tmpFile = Files.createTempFile(tmpDirPath, "germplasm_", ".csv");
writeToCSV(tmpFile, allGermplasm);
return tmpFile.toFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public GermplasmMcpdVO getAsMcpdById(String germplasmDbId) {
return germplasmRepository.getAsMcpdById(germplasmDbId);
}
@Override
public File exportGermplasmMcpd(FaidareGermplasmPOSTShearchCriteria criteria) {
try {
Iterator<GermplasmMcpdVO> allGermplasm = germplasmRepository.scrollAllGermplasmMcpd(criteria);
Path tmpDirPath = Files.createTempDirectory("germplasm");
Path tmpFile = Files.createTempFile(tmpDirPath, "germplasm_", ".csv");
writeMcpdToCSV(tmpFile, allGermplasm);
return tmpFile.toFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void writeToCSV(Path tmpFile, Iterator<GermplasmVO> germplasms) throws IOException {
Writer fileStream = new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8);
CSVWriter csvWriter = new CSVWriter(fileStream, ';', '"', '\\', "\n");
String[] header = new String[]{
"DOI", "AccessionNumber", "AccessionName", "TaxonGroup", "HoldingInstitution",
"LotName", "LotSynonym", "CollectionName", "CollectionType", "PanelName", "PanelSize"};
csvWriter.writeNext(header);
while (germplasms.hasNext()) {
List<String> collectionNames = new ArrayList<>();
List<String> panelNames = new ArrayList<>();
GermplasmVO germplasmVO = germplasms.next();
if (germplasmVO.getCollection() != null) {
for (CollPopVO collection : germplasmVO.getCollection()) {
collectionNames.add(collection.getName());
}
}
if (germplasmVO.getPanel() != null) {
for (CollPopVO panel : germplasmVO.getPanel()) {
panelNames.add(panel.getName());
}
}
String[] line = new String[header.length];
line[0] = germplasmVO.getGermplasmPUI();
line[1] = germplasmVO.getAccessionNumber();
line[2] = germplasmVO.getGermplasmName();
line[3] = germplasmVO.getCommonCropName();
line[4] = germplasmVO.getInstituteName();
line[7] = (collectionNames != null) ? String.join(", ", collectionNames) : "";
line[9] = (panelNames != null) ? String.join(", ", panelNames) : "";
csvWriter.writeNext(line);
}
csvWriter.close();
}
private void writeMcpdToCSV(Path tmpFile, Iterator<GermplasmMcpdVO> germplasms) throws IOException {
Writer fileStream = new OutputStreamWriter(new FileOutputStream(tmpFile.toFile()), StandardCharsets.UTF_8);
CSVWriter csvWriter = new CSVWriter(fileStream, ';', '"', '\\', "\n");
String[] header = new String[]{
"PUID", "INSTCODE", "ACCENUMB", "COLLNUMB", "COLLCODE", "COLLNAME",
"COLLINSTADDRESS", "COLLMISSID", "GENUS", "SPECIES", "SPAUTHOR", "SUBTAXA",
"SUBTAUTHOR", "CROPNAME", "ACCENAME", "ACQDATE", "ORIGCTY", "COLLSITE",
"DECLATITUDE", "LATITUDE", "DECLONGITUDE", "LONGITUDE", "COORDUNCERT",
"COORDDATUM", "GEOREFMETH", "ELEVATION", "COLLDATE", "BREDCODE",
"BREDNAME", "SAMPSTAT", "ANCEST","COLLSRC", "DONORCODE", "DONORNAME",
"DONORNUMB", "OTHERNUMB", "DUPLSITE", "DUPLINSTNAME", "STORAGE", "MLSSTAT", "REMARKS",
};
csvWriter.writeNext(header);
while (germplasms.hasNext()) {
List<String> collectionNames = new ArrayList<>();
List<String> panelNames = new ArrayList<>();
GermplasmMcpdVO germplasmMcpdVO = germplasms.next();
String[] line = new String[header.length];
line[0] = germplasmMcpdVO.getGermplasmPUI();
line[1] = germplasmMcpdVO.getInstituteCode();
line[2] = germplasmMcpdVO.getAccessionNumber();
line[3] = germplasmMcpdVO.getCollectingInfo().getCollectingNumber();
line[4] = germplasmMcpdVO.getCollectingInfo().getCollectingInstitutes().stream()
.map(InstituteVO::getInstituteCode).collect(Collectors.joining(";"));
line[5] = germplasmMcpdVO.getCollectingInfo().getCollectingInstitutes().stream()
.map(InstituteVO::getInstituteName).collect(Collectors.joining(";"));
line[6] = germplasmMcpdVO.getCollectingInfo().getCollectingInstitutes().stream()
.map(InstituteVO::getAddress).collect(Collectors.joining(";"));
line[7] = germplasmMcpdVO.getCollectingInfo().getCollectingMissionIdentifier();
line[8] = germplasmMcpdVO.getGenus();
line[9] = germplasmMcpdVO.getSpecies();
line[10] = germplasmMcpdVO.getSpeciesAuthority();
line[11] = germplasmMcpdVO.getSubtaxon();
line[12] = germplasmMcpdVO.getSubtaxonAuthority();
line[13] = germplasmMcpdVO.getCommonCropName();
line[14] = String.join(";",germplasmMcpdVO.getAccessionNames());
line[15] = germplasmMcpdVO.getAcquisitionDate();
line[16] = germplasmMcpdVO.getCountryOfOriginCode();
line[18] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getSiteName();
line[19] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getLatitudeDecimal();
line[20] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getLatitudeDegrees();
line[21] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getLongitudeDecimal();
line[22] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getLongitudeDegrees();
line[23] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getCoordinateUncertainty();
line[24] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getSpatialReferenceSystem();
line[25] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getGeoreferencingMethod();
line[26] = germplasmMcpdVO.getCollectingInfo().getCollectingSite().getElevation();
line[27] = germplasmMcpdVO.getCollectingInfo().getCollectingDate();
line[28] = germplasmMcpdVO.getBreedingInstitutes().stream()
.map(InstituteVO::getInstituteCode).collect(Collectors.joining(";"));
line[29] = germplasmMcpdVO.getBreedingInstitutes().stream()
.map(InstituteVO::getInstituteName).collect(Collectors.joining(";"));
line[30] = germplasmMcpdVO.getBiologicalStatusOfAccessionCode();
line[31] = germplasmMcpdVO.getAncestralData();
line[32] = germplasmMcpdVO.getAcquisitionSourceCode();
line[33] = germplasmMcpdVO.getDonorInfo().stream()
.map(donorInfoVO -> donorInfoVO.getDonorInstitute().getInstituteCode()).collect(Collectors.joining(";"));
line[34] = germplasmMcpdVO.getDonorInfo().stream()
.map(donorInfoVO -> donorInfoVO.getDonorInstitute().getInstituteName()).collect(Collectors.joining(";"));
line[35] = germplasmMcpdVO.getDonorInfo().stream()
.map(DonorInfoVO::getDonorAccessionNumber).collect(Collectors.joining(";"));
line[36] = String.join(";", germplasmMcpdVO.getAlternateIDs());
line[37] = germplasmMcpdVO.getSafetyDuplicateInstitutes().stream()
.map(InstituteVO::getInstituteName).collect(Collectors.joining(";"));
line[38] = String.join(";", germplasmMcpdVO.getStorageTypeCodes());
line[39] = germplasmMcpdVO.getMlsStatus();
line[40] = germplasmMcpdVO.getRemarks();
csvWriter.writeNext(line);
}
csvWriter.close();
}
@Override
public GermplasmVO getById(String germplasmDbId) {
return germplasmRepository.getById(germplasmDbId);
}
@Override
public PaginatedList<GermplasmVO> find(GermplasmSearchCriteria sCrit) {
return germplasmRepository.find(sCrit);
}
@Override
public GermplasmSearchResponse germplasmFind(FaidareGermplasmPOSTShearchCriteria germplasmSearchCriteria) {
return germplasmRepository.germplasmFind(germplasmSearchCriteria);
}
@Override
public PedigreeVO getPedigree(String germplasmDbId) {
return germplasmRepository.findPedigree(germplasmDbId);
}
@Override
public ProgenyVO getProgeny(String germplasmDbId) {
return germplasmRepository.findProgeny(germplasmDbId);
}
}
| 47.725664 | 121 | 0.66234 |
8a4bd2b558ce445d0356bcf71236f14116051776 | 1,886 | package org.evan.study.concurrent.chapter09;
import org.evan.study.concurrent.chapter04.ThreadDaemon;
import java.util.stream.Stream;
/**
* Created by marvel on 2017/10/15.
* # The diffrence of sleep and wait:
* 1. sleep is the method of Thread, and the wait is the method of Object;
* 2. sleep will not release the Object monitor(Lock), but the wait will be release the monitor and add to the Object monitor waiting queue;
* 3. use sleep not depend on the monitor, but wait need;
* 4. The sleep method not need be wakeup, but wait need(except wait(10));
*/
public class DiffrenceOfWaitAndSleep {
private final static Object LOCK = new Object();
public static void main(String[] args) {
// new Thread("T1") {
// @Override
// public void run() {
// m2();
// }
// }.start();
Stream.of("T1", "T2").forEach(n ->
new Thread() {
@Override
public void run() {
m2();
}
}.start()
);
}
/**
* m1 method is to test the sleep method of application
*/
public static void m1() {
synchronized (LOCK) {
try {
System.out.println("Thread " + Thread.currentThread().getName() + " Enter.");
Thread.sleep(10_000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* m2 method is to test the wait method of application.
*/
public static void m2() {
synchronized (LOCK) {
try {
System.out.println("Thread " + Thread.currentThread().getName() + " Enter.");
LOCK.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
| 29.46875 | 145 | 0.526511 |
497db0052b607f7ffd4d3d246c8a8784fa39f638 | 308 | package com.dota2.store.mails;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuthenticator extends Authenticator{
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("[email protected]", "$");
}
}
| 28 | 68 | 0.775974 |
94d05775d0d097fe1a03d26783ac7336b4b3e6dc | 295 | package org.kokzoz.dluid.domain.exception;
public class InvalidSwitchConnectionExistException extends AbstractInvalidLayerException {
public InvalidSwitchConnectionExistException(String layerId){
super(layerId, "Upward connection is impossible on merge and switch layer.");
}
}
| 36.875 | 90 | 0.80339 |
ab855499b384b85d6f7368fc91b07352ca310de8 | 4,768 | package cloud.foundry.cli.crosscutting.mapping;
import static com.google.common.base.Preconditions.checkNotNull;
import cloud.foundry.cli.crosscutting.exceptions.YamlTreeNodeNotFoundException;
import java.util.List;
import java.util.Map;
/**
* This class is responsible to descend a yaml tree according to a specific yaml pointer.
*
* It performs this task by implementing the {@link YamlTreeVisitor} interface. Its visitor-based implementation is
* entirely hidden to the user of this class.
*/
public class YamlTreeDescender implements YamlTreeVisitor {
private final Object yamlTreeRoot;
private final YamlPointer pointer;
private int nodeIndex;
private Object resultingYamlTreeNode;
private YamlTreeDescender(Object yamlTreeRoot, YamlPointer pointer) {
this.yamlTreeRoot = yamlTreeRoot;
this.pointer = pointer;
this.nodeIndex = 0;
this.resultingYamlTreeNode = null;
}
/**
* Descends the yaml tree according to the specified nodes in the yaml pointer. The node of the tree to which the
* pointer points to is returned.
* @param yamlTreeRoot the root of a yaml tree from which the descending procedure is started
* @param yamlPointer the pointer that specifies the nodes to descend
* @return the node to which the pointer points to
* @throws YamlTreeNodeNotFoundException if a node that is specified in the pointer cannot be found
* @throws NullPointerException if the yaml pointer parameter is null
*/
public static Object descend(Object yamlTreeRoot, YamlPointer yamlPointer) {
checkNotNull(yamlPointer);
YamlTreeDescender descendingVisitor = new YamlTreeDescender(yamlTreeRoot, yamlPointer);
return descendingVisitor.doDescend();
}
private Object doDescend() {
YamlTreeVisitor.visit(this, yamlTreeRoot);
return resultingYamlTreeNode;
}
/**
* Descends into a value node of the specified mapping or stops, if the target node of the pointer was reached.
* @param mappingNode the mapping node to be descended
* @throws YamlTreeNodeNotFoundException if the pointer specifies a key that is not present in the mapping node
* or if a descendant node of the mapping cannot be found
*/
@Override
public void visitMapping(Map<Object, Object> mappingNode) {
if (nodeIndex == pointer.getNumberOfNodeNames()) {
resultingYamlTreeNode = mappingNode;
return;
}
String currentNodeName = pointer.getNodeName(nodeIndex);
if (!mappingNode.containsKey(currentNodeName)) {
throw new YamlTreeNodeNotFoundException("Could not find the key '" + currentNodeName + "'");
}
Object descendantNode = mappingNode.get(currentNodeName);
++nodeIndex;
YamlTreeVisitor.visit(this, descendantNode);
}
/**
* Descends into a node of the specified sequence or stops, if the target node of the pointer was reached.
* @param sequenceNode the sequence node to be descended
* @throws YamlTreeNodeNotFoundException if the pointer specifies an invalid node index for this sequence
* or if a descendant node of the sequence cannot be found
*/
@Override
public void visitSequence(List<Object> sequenceNode) {
if (nodeIndex == pointer.getNumberOfNodeNames()) {
resultingYamlTreeNode = sequenceNode;
return;
}
String currentNodeName = pointer.getNodeName(nodeIndex);
int listIndex;
try {
listIndex = Integer.parseInt(currentNodeName);
} catch (NumberFormatException e) {
throw new YamlTreeNodeNotFoundException("Could not convert '" + currentNodeName + "' to a list index");
}
if (listIndex < 0 || listIndex >= sequenceNode.size()) {
throw new YamlTreeNodeNotFoundException("The list index '" + listIndex + "' is out of range");
}
Object descendantNode = sequenceNode.get(listIndex);
++nodeIndex;
YamlTreeVisitor.visit(this, descendantNode);
}
/**
* Stops the descending process.
* @param scalarNode the scalar node to be descended
* @throws YamlTreeNodeNotFoundException if the pointer specifies a node beyond the scalar node parameter
*/
@Override
public void visitScalar(Object scalarNode) {
if (nodeIndex < pointer.getNumberOfNodeNames()) {
throw new YamlTreeNodeNotFoundException("Cannot descend further to '" +
pointer.getNodeName(nodeIndex) + "' because a scalar was reached");
}
resultingYamlTreeNode = scalarNode;
}
}
| 39.404959 | 117 | 0.681628 |
7925a7eb2f632256420ba55f30e51249a0b4a764 | 782 | package com.by_syk.bigjpg.util;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.net.Uri;
import android.support.annotation.Nullable;
/**
* Created by By_syk on 2017-06-20.
*/
public class ImgUtil {
@Nullable
public static Point getImgSize(Context context, Uri uri) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri), null, options);
return new Point(options.outWidth, options.outHeight);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
| 26.965517 | 72 | 0.658568 |
01990b8be4cafcb65d072825e4195089084e41f2 | 451 | package com.desertkun.brainout.content.quest;
import com.desertkun.brainout.BrainOutClient;
import com.desertkun.brainout.reflection.Reflect;
import com.desertkun.brainout.reflection.ReflectAlias;
@Reflect("content.quest.DailyQuest")
public class ClientDailyQuest extends DailyQuest
{
public ClientDailyQuest()
{
}
@Override
protected long getTime()
{
return BrainOutClient.ClientController.getServerTime();
}
}
| 22.55 | 63 | 0.758315 |
cb9d57aaadfb230cf664df62571a0fa762e341c1 | 355 | package com.jingyuyao.tactical.model.script;
/**
* An event from the model that can trigger some script actions. Each implementation must have a
* corresponding method in {@link Condition}.
*/
public interface ScriptEvent {
/**
* Return whether this event is satisfied by the given condition.
*/
boolean satisfiedBy(Condition condition);
}
| 25.357143 | 96 | 0.740845 |
6e0e33678a5dddf3fc8d921e1a16955a7c051eb1 | 2,198 | /*
* Copyright 2016-2019 Tim Boudreau, Frédéric Yvon Vinet
*
* 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.nemesis.editor.function;
import org.nemesis.editor.impl.Hold;
import java.util.Objects;
import java.util.function.Consumer;
import javax.swing.text.BadLocationException;
/**
* A supplier which throws a BadLocationException or other declared exception.
*
* @author Tim Boudreau
*/
@FunctionalInterface
public interface DocumentSupplier<T, E extends Exception> {
T get() throws E, BadLocationException;
public interface Simple<T> extends DocumentSupplier<T, RuntimeException> {
}
static <T> T runNonThrowing(Consumer<Runnable> r, DocumentSupplier<T, RuntimeException> supp) throws BadLocationException {
return supp.run(r);
}
static <T, E extends Exception> T run(Consumer<Runnable> r, DocumentSupplier<T, E> supp) throws E, BadLocationException {
return supp.run(r);
}
default T run(Consumer<Runnable> runner) throws E, BadLocationException {
Hold<T, E> hold = new Hold<>();
runner.accept(() -> {
try {
hold.set(get());
} catch (Exception ex) {
hold.thrown(ex);
}
});
return hold.get();
}
/**
* Perform a get() catching any exception and returning either the string
* value of the return value of get() or the exception. For logging
* purposes.
*
* @return
*/
default String toStringGet() {
Object obj;
try {
obj = get();
} catch (Exception ex) {
obj = ex;
}
return Objects.toString(obj);
}
}
| 29.702703 | 127 | 0.651501 |
60f848a7d5b850ce1863ebaecfb4b935ec8100e1 | 13,231 | /*
* Licensed to GraphHopper GmbH under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*
* GraphHopper GmbH 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 com.graphhopper.storage;
import com.graphhopper.routing.util.*;
import com.graphhopper.util.EdgeExplorer;
import com.graphhopper.util.EdgeIteratorState;
import com.graphhopper.util.shapes.BBox;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* This class manages all storage related methods and delegates the calls to the associated graphs.
* The associated graphs manage their own necessary data structures and are used to provide e.g.
* different traversal methods. By default this class implements the graph interface and results in
* identical behavior as the Graph instance from getGraph(Graph.class)
* <p>
* @author Peter Karich
* @see GraphBuilder to create a (CH)Graph easier
* @see #getGraph(java.lang.Class)
*/
public final class GraphHopperStorage implements GraphStorage, Graph
{
private final Directory dir;
private final EncodingManager encodingManager;
private final StorableProperties properties;
private final BaseGraph baseGraph;
// same flush order etc
private final Collection<CHGraphImpl> chGraphs = new ArrayList<CHGraphImpl>(5);
public GraphHopperStorage( Directory dir, EncodingManager encodingManager, boolean withElevation, GraphExtension extendedStorage )
{
this(Collections.<Weighting>emptyList(), dir, encodingManager, withElevation, extendedStorage);
}
public GraphHopperStorage( List<? extends Weighting> chWeightings, Directory dir, final EncodingManager encodingManager,
boolean withElevation, GraphExtension extendedStorage )
{
if (extendedStorage == null)
throw new IllegalArgumentException("GraphExtension cannot be null, use NoOpExtension");
if (encodingManager == null)
throw new IllegalArgumentException("EncodingManager needs to be non-null since 0.7. Create one using new EncodingManager or EncodingManager.create(flagEncoderFactory, ghLocation)");
this.encodingManager = encodingManager;
this.dir = dir;
this.properties = new StorableProperties(dir);
InternalGraphEventListener listener = new InternalGraphEventListener()
{
@Override
public void initStorage()
{
for (CHGraphImpl cg : chGraphs)
{
cg.initStorage();
}
}
@Override
public void freeze()
{
for (CHGraphImpl cg : chGraphs)
{
cg._freeze();
}
}
};
this.baseGraph = new BaseGraph(dir, encodingManager, withElevation, listener, extendedStorage);
for (Weighting w : chWeightings)
{
chGraphs.add(new CHGraphImpl(w, dir, this.baseGraph));
}
}
/**
* This method returns the routing graph for the specified weighting, could be potentially
* filled with shortcuts.
*/
public <T extends Graph> T getGraph( Class<T> clazz, Weighting weighting )
{
if (clazz.equals(Graph.class))
return (T) baseGraph;
if (chGraphs.isEmpty())
throw new IllegalStateException("Cannot find graph implementation for " + clazz);
if (weighting == null)
throw new IllegalStateException("Cannot find CHGraph with null weighting");
List<Weighting> existing = new ArrayList<Weighting>();
for (CHGraphImpl cg : chGraphs)
{
if (cg.getWeighting() == weighting)
return (T) cg;
existing.add(cg.getWeighting());
}
throw new IllegalStateException("Cannot find CHGraph for specified weighting: " + weighting + ", existing:" + existing);
}
public <T extends Graph> T getGraph( Class<T> clazz )
{
if (clazz.equals(Graph.class))
return (T) baseGraph;
if (chGraphs.isEmpty())
throw new IllegalStateException("Cannot find graph implementation for " + clazz);
CHGraph cg = chGraphs.iterator().next();
return (T) cg;
}
public boolean isCHPossible()
{
return !chGraphs.isEmpty();
}
public List<Weighting> getCHWeightings()
{
List<Weighting> list = new ArrayList<Weighting>(chGraphs.size());
for (CHGraphImpl cg : chGraphs)
{
list.add(cg.getWeighting());
}
return list;
}
/**
* @return the directory where this graph is stored.
*/
@Override
public Directory getDirectory()
{
return dir;
}
@Override
public void setSegmentSize( int bytes )
{
baseGraph.setSegmentSize(bytes);
for (CHGraphImpl cg : chGraphs)
{
cg.setSegmentSize(bytes);
}
}
/**
* After configuring this storage you need to create it explicitly.
*/
@Override
public GraphHopperStorage create( long byteCount )
{
baseGraph.checkInit();
if (encodingManager == null)
throw new IllegalStateException("EncodingManager can only be null if you call loadExisting");
dir.create();
long initSize = Math.max(byteCount, 100);
properties.create(100);
properties.put("graph.bytes_for_flags", encodingManager.getBytesForFlags());
properties.put("graph.flag_encoders", encodingManager.toDetailsString());
properties.put("graph.byte_order", dir.getByteOrder());
properties.put("graph.dimension", baseGraph.nodeAccess.getDimension());
properties.putCurrentVersions();
baseGraph.create(initSize);
for (CHGraphImpl cg : chGraphs)
{
cg.create(byteCount);
}
properties.put("graph.ch.weightings", getCHWeightings().toString());
return this;
}
@Override
public EncodingManager getEncodingManager()
{
return encodingManager;
}
@Override
public StorableProperties getProperties()
{
return properties;
}
public void setAdditionalEdgeField( long edgePointer, int value )
{
baseGraph.setAdditionalEdgeField(edgePointer, value);
}
@Override
public void markNodeRemoved( int index )
{
baseGraph.getRemovedNodes().add(index);
}
@Override
public boolean isNodeRemoved( int index )
{
return baseGraph.getRemovedNodes().contains(index);
}
@Override
public void optimize()
{
if (isFrozen())
throw new IllegalStateException("do not optimize after graph was frozen");
int delNodes = baseGraph.getRemovedNodes().getCardinality();
if (delNodes <= 0)
return;
// Deletes only nodes.
// It reduces the fragmentation of the node space but introduces new unused edges.
baseGraph.inPlaceNodeRemove(delNodes);
// Reduce memory usage
baseGraph.trimToSize();
}
@Override
public boolean loadExisting()
{
baseGraph.checkInit();
if (properties.loadExisting())
{
properties.checkVersions(false);
// check encoding for compatiblity
String flagEncodersStr = properties.get("graph.flag_encoders");
if (!flagEncodersStr.isEmpty() && !encodingManager.toDetailsString().equalsIgnoreCase(flagEncodersStr))
{
throw new IllegalStateException("Encoding does not match:\nGraphhopper config: " + encodingManager.toDetailsString()
+ "\nGraph: " + flagEncodersStr + ", dir:" + dir.getLocation());
}
String byteOrder = properties.get("graph.byte_order");
if (!byteOrder.equalsIgnoreCase("" + dir.getByteOrder()))
throw new IllegalStateException("Configured graph.byte_order (" + dir.getByteOrder() + ") is not equal to loaded " + byteOrder + "");
String bytesForFlags = properties.get("graph.bytes_for_flags");
if (!bytesForFlags.equalsIgnoreCase("" + encodingManager.getBytesForFlags()))
throw new IllegalStateException("Configured graph.bytes_for_flags (" + encodingManager.getBytesForFlags() + ") is not equal to loaded " + bytesForFlags);
String dim = properties.get("graph.dimension");
baseGraph.loadExisting(dim);
String loadedCHWeightings = properties.get("graph.ch.weightings");
String configuredCHWeightings = getCHWeightings().toString();
if (!loadedCHWeightings.equals(configuredCHWeightings))
throw new IllegalStateException("Configured graph.ch.weightings: " + configuredCHWeightings + " is not equal to loaded " + loadedCHWeightings);
for (CHGraphImpl cg : chGraphs)
{
if (!cg.loadExisting())
throw new IllegalStateException("Cannot load " + cg);
}
return true;
}
return false;
}
@Override
public void flush()
{
for (CHGraphImpl cg : chGraphs)
{
cg.setEdgesHeader();
cg.flush();
}
baseGraph.flush();
properties.flush();
}
@Override
public void close()
{
properties.close();
baseGraph.close();
for (CHGraphImpl cg : chGraphs)
{
cg.close();
}
}
@Override
public boolean isClosed()
{
return baseGraph.nodes.isClosed();
}
@Override
public long getCapacity()
{
long cnt = baseGraph.getCapacity() + properties.getCapacity();
for (CHGraphImpl cg : chGraphs)
{
cnt += cg.getCapacity();
}
return cnt;
}
/**
* Avoid that edges and nodes of the base graph are further modified. Necessary as hook for e.g.
* ch graphs on top to initilize themself
*/
public synchronized void freeze()
{
if (!baseGraph.isFrozen())
baseGraph.freeze();
}
boolean isFrozen()
{
return baseGraph.isFrozen();
}
@Override
public String toDetailsString()
{
String str = baseGraph.toDetailsString();
for (CHGraphImpl cg : chGraphs)
{
str += ", " + cg.toDetailsString();
}
return str;
}
@Override
public String toString()
{
return (isCHPossible() ? "CH|" : "")
+ encodingManager
+ "|" + getDirectory().getDefaultType()
+ "|" + baseGraph.nodeAccess.getDimension() + "D"
+ "|" + baseGraph.extStorage
+ "|" + getProperties().versionsToString();
}
// now all delegation graph method to avoid ugly programming flow ala
// GraphHopperStorage storage = ..;
// Graph g = storage.getGraph(Graph.class);
// instead directly the storage can be used to traverse the base graph
@Override
public Graph getBaseGraph()
{
return baseGraph;
}
@Override
public int getNodes()
{
return baseGraph.getNodes();
}
@Override
public NodeAccess getNodeAccess()
{
return baseGraph.getNodeAccess();
}
@Override
public BBox getBounds()
{
return baseGraph.getBounds();
}
@Override
public EdgeIteratorState edge( int a, int b )
{
return baseGraph.edge(a, b);
}
@Override
public EdgeIteratorState edge( int a, int b, double distance, boolean bothDirections )
{
return baseGraph.edge(a, b, distance, bothDirections);
}
@Override
public EdgeIteratorState getEdgeIteratorState( int edgeId, int adjNode )
{
return baseGraph.getEdgeIteratorState(edgeId, adjNode);
}
@Override
public AllEdgesIterator getAllEdges()
{
return baseGraph.getAllEdges();
}
@Override
public EdgeExplorer createEdgeExplorer( EdgeFilter filter )
{
return baseGraph.createEdgeExplorer(filter);
}
@Override
public EdgeExplorer createEdgeExplorer()
{
return baseGraph.createEdgeExplorer();
}
@Override
public Graph copyTo( Graph g )
{
return baseGraph.copyTo(g);
}
@Override
public GraphExtension getExtension()
{
return baseGraph.getExtension();
}
}
| 29.665919 | 193 | 0.620664 |
30bea215c2a6f16d671e5433c714d39b5bc00886 | 3,169 | /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~ Copyright 2020 Adobe
~
~ 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.adobe.dx.admin.config.manager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.annotation.PostConstruct;
import com.day.cq.wcm.api.Page;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.ValueMapValue;
@Model(adaptables = { Resource.class },
defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class ColumnViewItem {
private static final String ICON_FOLDER = "folder";
private static final String ICON_CONFIG = "config";
private static final Collection<String> IGNORED_NODES = Arrays.asList("jcr:content", "rep:policy", "workflow", "granite");
private static final Collection<String> FOLDER_TYPES = Arrays.asList("nt:folder", "sling:Folder", "sling:OrderedFolder");
@Self
private Resource resource;
@ValueMapValue(name = "jcr:primaryType")
private String primaryType;
@ValueMapValue(name = "jcr:title")
private String title;
private Page page;
@PostConstruct
private void init() {
page = resource.adaptTo(Page.class);
}
public boolean getIsPage() {
return page != null;
}
public String getLabel() {
if (page != null && page.getTitle() != null) {
return page.getTitle();
}
if (title != null) {
return title;
}
return resource.getName();
}
public String getName() {
return resource.getName();
}
public String getPath() {
return resource.getPath();
}
public String getIconType() {
if (primaryType != null && FOLDER_TYPES.contains(primaryType)) {
return ICON_FOLDER;
}
return ICON_CONFIG;
}
public List<ColumnViewItem> getChildren() {
List<ColumnViewItem> children = new ArrayList<>();
Iterable<Resource> childrenIter = resource.getChildren();
childrenIter.forEach(child -> {
if (!IGNORED_NODES.contains(child.getName())) {
ColumnViewItem item = child.adaptTo(ColumnViewItem.class);
children.add(item);
}
});
return children;
}
} | 31.376238 | 126 | 0.64279 |
56308493f13cae8d0892f04b17b5b6360c65f747 | 538 | package com.github.archerda.spring.ioc.beanwire;
import org.springframework.stereotype.Component;
/**
* Create by archerda on 2017/11/19.
*/
@Component
public class SgtPeppers implements CompactDisc {
private String title = "Sgt.Pepper's Lonely Hearts Clue Band";
private String artist = "The Beatles";
public void play() {
System.out.println("Playing " + title + " By " + artist);
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
}
| 20.692308 | 66 | 0.654275 |
03b8d75d092a105c02920b61e5753c8d46d7fb31 | 891 | package xml;
import java.util.Map;
import rule.FireRule;
import rule.Rule;
public class FireXMLRule extends XMLRule
{
public static final String DATA_TYPE = "Fire";
// public static final List<String> DATA_FIELDS = makeDataFields();
@Override
public Rule getRule(Map<String, String> dataValues)
{
// double fireProb = 0.0;
// Exception invalidFireProbException = new Exception();
// try{
// fireProb = Double.parseDouble(dataValues.get(DATA_FIELDS.get(0)));
// if (fireProb < 0 || fireProb>1){
// throw invalidFireProbException;
// }
// }catch(Exception e){
// alert("INVALIDFIREPROB");
// }
return new FireRule(dataValues);
}
//
// private static List<String> makeDataFields()
// {
// List<String> dataFields = new ArrayList<String>();
// dataFields.add("fire_probability");
// dataFields.addAll(XMLRule.DATA_FIELDS);
// return dataFields;
// }
}
| 22.275 | 71 | 0.690236 |
6d707b5aa4056ffdff37dd74339477c73bde2929 | 13,518 | /*
* Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
*
* 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.epam.pipeline.manager;
import com.epam.pipeline.controller.vo.DataStorageVO;
import com.epam.pipeline.controller.vo.PipelineVO;
import com.epam.pipeline.controller.vo.configuration.RunConfigurationVO;
import com.epam.pipeline.controller.vo.docker.DockerRegistryVO;
import com.epam.pipeline.controller.vo.metadata.MetadataEntityVO;
import com.epam.pipeline.entity.configuration.AbstractRunConfigurationEntry;
import com.epam.pipeline.entity.configuration.FirecloudRunConfigurationEntry;
import com.epam.pipeline.entity.configuration.InputsOutputs;
import com.epam.pipeline.entity.configuration.PipelineConfiguration;
import com.epam.pipeline.entity.configuration.RunConfiguration;
import com.epam.pipeline.entity.configuration.RunConfigurationEntry;
import com.epam.pipeline.entity.datastorage.DataStorageType;
import com.epam.pipeline.entity.datastorage.StoragePolicy;
import com.epam.pipeline.entity.datastorage.aws.S3bucketDataStorage;
import com.epam.pipeline.entity.metadata.MetadataClass;
import com.epam.pipeline.entity.metadata.MetadataEntity;
import com.epam.pipeline.entity.metadata.MetadataFilter;
import com.epam.pipeline.entity.metadata.PipeConfValue;
import com.epam.pipeline.entity.pipeline.CommitStatus;
import com.epam.pipeline.entity.pipeline.Folder;
import com.epam.pipeline.entity.pipeline.Pipeline;
import com.epam.pipeline.entity.pipeline.PipelineRun;
import com.epam.pipeline.entity.pipeline.RunInstance;
import com.epam.pipeline.entity.pipeline.TaskStatus;
import com.epam.pipeline.entity.pipeline.Tool;
import com.epam.pipeline.entity.pipeline.ToolGroup;
import com.epam.pipeline.entity.region.AwsRegion;
import com.epam.pipeline.entity.region.AzureRegion;
import com.epam.pipeline.entity.region.AzureRegionCredentials;
import com.epam.pipeline.entity.region.CloudProvider;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public final class ObjectCreatorUtils {
private static final String TEST_REVISION_1 = "testtest1";
private static final String TEST_NAME = "TEST";
private static final String TEST_POD_ID = "pod1";
private static final String TEST_SERVICE_URL = "service_url";
public static final int TEST_DISK_SIZE = 100;
private ObjectCreatorUtils() {
}
public static DataStorageVO constructDataStorageVO(String name, String description, DataStorageType storageType,
String path, Integer stsDuration, Integer ltsDuration,
Long parentFolderId, String mountPoint, String mountOptions) {
DataStorageVO storageVO = constructDataStorageVO(name, description, storageType, path, parentFolderId,
mountPoint, mountOptions);
StoragePolicy policy = new StoragePolicy();
if (stsDuration != null) {
policy.setShortTermStorageDuration(stsDuration);
}
if (ltsDuration != null) {
policy.setLongTermStorageDuration(ltsDuration);
}
storageVO.setStoragePolicy(policy);
return storageVO;
}
public static DataStorageVO constructDataStorageVO(String name, String description, DataStorageType storageType,
String path, Long parentFolderId, String mountPoint,
String mountOptions) {
DataStorageVO storageVO = new DataStorageVO();
if (name != null) {
storageVO.setName(name);
}
if (path != null) {
storageVO.setPath(path);
}
if (description != null) {
storageVO.setDescription(description);
}
if (storageType != null) {
storageVO.setType(storageType);
}
storageVO.setMountOptions(mountOptions);
storageVO.setMountPoint(mountPoint);
if (parentFolderId != null) {
storageVO.setParentFolderId(parentFolderId);
}
return storageVO;
}
public static PipelineVO constructPipelineVO(String name, String repo, String repoSsh, Long parentFolderId) {
PipelineVO pipeline = new PipelineVO();
pipeline.setName(name);
pipeline.setRepository(repo);
pipeline.setRepositorySsh(repoSsh);
pipeline.setParentFolderId(parentFolderId);
return pipeline;
}
public static Pipeline constructPipeline(String name, String repo, String repoSsh, Long parentFolderId) {
Pipeline pipeline = new Pipeline();
pipeline.setName(name);
pipeline.setRepository(repo);
pipeline.setRepositorySsh(repoSsh);
pipeline.setParentFolderId(parentFolderId);
return pipeline;
}
public static RunConfiguration createConfiguration(String name, String description,
Long parentFolderId, String owner,
List<AbstractRunConfigurationEntry> entries) {
RunConfiguration configuration = new RunConfiguration();
configuration.setName(name);
if (parentFolderId != null) {
configuration.setParent(new Folder(parentFolderId));
}
configuration.setDescription(description);
configuration.setOwner(owner);
configuration.setEntries(entries);
return configuration;
}
public static RunConfigurationEntry createConfigEntry(String name, boolean defaultEntry,
PipelineConfiguration configuration) {
RunConfigurationEntry entry = new RunConfigurationEntry();
entry.setName(name);
entry.setDefaultConfiguration(defaultEntry);
entry.setConfiguration(configuration);
return entry;
}
public static FirecloudRunConfigurationEntry createFirecloudConfigEntry(String name,
List<InputsOutputs> inputs,
List<InputsOutputs> outputs,
String methodName, String methodSnapshot,
String configName) {
FirecloudRunConfigurationEntry entry = new FirecloudRunConfigurationEntry();
entry.setName(name);
entry.setMethodInputs(inputs);
entry.setMethodOutputs(outputs);
entry.setMethodName(methodName);
entry.setMethodSnapshot(methodSnapshot);
entry.setMethodConfigurationName(configName);
return entry;
}
public static RunConfigurationVO createRunConfigurationVO(String name, String description, Long parentFolderId,
List<AbstractRunConfigurationEntry> entries) {
RunConfigurationVO runConfigurationVO = new RunConfigurationVO();
runConfigurationVO.setName(name);
runConfigurationVO.setDescription(description);
runConfigurationVO.setParentId(parentFolderId);
runConfigurationVO.setEntries(entries);
return runConfigurationVO;
}
public static DockerRegistryVO createDockerRegistryVO(String name, String user, String password) {
DockerRegistryVO dockerRegistryVO = new DockerRegistryVO();
dockerRegistryVO.setPath(name);
dockerRegistryVO.setUserName(user);
dockerRegistryVO.setPassword(password);
return dockerRegistryVO;
}
public static ToolGroup createToolGroup(String name, Long registryId) {
ToolGroup toolGroup = new ToolGroup();
toolGroup.setName(name);
toolGroup.setRegistryId(registryId);
return toolGroup;
}
public static Folder createFolder(String name, Long parentId) {
Folder folder = new Folder();
folder.setName(name);
folder.setParentId(parentId);
return folder;
}
public static MetadataClass createMetadataClass(String name) {
MetadataClass metadataClass = new MetadataClass();
metadataClass.setName(name);
return metadataClass;
}
public static MetadataEntity createMetadataEntity(Folder folder, MetadataClass metadataClass, String name,
String externalId, Map<String, PipeConfValue> data) {
MetadataEntity metadataEntity = new MetadataEntity();
metadataEntity.setName(name);
metadataEntity.setClassEntity(metadataClass);
metadataEntity.setExternalId(externalId);
metadataEntity.setParent(folder);
metadataEntity.setData(data);
return metadataEntity;
}
public static MetadataEntityVO createMetadataEntityVo(Long classId, Long parentId,
String name, String externalId,
Map<String, PipeConfValue> data) {
MetadataEntityVO vo = new MetadataEntityVO();
vo.setClassId(classId);
vo.setEntityName(name);
vo.setExternalId(externalId);
vo.setParentId(parentId);
vo.setData(data);
return vo;
}
public static MetadataFilter createMetadataFilter(String metadataClass, Long folderId,
Integer pageSize, Integer page) {
MetadataFilter filter = new MetadataFilter();
filter.setFolderId(folderId);
filter.setMetadataClass(metadataClass);
filter.setPage(page);
filter.setPageSize(pageSize);
return filter;
}
public static S3bucketDataStorage clone(S3bucketDataStorage s3Bucket) {
S3bucketDataStorage storage = new S3bucketDataStorage(
s3Bucket.getId(), s3Bucket.getName(), s3Bucket.getPath(),
s3Bucket.getStoragePolicy(), s3Bucket.getMountPoint());
storage.setParentFolderId(s3Bucket.getParentFolderId());
storage.setParent(s3Bucket.getParent());
storage.setMountOptions(s3Bucket.getMountOptions());
storage.setOwner(s3Bucket.getOwner());
storage.setDescription(s3Bucket.getDescription());
storage.setRegionId(s3Bucket.getRegionId());
storage.setAllowedCidrs(new ArrayList<>(s3Bucket.getAllowedCidrs()));
return storage;
}
public static S3bucketDataStorage createS3Bucket(Long id, String name, String path, String owner) {
S3bucketDataStorage s3bucketDataStorage = new S3bucketDataStorage(id, name, path);
s3bucketDataStorage.setOwner(owner);
return s3bucketDataStorage;
}
public static PipelineRun createPipelineRun(Long runId, Long pipelineId,
Long parentRunId, Long regionId) {
PipelineRun run = new PipelineRun();
run.setId(runId);
run.setPipelineId(pipelineId);
run.setVersion(TEST_REVISION_1);
run.setStartDate(new Date());
run.setEndDate(new Date());
run.setStatus(TaskStatus.RUNNING);
run.setCommitStatus(CommitStatus.NOT_COMMITTED);
run.setLastChangeCommitTime(new Date());
run.setPodId(TEST_POD_ID);
run.setOwner(TEST_NAME);
run.setParentRunId(parentRunId);
run.setServiceUrl(TEST_SERVICE_URL);
RunInstance instance = new RunInstance();
instance.setSpot(true);
instance.setNodeId("1");
instance.setCloudRegionId(regionId);
instance.setCloudProvider(CloudProvider.AWS);
run.setInstance(instance);
return run;
}
public static AwsRegion getDefaultAwsRegion() {
AwsRegion region = new AwsRegion();
region.setRegionCode("us-east-1");
region.setName("US East");
region.setDefault(true);
return region;
}
public static AzureRegion getDefaultAzureRegion(final String resourceGroup,
final String storageAcc) {
AzureRegion region = new AzureRegion();
region.setDefault(true);
region.setProvider(CloudProvider.AZURE);
region.setResourceGroup(resourceGroup);
region.setStorageAccount(storageAcc);
return region;
}
public static AzureRegionCredentials getAzureCredentials(final String storageKey) {
AzureRegionCredentials creds = new AzureRegionCredentials();
creds.setStorageAccountKey(storageKey);
return creds;
}
public static Tool createTool(final String image, final Long toolGroupId) {
Tool tool = new Tool();
tool.setImage(image);
tool.setToolGroupId(toolGroupId);
tool.setCpu("100");
tool.setDisk(TEST_DISK_SIZE);
tool.setRam("100");
return tool;
}
} | 42.914286 | 117 | 0.662746 |
3e8b46cb76ab67dcc8501deb75c34fb1a118ff15 | 4,275 | /*
* Copyright (c) 2015 Christian Chevalley
* This file is part of Project Ethercis
*
* 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.ethercis.dao.access.interfaces;
import com.ethercis.dao.access.support.DataAccess;
import com.ethercis.dao.access.support.ServiceDataAccess;
import com.ethercis.ehr.knowledge.I_KnowledgeCache;
import com.ethercis.opt.query.I_IntrospectCache;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import java.sql.Connection;
import java.util.Map;
/**
* Helper to hold SQL context and knowledge cache reference
* Created by Christian Chevalley on 4/21/2015.
*/
public interface I_DomainAccess {
String PG_POOL = "PG_POOL";
String DBCP2_POOL = "DBCP2_POOL";
String KEY_MAX_IDLE = "max_idle";
String KEY_MAX_ACTIVE = "max_active";
String KEY_REMOVE_ABANDONNED = "remove_abandonned";
String KEY_REMOVE_ABANDONNED_TIMEOUT = "remove_abandonned_timeout";
String KEY_TEST_ON_BORROW = "test_on_borrow";
String KEY_LOG_ABANDONNED = "log_abandonned";
String KEY_AUTO_RECONNECT = "auto_reconnect";
String KEY_DIALECT = "dialect";
String KEY_URL = "url";
String KEY_LOGIN = "login";
String KEY_PASSWORD = "password";
String KEY_KNOWLEDGE = "knowledge";
String KEY_HOST = "host";
String KEY_PORT = "port";
String KEY_MAX_CONNECTION = "max_connection";
String KEY_INITIAL_CONNECTIONS = "initial_connections";
String KEY_CONNECTION_MODE = "connection_mode";
String KEY_DATABASE = "database";
String KEY_WAIT_MS = "wait_milliseconds";
String KEY_SCHEMA = "schema";
String KEY_SET_POOL_PREPARED_STATEMENTS = "set_pool_prepared_statement";
String KEY_SET_MAX_PREPARED_STATEMENTS = "set_max_prepared_statements";
String KEY_INTROSPECT_CACHE = "introspect";
//added to deal with postgresql jdbc 42.2.2 (https://github.com/pgjdbc/pgjdbc)
//as of v1.3 jdbc parameters can be passed prefixed with 'pgjdbc.' f.e. 'pgjdbc.ssl="true"'
String KEY_PGJDBC_PREFIX = "pgjdbc";
String[] pgjdbc_booleanArg = {"ssl", "allowEncodingChanges", "logUnclosedConnections", "tcpKeepAlive", "readOnly", "disableColumnSanitiser", "loadBalanceHosts", "reWriteBatchedInserts"};
String[] pgjdbc_integerArg = {"sendBufferSize", "recvBufferSize", "prepareThreshold", "preparedStatementCacheQueries",
"preparedStatementCacheSizeMiB", "defaultRowFetchSize", "loginTimeout", "connectTimeout",
"socketTimeout", "hostRecheckSeconds"};
/**
* get jOOQ SQL dialect
* @return SQLDialect
* @see org.jooq.SQLDialect
*/
SQLDialect getDialect();
/**
* get the JDBC connection to the DB
* @return Connection
* @see java.sql.Connection
*/
Connection getConnection();
/**
* have JOOQ release the DB connection
*/
void releaseConnection(Connection connection);
/**
* get the jOOQ DSL context to perform DB queries
* @return DSLContext
* @see org.jooq.DSLContext
*/
DSLContext getContext();
/**
* get the interface to the current knowledge cache
* @return I_KnowledgeCache
* @see com.ethercis.ehr.knowledge.I_KnowledgeCache
*/
I_KnowledgeCache getKnowledgeManager();
I_IntrospectCache getIntrospectCache();
static I_DomainAccess getInstance(Map<String, Object> properties) throws Exception {
return new ServiceDataAccess(properties);
}
static I_DomainAccess getInstance(DataAccess dataAccess) throws Exception {
return new ServiceDataAccess(dataAccess);
}
I_IntrospectCache initializeIntrospectCache() throws Exception;
void setKnowledgeManager(I_KnowledgeCache knowledgeCache);
String getServerNodeId();
DataAccess getDataAccess();
}
| 34.475806 | 190 | 0.72538 |
e3b24e7b93cd0ebca5c7b805c90df9453dbca4a1 | 3,133 | package tk.greydynamics.Entity;
import tk.greydynamics.Game.Core;
import tk.greydynamics.Resource.ResourceHandler.ResourceType;
import tk.greydynamics.Resource.Frostbite3.EBX.EBXExternalGUID;
import tk.greydynamics.Resource.Frostbite3.EBX.Structure.EBXStructureFile;
import tk.greydynamics.Resource.Frostbite3.EBX.Structure.Entry.EBXMeshVariationDatabaseEntry;
import tk.greydynamics.Resource.Frostbite3.EBX.Structure.Entry.EBXMeshVariationDatabaseMaterial;
import tk.greydynamics.Resource.Frostbite3.EBX.Structure.Entry.EBXObjArray;
import tk.greydynamics.Resource.Frostbite3.EBX.Structure.Entry.EBXTextureShaderParameter.ParameterName;
import tk.greydynamics.Resource.Frostbite3.MESH.MeshVariationDatabaseHandler;
import tk.greydynamics.Resource.Frostbite3.Toc.ResourceLink;
public class EntityTextureData {
private int[] diffuseIDs;
private EBXExternalGUID meshGUID = null;
//private EBXExternalGUID materialGUID = null;
public EntityTextureData(EBXExternalGUID meshGUID, /*EBXExternalGUID materialGUID,*/ EBXStructureFile meshVariationDatabase) {
this.meshGUID = meshGUID;
//this.materialGUID = materialGUID;
updateTextures(meshVariationDatabase);
}
public boolean updateTextures(EBXStructureFile meshVariationDatabase){
if (meshGUID!=null&&meshVariationDatabase!=null){
MeshVariationDatabaseHandler dbH = Core.getGame().getResourceHandler().getMeshVariationDatabaseHandler();
EBXMeshVariationDatabaseEntry entry = dbH.getVariationDatabaseEntry(meshVariationDatabase, -1, this.meshGUID, false);
if (entry!=null){
EBXObjArray materialsArr = entry.getMaterials();
if (materialsArr!=null){
Object[] materials = materialsArr.getObjects();
diffuseIDs = new int[materials.length];
int counter = 0;
for (Object obj : materials){
EBXMeshVariationDatabaseMaterial material = (EBXMeshVariationDatabaseMaterial) obj;
boolean diffuseSuccess = false;
if (material!=null){
//Diffuse
EBXExternalGUID diffuseTextureGUID = dbH.getTexture(material, ParameterName.Diffuse);
if (diffuseTextureGUID!=null){
ResourceLink diffuseLinkEBX = Core.getGame().getResourceHandler().getResourceLinkByEBXGUID(diffuseTextureGUID.getFileGUID());
if (diffuseLinkEBX!=null){
ResourceLink diffuseLinkITEXTURE = Core.getGame().getResourceHandler().getResourceLink(diffuseLinkEBX.getName(), ResourceType.ITEXTURE);
if (diffuseLinkITEXTURE!=null){
diffuseIDs[counter] = Core.getGame().getResourceHandler().getTextureHandler().loadITexture(diffuseLinkITEXTURE);
diffuseSuccess = true;
}
}
}
//Specular
//Normal
}
if (!diffuseSuccess){
diffuseIDs[counter] = Core.getGame().getModelHandler().getLoader().getNotFoundID();
}
counter++;
}
}
}
return true;
}
this.diffuseIDs = null;
return false;
}
public int[] getDiffuseIDs() {
return diffuseIDs;
}
public EBXExternalGUID getMeshGUID() {
return meshGUID;
}
}
| 38.207317 | 146 | 0.73029 |
fb73b42cee86eb5ba36f5cb4c36df40211bbba4a | 135 | class TypeAnnoOnMethodTypeParameterBound {
<T extends @Anno String & java.util.@Anno(2) Map<Integer, @Anno(3) String>> void m() {}
}
| 33.75 | 89 | 0.711111 |
8cf8e71c90491a23ca1b496607c8a40d5b0ccfa9 | 1,855 | package com.lollito.releasedashboard.dto;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
public class RepositoryResponse {
private String name;
private String release;
@JsonFormat(pattern = "dd-MM-yyyy")
private Date releaseDate;
private Long releaseCommits;
private String compare;
@JsonFormat(pattern = "dd-MM-yyyy")
private Date compareDate;
private Long compareCommits;
private Long diffCommits;
private Long diffDays;
private String status;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public Date getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public Long getReleaseCommits() {
return releaseCommits;
}
public void setReleaseCommits(Long releaseCommits) {
this.releaseCommits = releaseCommits;
}
public String getCompare() {
return compare;
}
public void setCompare(String compare) {
this.compare = compare;
}
public Date getCompareDate() {
return compareDate;
}
public void setCompareDate(Date compareDate) {
this.compareDate = compareDate;
}
public Long getCompareCommits() {
return compareCommits;
}
public void setCompareCommits(Long compareCommits) {
this.compareCommits = compareCommits;
}
public Long getDiffCommits() {
return diffCommits;
}
public void setDiffCommits(Long diffCommits) {
this.diffCommits = diffCommits;
}
public Long getDiffDays() {
return diffDays;
}
public void setDiffDays(Long diffDays) {
this.diffDays = diffDays;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| 17.336449 | 53 | 0.734771 |
90f3589aba365e3c4f2ea2b7dd729c344060921f | 167 | package dev.abarmin.home.is.backend.readings.model.device;
/**
* @author Aleksandr Barmin
*/
public enum ImportDeviceFeature {
READINGS,
INVOICES,
RECEIPTS
}
| 15.181818 | 58 | 0.736527 |
d6d5909093270622a9945bab1ec4f319d2d961ca | 3,207 | package org.obd.metrics.api;
import java.io.IOException;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.obd.metrics.DataCollector;
public class StatisticsTest {
@Test
public void mode01WorkflowTest() throws IOException, InterruptedException {
var collector = new DataCollector();
var workflow = SimpleWorkflowFactory.getMode01Workflow(collector);
var query = Query.builder()
.pid(6l) // Engine coolant temperature
.pid(12l) // Intake manifold absolute pressure
.pid(13l) // Engine RPM
.pid(16l) // Intake air temperature
.pid(18l) // Throttle position
.pid(14l) // Vehicle speed
.build();
var connection = MockConnection.builder()
.commandReply("0100", "4100be3ea813")
.commandReply("0200", "4140fed00400")
.commandReply("01 0B 0C 11 0D 0F 05", "00e0:410bff0c00001:11000d000f00052:00aaaaaaaaaaaa")
.build();
var optional = Adjustments.builder()
.initDelay(0)
.batchEnabled(true)
.build();
workflow.start(connection, query, optional);
WorkflowFinalizer.finalizeAfter(workflow,1000l);
var pids = workflow.getPidRegistry();
var engineTemp = pids.findBy(6l);
Assertions.assertThat(engineTemp.getPid()).isEqualTo("05");
Assertions.assertThat(workflow.getStatisticsRegistry().getRatePerSec(engineTemp)).isGreaterThan(10d);
Assertions.assertThat(workflow.getStatisticsRegistry().getRatePerSec(pids.findBy(12l))).isGreaterThan(10d);
}
@Test
public void genericWorkflowTest() throws IOException, InterruptedException {
var collector = new DataCollector();
var workflow = SimpleWorkflowFactory.getMode22Workflow(collector);
var query = Query.builder()
.pid(8l) // Coolant
.pid(4l) // RPM
.pid(7l) // Intake temp
.pid(15l)// Oil temp
.pid(3l) // Spark Advance
.build();
var connection = MockConnection.builder()
.commandReply("221003", "62100340")
.commandReply("221000", "6210000BEA")
.commandReply("221935", "62193540")
.commandReply("22194f", "62194f2d85")
.build();
workflow.start(connection, query, Adjustments.builder().initDelay(0).build());
WorkflowFinalizer.finalizeAfter500ms(workflow);
var pids = workflow.getPidRegistry();
var pid8l = pids.findBy(8l);
var stat8l = workflow.getStatisticsRegistry().findBy(pid8l);
Assertions.assertThat(stat8l).isNotNull();
var pid4l = pids.findBy(4l);
var stat4L = workflow.getStatisticsRegistry().findBy(pid4l);
Assertions.assertThat(stat4L).isNotNull();
Assertions.assertThat(stat4L.getMax()).isEqualTo(762);
Assertions.assertThat(stat4L.getMin()).isEqualTo(762);
Assertions.assertThat(stat4L.getMedian()).isEqualTo(762);
Assertions.assertThat(stat8l.getMax()).isEqualTo(-1);
Assertions.assertThat(stat8l.getMin()).isEqualTo(-1);
Assertions.assertThat(stat8l.getMedian()).isEqualTo(-1);
Assertions.assertThat(workflow.getStatisticsRegistry().getRatePerSec(pid8l)).isGreaterThan(10d);
Assertions.assertThat(workflow.getStatisticsRegistry().getRatePerSec(pid4l)).isGreaterThan(10d);
}
}
| 33.061856 | 109 | 0.698472 |
101378f463789789c7c8c669029eff43a018d1c3 | 1,832 | package tv.camment.cammentsdk.sofa;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import java.util.concurrent.Executors;
import tv.camment.cammentsdk.asyncclient.CammentCallback;
import tv.camment.cammentsdk.utils.LogUtils;
public class SofaBgImageView extends AppCompatImageView {
public SofaBgImageView(Context context) {
this(context, null);
}
public SofaBgImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setImageUrl(String imageUrl) {
setVisibility(INVISIBLE);
Glide.with(getContext()).asBitmap().load(imageUrl).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
new SofaBitmapClient(Executors.newSingleThreadExecutor()).processBitmap(resource, getMeasuredWidth(), getMeasuredHeight(), new CammentCallback<SofaBitmapClient.BitmapResult>() {
@Override
public void onSuccess(SofaBitmapClient.BitmapResult bitmapResult) {
setImageBitmap(bitmapResult.result);
setVisibility(VISIBLE);
}
@Override
public void onException(Exception exception) {
LogUtils.debug("onException", "processSofaBgImage", exception);
}
});
}
});
}
}
| 34.566038 | 193 | 0.671943 |
1e503fb46e68066b6773922486f2094cb6c55fa3 | 1,178 | package lk.sliit.hotelManagement.entity.restaurant.onlineOrder;
import javax.persistence.Embeddable;
import java.io.Serializable;
@Embeddable
public class RestaurantOnlineOrderDetailsPK implements Serializable {
private int foodItemId;
private int restaurantOnlineOrder;
public RestaurantOnlineOrderDetailsPK(int foodItemId, int restaurantOnlineOrder) {
this.foodItemId = foodItemId;
this.restaurantOnlineOrder = restaurantOnlineOrder;
}
public RestaurantOnlineOrderDetailsPK() {
}
public int getFoodItemId() {
return foodItemId;
}
public void setFoodItemId(int foodItemId) {
this.foodItemId = foodItemId;
}
public int getRestaurantOnlineOrderId() {
return restaurantOnlineOrder;
}
public void setRestaurantOnlineOrderId(int restaurantOnlineOrderId) {
this.restaurantOnlineOrder = restaurantOnlineOrderId;
}
@Override
public String toString() {
return "RestaurantOnlineOrderDetailsPK{" +
"foodItemId='" + foodItemId + '\'' +
", restaurantOnlineOrder='" + restaurantOnlineOrder + '\'' +
'}';
}
}
| 26.772727 | 86 | 0.688455 |
90201162af6a86ae6175f7c731199de90567623c | 8,037 | package pirexGUI;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import sourceProcessor.SourceProcessor;
/**
*
* @author Andrew Fuller
*
*/
public class LoadTab extends JPanel implements ActionListener
{
public static SourceProcessor sp;
public static List<SourceProcessor> spList = new ArrayList<SourceProcessor>();
static final String LOAD_TAB_BROWSE = "LOAD_TAB_BROWSE";
static final String LOAD_TAB_PROCESS = "LOAD_TAB_PROCESS";
static final String LOAD_TAB_CLEAR = "LOAD_TAB_CLEAR";
private static final long serialVersionUID = 1L;
int ordNum = 0;
JFileChooser fileDialog;
String pathResult;
// Load tab components
JButton browseBtn, btnProcess, loadTabClearBtn;
JComboBox<String> fileType;
JTextField textFileField, titleTextField, authorTextField;
JTextArea processTextArea;
/**
* Creates a JPanel object to be used in JTabbedPane
*
*/
public LoadTab()
{
super();
setLayout(new BorderLayout()); // set layout for container to BorderLayout
JPanel north = new JPanel(new BorderLayout()); // create north JPanel w/ BorderLayout
JPanel south = new JPanel(new BorderLayout()); // create south JPanel w/ BorderLayout
JPanel n1 = new JPanel(new BorderLayout()); // create n1 JPanel w/ BorderLayout. Part of north panel
JPanel n2 = new JPanel(new BorderLayout()); // create n2 JPanel w/ BorderLayout. Part of north panel
JPanel n3 = new JPanel(new GridLayout(1,2)); // create n3 JPanel w/ GridLayout. Part of north panel
JPanel s1 = new JPanel(new BorderLayout()); // create s1 JPanel w/ BorderLayout. Part of south panel
JPanel s2 = new JPanel(new BorderLayout()); // create s2 JPanel w/ BorderLayout. Part of south panel
JLabel textFileLabel = new JLabel("Text File:"); // create Text File label
textFileField = new JTextField(); // create text field for file name
textFileField.addActionListener(this); // add action listener to text field
btnProcess = new JButton("Process"); // create Process JButton
btnProcess.setEnabled(false); // disable button
btnProcess.setActionCommand(LOAD_TAB_PROCESS); // set action command of Process button
Document doc = textFileField.getDocument(); // create a javax.swing.text Document
doc.addDocumentListener(new DocumentListener() // add/create Document listener
{
public void insertUpdate(DocumentEvent e)
{
updateEnable(e);
}
public void removeUpdate(DocumentEvent e)
{
updateEnable(e);
}
public void changedUpdate(DocumentEvent e)
{
updateEnable(e);
}
public void updateEnable(DocumentEvent e) // if file name text field is populated, enable Process button
{
boolean enable = e.getDocument().getLength() > 0;
btnProcess.setEnabled(enable);
}
});
browseBtn = new JButton("Browse"); // create Browse JButton
browseBtn.setActionCommand(LOAD_TAB_BROWSE); // set action command for Browse button
JLabel titleLabel = new JLabel("Title:"); // create Title JLabel
titleTextField = new JTextField(); // create title text field
JLabel authorLabel = new JLabel("Author:"); // create Author JLabel
authorTextField = new JTextField(); // create author text field
JLabel textFileTypeLabel = new JLabel("Text File Type:"); // create Text File Type JLabel
fileType = new JComboBox<String>(); // create file type JComboBox
fileType.addItem("Project Gutenberg File"); // add Project Gutenberg File type
fileType.addActionListener(this); // add action listener to file type combo box
processTextArea = new JTextArea(); // create process text area JTextArea
processTextArea.setEditable(false); // disable editing
loadTabClearBtn = new JButton("Clear"); // create Clear JButton
loadTabClearBtn.setActionCommand(LOAD_TAB_CLEAR); // set action command for Clear button
n1.add(textFileLabel, BorderLayout.WEST); // add text file label to n1, WEST
n1.add(textFileField, BorderLayout.CENTER); // add text file field to n1, CENTER
n1.add(browseBtn, BorderLayout.EAST); // add Browse button to n1, EAST
north.add(n1, BorderLayout.NORTH); // add n1 to north, NORTH
n2.add(textFileTypeLabel, BorderLayout.WEST); // add text file type label to n2, WEST
n2.add(fileType, BorderLayout.CENTER); // add file type combo box to n2, CENTER
north.add(n2, BorderLayout.CENTER); // add n2 to north, CENTER
JPanel n31 = new JPanel(new BorderLayout()); // create n31 JPanel w/ BorderLayout. Part of n3
n31.add(titleLabel, BorderLayout.WEST); // add title label to n31, WEST
n31.add(titleTextField, BorderLayout.CENTER); // add title text field to n31, CENTER
n3.add(n31); // add n31 to n3
JPanel n32 = new JPanel(new BorderLayout()); // create n32 JPanel w/ BorderLayout. Part of n3
n32.add(authorLabel, BorderLayout.WEST); // add author label to n32, WEST
n32.add(authorTextField, BorderLayout.CENTER); // add author text field to n32, CENTER
n3.add(n32); // add n32 to n3
north.add(n3, BorderLayout.SOUTH); // add n3 to north, SOUTH
JPanel btnPanel = new JPanel(new GridLayout(1,2)); // create JPanel for Process and Clear buttons
btnPanel.add(btnProcess); // add Process button to btnPanel
btnPanel.add(loadTabClearBtn); // add Clear button to btnPanel
s1.add(btnPanel, BorderLayout.WEST); // add btnPanel to s1, WEST
south.add(s1, BorderLayout.NORTH); // add s1 to south, NORTH
s2.add(processTextArea, BorderLayout.CENTER); // add process text area to s2, CENTER
south.add(s2, BorderLayout.CENTER); // add s2 to south, CENTER
add(north, BorderLayout.NORTH); // add north to container, NORTH
add(south, BorderLayout.CENTER); // add south to container, CENTER
}
/**
* Creates JFileChooser object that lets you search your local file system for a text file.
* Upon approved selection, automatically searches document for title and author lines.
*
* @throws IOException -
*/
public void browse() throws IOException
{
fileDialog = new JFileChooser();
int returnVal = fileDialog.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
pathResult = fileDialog.getSelectedFile().getAbsolutePath();
textFileField.setText(pathResult);
if (fileType.getSelectedItem().equals("Project Gutenberg File"))
{
titleTextField.setText(SourceProcessor.getTitleFromFile(pathResult));
authorTextField.setText(SourceProcessor.getAuthorFromFile(pathResult));
}
}
}
/**
* Clears text fields/area.
*/
public void clear()
{
textFileField.setText("");
titleTextField.setText("");
authorTextField.setText("");
processTextArea.setText("");
}
@Override
public void actionPerformed(ActionEvent e)
{
}
}
| 39.591133 | 115 | 0.667538 |
c8bde5560fcae0c5800b519c7fd7b90042e6b957 | 1,446 | package org.jeff.lune.object;
import java.util.HashMap;
/**
* Lune语言中数据结构的对象 -在C/C++中将使用Union进行表示
* struct LuneObject
* {
* int type;
* union{
* long long iValue;
* double fValue;
* char* sValue;
* bool bValue;
* // 这些需要待实际写的时候看怎么定义
* List* lValue;
* Dict* dValue;
* Function* mValue;
* Class* cValue;
* } value;
* }
* obj (可以是数字,字符,布尔值,列表,字典,函数,类等)
* @author 覃贵锋
*
*/
public class LunePropertyObject extends LuneObject
{
/**
* 对象的属性列表 - 这里采用字段存储,Lune中对象的所有属性访问都来自此字典中,不准备支持反射,方便与C/C++保持一致。
* 这里的属性对象即包括基本的数据类型,也包含列表,字段,类对象,函数等复杂对象。
*/
HashMap<String, LuneObject> __attributes = new HashMap<String, LuneObject>();
/** 创建默认的LuneObject对象,value_为空值 */
public LunePropertyObject()
{
this.objType = LuneObjectType.None;
}
/**
* 对象内部进行拷贝
* @param v
*/
public LunePropertyObject(LuneObject v)
{
this.SetValue(v);
}
/**
* 设置对象的值是一个Lune对象
* @param v
*/
public void SetValue(LuneObject v)
{
//TODO 这里不能简单的赋值,因为如果这个对象是复杂对象需要进行一些处理
this.value_ = v.value_;
this.objType = v.objType;
}
@Override
public boolean toBool() throws Exception
{
if(this.objType == LuneObjectType.OBJECT)
return !this.__attributes.isEmpty();
return super.toBool();
}
public LuneObject GetAttribute(String name)
{
return this.__attributes.get(name);
}
public void SetAttribute(String name, LuneObject value)
{
this.__attributes.put(name, value);
}
}
| 19.28 | 78 | 0.665284 |
aa35178c3336655fd182e845b4e77a13749c4030 | 4,148 | package com.cc.mobilesafe.Service;
import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
import com.cc.mobilesafe.Engine.BlackNumberDao;
import com.cc.mobilesafe.Reciver.BlackNumberContentObserver;
import com.cc.mobilesafe.Reciver.BlackNumberReciver;
import com.cc.mobilesafe.Service.AddressService.MyPhoneStateListener;
import com.cc.mobilesafe.Utils.LogUtils;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
public class BlackNumberService extends Service {
private static final String TAG = "BlackNumberService++++++++++++++";
private BlackNumberReciver blackNumberReciver;
private TelephonyManager telephonyManager;
private MyPhoneStateListener myPhoneStateListener;
private BlackNumberDao mDao;
private ContentResolver contentResolver;
private Uri uri;
private BlackNumberContentObserver blackNumberContentObserver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.setPriority(1000);
blackNumberReciver = new BlackNumberReciver();
registerReceiver(blackNumberReciver, filter);
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
myPhoneStateListener = new MyPhoneStateListener();
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
mDao = BlackNumberDao.getInstance(getApplicationContext());
super.onCreate();
}
/**
* @author Rhymedys 继承监听电话状态改变
*/
class MyPhoneStateListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
//
switch (state) {
// 摘机状态
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
// 空闲状态
case TelephonyManager.CALL_STATE_IDLE:
break;
// 来电状态
case TelephonyManager.CALL_STATE_RINGING:
endCall(incomingNumber);
break;
default:
break;
}
super.onCallStateChanged(state, incomingNumber);
}
}
/**
* 挂断电话
*/
public void endCall(String phone) {
if (mDao == null || TextUtils.isEmpty(phone)) {
return;
}
int queryMode = mDao.queryMode(phone);
if (queryMode == 1 || queryMode == 2) {
// AIDL注意包名
// ITelephony.Stub.asInterface(Context.getService(Context.TELEPHONY_SERVICE));
// import android.os.ServiceManager;
LogUtils.i(TAG, queryMode + "");
try {
Class<?> clazz = Class.forName("android.os.ServiceManager");
// 方法名,方法中形参的的类型
Method method = clazz.getMethod("getService", String.class);
// 反射调用此方法
IBinder iBinder = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE);
ITelephony iTelephony = ITelephony.Stub.asInterface(iBinder);
iTelephony.endCall();
} catch (Exception e) {
LogUtils.i(TAG, " endCall try error ");
e.printStackTrace();
}
}
uri = Uri.parse("content://call_log/calls");
blackNumberContentObserver = new BlackNumberContentObserver(new Handler(), getApplicationContext(), uri, phone);
getContentResolver().registerContentObserver(uri, true, blackNumberContentObserver);
}
@Override
public void onDestroy() {
if (blackNumberReciver != null) {
unregisterReceiver(blackNumberReciver);
}
if (blackNumberContentObserver != null) {
getContentResolver().unregisterContentObserver(blackNumberContentObserver);
}
if (myPhoneStateListener != null) {
telephonyManager.listen(myPhoneStateListener, PhoneStateListener.LISTEN_NONE);
}
LogUtils.i(TAG, "onDestroy+++++++++++");
super.onDestroy();
}
}
| 27.470199 | 115 | 0.729267 |
29e18a80880c00eb0b5b3ee5f7c78cc2b87d7bb8 | 495 | package pipe.gui.imperial.reachability.algorithm;
import pipe.gui.imperial.pipe.models.petrinet.PetriNet;
public class BoundedExplorerUtilities extends CachingExplorerUtilities {
private final int maxNumberOfStates;
public BoundedExplorerUtilities(PetriNet petriNet, int maxNumberOfStates) {
super(petriNet);
this.maxNumberOfStates = maxNumberOfStates;
}
public final boolean canExploreMore(int stateCount) {
return stateCount <= this.maxNumberOfStates;
}
}
| 29.117647 | 78 | 0.781818 |
e821c50c75d31fcb63f62f3fb4807507e2eb356a | 988 | package j2html.comparison;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;
import com.carrotsearch.junitbenchmarks.Clock;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
@Ignore
@BenchmarkOptions(callgc = false, benchmarkRounds = 20_000, warmupRounds = 200, concurrency = 2, clock = Clock.NANO_TIME)
public class RenderPerformanceComparisonTest {
@Rule
public TestRule benchmarkRun = new BenchmarkRule();
@Test
public void j2htmlPerformance() throws Exception {
TestJ2html.helloWorld();
TestJ2html.fiveHundredEmployees();
TestJ2html.macros();
TestJ2html.multiplicationTable();
}
@Test
public void velocityPerformance() throws Exception {
TestVelocity.helloWorld();
TestVelocity.fiveHundredEmployees();
TestVelocity.macros();
TestVelocity.multiplicationTable();
}
}
| 28.228571 | 121 | 0.736842 |
2f6cd27f38d6db5f132efc82dc98cfbad1f23440 | 356 | package zhushen.com.shejimoshi.leetcode;
/**
* Created by Zhushen on 2018/9/10.
*/
public class isOneBitCharacter {
public boolean isOneBitCharacter(int[] bits) {
int len = bits.length;
int i;
for( i=0;i<len-1;i++){
if(bits[i]==1){
i += 1;
}
}
return i==len-1;
}
}
| 19.777778 | 50 | 0.497191 |
97fe4ed0acee09519ea24c46537bd93adc849937 | 8,820 | package com.hbm.tileentity.machine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.hbm.handler.FluidTypeHandler.FluidType;
import com.hbm.interfaces.IConsumer;
import com.hbm.interfaces.IFluidAcceptor;
import com.hbm.interfaces.IFluidContainer;
import com.hbm.inventory.FluidTank;
import com.hbm.inventory.MachineRecipes;
import com.hbm.inventory.MachineRecipes.GasCentOutput;
import com.hbm.lib.Library;
import com.hbm.packet.AuxElectricityPacket;
import com.hbm.packet.AuxGaugePacket;
import com.hbm.packet.LoopedSoundPacket;
import com.hbm.packet.PacketDispatcher;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
public class TileEntityMachineGasCent extends TileEntity implements ISidedInventory, IConsumer, IFluidContainer, IFluidAcceptor {
private ItemStack slots[];
public long power;
public int progress;
public boolean isProgressing;
public static final int maxPower = 100000;
public static final int processingSpeed = 200;
public FluidTank tank;
private static final int[] slots_top = new int[] {3};
private static final int[] slots_bottom = new int[] {5, 6, 7, 8};
private static final int[] slots_side = new int[] {0, 3};
private String customName;
public TileEntityMachineGasCent() {
slots = new ItemStack[9];
tank = new FluidTank(FluidType.UF6, 8000, 0);
}
@Override
public int getSizeInventory() {
return slots.length;
}
@Override
public ItemStack getStackInSlot(int i) {
return slots[i];
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
if(slots[i] != null)
{
ItemStack itemStack = slots[i];
slots[i] = null;
return itemStack;
} else {
return null;
}
}
@Override
public void setInventorySlotContents(int i, ItemStack itemStack) {
slots[i] = itemStack;
if(itemStack != null && itemStack.stackSize > getInventoryStackLimit())
{
itemStack.stackSize = getInventoryStackLimit();
}
}
@Override
public String getInventoryName() {
return this.hasCustomInventoryName() ? this.customName : "container.gasCentrifuge";
}
@Override
public boolean hasCustomInventoryName() {
return this.customName != null && this.customName.length() > 0;
}
public void setCustomName(String name) {
this.customName = name;
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player) {
if(worldObj.getTileEntity(xCoord, yCoord, zCoord) != this)
{
return false;
}else{
return player.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) <=64;
}
}
//You scrubs aren't needed for anything (right now)
@Override
public void openInventory() {}
@Override
public void closeInventory() {}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemStack) {
if(i == 2 || i == 3 || i == 4 || i == 5)
{
return false;
}
return true;
}
@Override
public ItemStack decrStackSize(int i, int j) {
if(slots[i] != null)
{
if(slots[i].stackSize <= j)
{
ItemStack itemStack = slots[i];
slots[i] = null;
return itemStack;
}
ItemStack itemStack1 = slots[i].splitStack(j);
if (slots[i].stackSize == 0)
{
slots[i] = null;
}
return itemStack1;
} else {
return null;
}
}
@Override
public void readFromNBT(NBTTagCompound nbt) {
super.readFromNBT(nbt);
NBTTagList list = nbt.getTagList("items", 10);
power = nbt.getLong("powerTime");
progress = nbt.getShort("CookTime");
tank.readFromNBT(nbt, "tank");
slots = new ItemStack[getSizeInventory()];
for(int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound nbt1 = list.getCompoundTagAt(i);
byte b0 = nbt1.getByte("slot");
if(b0 >= 0 && b0 < slots.length)
{
slots[b0] = ItemStack.loadItemStackFromNBT(nbt1);
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbt) {
super.writeToNBT(nbt);
nbt.setLong("powerTime", power);
nbt.setShort("cookTime", (short) progress);
tank.writeToNBT(nbt, "tank");
NBTTagList list = new NBTTagList();
for(int i = 0; i < slots.length; i++)
{
if(slots[i] != null)
{
NBTTagCompound nbt1 = new NBTTagCompound();
nbt1.setByte("slot", (byte)i);
slots[i].writeToNBT(nbt1);
list.appendTag(nbt1);
}
}
nbt.setTag("items", list);
}
@Override
public int[] getAccessibleSlotsFromSide(int p_94128_1_)
{
return p_94128_1_ == 0 ? slots_bottom : (p_94128_1_ == 1 ? slots_top : slots_side);
}
@Override
public boolean canInsertItem(int i, ItemStack itemStack, int j) {
return this.isItemValidForSlot(i, itemStack);
}
@Override
public boolean canExtractItem(int i, ItemStack itemStack, int j) {
return j != 0 || i != 1 || itemStack.getItem() == Items.bucket;
}
public int getCentrifugeProgressScaled(int i) {
return (progress * i) / processingSpeed;
}
public long getPowerRemainingScaled(int i) {
return (power * i) / maxPower;
}
private boolean canProcess() {
if(power > 0 && this.tank.getFill() >= MachineRecipes.getFluidConsumedGasCent(tank.getTankType())) {
List<GasCentOutput> list = MachineRecipes.getGasCentOutput(tank.getTankType());
if(list == null)
return false;
if(list.size() < 1 || list.size() > 4)
return false;
for(int i = 0; i < list.size(); i++) {
int slot = i + 5;
if(slots[slot] == null)
continue;
if(slots[slot].getItem() == list.get(i).output.getItem() &&
slots[slot].getItemDamage() == list.get(i).output.getItemDamage() &&
slots[slot].stackSize + list.get(i).output.stackSize <= slots[slot].getMaxStackSize())
continue;
return false;
}
return true;
}
return false;
}
private void process() {
List<GasCentOutput> out = MachineRecipes.getGasCentOutput(tank.getTankType());
this.progress = 0;
tank.setFill(tank.getFill() - MachineRecipes.getFluidConsumedGasCent(tank.getTankType()));
List<GasCentOutput> random = new ArrayList();
for(int i = 0; i < out.size(); i++) {
for(int j = 0; j < out.get(i).weight; j++) {
random.add(out.get(i));
}
}
Collections.shuffle(random);
GasCentOutput result = random.get(worldObj.rand.nextInt(random.size()));
int slot = result.slot + 4;
if(slots[slot] == null) {
slots[slot] = result.output.copy();
} else {
slots[slot].stackSize += result.output.stackSize;
}
}
@Override
public void updateEntity() {
if(!worldObj.isRemote) {
power = Library.chargeTEFromItems(slots, 0, power, maxPower);
tank.setType(1, 2, slots);
tank.loadTank(3, 4, slots);
tank.updateTank(xCoord, yCoord, zCoord);
if(canProcess()) {
isProgressing = true;
this.progress++;
this.power -= 200;
if(this.power < 0)
power = 0;
if(progress >= processingSpeed) {
process();
}
} else {
isProgressing = false;
this.progress = 0;
}
PacketDispatcher.wrapper.sendToAll(new AuxElectricityPacket(xCoord, yCoord, zCoord, power));
PacketDispatcher.wrapper.sendToAll(new AuxGaugePacket(xCoord, yCoord, zCoord, progress, 0));
PacketDispatcher.wrapper.sendToAll(new AuxGaugePacket(xCoord, yCoord, zCoord, isProgressing ? 1 : 0, 1));
PacketDispatcher.wrapper.sendToAll(new LoopedSoundPacket(xCoord, yCoord, zCoord));
}
}
@Override
public AxisAlignedBB getRenderBoundingBox() {
return TileEntity.INFINITE_EXTENT_AABB;
}
@Override
@SideOnly(Side.CLIENT)
public double getMaxRenderDistanceSquared()
{
return 65536.0D;
}
@Override
public void setPower(long i) {
power = i;
}
@Override
public long getPower() {
return power;
}
@Override
public long getMaxPower() {
return maxPower;
}
@Override
public void setFillstate(int fill, int index) {
tank.setFill(fill);
}
@Override
public void setType(FluidType type, int index) {
tank.setTankType(type);
}
@Override
public int getMaxFluidFill(FluidType type) {
return type.name().equals(this.tank.getTankType().name()) ? tank.getMaxFill() : 0;
}
@Override
public int getFluidFill(FluidType type) {
return type.name().equals(this.tank.getTankType().name()) ? tank.getFill() : 0;
}
@Override
public void setFluidFill(int i, FluidType type) {
if(type.name().equals(tank.getTankType().name()))
tank.setFill(i);
}
@Override
public List<FluidTank> getTanks() {
List<FluidTank> list = new ArrayList();
list.add(tank);
return list;
}
}
| 23.333333 | 129 | 0.6839 |
b6aead43d6ee73e75cf732590f399eeb3ad2997d | 961 | package frc.robot.commands;
import java.util.function.BooleanSupplier;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.subsystems.OTBSubsystem;
public class OTBCommand extends CommandBase {
private OTBSubsystem subsystem;
private BooleanSupplier bumperSupplier;
private BooleanSupplier aButtonSupplier;
public static final double power = .3;
public OTBCommand(OTBSubsystem subsystem, BooleanSupplier supplier, BooleanSupplier aButtonSupplier) {
this.subsystem = subsystem;
this.bumperSupplier = supplier;
this.aButtonSupplier = aButtonSupplier;
addRequirements(subsystem);
}
@Override
public void execute() {
if (bumperSupplier.getAsBoolean() && !aButtonSupplier.getAsBoolean()) {
subsystem.start();
} else if (aButtonSupplier.getAsBoolean()) {
subsystem.reverse();
} else {
subsystem.stop();
}
}
}
| 29.121212 | 106 | 0.690947 |
5cb39ffb31fe58dd4fee565bcc04e4f1d5a624c8 | 1,401 | /*
* Copyright 2017 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.migration.core.jboss;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Function;
/**
* A function which computes the path of a content, from its hash.
*/
public class ContentHashToPathMapper implements Function<byte[], Path> {
private static char[] table = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
@Override
public Path apply(byte[] bytes) {
final StringBuilder builder = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
builder.append(table[b >> 4 & 0x0f]).append(table[b & 0x0f]);
}
final String hexString = builder.toString();
return Paths.get(hexString.substring(0,2), hexString.substring(2));
}
}
| 33.357143 | 75 | 0.655246 |
53411e11cb98e411d0571d2f019a8682b0ada752 | 1,612 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.debug.internal.ui.script;
import org.eclipse.birt.report.designer.core.IReportElementConstants;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IFile;
import org.eclipse.ui.part.FileEditorInput;
/**
*
*/
public class ScriptDebuggerPropertyTester extends PropertyTester
{
/**
*
*/
public ScriptDebuggerPropertyTester( )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.core.expressions.IPropertyTester#test(java.lang.Object,
* java.lang.String, java.lang.Object[], java.lang.Object)
*/
public boolean test( Object receiver, String property, Object[] args,
Object expectedValue )
{
if ( property.equals( "isRptdesign" ) )//$NON-NLS-1$
{
IFile file = null;
if ( receiver instanceof FileEditorInput )
{
FileEditorInput input = (FileEditorInput) receiver;
if ( input.getFile( ) != null
&& IReportElementConstants.DESIGN_FILE_EXTENSION.equals( input.getFile( )
.getFileExtension( ) ) )
{
return true;
}
}
}
return false;
}
}
| 26.42623 | 81 | 0.638337 |
de7ed99651430db84b38f2aede03ecc7be1a5016 | 621 | package cn.sxt.service;
import java.util.List;
import cn.sxt.pojo.Pagination;
import cn.sxt.pojo.RentTable;
public interface RentTableService {
/**
* 生成出租单
*
* @param rentTable
*/
public void makeRenttable(RentTable rentTable);
/**
* 查询所有出租单
*
* @return
*/
public List<RentTable> selAllRentTables();
/**
* 得到所有的出租单编号
*
* @return
*/
public List<RentTable> selAllTableId();
/**
* 根据出租单编号查询信息
*
* @param tableId
* @return
*/
public List<RentTable> selByTableID(Integer tableId);
public Pagination<RentTable> selRentTable(int page, int rows,
RentTable rentTable);
}
| 14.44186 | 62 | 0.669887 |
d8a2ed5e672c0791e84d63ccc3ebbb151bb3f921 | 2,972 | package lv.dium.riskclient;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import java.util.Random;
public class ActionButton extends Actor {
Sprite sprite;
public String label = "Click me!";
public String action = "";
public boolean isHandled = false;
public ActionButton(final float x, final float y) {
Texture texture = ActorExample.manager.get(AssetDescriptors.hex);
texture.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear);
sprite = new Sprite(texture);
spritePos(x, y);
setTouchable(Touchable.enabled);
final ActionButton currentActor = this;
addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float mx, float my, int pointer, int button) {
double r = 54f; // radius
double s = 6f; // sides
double cx = 57f;
double cy = 50f;
double m = r * Math.cos(Math.PI / s); // the min dist from an edge to the center
double d = Math.hypot(mx-cx, my-cy), // the mouse's distance to the center of the polygon
a = Math.atan2(cy-my, mx-cx); // angle of the mouse pointer
if(d <= (r+m)/2 + Math.cos(a*s) * (r-m) / 2){
Gdx.app.log("Touch down button with label ", label);
if(action.equals("login")) {
if(!isHandled) {
isHandled = true;
int playerIndex = new Random().nextInt(100);
playerIndex = 22;
SecureChatClient.send("!lJohnDoe" + playerIndex + ":psw");
currentActor.setColor(Color.CORAL);
label = "OK";
}
}
}
return true;
}
});
}
public void spritePos(float x, float y){
sprite.setPosition(x, y);
setBounds(sprite.getX(), sprite.getY(), sprite.getWidth(), sprite.getHeight());
}
@Override
public void act(float delta) {
super.act(delta);
}
@Override
public void draw(Batch batch, float parentAlpha) {
Color color = getColor(); //keep reference to avoid multiple method calls
sprite.setColor(color.r, color.g, color.b, color.a * parentAlpha);
sprite.draw(batch);
ActorExample.font.draw(batch, label, sprite.getX()+17, sprite.getY()+60);
}
} | 33.772727 | 105 | 0.57638 |
1615c02fe67c740a190ca5f44005b7513e3a7eac | 1,061 | package shoppingappextract.extract;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import org.requirementsascode.Model;
import org.requirementsascode.extract.freemarker.FreeMarkerEngine;
import shoppingapp.boundary.Boundary;
public class ShoppingAppExtract {
public static void main(String[] args) throws Exception {
new ShoppingAppExtract().start();
}
private void start() throws Exception {
Model model = buildModel();
FreeMarkerEngine engine = new FreeMarkerEngine("shoppingappextract/extract");
File outputFile = outputFile();
engine.extract(model, templateFileName(), new FileWriter(outputFile));
System.out.println("Wrote file to: " + outputFile);
}
private Model buildModel() {
Boundary boundary = new Boundary(null, null);
Model model = boundary.getModel();
return model;
}
private String templateFileName() {
return "htmlExample.ftlh";
}
private File outputFile() throws IOException {
File outputFile = File.createTempFile("shoppingappextract_", ".html");
return outputFile;
}
}
| 25.261905 | 79 | 0.759661 |
9b5770b6fdd36ba412e862700f2a54e0674b947f | 1,916 | package loghub.processors;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.log4j.spi.LoggingEvent;
import loghub.Event;
import loghub.Helpers;
public class Log4Extract extends ObjectExtractor<LoggingEvent> {
@Override
public void extract(Event event, LoggingEvent o) {
Helpers.putNotEmpty(event, "path", o.getLoggerName());
Helpers.putNotEmpty(event, "priority", o.getLevel().toString());
Helpers.putNotEmpty(event, "logger_name", o.getLoggerName());
Helpers.putNotEmpty(event, "thread", o.getThreadName());
o.getLocationInformation();
if(o.getLocationInformation().fullInfo != null) {
Helpers.putNotEmpty(event, "class", o.getLocationInformation().getClassName());
Helpers.putNotEmpty(event, "file", o.getLocationInformation().getFileName());
Helpers.putNotEmpty(event, "method", o.getLocationInformation().getMethodName());
Helpers.putNotEmpty(event, "line", o.getLocationInformation().getLineNumber());
}
Helpers.putNotEmpty(event, "NDC", o.getNDC());
if(o.getThrowableStrRep() != null) {
List<String> stack = new ArrayList<>();
for(String l: o.getThrowableStrRep()) {
stack.add(l.replace("\t", " "));
}
event.put("stack_trace", stack);
}
@SuppressWarnings("unchecked")
Map<String, ?> m = o.getProperties();
if(m.size() > 0) {
event.put("properties", m);
}
Date d = new Date(o.getTimeStamp());
event.put(Event.TIMESTAMPKEY, d);
event.put("message", o.getRenderedMessage());
}
@Override
public String getName() {
return "log4extract";
}
@Override
protected Class<LoggingEvent> getClassType() {
return LoggingEvent.class;
}
}
| 33.614035 | 93 | 0.623695 |
df22741f17d6eff242a655429bc4eb6a1440ff7e | 1,892 | package com.jzy.model.dto.search;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* @ClassName StudentAndClassSearchCondition
* @Author JinZhiyun
* @Description 学生上课信息查询条件的封装
* @Date 2019/11/25 18:02
* @Version 1.0
**/
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Data
public class StudentAndClassSearchCondition extends SearchCondition {
private static final long serialVersionUID = 3988969329024041901L;
/**
* 学员号
*/
private String studentId;
/**
* 学生姓名
*/
private String studentName;
/**
* 班级编码,唯一,非空,长度小于32,2019年新东方优能中学部的班级编码为12位,U6MCFB020001,
* 其中‘u'表示优能中学部,6表示六年级,M学科,C为班型:志高,F为班级规模:25人,B表示季度,’02‘表示曹杨校区,'0001'为序号。
* 所以这里另外加年级,学科等字段,以便后续班级编码规则改变系统更新
*/
private String classId;
/**
* 班级名称,可以为空,长度不超过50
*/
private String className;
/**
* 班级所属的校区,可以为空,长度不超过50
*/
private String classCampus;
/**
* 班级所属年级,可以为空,长度不超过50
*/
private String classGrade;
/**
* 班级所属学科,可以为空,长度不超过50
*/
private String classSubject;
/**
* 班级类型,可以为空,长度不超过20
*/
private String classType;
/**
* 班级开设的年份,可以为空,2019版的班级编码中没有能标识年份的字段
*/
private String classYear;
/**
* 班级开设的季度,如春季,暑假等,可以为空,长度不超过50
*/
private String classSeason;
/**
* 班级开设的季度的分期,如(暑假)一期、二期等等
*/
private String classSubSeason;
/**
* 班级上课时间
*/
private String classTime;
/**
* 班级上课上课教室
*/
private String classroom;
/**
* 任课教师的工号
*/
private String teacherId;
/**
* 教师工号
*/
private String teacherWorkId;
/**
* 任课教师的姓名
*/
private String teacherName;
/**
* 助教工号
*/
private String assistantWorkId;
/**
* 助教的姓名
*/
private String assistantName;
}
| 16.596491 | 77 | 0.598837 |
b711c1b62d398e8c9ca03368ea0de37a0df574ff | 3,186 | package com.github.maxopoly.WurstCivTools.effect;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.Vector;
import com.github.maxopoly.WurstCivTools.WurstCivTools;
import com.github.maxopoly.WurstCivTools.enchantment.CustomEnchantManager;
import com.github.maxopoly.WurstCivTools.enchantment.CustomEnchantment;
import com.github.maxopoly.WurstCivTools.misc.MultiplierConfig;
public class ExtraBlockDropEffect extends AbstractEnchantmentEffect {
private MultiplierConfig dropConfig;
private ItemStack item;
private boolean removeNormalDrops;
private Set<Material> appliedBlocks;
private List<CustomEnchantment> disallowedEnchants;
@Override
public void handleBreak(Player p, BlockBreakEvent e) {
if (appliedBlocks != null && !appliedBlocks.contains(e.getBlock().getType())) {
return;
}
for(CustomEnchantment disEnchant : disallowedEnchants) {
if (getEnchantLevel(p.getInventory().getItemInMainHand(), disEnchant) > 0) {
return;
}
}
if (removeNormalDrops) {
e.setDropItems(false);
}
int enchantLevel = getEnchantLevel(p.getInventory().getItemInMainHand());
int amount = (int) dropConfig.apply(enchantLevel);
ItemStack is = new ItemStack(item);
is.setAmount(amount);
// Schedule the item to drop 1 tick later
Bukkit.getScheduler().scheduleSyncDelayedTask(WurstCivTools.getPlugin(), new Runnable() {
@Override
public void run() {
e.getBlock().getLocation().getWorld().dropItem(e.getBlock().getLocation().add(0.5, 0.5, 0.5), is)
.setVelocity(new Vector(0, 0.05, 0));
}
}, 1);
}
@Override
public boolean parseParameters(ConfigurationSection config) {
dropConfig = new MultiplierConfig(config);
item = config.getItemStack("item");
if (item == null) {
logger.warning("No item supplied for effect at " + config.getCurrentPath());
return false;
}
removeNormalDrops = config.getBoolean("removeNormalDrops", false);
if (config.isList("blocks")) {
appliedBlocks = new HashSet<>();
for (String s : config.getStringList("blocks")) {
try {
Material m = Material.valueOf(s.toUpperCase());
appliedBlocks.add(m);
} catch (IllegalArgumentException e) {
logger.warning("Could not parse material " + s + " at " + config.getCurrentPath());
}
}
}
disallowedEnchants = new LinkedList<CustomEnchantment>();
CustomEnchantManager enchManager = WurstCivTools.getPlugin().getCustomEnchantManager();
if (config.isList("disallowedEnchants")) {
for (String s : config.getStringList("disallowedEnchants")) {
CustomEnchantment disEnchant = enchManager.getEnchantment(s);
if (disEnchant == null) {
logger.warning("Could not parse disallowed enchantment " + s + " at " + config.getCurrentPath());
continue;
}
disallowedEnchants.add(disEnchant);
}
}
return true;
}
@Override
public String getIdentifier() {
return "BLOCKDROP_REPLACE";
}
}
| 32.510204 | 102 | 0.737602 |
6f6ae1f8bd0fb8fb4ee9ac7db49aa3f8074b7535 | 2,728 | /**
* 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.hadoop.hbase.replication.regionserver;
import org.apache.hadoop.hbase.HBaseInterfaceAudience;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.AsyncConnection;
import org.apache.yetus.audience.InterfaceAudience;
import org.apache.yetus.audience.InterfaceStability;
/**
* Implementations are installed on a Replication Sink called from inside
* ReplicationSink#replicateEntries to filter replicated WALEntries based off WALEntry attributes.
* Currently only table name and replication write time are exposed (WALEntry is a private,
* internal class so we cannot pass it here). To install, set
* <code>hbase.replication.sink.walentryfilter</code> to the name of the implementing
* class. Implementing class must have a no-param Constructor.
* <p>This filter is of limited use. It is better to filter on the replication source rather than
* here after the edits have been shipped on the replication sink. That said, applications such
* as the hbase-indexer want to filter out any edits that were made before replication was enabled.
* @see org.apache.hadoop.hbase.replication.WALEntryFilter for filtering on the replication
* source-side.
*/
@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.REPLICATION)
@InterfaceStability.Evolving
public interface WALEntrySinkFilter {
/**
* Name of configuration to set with name of implementing WALEntrySinkFilter class.
*/
public static final String WAL_ENTRY_FILTER_KEY = "hbase.replication.sink.walentrysinkfilter";
/**
* Called after Construction.
* Use passed Connection to keep any context the filter might need.
*/
void init(AsyncConnection conn);
/**
* @param table Table edit is destined for.
* @param writeTime Time at which the edit was created on the source.
* @return True if we are to filter out the edit.
*/
boolean filter(TableName table, long writeTime);
}
| 45.466667 | 99 | 0.773827 |
b7d3e824fc6e7aae337e830521d263c395ec4612 | 260 | package interfac.interface_interface;
public class Main implements Interface1, Interface2 {
// interface vs interface, the class must implements default method of interfaces
@Override
public void method() {
System.out.println("");
}
}
| 26 | 85 | 0.715385 |
5a70d6550313894a3f032b12d7aab8323b5b257b | 16,144 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the KiWi Project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Contributor(s):
*
*
*/
package kiwi.service.importexport.importer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.xml.transform.TransformerException;
import kiwi.api.content.ContentItemService;
import kiwi.api.entity.KiWiEntityManager;
import kiwi.api.event.KiWiEvents;
import kiwi.api.importexport.ImportService;
import kiwi.api.importexport.importer.ImporterLocal;
import kiwi.api.importexport.importer.ImporterRemote;
import kiwi.api.multimedia.MultimediaService;
import kiwi.api.tagging.TaggingService;
import kiwi.api.triplestore.TripleStore;
import kiwi.api.user.UserService;
import kiwi.model.content.ContentItem;
import kiwi.model.kbase.KiWiNamespace;
import kiwi.model.kbase.KiWiTriple;
import kiwi.model.kbase.KiWiUriResource;
import kiwi.model.user.User;
import kiwi.service.importexport.importer.ikewiki.RXRReader;
import nu.xom.Builder;
import nu.xom.Document;
import nu.xom.Element;
import nu.xom.Elements;
import nu.xom.Nodes;
import nu.xom.ParsingException;
import nu.xom.Text;
import nu.xom.ValidityException;
import nu.xom.XPathContext;
import nu.xom.xslt.XSLException;
import nu.xom.xslt.XSLTransform;
import org.bouncycastle.util.encoders.Base64;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Observer;
import org.jboss.seam.annotations.RaiseEvent;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.log.Log;
/**
* Importer that supports importing data from old IkeWiki installations using IkeWiki's WIF
* format.
*
* @author Sebastian Schaffert
*
*/
@Stateless
@Name("kiwi.service.importer.ikewiki")
@Scope(ScopeType.STATELESS)
public class IkeWikiImporter implements ImporterLocal, ImporterRemote {
@Logger
private Log log;
@In(create = true)
private TripleStore tripleStore;
@In(create = true)
private EntityManager entityManager;
@In(create = true)
private KiWiEntityManager kiwiEntityManager;
@In(create = true)
private ContentItemService contentItemService;
@In(create = true)
private MultimediaService multimediaService;
@In(create = true)
private UserService userService;
@In(create = true)
private TaggingService taggingService;
private static String[] mime_types = {
"application/ikewiki+xml"
};
@Observer(KiWiEvents.SEAM_POSTINIT)
@BypassInterceptors
public void initialise() {
log.info("registering IkeWiki importer ...");
ImportService ies = (ImportService) Component.getInstance("kiwi.core.importService");
ies.registerImporter(this.getName(),"kiwi.service.importer.ikewiki",this);
}
/**
* Get a collection of all mime types accepted by this importer. Used for automatically
* selecting the appropriate importer in ImportService.
*
* @return a set of strings representing the mime types accepted by this importer
*/
@Override
public Set<String> getAcceptTypes() {
return new HashSet<String>(Arrays.asList(mime_types));
}
/**
* Get a description of this importer for presentation to the user.
*
* @return a string describing this importer for the user
*/
@Override
public String getDescription() {
return "Importer for importing data from old IkeWiki installations";
}
/**
* Get the name of this importer. Used for presentation to the user and for internal
* identification.
*
* @return a string uniquely identifying this importer
*/
@Override
public String getName() {
return "IkeWiki";
}
/**
* Import data from the input stream provided as argument into the KiWi database.
*
* @param url the url from which to read the data
* @param types the set of types to associate with each generated content item
* @param tags the set of content items to use as tags
* @param user the user to use as author of all imported data
*/
@Override
public int importData(URL url, String format, Set<KiWiUriResource> types, Set<ContentItem> tags, User user, Collection<ContentItem> output) {
try {
return importData(url.openStream(), format, types, tags, user, output);
} catch (IOException ex) {
log.error("I/O error while importing data from URL #0: #1",url, ex.getMessage());
return 0;
}
}
/**
* Import data from the input stream provided as argument into the KiWi database.
* <p>
* Import function for formats supported by Sesame; imports the data first into a separate memory
* repository, and then iterates over all statements, adding them to the current knowledge space.
* This method also checks for resources that have a rdfs:label, dc:title, or skos:prefLabel and uses
* it as the title for newly created ContentItems.
*
* @param is the input stream from which to read the data
* @param types the set of types to associate with each generated content item
* @param tags the set of content items to use as tags
* @param user the user to use as author of all imported data
*/
@Override
@RaiseEvent("ontologyChanged")
public int importData(InputStream is, String format, Set<KiWiUriResource> types, Set<ContentItem> tags, User user, Collection<ContentItem> output) {
Builder parser = new Builder();
try {
return importData(parser.build(is), types, tags, user, output);
} catch (ValidityException e) {
log.error("the IkeWiki WIF document was not valid",e);
} catch (ParsingException e) {
log.error("the IkeWiki WIF document could not be parsed",e);
} catch (IOException e) {
log.error("I/O error while reading IkeWiki WIF document",e);
}
return 0;
}
/**
* Import data from the reader provided as argument into the KiWi database.
* <p>
* Import function for formats supported by Sesame; imports the data first into a separate memory
* repository, and then iterates over all statements, adding them to the current knowledge space.
* This method also checks for resources that have a rdfs:label, dc:title, or skos:prefLabel and uses
* it as the title for newly created ContentItems.
*
* @param reader the reader from which to read the data
* @param types the set of types to associate with each generated content item
* @param tags the set of content items to use as tags
* @param user the user to use as author of all imported data
*/
@Override
@RaiseEvent("ontologyChanged")
public int importData(Reader reader, String format, Set<KiWiUriResource> types, Set<ContentItem> tags, User user, Collection<ContentItem> output) {
Builder parser = new Builder();
try {
return importData(parser.build(reader), types, tags, user, output);
} catch (ValidityException e) {
log.error("the IkeWiki WIF document was not valid",e);
} catch (ParsingException e) {
log.error("the IkeWiki WIF document could not be parsed",e);
} catch (IOException e) {
log.error("I/O error while reading IkeWiki WIF document",e);
}
return 0;
}
private int importData(Document doc, Set<KiWiUriResource> types, Set<ContentItem> tags, User user, Collection<ContentItem> outputCIs) {
if(types == null) {
types = new HashSet<KiWiUriResource>();
}
if(tags == null) {
tags = new HashSet<ContentItem>();
}
Builder parser = new Builder();
XPathContext xPathContext = new XPathContext();
String NS_IKEWIKI_EXT = "http://ikewiki.srfg.at/syntax/1.0/ext";
xPathContext.addNamespace("wif", "http://ikewiki.srfg.at/syntax/1.0/core");
xPathContext.addNamespace("iw", NS_IKEWIKI_EXT);
xPathContext.addNamespace("rxr", "http://ilrt.org/discovery/2004/03/rxr/");
try {
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
Document stylesheet = parser.build(this.getClass().getResourceAsStream("ikewiki/transform-html.xsl"));
XSLTransform transform = new XSLTransform(stylesheet);
// add all namespaces from the imported knowledge base
// if a namespace URI already exists, it is updated to the prefix of the imported declaration
Nodes nl = doc.getRootElement().query("//iw:namespace",xPathContext);
for(int i=0; i<nl.size(); i++) {
nu.xom.Element e = (nu.xom.Element)nl.get(i);
tripleStore.setNamespace(e.getAttributeValue("prefix"), e.getAttributeValue("uri"));
}
// add all pages from the imported knowledge base
Nodes pages = doc.query("//wif:page",xPathContext);
for(int i=0; i<pages.size(); i++) {
nu.xom.Element e = (nu.xom.Element)pages.get(i);
KiWiUriResource r = null;
// check whether URI exists
Nodes uris = e.query("*[local-name() = 'uri' and namespace-uri() = '"+NS_IKEWIKI_EXT+"']/text()", xPathContext);
if(uris.size() > 0) {
Text text = (Text)uris.get(0);
r = tripleStore.createUriResource(text.getValue());
} else {
// check whether QTitle exists
Nodes qtitles = e.query("*[local-name() = 'qtitle' and namespace-uri() = '"+NS_IKEWIKI_EXT+"']/text()",xPathContext);
if(qtitles.size() > 0) {
Text text = (Text)qtitles.get(0);
r = tripleStore.createUriResource(getUriForQTitle(text.getValue()));
}
}
if(r != null) {
//if(hasImportPermission(user, r)) { // TODO: permissions are not yet setup when importing!
log.info("importing page #0",r);
// determine whether this page comes with multimedia data and decode it if yes
boolean ismm = false; byte[] bytes = null; String mime_type = "";
Elements datanodes = e.getChildElements(NS_IKEWIKI_EXT, "data");
if(datanodes.size() == 1) {
nu.xom.Element datanode = datanodes.get(0);
mime_type = datanode.getAttributeValue("mime-type");
String datacontent = "";
for(int j=0; j<datanode.getChildCount(); j++) {
if(datanode.getChild(j) instanceof Text) {
Text txt = (Text)datanode.getChild(j);
datacontent += txt.getValue();
}
}
if(!datacontent.equals("")) {
bytes = Base64.decode(datacontent);
}
// remove data node, we don't want it to be stored in the database
e.removeChild(datanode);
ismm = true;
}
Document d = new Document((Element)e.copy());
ContentItem ci = contentItemService.createExternContentItem(r.getUri());
// set title; label overrides if given
Nodes titles = d.query("//wif:title/text()",xPathContext);
if(titles.size() > 0) {
contentItemService.updateTitle(ci, ((Text)titles.get(0)).getValue());
}
Nodes labels = d.query("//iw:label/text()",xPathContext);
if(labels.size() > 0) {
contentItemService.updateTitle(ci, ((Text)labels.get(0)).getValue());
}
// set content
Nodes output = transform.transform(d);
Document result = XSLTransform.toDocument(output);
contentItemService.updateTextContentItem(ci, result.toXML());
// set user to current user (we don't use IkeWiki's user information).
ci.setAuthor(user);
if(ismm) {
File tmpfile = File.createTempFile("ikewiki-multimedia", "tmp");
OutputStream tmpout = new BufferedOutputStream(new FileOutputStream(tmpfile));
tmpout.write(bytes);
tmpout.close();
String type = multimediaService.getMimeType("", bytes);
contentItemService.updateMediaContentItem(ci, bytes, type, UUID.randomUUID().toString());
/*
MediaContent mediaContent = new MediaContent(ci);
mediaContent.setData(bytes);
mediaContent.setMimeType(type);
mediaContent.setFileName(UUID.randomUUID().toString());
ci.setMediaContent(mediaContent);
*/
}
contentItemService.saveContentItem(ci);
// add parameter categories as tags
for(ContentItem tag : tags) {
taggingService.createTagging(tag.getTitle(), ci, tag, user);
}
// add parameter types as types
for(KiWiUriResource type : types) {
ci.addType(type);
}
// add kiwi:FeedPost type
ci.addType(tripleStore.createUriResource("http://ikewiki.srfg.at/base/Page"));
// entityManager.flush();
log.info("imported content item '#0' with URI '#1'", ci.getTitle(), ci.getResource());
} else {
log.warn("page with empty URI ignored");
}
}
// add all statements from the RXR graph
RXRReader rxrReader = new RXRReader(doc);
for (KiWiTriple triple : rxrReader) {
tripleStore.storeTriple(triple);
}
log.info("finished import");
return pages.size();
} catch(IOException ex) {
log.error("error while parsing XML exchange format",ex);
} catch(XSLException ex) {
log.error("error while transforming IkeWiki WIF to HTML",ex);
log.error("cause was: ",ex.getCause());
log.error("location: #0",((TransformerException)ex.getCause()).getMessageAndLocation());
} catch(ValidityException ex) {
log.error("XSL stylesheet is not valid",ex);
} catch(ParsingException ex) {
log.error("error while parsing XSL stylesheet",ex);
} catch(Throwable ex) {
ex.printStackTrace();
}
return 0;
}
/**
* resolve a qualified title and return the corresponding unique URI.
* @param qtitle
* @return
* @throws DBException
*/
public String getUriForQTitle(String qtitle) {
String article_ns, article_title;
String[] components = qtitle.replace(" ","_").split(":",2);
if(components.length == 2) {
article_ns = components[0];
article_title = components[1];
} else if(components.length == 1){
article_ns = "";
article_title = components[0];
} else {
article_ns = "";
article_title = "";
}
KiWiNamespace ns = tripleStore.getNamespace(article_ns);
if(ns == null) {
ns = new KiWiNamespace(article_ns,"");
log.warn("namespace "+article_ns+" not found in database (for resource "+article_title+")");
}
return ns.getUri()+article_title;
}
}
| 34.131078 | 149 | 0.699393 |
c465c893f8458e42321116b760a57933297f64c0 | 237 | package com.shihy;
import com.shihy.web.TulingExternalSpringBootApplication;
/**3
*/
public class MainStarter {
public static void main(String[] args) throws Exception {
TulingExternalSpringBootApplication.run();
}
}
| 18.230769 | 61 | 0.729958 |
dae94c8690c0a417f01a6c221682618844db2ea3 | 9,388 | package com.sasconsul.rcp.web.rest;
import com.sasconsul.rcp.Rcp2App;
import com.sasconsul.rcp.domain.Words;
import com.sasconsul.rcp.repository.WordsRepository;
import com.sasconsul.rcp.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.util.List;
import static com.sasconsul.rcp.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the WordsResource REST controller.
*
* @see WordsResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Rcp2App.class)
public class WordsResourceIntTest {
private static final String DEFAULT_WORD = "AAAAAAAAAA";
private static final String UPDATED_WORD = "BBBBBBBBBB";
private static final Long DEFAULT_COUNT = 1L;
private static final Long UPDATED_COUNT = 2L;
private static final Long DEFAULT_PAGE = 1L;
private static final Long UPDATED_PAGE = 2L;
@Autowired
private WordsRepository wordsRepository;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restWordsMockMvc;
private Words words;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final WordsResource wordsResource = new WordsResource(wordsRepository);
this.restWordsMockMvc = MockMvcBuilders.standaloneSetup(wordsResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Words createEntity(EntityManager em) {
Words words = new Words()
.word(DEFAULT_WORD)
.count(DEFAULT_COUNT)
.page(DEFAULT_PAGE);
return words;
}
@Before
public void initTest() {
words = createEntity(em);
}
@Test
@Transactional
public void createWords() throws Exception {
int databaseSizeBeforeCreate = wordsRepository.findAll().size();
// Create the Words
restWordsMockMvc.perform(post("/api/words")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(words)))
.andExpect(status().isCreated());
// Validate the Words in the database
List<Words> wordsList = wordsRepository.findAll();
assertThat(wordsList).hasSize(databaseSizeBeforeCreate + 1);
Words testWords = wordsList.get(wordsList.size() - 1);
assertThat(testWords.getWord()).isEqualTo(DEFAULT_WORD);
assertThat(testWords.getCount()).isEqualTo(DEFAULT_COUNT);
assertThat(testWords.getPage()).isEqualTo(DEFAULT_PAGE);
}
@Test
@Transactional
public void createWordsWithExistingId() throws Exception {
int databaseSizeBeforeCreate = wordsRepository.findAll().size();
// Create the Words with an existing ID
words.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restWordsMockMvc.perform(post("/api/words")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(words)))
.andExpect(status().isBadRequest());
// Validate the Words in the database
List<Words> wordsList = wordsRepository.findAll();
assertThat(wordsList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllWords() throws Exception {
// Initialize the database
wordsRepository.saveAndFlush(words);
// Get all the wordsList
restWordsMockMvc.perform(get("/api/words?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(words.getId().intValue())))
.andExpect(jsonPath("$.[*].word").value(hasItem(DEFAULT_WORD.toString())))
.andExpect(jsonPath("$.[*].count").value(hasItem(DEFAULT_COUNT.intValue())))
.andExpect(jsonPath("$.[*].page").value(hasItem(DEFAULT_PAGE.intValue())));
}
@Test
@Transactional
public void getWords() throws Exception {
// Initialize the database
wordsRepository.saveAndFlush(words);
// Get the words
restWordsMockMvc.perform(get("/api/words/{id}", words.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(words.getId().intValue()))
.andExpect(jsonPath("$.word").value(DEFAULT_WORD.toString()))
.andExpect(jsonPath("$.count").value(DEFAULT_COUNT.intValue()))
.andExpect(jsonPath("$.page").value(DEFAULT_PAGE.intValue()));
}
@Test
@Transactional
public void getNonExistingWords() throws Exception {
// Get the words
restWordsMockMvc.perform(get("/api/words/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateWords() throws Exception {
// Initialize the database
wordsRepository.saveAndFlush(words);
int databaseSizeBeforeUpdate = wordsRepository.findAll().size();
// Update the words
Words updatedWords = wordsRepository.findOne(words.getId());
updatedWords
.word(UPDATED_WORD)
.count(UPDATED_COUNT)
.page(UPDATED_PAGE);
restWordsMockMvc.perform(put("/api/words")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedWords)))
.andExpect(status().isOk());
// Validate the Words in the database
List<Words> wordsList = wordsRepository.findAll();
assertThat(wordsList).hasSize(databaseSizeBeforeUpdate);
Words testWords = wordsList.get(wordsList.size() - 1);
assertThat(testWords.getWord()).isEqualTo(UPDATED_WORD);
assertThat(testWords.getCount()).isEqualTo(UPDATED_COUNT);
assertThat(testWords.getPage()).isEqualTo(UPDATED_PAGE);
}
@Test
@Transactional
public void updateNonExistingWords() throws Exception {
int databaseSizeBeforeUpdate = wordsRepository.findAll().size();
// Create the Words
// If the entity doesn't have an ID, it will be created instead of just being updated
restWordsMockMvc.perform(put("/api/words")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(words)))
.andExpect(status().isCreated());
// Validate the Words in the database
List<Words> wordsList = wordsRepository.findAll();
assertThat(wordsList).hasSize(databaseSizeBeforeUpdate + 1);
}
@Test
@Transactional
public void deleteWords() throws Exception {
// Initialize the database
wordsRepository.saveAndFlush(words);
int databaseSizeBeforeDelete = wordsRepository.findAll().size();
// Get the words
restWordsMockMvc.perform(delete("/api/words/{id}", words.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Words> wordsList = wordsRepository.findAll();
assertThat(wordsList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Words.class);
Words words1 = new Words();
words1.setId(1L);
Words words2 = new Words();
words2.setId(words1.getId());
assertThat(words1).isEqualTo(words2);
words2.setId(2L);
assertThat(words1).isNotEqualTo(words2);
words1.setId(null);
assertThat(words1).isNotEqualTo(words2);
}
}
| 36.671875 | 93 | 0.689391 |
0033bae76f5f73d50a1b3af6d3df6b4fc70cc304 | 1,080 | package org.concept.lambda.ex19;
import org.concept.lambda.ex18.MethodReferencesLEX;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
public class MethodReferencesGenerics {
private static final Logger LOG = Logger.getLogger(MethodReferencesGenerics.class.getName());
private int size = 10;
private static List<Integer> numbers = new ArrayList<>();
private static List<String> names = new LinkedList<>();
private static void init() {
for (int i = 0; i < 10; i++) {
numbers.add(10 + i);
}
for (int i = 0; i < 10; i++) {
names.add("USER-" + i);
}
names.add("USER-" + 5);
numbers.add(15);
}
public static <E> void executeLEX91(Match<E> match, List<E> list, E value) {
match.searchCount(list, value);
}
public static void main(String[] args) {
init();
executeLEX91(MatchFounder::resultFound, numbers, 15);
executeLEX91(MatchFounder::resultFound, names, "USER-5");
}
}
| 27.692308 | 97 | 0.625926 |
1af7edcadddf3f00645330310170b588ba2f2b28 | 3,883 | package Trip;
/*
*
* @Author: Sandeep Sasidharan
*/
import org.joda.time.DateTime;
public class FilterFunctions {
/*Distance calculator*/
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return dist;
}
public static boolean inLaG(double lat1, double lng1) {
double lat2 = NYCConstants.LaG_lat;
double lng2 = NYCConstants.LaG_lng;
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
if(dist<=0.5)
return true;
else
return false;
}
public static boolean inLaGRange(double lat1, double lng1) {
double lat2 = NYCConstants.LaG_lat;
double lng2 = NYCConstants.LaG_lng;
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double sindLat = Math.sin(dLat / 2);
double sindLng = Math.sin(dLng / 2);
double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2)
* Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
if(dist<75)
return true;
else
return false;
}
public static boolean inNYBoundingBox(double lat1, double lng1){
double north_lat = 40.915256;
double south_lat = 40.496044;
double east_lon = -73.700272 ;
double west_lon = -74.255735;
boolean lat_check = (lat1 <north_lat && lat1 >south_lat);
boolean lon_check = (lng1 >west_lon && lng1 <east_lon);
return (lat_check && lon_check);
}
public static boolean inManhattanBoundingBox(double lat1, double lng1){
double north_lat = 40.882214;
double south_lat = 40.680396;
double east_lon = -73.907000 ;
double west_lon = -74.047285;
boolean lat_check = (lat1 <north_lat && lat1 >south_lat);
boolean lon_check = (lng1 >west_lon && lng1 <east_lon);
return (lat_check && lon_check);
}
/*For data integrity*/
public static boolean isMedallion(String medallion)
{
if(medallion.length()!=10)
{
return false;
}
return true;
}
public static boolean isLatitude(double latitude)
{
if(latitude == 0)
{
//Runner.LOGGER.info("Latitude = 0, Skipped!");
return false;
}
return true;
}
public static boolean isLongitude(double longitude)
{
if(longitude == 0)
{
//Runner.LOGGER.info("Longitude = 0, Skipped!");
return false;
}
return true;
}
public static boolean isTripTime(double trip_time_in_secs)
{
if(trip_time_in_secs == 0)
{
//Runner.LOGGER.info("trip_time_in_secs = 0, Check and Skip!");
return false;
}
if(trip_time_in_secs < 10)
{
//Runner.LOGGER.info("trip_time_in_secs"+trip_time_in_secs+", Check and Skip!");
return false;
}
return true;
}
public static boolean isTripDistance(double trip_distance)
{
if(trip_distance == 0)
{
//Runner.LOGGER.info("trip_distance = 0, Check and Skip!");
return false;
}
return true;
}
public static boolean isWeekday(String dateTime)
{
DateTime f_date = NYCConstants.dt_formatter.parseDateTime(dateTime);
int dayOfWeek = f_date.getDayOfWeek();
if(dayOfWeek>5)
return false;
return true;
}
}
| 25.214286 | 84 | 0.680402 |
8150384f800bbbf6e5e71a55584d011cee9bc3c1 | 9,454 | /**
* Copyright (c) Dell Inc., or its subsidiaries. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package io.pravega.connectors.flink;
import lombok.Getter;
import org.apache.commons.lang3.NotImplementedException;
import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.api.common.serialization.SerializationSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSink;
import org.apache.flink.table.sinks.AppendStreamTableSink;
import org.apache.flink.table.sinks.BatchTableSink;
import org.apache.flink.types.Row;
import org.apache.flink.util.Preconditions;
import java.util.Arrays;
import java.util.function.Function;
import static org.apache.flink.util.Preconditions.checkArgument;
import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;
/**
* An append-only table sink to emit a streaming table as a Pravega stream.
*/
public abstract class FlinkPravegaTableSink implements AppendStreamTableSink<Row>, BatchTableSink<Row> {
/** A factory for the stream writer. */
protected final Function<TableSinkConfiguration, FlinkPravegaWriter<Row>> writerFactory;
/** A factory for output format. */
protected final Function<TableSinkConfiguration, FlinkPravegaOutputFormat<Row>> outputFormatFactory;
/** The effective table sink configuration */
private TableSinkConfiguration tableSinkConfiguration;
/**
* Creates a Pravega {@link AppendStreamTableSink}.
*
* <p>Each row is written to a Pravega stream with a routing key based on the {@code routingKeyFieldName}.
* The specified field must of type {@code STRING}.
*
* @param writerFactory A factory for the stream writer.
* @param outputFormatFactory A factory for the output format.
*/
protected FlinkPravegaTableSink(Function<TableSinkConfiguration, FlinkPravegaWriter<Row>> writerFactory,
Function<TableSinkConfiguration, FlinkPravegaOutputFormat<Row>> outputFormatFactory) {
this.writerFactory = Preconditions.checkNotNull(writerFactory, "writerFactory");
this.outputFormatFactory = Preconditions.checkNotNull(outputFormatFactory, "outputFormatFactory");
}
/**
* Creates a copy of the sink for configuration purposes.
*/
protected abstract FlinkPravegaTableSink createCopy();
/**
* NOTE: This method is for internal use only for defining a TableSink.
* Do not use it in Table API programs.
*/
@Override
public void emitDataStream(DataStream<Row> dataStream) {
throw new NotImplementedException("This method is deprecated and should not be called.");
}
@Override
public DataStreamSink<?> consumeDataStream(DataStream<Row> dataStream) {
checkState(tableSinkConfiguration != null, "Table sink is not configured");
FlinkPravegaWriter<Row> writer = writerFactory.apply(tableSinkConfiguration);
return dataStream.addSink(writer);
}
@Override
public void emitDataSet(DataSet<Row> dataSet) {
checkState(tableSinkConfiguration != null, "Table sink is not configured");
FlinkPravegaOutputFormat<Row> outputFormat = outputFormatFactory.apply(tableSinkConfiguration);
dataSet.output(outputFormat);
}
@Override
public TypeInformation<Row> getOutputType() {
return new RowTypeInfo(getFieldTypes());
}
public String[] getFieldNames() {
checkState(tableSinkConfiguration != null, "Table sink is not configured");
return tableSinkConfiguration.fieldNames;
}
@Override
public TypeInformation<?>[] getFieldTypes() {
checkState(tableSinkConfiguration != null, "Table sink is not configured");
return tableSinkConfiguration.fieldTypes;
}
@Override
public FlinkPravegaTableSink configure(String[] fieldNames, TypeInformation<?>[] fieldTypes) {
// called to configure the sink with a specific subset of fields
checkNotNull(fieldNames, "fieldNames");
checkNotNull(fieldTypes, "fieldTypes");
Preconditions.checkArgument(fieldNames.length == fieldTypes.length,
"Number of provided field names and types does not match.");
FlinkPravegaTableSink copy = createCopy();
copy.tableSinkConfiguration = new TableSinkConfiguration(fieldNames, fieldTypes);
return copy;
}
/**
* The table sink configuration which is provided by the table environment via {@code TableSink::configure}.
*/
@Getter
protected static class TableSinkConfiguration {
// the set of projected fields and their types
private String[] fieldNames;
private TypeInformation[] fieldTypes;
public TableSinkConfiguration(String[] fieldNames, TypeInformation[] fieldTypes) {
this.fieldNames = Preconditions.checkNotNull(fieldNames, "fieldNames");
this.fieldTypes = Preconditions.checkNotNull(fieldTypes, "fieldTypes");
}
}
/**
* An event router that extracts the routing key from a {@link Row} by field name.
*/
static class RowBasedRouter implements PravegaEventRouter<Row> {
private final int keyIndex;
public RowBasedRouter(String keyFieldName, String[] fieldNames, TypeInformation<?>[] fieldTypes) {
checkArgument(fieldNames.length == fieldTypes.length,
"Number of provided field names and types does not match.");
int keyIndex = Arrays.asList(fieldNames).indexOf(keyFieldName);
checkArgument(keyIndex >= 0,
"Key field '" + keyFieldName + "' not found");
checkArgument(Types.STRING.equals(fieldTypes[keyIndex]),
"Key field must be of type 'STRING'");
this.keyIndex = keyIndex;
}
@Override
public String getRoutingKey(Row event) {
return (String) event.getField(keyIndex);
}
int getKeyIndex() {
return keyIndex;
}
}
/**
* An abstract {@link FlinkPravegaTableSink} builder.
* @param <B> the builder type.
*/
@Internal
public abstract static class AbstractTableSinkBuilder<B extends AbstractTableSinkBuilder> extends AbstractStreamingWriterBuilder<Row, B> {
private String routingKeyFieldName;
/**
* Sets the field name to use as a Pravega event routing key.
*
* Each row is written to a Pravega stream with a routing key based on the given field name.
* The specified field must of type {@code STRING}.
*
* @param fieldName the field name.
*/
public B withRoutingKeyField(String fieldName) {
this.routingKeyFieldName = fieldName;
return builder();
}
// region Internal
/**
* Gets a serialization schema based on the given output field names.
* @param fieldNames the field names to emit.
*/
protected abstract SerializationSchema<Row> getSerializationSchema(String[] fieldNames);
/**
* Creates the sink function based on the given table sink configuration and current builder state.
*
* @param configuration the table sink configuration, incl. projected fields
*/
protected FlinkPravegaWriter<Row> createSinkFunction(TableSinkConfiguration configuration) {
Preconditions.checkState(routingKeyFieldName != null, "The routing key field must be provided.");
SerializationSchema<Row> serializationSchema = getSerializationSchema(configuration.getFieldNames());
PravegaEventRouter<Row> eventRouter = new RowBasedRouter(routingKeyFieldName, configuration.getFieldNames(), configuration.getFieldTypes());
return createSinkFunction(serializationSchema, eventRouter);
}
/**
* Creates FlinkPravegaOutputFormat based on the given table sink configuration and current builder state.
*
* @param configuration the table sink configuration, incl. projected fields
*/
protected FlinkPravegaOutputFormat<Row> createOutputFormat(TableSinkConfiguration configuration) {
Preconditions.checkState(routingKeyFieldName != null, "The routing key field must be provided.");
SerializationSchema<Row> serializationSchema = getSerializationSchema(configuration.getFieldNames());
PravegaEventRouter<Row> eventRouter = new RowBasedRouter(routingKeyFieldName, configuration.getFieldNames(), configuration.getFieldTypes());
return new FlinkPravegaOutputFormat<>(
getPravegaConfig().getClientConfig(),
resolveStream(),
serializationSchema,
eventRouter
);
}
// endregion
}
}
| 42.017778 | 152 | 0.687857 |
2b17421cac428c92964f2c975a81fb071c1360f7 | 5,587 | /*
* Copyright 2021-present Open Networking 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.onosproject.net.behaviour.upf;
import com.google.common.annotations.Beta;
import java.nio.ByteBuffer;
import java.util.Collection;
/**
* Provides means to update forwarding state to implement a 3GPP User Plane Function.
*/
@Beta
public interface UpfDevice {
/**
* Removes any state previously created by this API.
*/
void cleanUp();
/**
* Applies the given UPF entity to the UPF-programmable device.
*
* @param entity The UPF entity to be applied.
* @throws UpfProgrammableException if the given UPF entity can not be applied or
* the operation is not supported on the given UPF entity.
*/
void apply(UpfEntity entity) throws UpfProgrammableException;
/**
* Reads all the UPF entities of the given type from the UPF-programmable device.
*
* @param entityType The type of entities to read.
* @return A collection of installed UPF entities.
* @throws UpfProgrammableException if UPF entity type is not available to be read or
* the operation is not supported on the given UPF entity type.
*/
Collection<? extends UpfEntity> readAll(UpfEntityType entityType) throws UpfProgrammableException;
/**
* Reads the given UPF counter ID from the UPF-programmable device.
*
* @param counterId The counter ID from which to read.
* @return The content of the UPF counter.
* @throws UpfProgrammableException if the counter ID is out of bounds.
*/
UpfCounter readCounter(int counterId) throws UpfProgrammableException;
/**
* Reads the UPF counter contents for all indices that are valid on the
* UPF-programmable device. {@code maxCounterId} parameter is used to limit
* the number of counters retrieved from the UPF. If the limit given is
* larger than the physical limit, the physical limit will be used.
* A limit of -1 removes limitations, and it is equivalent of calling
* {@link #readAll(UpfEntityType)} passing the {@code COUNTER} {@link UpfEntityType}.
*
* @param maxCounterId Maximum counter ID to retrieve from the UPF device.
* @return A collection of UPF counters for all valid hardware counter cells.
* @throws UpfProgrammableException if the counters are unable to be read.
*/
Collection<UpfCounter> readCounters(long maxCounterId) throws UpfProgrammableException;
/**
* Deletes the given UPF entity from the UPF-programmable device.
*
* @param entity The UPF entity to be removed.
* @throws UpfProgrammableException if the given UPF entity is not found or
* the operation is not supported on the given UPF entity.
*/
void delete(UpfEntity entity) throws UpfProgrammableException;
/**
* Deletes the given UPF entity from the UPF-programmable device.
*
* @param entityType The UPF entity type to be removed.
* @throws UpfProgrammableException if the given UPF entity is not found or
* the operation is not supported on the given UPF entity.
*/
void deleteAll(UpfEntityType entityType) throws UpfProgrammableException;
/**
* Returns the total number of UPF entities of the given type supported by
* the UPF-programmable device. For entities that have a direction,returns
* the total amount of entities including both the downlink and the uplink
* directions.
* @param entityType The type of UPF programmable entities to retrieve the size from.
* @return The total number of supported UPF entities.
* @throws UpfProgrammableException if the operation is not supported on the given UPF entity.
*/
long tableSize(UpfEntityType entityType) throws UpfProgrammableException;
/**
* Instructs the UPF-programmable device to use GTP-U extension PDU Session Container (PSC) when
* doing encap of downlink packets, with the given QoS Flow Identifier (QFI).
*
* @throws UpfProgrammableException if operation is not available
*/
void enablePscEncap() throws UpfProgrammableException;
/**
* Disable PSC encap previously enabled with {@link #enablePscEncap()}.
*
* @throws UpfProgrammableException if operation is not available
*/
void disablePscEncap() throws UpfProgrammableException;
/**
* Sends the given data as a data plane packet-out through this device. Data is expected to
* contain an Ethernet frame.
* <p>
* The device should process the packet through the pipeline tables to select an output port
* and to apply eventual modifications (e.g., MAC rewrite for routing, pushing a VLAN tag,
* etc.).
*
* @param data Ethernet frame bytes
* @throws UpfProgrammableException if operation is not available
*/
void sendPacketOut(ByteBuffer data) throws UpfProgrammableException;
}
| 41.69403 | 102 | 0.697512 |
49482a0138171030420af6bbc611a2d7766605d4 | 9,746 | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package leap.web;
import leap.core.*;
import leap.core.ioc.*;
import leap.core.web.ServletContextInitializerBase;
import leap.lang.Classes;
import leap.lang.beans.BeanCreationException;
import leap.lang.exception.ObjectNotFoundException;
import leap.lang.logging.Log;
import leap.lang.logging.LogFactory;
import leap.lang.reflect.Reflection;
import leap.lang.servlet.Servlets;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class AppBootstrap extends ServletContextInitializerBase implements ServletContextListener {
private static final Log log = LogFactory.get(AppBootstrap.class);
public static final String GLOBAL_CLASS_NAME = "Global";
public static final String APP_ATTR_NAME = App.class.getName();
public static final String BOOTSTRAP_ATTR_NAME = AppBootstrap.class.getName();
protected String basePath;
protected App app;
protected ServletContext servletContext;
protected AppHandler handler;
protected boolean selfStarted;
protected List<BeanDefinition> bootables = new ArrayList<>();
private Object _token;
public static AppBootstrap get(ServletContext sc) throws ObjectNotFoundException {
AppBootstrap b = (AppBootstrap) sc.getAttribute(BOOTSTRAP_ATTR_NAME);
if(null == b){
throw new ObjectNotFoundException("AppBootstrap not exists in the given ServletContext");
}
return b;
}
public static AppBootstrap tryGet(ServletContext sc) {
return (AppBootstrap)sc.getAttribute(BOOTSTRAP_ATTR_NAME);
}
public static App getApp(ServletContext sc) throws ObjectNotFoundException{
App c = (App)sc.getAttribute(APP_ATTR_NAME);
if(null == c){
throw new ObjectNotFoundException("App not exists in the given ServletContext");
}
return c;
}
public static boolean isInitialized(ServletContext sc) {
return null != tryGet(sc);
}
public void initialize(ServletContext sc) {
initialize(sc, null);
}
public void initialize(ServletContext sc, Map<String,String> props) {
try {
Map<String, String> initProps = Servlets.getInitParamsMap(sc);
if(null != props) {
initProps.putAll(props);
}
bootApplication(sc, initProps);
startApplication();
selfStarted = true;
} catch (ServletException e) {
throw new AppInitException("Error booting app, " + e.getMessage(), e);
}
}
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext sc = sce.getServletContext();
initialize(sc);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
stopApplication();
}
public boolean isSelfStarted() {
return selfStarted;
}
public String getBasePath() {
return basePath;
}
public App getApp() {
return app;
}
public AppHandler getAppHandler() {
return handler;
}
public AppContext getAppContext() {
return appContext;
}
public AppConfig getAppConfig() {
return null != appContext ? appContext.getConfig() : null;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
protected final void bootApplication(final ServletContext sc,final Map<String,String> initParams) throws ServletException {
try {
this.servletContext = sc;
sc.setAttribute(BOOTSTRAP_ATTR_NAME, this);
log.info("Booting app '{}'...", getAppDisplayName(sc));
preBooting();
super.initAppContext(sc,initParams);
for(BeanDefinition bootable : bootables) {
beanFactory.tryInitBean(bootable);
((AppBootable)bootable.getSingletonInstance()).onAppBooting(app,sc);
}
postBooting();
} catch (Throwable e) {
if(e instanceof RuntimeException){
throw (RuntimeException)e;
}
throw new ServletException("Error booting application, message : " + e.getMessage(),e);
}
}
protected void preBooting() {
}
protected void postBooting() {
}
@Override
protected void onAppConfigReady(AppConfig config,Map<String, String> initParams) {
this.basePath = initParams.getOrDefault(App.INIT_PARAM_BASE_PATH, App.DEFAULT_BASE_PATH);
this.app = scanGlobalObject(servletContext, config);
if(null == app){
app = new App();
}
app.onConfigReady(config, servletContext, basePath);
servletContext.setAttribute(APP_ATTR_NAME, app);
}
@Override
protected void onBeanFactoryReady(BeanFactory factory) {
app.onBeanFactoryReady(factory);
}
@Override
protected void onAppContextReady(AppContext context) {
beanFactory.addBean(App.class, app, true);
beanFactory.addBean(ServletContext.class, servletContext, true);
beanFactory.inject(app);
if(app.getClass() != App.class){
beanFactory.addBean(app);
}
app.onContextReady(context);
this.handler = beanFactory.getBean(AppHandler.class);
try {
this.handler.initApp();
} catch (Throwable e) {
if(e instanceof RuntimeException){
throw (RuntimeException)e;
}
throw new AppException("Error init app, " + e.getMessage(), e);
}
}
protected final void startApplication() throws ServletException {
this._token = handler.startApp();
}
protected final void stopApplication(){
try{
AppContext.setCurrent(appContext);
if(null != handler && null != _token){
handler.stopApp(_token);
servletContext.removeAttribute(APP_ATTR_NAME);
}
for(BeanDefinition bootable : bootables) {
try{
AppBootable bean = ((AppBootable)bootable.getSingletonInstance());
if(null != bean) {
bean.onAppStopped(app, servletContext);
}
}catch(Throwable e) {
log.warn("Error invoke onAppStopped on bootable bean, {}", e.getMessage(), e);
}
}
}finally{
super.destroyAppContext();
}
}
protected App scanGlobalObject(ServletContext sc, AppConfig config) {
String globalClassName = config.getBasePackage() + "." + GLOBAL_CLASS_NAME;
Class<?> globalClass = Classes.tryForName(Thread.currentThread().getContextClassLoader(), globalClassName);
if(null != globalClass && App.class.isAssignableFrom(globalClass)){
return (App)Reflection.newInstance(globalClass);
}else {
return null;
}
}
protected static String getAppDisplayName(ServletContext sc){
String path = sc.getContextPath();
if("".equals(path)){
return "ROOT";
}else{
return path;
}
}
public static final class AppBeanProcessor implements BeanProcessor,ServletOnlyBean {
@Override
public void postInitBean(AppContext context, BeanFactory factory, BeanDefinitionConfigurator c) throws Throwable {
BeanDefinition bd = c.definition();
boolean initializable = AppInitializable.class.isAssignableFrom(bd.getBeanClass());
boolean bootable = AppBootable.class.isAssignableFrom(bd.getBeanClass());
if(initializable || bootable) {
ServletContext sc = context.tryGetServletContext();
if(null == sc) {
throw new BeanDefinitionException("Current app context must be servlet environment, cannot init bean " + bd);
}
if(!bd.isSingleton()) {
throw new BeanDefinitionException("Bean must be singleton, check the bean " + bd);
}
if(initializable) {
app(sc,bd).initializableBeans().add(bd);
}
if(bootable) {
get(sc).bootables.add(bd);
}
}
}
@Override
public void postCreateBean(AppContext appContext, BeanFactory beanFactory, BeanDefinition definition, Object bean) throws Exception {
ServletContext sc = appContext.tryGetServletContext();
if(bean instanceof AppAware){
if(null == sc){
throw new BeanCreationException("Current app context must be servlet environment, cannot create bean " + definition);
}
((AppAware) bean).setApp(app(sc, definition));
}
}
protected App app(ServletContext sc, BeanDefinition bd) {
App app = (App)sc.getAttribute(APP_ATTR_NAME);
if(null == app){
throw new BeanCreationException("App not ready yet, cannot create bean " + bd);
}
return app;
}
}
} | 31.642857 | 142 | 0.641391 |
f353e61f3fff88055607fa6c473870a3c1cb4203 | 1,067 | package net.md_5.bungee.protocol.packet;
import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import net.md_5.bungee.protocol.AbstractPacketHandler;
import net.md_5.bungee.protocol.DefinedPacket;
import net.md_5.bungee.protocol.ProtocolConstants;
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class SystemChat extends DefinedPacket
{
private String message;
private int position;
@Override
public void read(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
{
message = readString( buf, 262144 );
position = readVarInt( buf );
}
@Override
public void write(ByteBuf buf, ProtocolConstants.Direction direction, int protocolVersion)
{
writeString( message, buf );
writeVarInt( position, buf );
}
@Override
public void handle(AbstractPacketHandler handler) throws Exception
{
handler.handle( this );
}
}
| 25.404762 | 94 | 0.740394 |
f9583f51aab4220fd4b3737e56a3eb5e2105b2bc | 5,433 | /* Author: Mingcheng Chen
* Editor: Felix Wang
* */
import java.util.Random;
import java.util.ArrayList;
import java.io.PrintWriter;
public class Simulator {
public static void main(String[] args) {
if (args.length != 6) {
System.out.println("Usage: java Simulator <world> <agent> <steps> <episodes> <policy_output> <episode_output>");
return;
}
World world;
try {
Class c = Class.forName(args[0]);
world = (World)c.newInstance();
} catch (Exception e) {
System.out.println("Error: invalid world class");
return;
}
Agent agent;
try {
Class c = Class.forName(args[1]);
agent = (Agent)c.newInstance();
} catch (Exception e) {
System.out.println("Error: invalid agent class");
return;
}
int steps;
try {
steps = Integer.parseInt(args[2]);
} catch (Exception e) {
System.out.println("Error: invalid steps");
return;
}
int episodes;
try {
episodes = Integer.parseInt(args[3]);
} catch (Exception e) {
System.out.println("Error: invalid episodes");
return;
}
String policyOutput = args[4];
String episodeOutput = args[5];
(new Simulator(world, agent, steps, episodes, policyOutput, episodeOutput)).simulate();
}
public Simulator(World world, Agent agent, int steps, int episodes, String policyOutput, String episodeOutput) {
this.world = world;
this.agent = agent;
this.steps = steps;
this.episodes = episodes;
this.policyOutput = policyOutput;
this.episodeOutput = episodeOutput;
this.rand = new Random(System.currentTimeMillis());
}
public void simulate() {
this.agent.initialize(this.world.getNumberOfStates(), numOfActions);
ArrayList<Double> episodeList = new ArrayList<Double>();
for (int episode = 0; episode < this.episodes; episode++) {
this.world.initialize();
int initialState = this.world.getInitialState();
int robotRow = this.world.getNumberOfRows() - 1;
int robotCol = 2;
int forkliftCol = -1;
if (this.world.hasForklift()) {
forkliftCol = this.world.getForkliftCol();
}
boolean hasP1 = true, hasP2 = true;
int currState = initialState;
double totalReward = 0.0;
for (int step = 0; step < this.steps; step++) {
int action = this.agent.chooseAction(currState);
int nextRobotRow = robotRow + directions[action][0];
int nextRobotCol = robotCol + directions[action][1];
// Test for wall
if (nextRobotRow < 0 || nextRobotCol < 0 || nextRobotRow >= this.world.getNumberOfRows() ||
nextRobotCol >= this.world.getNumberOfCols()) {
nextRobotRow = robotRow;
nextRobotCol = robotCol;
}
// update position
robotRow = nextRobotRow;
robotCol = nextRobotCol;
double reward = 0.0;
// Test for obstacles
if (this.world.collideObstacle(nextRobotRow, nextRobotCol) > 0.0) {
if (rand.nextDouble() <= this.world.collideObstacle(nextRobotRow, nextRobotCol)) {
reward -= lossByLockup;
}
}
// Move forklift
this.world.evolve();
// Test for forklift
if (this.world.hasForklift()) {
forkliftCol = this.world.getForkliftCol();
}
if (this.world.collideForklift(robotRow, robotCol)) {
reward -= lossByLockup;
}
if (!hasP1 && !hasP2) { // has nothing (needs to go back to the loading dock)
if (this.world.atLoading(robotRow, robotCol)) { // load new pallets
hasP1 = true;
hasP2 = true;
}
} else { // has at least one pallet (successfully delivered one)
if (hasP1 && this.world.atStacking(robotRow, robotCol) == 1) {
hasP1 = false;
}
if (hasP2 && this.world.atStacking(robotRow, robotCol) == 2) {
hasP2 = false;
}
if (!hasP1 && !hasP2) { // successful delivery
reward += rewardByStacking;
}
}
totalReward += reward;
int newState = this.world.hasForklift() ? this.world.getState(robotRow, robotCol, forkliftCol, hasP1, hasP2) :
this.world.getState(robotRow, robotCol, hasP1, hasP2);
this.agent.updatePolicy(reward, action, currState, newState);
currState = newState;
}
System.out.println("Episode " + (episode + 1) + ": reward = " + totalReward);
episodeList.add(totalReward);
}
this.agent.getPolicy().save(this.policyOutput);
try {
PrintWriter writer = new PrintWriter(this.episodeOutput);
for (int i = 0; i < episodeList.size(); i++) {
writer.println(episodeList.get(i));
}
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static final int numOfActions = 5;
private static final int[][] directions = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}, {0, 0}}; // NSEW
private static final double lossByLockup = 1.0;
private static final double rewardByStacking = 1.0;
private World world;
private Agent agent;
private int steps;
private int episodes;
private String policyOutput;
private String episodeOutput;
private Random rand;
}
| 28.445026 | 118 | 0.590282 |
36c222675458043d15c1ea335d7b0138bff7610a | 8,255 | package com.universalcinemas.application.views.crudplans;
import java.util.Optional;
import javax.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;
import org.vaadin.artur.helpers.CrudServiceDataProvider;
import com.universalcinemas.application.data.plan.Plan;
import com.universalcinemas.application.data.plan.PlanService;
import com.universalcinemas.application.data.genre.Genre;
import com.universalcinemas.application.data.genre.GenreService;
import com.universalcinemas.application.views.MainLayout;
import com.universalcinemas.application.views.crudplans.CrudPlansView;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.IntegerField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
@PageTitle("Panel plans")
@Route(value = "crudplans/:PlanID?/:action?(edit)", layout = MainLayout.class)
@RolesAllowed("ROLE_admin")
public class CrudPlansView extends Div implements BeforeEnterObserver {
private static final long serialVersionUID = 1L;
private final String FILM_ID = "PlanID";
private final String FILM_EDIT_ROUTE_TEMPLATE = "crudplans/%d/edit";
private Grid<Plan> grid = new Grid<>(Plan.class, false);
private TextField name;
private TextField description;
private IntegerField percent;
private IntegerField price;
private ComboBox<Genre> genre;
private Button cancel = new Button("Cancelar");
private Button save = new Button("Guardar");
private Button delete = new Button("Eliminar");
private BeanValidationBinder<Plan> binder;
private Plan plan;
private PlanService planService;
private GenreService genreService;
@SuppressWarnings("deprecation")
public CrudPlansView(@Autowired PlanService planService, GenreService genreService) {
this.planService = planService;
this.genreService = genreService;
addClassNames("crud-plans-view-view", "flex", "flex-col", "h-full");
// Create UI
SplitLayout splitLayout = new SplitLayout();
splitLayout.setSizeFull();
createGridLayout(splitLayout);
createEditorLayout(splitLayout);
add(splitLayout);
// Configure Grid
grid.addColumn("name").setAutoWidth(true).setHeader("Nombre");
grid.addColumn("description").setAutoWidth(true).setHeader("Descripción");
grid.addColumn("percent").setAutoWidth(true).setHeader("Porcentaje de descuento");
grid.addColumn("price").setAutoWidth(true).setHeader("Precio");
grid.addColumn(plan -> {return plan.getGenre().getName();}).setAutoWidth(true).setHeader("Género");
grid.setDataProvider(new CrudServiceDataProvider<>(planService));
grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);
grid.setHeightFull();
// when a row is selected or deselected
grid.asSingleSelect().addValueChangeListener(event -> {
if (event.getValue() != null) {
UI.getCurrent().navigate(String.format(FILM_EDIT_ROUTE_TEMPLATE, event.getValue().getId()));
delete.setVisible(true);
} else {
clearForm();
UI.getCurrent().navigate(CrudPlansView.class);
delete.setVisible(false);
}
});
// Configure Form
binder = new BeanValidationBinder<>(Plan.class);
binder.bindInstanceFields(this);
cancel.addClickListener(e -> {
clearForm();
refreshGrid();
});
save.addClickListener(e -> {
try {
if (this.plan == null) {
this.plan = new Plan();
}
if (name.isEmpty()) {
Notification.show("Introduce el nombre del plan");
} else if (description.isEmpty()) {
Notification.show("Introduce la description del plan");
} else if (percent.isEmpty()) {
Notification.show("Introduce el porcentaje");
} else if (price.isEmpty()) {
Notification.show("Introduce el precio");
} else if (genre.isEmpty()) {
Notification.show("Introduce el género");
} else {
//Plan plan_exists = planService.loadPlanByName(name.getValue());
//if(plan_exists.getName() == null) {
binder.writeBean(this.plan);
planService.update(this.plan);
clearForm();
refreshGrid();
Notification.show("Plan guardado correctamente.");
UI.getCurrent().navigate(CrudPlansView.class);
//}
//else {
// Notification.show("Plan ya registrada.");
//}
}
} catch (ValidationException validationException) {
Notification.show("Ocurrió un error al guardar los datos del plan.");
}
});
delete.addClickListener(e -> {
try {
binder.getBean();
planService.delete(this.plan.getId());
clearForm();
refreshGrid();
Notification.show("Plan eliminado correctamente.");
UI.getCurrent().navigate(CrudPlansView.class);
} catch (Exception exception) {
Notification.show("No se puede borrar el el plan ya que hay usuarios que están suscritos a él.");
}
});
}
@Override
public void beforeEnter(BeforeEnterEvent event) {
Optional<Integer> PlanId = event.getRouteParameters().getInteger(FILM_ID);
if (PlanId.isPresent()) {
Optional<Plan> PlanFromBackend = planService.get(PlanId.get());
if (PlanFromBackend.isPresent()) {
populateForm(PlanFromBackend.get());
} else {
Notification.show("No se pudo encontrar ese plan");
// when a row is selected but the data is no longer available
refreshGrid();
event.forwardTo(CrudPlansView.class);
}
}
}
private void createEditorLayout(SplitLayout splitLayout) {
Div editorLayoutDiv = new Div();
editorLayoutDiv.setClassName("flex flex-col");
editorLayoutDiv.setWidth("400px");
Div editorDiv = new Div();
editorDiv.setClassName("p-l flex-grow");
editorLayoutDiv.add(editorDiv);
FormLayout formLayout = new FormLayout();
name = new TextField("Nombre");
description = new TextField("Descripción");
genre = new ComboBox<Genre>("Género");
genre.setItems(genreService.findAll()); // list/set of possible cities.
genre.setItemLabelGenerator(genre -> genre.getName());
percent = new IntegerField("Porcentaje");
price = new IntegerField("Precio");
Component[] fields = new Component[] { name, description, percent, price, genre };
for (Component field : fields) {
((HasStyle) field).addClassName("full-width");
}
formLayout.add(fields);
editorDiv.add(formLayout);
createButtonLayout(editorLayoutDiv);
splitLayout.addToSecondary(editorLayoutDiv);
}
private void createButtonLayout(Div editorLayoutDiv) {
HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setClassName("w-full flex-wrap bg-contrast-5 py-s px-l");
buttonLayout.setSpacing(true);
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
delete.getStyle().set("margin-inline-start", "auto");
delete.setVisible(false);
buttonLayout.add(save, cancel, delete);
editorLayoutDiv.add(buttonLayout);
}
private void createGridLayout(SplitLayout splitLayout) {
Div wrapper = new Div();
wrapper.setId("grid-wrapper");
wrapper.setWidthFull();
splitLayout.addToPrimary(wrapper);
wrapper.add(grid);
}
private void refreshGrid() {
grid.select(null);
grid.getDataProvider().refreshAll();
}
private void clearForm() {
populateForm(null);
}
private void populateForm(Plan value) {
this.plan = value;
binder.readBean(this.plan);
}
}
| 33.28629 | 101 | 0.732889 |
cc5002321337b0d67bcde1fb54bb06f990b97d9a | 220 | package com.ywj.util.base;
/**
* author: ywj
* created on: 2018/10/31 10:34
* description: App常量
*/
public class AppConstant {
public static String USER_ID;
public static final String DATA = "DATA";
}
| 12.222222 | 45 | 0.659091 |
b0877a831b3b1e5f3b88615dea406f1af0e1c435 | 2,170 | /*
* Copyright 2017 Apereo
*
* 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.tle.core.item.security;
import com.tle.common.Check;
import com.tle.common.security.SecurityConstants;
import com.tle.core.guice.Bind;
import com.tle.core.security.SecurityTargetHandler;
import java.util.Collection;
import java.util.Set;
import javax.inject.Singleton;
@Bind
@Singleton
public class SimpleItemSecurityTargetHandler implements SecurityTargetHandler {
@Override
public void gatherAllLabels(Set<String> labels, Object target) {
SimpleItemSecurity itemSecurity = (SimpleItemSecurity) target;
long collectionId = itemSecurity.getCollectionId();
String status = itemSecurity.getStatus();
labels.add(SecurityConstants.TARGET_ITEM + ':' + itemSecurity.getItemId());
labels.add(SecurityConstants.TARGET_ITEM_STATUS + ':' + status);
labels.add(SecurityConstants.TARGET_ITEM_STATUS + ':' + collectionId + ':' + status);
labels.add(SecurityConstants.TARGET_BASEENTITY + ':' + collectionId);
Collection<String> metadataTargets = itemSecurity.getMetadataTargets();
if (!Check.isEmpty(metadataTargets)) {
for (String metaTarget : metadataTargets) {
labels.add(SecurityConstants.TARGET_ITEM_METADATA + ':' + collectionId + ':' + metaTarget);
}
}
}
@Override
public String getPrimaryLabel(Object target) {
throw new UnsupportedOperationException();
}
@Override
public Object transform(Object target) {
throw new UnsupportedOperationException();
}
@Override
public boolean isOwner(Object target, String userId) {
return ((SimpleItemSecurity) target).isOwner();
}
}
| 33.384615 | 99 | 0.742396 |
b36f0d085a5c7dbbfb3ab811ba7d10d8bd65dbb9 | 9,602 | package src.main.gov.va.vha09.grecc.raptat.gg.oneoffs.raptatutilities;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.SwingUtilities;
import org.apache.commons.io.FileUtils;
import src.main.gov.va.vha09.grecc.raptat.gg.core.RaptatConstants;
import src.main.gov.va.vha09.grecc.raptat.gg.core.RaptatConstants.ContextHandling;
import src.main.gov.va.vha09.grecc.raptat.gg.core.UserPreferences;
import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.AnnotatedPhrase;
import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.annotationcomponents.RaptatToken;
import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.hashtrees.HashTreeFields;
import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.hashtrees.UnlabeledHashTree;
import src.main.gov.va.vha09.grecc.raptat.gg.datastructures.hashtrees.UnlabeledHashTreeFields;
import src.main.gov.va.vha09.grecc.raptat.gg.helpers.GeneralHelper;
import src.main.gov.va.vha09.grecc.raptat.gg.textanalysis.RaptatDocument;
import src.main.gov.va.vha09.grecc.raptat.gg.textanalysis.TextAnalyzer;
public class WordSequenceFrequency {
private final static RaptatToken TOKEN_FOR_INSERT = new RaptatToken("$**NOTOKEN@@$", -1, -1);
private final static Matcher NON_ALPHANUMERIC_MATCHER = Pattern.compile("^\\W").matcher("");
private final static Matcher NUMBER_MATCHER =
Pattern.compile("^[+-]?(?:(?:\\.\\d+)|(?:\\d{1,3}(,?\\d{3})*(?:\\.\\d+|\\.)?))$").matcher("");
public WordSequenceFrequency() {}
public static void main(final String[] args) {
// UserPreferences.INSTANCE.initializeLVGLocation();
// final Map<String, String> envMap = System.getenv();
String lvgPath = System.getenv("LVG_DIR");
UserPreferences.INSTANCE.setLvgPath(lvgPath);
// Set to any integer less than 1 to print all phrase lengths
final int targetNgramLength = 0;
final int maxNgramLength = 4;
final int minOccurrences = 4;
final String directoryPath =
"P:/ORD_Oh_PTR_201903029D/GobbelWorkspace/SmallPatientSet/010_PatientDocs";
// "P:\\ORD_Girotra_201607120D\\Glenn\\eHOSTWorkspace\\FirstReference200DocsTokenPhraseLabels_Updated_191015\\corpus";
final String outputDirectoryName = "Output";
final String assignedLabel = "DermNgrams";
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
List<File> documentFiles = getDocumentFiles(directoryPath);
final UnlabeledHashTree phraseFrequencyTree = buildPhraseFrequencyTree(documentFiles);
final String outputDirectoryPath =
new File(directoryPath).getParent() + File.separator + outputDirectoryName;
final String outputPath =
outputDirectoryPath + File.separator + assignedLabel + "_Output_PhraseLength_"
+ targetNgramLength + "_" + GeneralHelper.getTimeStamp() + ".txt";
try {
FileUtils.forceMkdir(new File(outputDirectoryPath));
System.out.println("Writing results to :\n" + outputPath);
final PrintWriter pw = new PrintWriter(outputPath);
printPhraseOccurrences(phraseFrequencyTree, targetNgramLength, minOccurrences, pw);
// '**************************************************************************
// final Map<Long, List<String>> phraseOccurrenceMap =
// this.getPhraseOccurrenceMap(phraseFrequencyTree, targetNgramLength);
//
// final List<Long> occurrenceList = new ArrayList<>(phraseOccurrenceMap.keySet());
// Collections.sort(occurrenceList, Collections.reverseOrder());
//
// for (final Long listKey : occurrenceList) {
// final List<String> phraseList = phraseOccurrenceMap.get(listKey);
// Collections.sort(phraseList);
// for (final String phrase : phraseList) {
// // Add apostrophe (') so excel will read unusual, non-alphanumeric characters
// // properly
// final String prepend = nonAlphanumericMatcher.reset(phrase).find() ? "'" : "";
// final String outputString = prepend + phrase + "\t" + listKey;
// System.out.println(outputString);
// pw.println(outputString);
// pw.flush();
// }
// }
// '**************************************************************************
pw.close();
System.out.println("Completed writing results to :\n" + outputPath);
System.exit(0);
} catch (final FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} catch (final IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected UnlabeledHashTree buildPhraseFrequencyTree(final List<File> documentFiles) {
UnlabeledHashTree phraseFrequencyTree = new UnlabeledHashTree();
final TextAnalyzer theAnalyzer = new TextAnalyzer();
theAnalyzer.setGenerateTokenPhrases(false);
theAnalyzer.setTokenProcessingParameters(false, false, true, maxNgramLength,
ContextHandling.NONE);
int index = 1;
for (final File nextFile : documentFiles) {
System.out.println("Processing " + index++ + " of " + documentFiles.size() + " files");
final RaptatDocument inputDocument =
theAnalyzer.processDocument(nextFile.getAbsolutePath());
inputDocument.activateBaseSentences();
System.out.println("Building frequency tree for " + nextFile.getName());
addToFrequencyTree(phraseFrequencyTree, inputDocument);
}
System.out.println("Phrase frequency tree complete");
return phraseFrequencyTree;
}
private void addToFrequencyTree(final UnlabeledHashTree frequencyTree,
final RaptatDocument raptatDocument) {
final List<AnnotatedPhrase> activeSentences = raptatDocument.getActiveSentences();
for (final AnnotatedPhrase curSentence : activeSentences) {
final List<RaptatToken> sentenceTokens = curSentence.getProcessedTokens();
final int sentenceSize = sentenceTokens.size();
for (int curTokenIndex = 0; curTokenIndex < sentenceSize; curTokenIndex++) {
frequencyTree.addUnlabeledSequence(sentenceTokens, curTokenIndex, -1,
RaptatConstants.MAX_TOKENS_DEFAULT);
}
}
}
/**
* @param directoryPath
* @return
*/
private List<File> getDocumentFiles(final String directoryPath) {
File fileDirectory = new File(directoryPath);
if (!fileDirectory.exists()) {
fileDirectory =
GeneralHelper.getDirectory("Select directory containing files for analysis");
}
// final File[] files = fileDirectory.listFiles(GeneralHelper.getFilenameFilter(".txt"));
List<File> fileList = new ArrayList<>();
try (final Stream<Path> fileWalk = Files.walk(Paths.get(directoryPath))) {
fileList = fileWalk.filter(filePath -> filePath.toString().endsWith(".txt"))
.map(Path::toFile).collect(Collectors.toList());
} catch (final IOException e) {
System.err.print("Unable to get files\n" + e.getLocalizedMessage());
e.printStackTrace();
System.exit(-1);
}
return fileList;
}
private void printPhraseOccurrences(final UnlabeledHashTree phrases,
final int targetPhraseLength, final int minOccurrences, final PrintWriter pw) {
for (final HashTreeFields phrase : phrases) {
final UnlabeledHashTreeFields unlabeledPhrase = (UnlabeledHashTreeFields) phrase;
if (targetPhraseLength < 1
|| unlabeledPhrase.tokenSequence.size() == targetPhraseLength) {
final Iterator<String> sequenceIterator = unlabeledPhrase.tokenSequence.iterator();
int actualPhraseLength = 1;
String phraseString = sequenceIterator.next();
if (!WordSequenceFrequency.NON_ALPHANUMERIC_MATCHER.reset(phraseString).find()) {
if (WordSequenceFrequency.NUMBER_MATCHER.reset(phraseString).find()) {
phraseString = "NUMBER";
}
final StringBuilder sb = new StringBuilder(phraseString);
while (sequenceIterator.hasNext()) {
phraseString = sequenceIterator.next();
if (!WordSequenceFrequency.NON_ALPHANUMERIC_MATCHER.reset(phraseString).find()) {
if (WordSequenceFrequency.NUMBER_MATCHER.reset(phraseString).find()) {
phraseString = "NUMBER";
}
++actualPhraseLength;
sb.append(" ").append(phraseString);
}
}
final Long occurrences = unlabeledPhrase.unlabeled / 967680;
if (occurrences >= minOccurrences) {
String outputString =
actualPhraseLength + "\t" + occurrences + "\t" + "'" + sb.toString();
System.out.println(outputString);
pw.println(outputString);
pw.flush();
}
}
}
}
}
});
}
}
| 45.942584 | 122 | 0.649552 |
b265fc9dee08d750abeef3f214c440701fd7bb4c | 954 | package com.develdio.remotesearch.shared.helper;
import java.util.List;
import java.util.Map;
import com.develdio.remotesearch.shared.Info;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This class plays with JSON Notation, providing the final user the possibility
* of writes to standard output the JSON format.
*
* @author Diogo Pinto <[email protected]>
* @since 1.1
*/
public final class JSONNotation
{
/**
* This class provides a map with list of Info, into String.
*
* @param mapListInfo
* map with list of info that will be writen into String
* @return the String with Info data
*/
public static String
notationInfo( final Map<String, List<Info>> mapListInfo )
{
String out = "";
try
{
out = new ObjectMapper().writeValueAsString( mapListInfo );
}
catch( JsonProcessingException ignored )
{
return "";
}
return out;
}
} | 23.268293 | 80 | 0.714885 |
f9d510c1672e44e0e073b1a6c31843daef072954 | 1,191 | package ru.mydesignstudio.database.metadata.extractor.extractors.type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.mydesignstudio.database.metadata.extractor.extractors.ExtractHelper;
import ru.mydesignstudio.database.metadata.extractor.extractors.TableMetadataAppender;
import ru.mydesignstudio.database.metadata.extractor.extractors.model.TableMetadata;
import ru.mydesignstudio.database.metadata.extractor.extractors.model.TypeModel;
import ru.mydesignstudio.database.metadata.extractor.resource.StringResource;
@Slf4j
@Component
public class TypeExtractor implements TableMetadataAppender {
@StringResource("classpath:sql/extract_type.sql")
private String typeQuery;
@Autowired
private ExtractHelper helper;
@Override
public void append(TableMetadata metadata, String schemaName, String tableName) {
log.info("Extracting types for table {} in schema {}", tableName, schemaName);
metadata.setTypes(helper.extract(typeQuery, new Object[]{tableName, schemaName}, TypeModel.class));
log.debug("Extracted {} types", metadata.getTypes().size());
}
} | 41.068966 | 103 | 0.816961 |
c2e66b0efaa9d7931318d037c0d21f7529396bfb | 164 | package yom2;
/**
* Represents an action without parameters.
* @author erelsgl
*
*/
public interface Runnable {
/**
* The action to do.
*/
void run();
}
| 11.714286 | 43 | 0.621951 |
f505199cc92eb5063c8ac04d6105f8975baf1e78 | 1,721 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright 2006, 2007 Sakai Foundation
*
* Licensed 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://www.opensource.org/licenses/ECL-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.sakaiproject.emailtemplateservice.api;
import org.sakaiproject.emailtemplateservice.api.model.EmailTemplate;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class RenderedTemplate extends EmailTemplate {
private static final long serialVersionUID = -6279976323700630617L;
private String renderedSubject;
private String renderedMessage;
private String renderedHtmlMessage;
private List<String> headers;
public RenderedTemplate(EmailTemplate template) {
this.setId(template.getId());
this.setSubject(template.getSubject());
this.setMessage(template.getMessage());
this.setKey(template.getKey());
this.setLocale(template.getLocale());
this.setHtmlMessage(template.getHtmlMessage());
}
}
| 33.096154 | 84 | 0.627542 |
92016d69598612934f33dbe388eca563b428d7fb | 483 | package org.cx.game.utils;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import lombok.Data;
@Data
public class Connect {
@NotNull
@NotBlank
private String playNo; //比赛ID号
@NotNull
@Min(1)
private Integer troop; //阵营
@NotNull
@Min(0)
private Integer sequence = 0; //同步进程
private Boolean firstHand = false; //先手
private Integer hostStatus = 0; //主机状态
}
| 18.576923 | 45 | 0.706004 |
fe138625c2053d47d92f9e6c1ddb83065b41a0fa | 409 | package com.denizenscript.denizen.nms.util;
import org.bukkit.util.Vector;
public class BoundingBox {
private Vector low;
private Vector high;
public BoundingBox(Vector location, Vector size) {
this.low = location;
this.high = size;
}
public Vector getLow() {
return low;
}
public Vector getHigh() {
return high;
}
}
| 17.782609 | 55 | 0.589242 |
bb45cb429bc7d7698b472d1739eedef469404b6c | 8,384 | package ru.solargateteam.galnetru.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import ru.solargateteam.galnetru.Global;
import ru.solargateteam.galnetru.util.Util;
import ru.solargateteam.galnetru.rss.RSSItem;
public class DBEngine {
DBHelper dbh;
SQLiteDatabase db;
public DBEngine(Context context) {
dbh = new DBHelper(context);
db = dbh.getWritableDatabase();
}
public void close() {
Log.d(Global.TAG, "DB Close");
dbh.close();
}
private boolean checkContentExistsByLink(String link, String feedContent) {
boolean result;
Cursor c = db.rawQuery(String.format(DBHelper.DB_SQL_SELECTBY_LINK, link, feedContent), null);
result = (c.getCount() != 0);
c.close();
return result;
}
public void insertContentItem(RSSItem rssItem, String feedContent) {
if (!checkContentExistsByLink(rssItem.getLink(), feedContent) &&
Util.checkURL(rssItem.getLink())) {
ContentValues cv = new ContentValues();
cv.put(DBHelper.FIELD_KEY_GUID, rssItem.getGuid());
cv.put(DBHelper.FIELD_TITLE, rssItem.getTitle());
cv.put(DBHelper.FIELD_LINK, rssItem.getLink());
cv.put(DBHelper.FIELD_DESCRIPTION, rssItem.getDescription());
cv.put(DBHelper.FIELD_PUBDATE, Util.getUnixTime(rssItem.getPubDate()));
cv.put(DBHelper.FIELD_FEED_TYPE, feedContent);
cv.put(DBHelper.FIELD_NEW_POST, DBHelper.NEW_POST_TRUE);
db.beginTransaction();
db.insert(DBHelper.DB_TABLE_CONTENT, null, cv);
db.setTransactionSuccessful();
db.endTransaction();
Log.i(Global.TAG, "INSERT: " + rssItem.getTitle() + " " + feedContent + " " + rssItem.getLink());
}
}
public void updateImage(DBItem dbItem) {
ContentValues cv = new ContentValues();
cv.put(DBHelper.FIELD_IMAGE_PATH, dbItem.getImagePath());
db.beginTransaction();
db.update(DBHelper.DB_TABLE_CONTENT, cv, DBHelper.FIELD_LINK + " = ?", new String[]{dbItem.getLink()});
db.setTransactionSuccessful();
db.endTransaction();
}
public void updateNewPostToOld() {
Log.d(Global.TAG, "updateNewPostToOld");
ContentValues cv = new ContentValues();
cv.put(DBHelper.FIELD_NEW_POST, DBHelper.NEW_POST_FALSE);
db.beginTransaction();
db.update(DBHelper.DB_TABLE_CONTENT, cv, DBHelper.FIELD_NEW_POST + " = ?", new String[]{Integer.toString(DBHelper.NEW_POST_TRUE)});
db.setTransactionSuccessful();
db.endTransaction();
}
public List<DBItem> readContent(String feedType) {
List<DBItem> returnList = new ArrayList<DBItem>();
String selection = null;
String[] selectionArgs = null;
if (feedType.equals(Global.FEED_TYPE_ALL)) {
selection = null;
selectionArgs = null;
} else {
selection = DBHelper.FIELD_FEED_TYPE + " = ?";
selectionArgs = new String[] { feedType };
}
Cursor c = db.query(DBHelper.DB_TABLE_CONTENT, null, selection, selectionArgs, null, null, DBHelper.FIELD_PUBDATE + " desc");
if (c != null) {
if (c.moveToFirst()) {
do {
DBItem currentItem = new DBItem();
currentItem.setId(c.getInt(c.getColumnIndex(DBHelper.FIELD_KEY_ID)));
currentItem.setTitle(c.getString(c.getColumnIndex(DBHelper.FIELD_TITLE)));
currentItem.setLink(c.getString(c.getColumnIndex(DBHelper.FIELD_LINK)));
currentItem.setDescription(c.getString(c.getColumnIndex(DBHelper.FIELD_DESCRIPTION)));
currentItem.setImagePath(c.getString(c.getColumnIndex(DBHelper.FIELD_IMAGE_PATH)));
currentItem.setPubDate(c.getLong(c.getColumnIndex(DBHelper.FIELD_PUBDATE)));
currentItem.setNewPost(c.getInt(c.getColumnIndex(DBHelper.FIELD_NEW_POST)));
returnList.add(currentItem);
} while (c.moveToNext());
}
c.close();
}
return returnList;
}
public List<DBItem> readContentNew() {
List<DBItem> returnList = new ArrayList<DBItem>();
Cursor c = db.query(DBHelper.DB_TABLE_CONTENT, null, DBHelper.FIELD_NEW_POST + " = ?", new String[]{Integer.toString(DBHelper.NEW_POST_TRUE)}, null, null, DBHelper.FIELD_PUBDATE + " desc");
if (c != null) {
if (c.moveToFirst()) {
do {
DBItem currentItem = new DBItem();
currentItem.setId(c.getInt(c.getColumnIndex(DBHelper.FIELD_KEY_ID)));
currentItem.setTitle(c.getString(c.getColumnIndex(DBHelper.FIELD_TITLE)));
currentItem.setLink(c.getString(c.getColumnIndex(DBHelper.FIELD_LINK)));
currentItem.setDescription(c.getString(c.getColumnIndex(DBHelper.FIELD_DESCRIPTION)));
currentItem.setImagePath(c.getString(c.getColumnIndex(DBHelper.FIELD_IMAGE_PATH)));
currentItem.setPubDate(c.getLong(c.getColumnIndex(DBHelper.FIELD_PUBDATE)));
currentItem.setNewPost(c.getInt(c.getColumnIndex(DBHelper.FIELD_NEW_POST)));
returnList.add(currentItem);
} while (c.moveToNext());
}
c.close();
}
return returnList;
}
private class DBHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1;
private static final String DB_NAME = "GalNET.ru.db";
private static final String DB_TABLE_CONTENT = "Content";
private static final String FIELD_KEY_ID = "id";
private static final String FIELD_KEY_GUID = "guid";
private static final String FIELD_TITLE = "title";
private static final String FIELD_LINK = "link";
private static final String FIELD_DESCRIPTION = "description";
private static final String FIELD_PUBDATE = "pubdate";
private static final String FIELD_FEED_TYPE = "feedtype";
private static final String FIELD_IMAGE_PATH = "imagepath";
private static final String FIELD_NEW_POST = "newpost";
private static final int NEW_POST_TRUE = 1;
private static final int NEW_POST_FALSE = 0;
private static final String DB_SQL_CREATE_CONTENT = "create table " + DB_TABLE_CONTENT + " (" +
FIELD_KEY_ID + " integer primary key autoincrement, " +
FIELD_KEY_GUID + " text, " +
FIELD_TITLE + " text, " +
FIELD_LINK + " text, " +
FIELD_DESCRIPTION + " text, " +
FIELD_IMAGE_PATH + " text, " +
FIELD_FEED_TYPE + " text, " +
FIELD_PUBDATE + " integer, " +
FIELD_NEW_POST + " integer" +
");";
private static final String DB_SQL_DROP_CONTENT = "drop table " + DB_TABLE_CONTENT + ";";
private static final String DB_SQL_SELECTBY_LINK = "select * from " + DB_TABLE_CONTENT +
" where " + FIELD_LINK + " = \"%1$s\"" +
" and " + FIELD_FEED_TYPE + " = \"%2$s\"";
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(Global.TAG, "Creating DB...");
Log.i(Global.TAG, DB_SQL_CREATE_CONTENT);
db.execSQL(DB_SQL_CREATE_CONTENT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(Global.TAG, "Upgrading DB...");
db.execSQL(DB_SQL_DROP_CONTENT);
db.execSQL(DB_SQL_CREATE_CONTENT);
}
}
}
| 40.897561 | 198 | 0.597805 |
2bf22f911c011b03896f800f9b80c3512f0ffaa2 | 2,247 | package com.daemon.pas.ui.activity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.daemon.framework.drecyclerviewadapter.DRecyclerViewAdapter;
import com.daemon.framework.drecyclerviewadapter.DRecyclerViewScrollListener;
import com.daemon.mvp.view.AppView;
import com.daemon.pas.R;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by Daemon on 2015/12/10.
*/
public class SearchPicActivityView extends AppView {
@Bind(R.id.toolbar)
public Toolbar toolbar;
@Bind(R.id.et_search)
EditText etSearch;
@Bind(R.id.rl_search)
RelativeLayout rlSearch;
@Bind(R.id.iv_search)
ImageView ivSearch;
@Bind(R.id.rlv_pics)
RecyclerView rlvPics;
@Bind(R.id.ll_serach)
LinearLayout llSerach;
@Override
protected int getRootLayoutId() {
return R.layout.activity_search_pic;
}
@Override
public void initWeidget() {
ButterKnife.bind(this, getRootView());
}
@Override
public void destory() {
super.destory();
ButterKnife.unbind(this);
}
public void setEditextKey(String key) {
etSearch.setText(key);
}
public String getEdittextKey() {
return etSearch.getText().toString().trim();
}
public void setRecyclerViewInit(DRecyclerViewAdapter dRecyclerViewAdapter,
GridLayoutManager dStaggeredGridLayoutManager) {
rlvPics.setLayoutManager(dStaggeredGridLayoutManager);
rlvPics.setAdapter(dRecyclerViewAdapter);
rlvPics.setItemAnimator(new DefaultItemAnimator());
}
public void addLoadMoreListener(DRecyclerViewScrollListener dRecyclerViewScrollListener) {
rlvPics.addOnScrollListener(dRecyclerViewScrollListener);
}
public void scrollToTop() {
rlvPics.scrollToPosition(0);
}
public void setSearchGone() {
llSerach.setVisibility(View.GONE);
}
}
| 25.247191 | 94 | 0.719181 |
26749013e54349400fe6447d4b4a31303578405d | 3,159 | package com.rance.chatui.util;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
/**
* 作者:Rance on 2016/11/29 10:47
* 邮箱:[email protected]
*/
public class PopupWindowFactory {
private Context mContext;
private PopupWindow mPop;
/**
* @param mContext 上下文
* @param view PopupWindow显示的布局文件
*/
public PopupWindowFactory(Context mContext, View view){
this(mContext,view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
/**
* @param mContext 上下文
* @param view PopupWindow显示的布局文件
* @param width PopupWindow的宽
* @param heigth PopupWindow的高
*/
public PopupWindowFactory(Context mContext, View view, int width, int heigth){
init(mContext,view,width,heigth);
}
private void init(Context mContext, View view, int width, int heigth){
this.mContext = mContext;
//下面这两个必须有!!
view.setFocusable(true);
view.setFocusableInTouchMode(true);
// PopupWindow(布局,宽度,高度)
mPop = new PopupWindow(view,width,heigth,true);
mPop.setFocusable(true);
// 重写onKeyListener,按返回键消失
view.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
mPop.dismiss();
return true;
}
return false;
}
});
//点击其他地方消失
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mPop != null && mPop.isShowing()) {
mPop.dismiss();
return true;
}
return false;
}});
}
public PopupWindow getPopupWindow(){
return mPop;
}
/**
* 以触发弹出窗的view为基准,出现在view的内部上面,弹出的pop_view左上角正对view的左上角
* @param parent view
* @param gravity 在view的什么位置 Gravity.CENTER、Gravity.TOP......
* @param x 与控件的x坐标距离
* @param y 与控件的y坐标距离
*/
public void showAtLocation(View parent, int gravity, int x, int y){
if(mPop.isShowing()){
return ;
}
mPop.showAtLocation(parent, gravity, x, y);
}
/**
* 以触发弹出窗的view为基准,出现在view的正下方,弹出的pop_view左上角正对view的左下角
* @param anchor view
*/
public void showAsDropDown(View anchor){
showAsDropDown(anchor,0,0);
}
/**
* 以触发弹出窗的view为基准,出现在view的正下方,弹出的pop_view左上角正对view的左下角
* @param anchor view
* @param xoff 与view的x坐标距离
* @param yoff 与view的y坐标距离
*/
public void showAsDropDown(View anchor, int xoff, int yoff){
if(mPop.isShowing()){
return ;
}
mPop.showAsDropDown(anchor, xoff, yoff);
}
/**
* 隐藏PopupWindow
*/
public void dismiss(){
if (mPop.isShowing()) {
mPop.dismiss();
}
}
}
| 24.3 | 102 | 0.586578 |
9f75674b9fa5d6c58bce3b7845d3c5acd48291f5 | 699 | package be.pxl.mockitis;
import java.util.ArrayList;
import java.util.List;
public class RaidersTestBuilder
{
private boolean hasLegendary;
private List<Raider> actualRaiders = new ArrayList<Raider>();
public RaidersTestBuilder()
{
}
public Raiders build()
{
Raiders raiders = new Raiders(hasLegendary);
//Steek elke individuele raider is de raiders groep
actualRaiders.forEach(raiders::addAttacker);
return raiders;
}
public RaidersTestBuilder withHaslegendary(boolean hasLegendary)
{
this.hasLegendary = hasLegendary;
return this;
}
public RaidersTestBuilder withActualRaiders(List<Raider> actualRaiders)
{
this.actualRaiders = actualRaiders;
return this;
}
}
| 19.971429 | 72 | 0.76681 |
4ef7f944cb4f2a9deb5a6d255ced8acf25e32e6d | 738 | package cloud.lemonslice.afterthedrizzle.common.item;
import cloud.lemonslice.afterthedrizzle.AfterTheDrizzle;
import cloud.lemonslice.afterthedrizzle.common.config.ServerConfig;
import net.minecraft.item.ItemUseContext;
import net.minecraft.item.Items;
import net.minecraft.util.ActionResultType;
public class FertilizerItem extends NormalItem
{
public FertilizerItem(String name)
{
super(name, new Properties().group(AfterTheDrizzle.GROUP_CORE));
}
@Override
public ActionResultType onItemUse(ItemUseContext context)
{
if (ServerConfig.Agriculture.useAshAsBoneMeal.get())
{
return Items.BONE_MEAL.onItemUse(context);
}
return ActionResultType.PASS;
}
}
| 28.384615 | 72 | 0.743902 |
1cb8ab174372e37f82234c93f2f392d541d3a73e | 72 | package net.livecourse.android.chat;
public class Document
{
}
| 10.285714 | 37 | 0.694444 |
d4ef1f5ae8f80ac019e73ad6105941e1fa68a8bd | 3,413 | package org.codeforamerica.shiba.output.pdf;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.BinaryOperator;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDCheckBox;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.codeforamerica.shiba.output.ApplicationFile;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.Resource;
@Slf4j
public class PDFBoxFieldFiller implements PdfFieldFiller {
private final List<Resource> pdfs;
public PDFBoxFieldFiller(List<Resource> pdfs) {
this.pdfs = pdfs;
}
@Override
public ApplicationFile fill(Collection<PdfField> fields, String applicationId, String filename) {
PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
byte[] fileContents = pdfs.stream()
.map(pdfResource -> fillOutPdfs(fields, pdfResource))
.reduce(mergePdfs(pdfMergerUtility))
.map(this::outputByteArray)
.orElse(new byte[]{});
return new ApplicationFile(fileContents, filename);
}
private byte[] outputByteArray(PDDocument pdDocument) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
pdDocument.save(outputStream);
pdDocument.close();
} catch (IOException e) {
log.error("Unable to save output", e);
}
return outputStream.toByteArray();
}
@NotNull
private BinaryOperator<@NotNull PDDocument> mergePdfs(PDFMergerUtility pdfMergerUtility) {
return (pdDocument1, pdDocument2) -> {
try {
pdfMergerUtility.appendDocument(pdDocument1, pdDocument2);
pdDocument2.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
return pdDocument1;
};
}
@NotNull
private PDDocument fillOutPdfs(Collection<PdfField> fields, Resource pdfResource) {
try {
PDDocument loadedDoc = PDDocument.load(pdfResource.getInputStream());
PDAcroForm acroForm = loadedDoc.getDocumentCatalog().getAcroForm();
acroForm.setNeedAppearances(true);
fillAcroForm(fields, acroForm);
return loadedDoc;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void fillAcroForm(Collection<PdfField> fields, PDAcroForm acroForm) {
fields.forEach(field ->
Optional.ofNullable(acroForm.getField(field.getName())).ifPresent(pdField -> {
try {
String fieldValue = field.getValue();
if (pdField instanceof PDCheckBox && field.getValue().equals("No")) {
fieldValue = "Off";
}
setPdfFieldWithoutUnsupportedUnicode(fieldValue, pdField);
} catch (Exception e) {
throw new RuntimeException("Error setting field: " + field.getName(), e);
}
}));
}
private void setPdfFieldWithoutUnsupportedUnicode(String field, PDField pdField)
throws IOException {
try {
pdField.setValue(field);
} catch (IllegalArgumentException e) {
log.error(
"Error setting value '%s' for field %s".formatted(field,
pdField.getFullyQualifiedName()));
}
}
}
| 32.817308 | 99 | 0.70085 |
70331c301f40b19a920bb2242944f22270c9939d | 667 | package dgm.degraphmalizr.degraphmalize;
import dgm.ID;
public class JobRequest {
private final DegraphmalizeRequestType requestType;
private final DegraphmalizeRequestScope requestScope;
private final ID id;
public JobRequest(DegraphmalizeRequestType requestType, DegraphmalizeRequestScope requestScope, ID id) {
this.requestType = requestType;
this.requestScope = requestScope;
this.id = id;
}
public DegraphmalizeRequestType actionType() {
return requestType;
}
public DegraphmalizeRequestScope actionScope() {
return requestScope;
}
public ID id() {
return id;
}
}
| 23.821429 | 108 | 0.703148 |
ed2b709a56902e450db432881ea00499adbbcb68 | 1,818 | package com.remote2call.common.util;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class SerializationUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
private static Objenesis objenesis = new ObjenesisStd(true);
private SerializationUtil() {
}
private static <T> Schema<T> getSchema(Class<T> cls) {
return (Schema<T>) cachedSchema.computeIfAbsent(cls, RuntimeSchema::createFrom);
}
/**
* object -> bytes
* @param obj
* @param <T>
* @return
*/
public static <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* bytes -> object
* @param data
* @param cls
* @param <T>
* @return
*/
public static <T> T deserialize(byte[] data, Class<T> cls) {
try {
T message = (T) objenesis.newInstance(cls);
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| 28.40625 | 88 | 0.627613 |
8461f9d369d95ccaea06322c4cdcbd48a85307eb | 3,617 | package nc.multiblock.fission.salt.block;
import nc.NuclearCraft;
import nc.enumm.MetaEnums;
import nc.multiblock.fission.FissionReactor;
import nc.multiblock.fission.block.BlockFissionMetaPart;
import nc.multiblock.fission.salt.tile.TileSaltFissionHeater;
import nc.util.*;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.*;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.*;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
public class BlockSaltFissionHeater extends BlockFissionMetaPart<MetaEnums.CoolantHeaterType> {
public final static PropertyEnum TYPE = PropertyEnum.create("type", MetaEnums.CoolantHeaterType.class);
public BlockSaltFissionHeater() {
super(MetaEnums.CoolantHeaterType.class, TYPE);
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, TYPE);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
switch (metadata) {
case 0:
return new TileSaltFissionHeater.Standard();
case 1:
return new TileSaltFissionHeater.Iron();
case 2:
return new TileSaltFissionHeater.Redstone();
case 3:
return new TileSaltFissionHeater.Quartz();
case 4:
return new TileSaltFissionHeater.Obsidian();
case 5:
return new TileSaltFissionHeater.NetherBrick();
case 6:
return new TileSaltFissionHeater.Glowstone();
case 7:
return new TileSaltFissionHeater.Lapis();
case 8:
return new TileSaltFissionHeater.Gold();
case 9:
return new TileSaltFissionHeater.Prismarine();
case 10:
return new TileSaltFissionHeater.Slime();
case 11:
return new TileSaltFissionHeater.EndStone();
case 12:
return new TileSaltFissionHeater.Purpur();
case 13:
return new TileSaltFissionHeater.Diamond();
case 14:
return new TileSaltFissionHeater.Emerald();
case 15:
return new TileSaltFissionHeater.Copper();
}
return new TileSaltFissionHeater.Standard();
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {
if (player == null) {
return false;
}
if (hand != EnumHand.MAIN_HAND || player.isSneaking()) {
return false;
}
if (!world.isRemote) {
TileEntity tile = world.getTileEntity(pos);
if (tile instanceof TileSaltFissionHeater) {
TileSaltFissionHeater heater = (TileSaltFissionHeater) tile;
FissionReactor reactor = heater.getMultiblock();
if (reactor != null) {
FluidStack fluidStack = FluidStackHelper.getFluid(player.getHeldItem(hand));
if (heater.canModifyFilter(0) && heater.getTanks().get(0).isEmpty() && fluidStack != null && !FluidStackHelper.stacksEqual(heater.getFilterTanks().get(0).getFluid(), fluidStack) && heater.getTanks().get(0).canFillFluidType(fluidStack)) {
player.sendMessage(new TextComponentString(Lang.localise("message.nuclearcraft.filter") + " " + TextFormatting.BOLD + Lang.localise(fluidStack.getUnlocalizedName())));
FluidStack filter = fluidStack.copy();
filter.amount = 1000;
heater.getFilterTanks().get(0).setFluid(filter);
heater.onFilterChanged(0);
}
else {
player.openGui(NuclearCraft.instance, 203, world, pos.getX(), pos.getY(), pos.getZ());
}
return true;
}
}
}
return rightClickOnPart(world, pos, player, hand, facing, true);
}
}
| 34.778846 | 242 | 0.739563 |
6e5946f8c667df7a0730ae6b1e016cd77dd4f7b0 | 1,150 | import java.io.File;
import java.util.ArrayDeque;
import java.util.Iterator;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayDeque<Integer> task1 = new ArrayDeque<>();
ArrayDeque<Integer> task2 = new ArrayDeque<>();
Scanner scanner = new Scanner(System.in);
int jobCount = scanner.nextInt();
int j1Load = 0, j2Load=0;
for (int x=0; x<jobCount; x++){
int jobNum = scanner.nextInt();
int jobWork = scanner.nextInt();
if(j1Load <= j2Load) {
task1.push(jobNum);
j1Load += jobWork;
}
else {
task2.push(jobNum);
j2Load += jobWork;
}
//System.out.println(x+1);
}
StringBuilder J1 = new StringBuilder();
StringBuilder J2 = new StringBuilder();
Iterator<Integer> t1IT = task1.descendingIterator();
Iterator<Integer> t2IT = task2.descendingIterator();
while(t1IT.hasNext()){
J1.append(t1IT.next()+" ");
}
while(t2IT.hasNext()){
J2.append(t2IT.next()+" ");
}
System.out.println(J1.toString());
System.out.println(J2.toString());
}
} | 27.380952 | 56 | 0.617391 |
644c3577063fa9bf6a4cda5ac6405f2a86084e9b | 2,211 | package gugugu.commands;
import cc.moecraft.icq.command.CommandProperties;
import cc.moecraft.icq.command.interfaces.EverywhereCommand;
import cc.moecraft.icq.event.events.message.EventMessage;
import cc.moecraft.icq.user.User;
import gugugu.bots.LoggerRabbit;
import gugugu.constant.ConstantQRCode;
import gugugu.service.QRCodeService;
import utils.StringUtil;
import java.util.ArrayList;
/**
* @author MikuLink
* @date 2020/03/31 17:33
* for the Reisen
* <p>
* 生成二维码
*/
public class CommandQRCode implements EverywhereCommand {
/**
* 执行指令
*
* @param event 事件
* @param sender 发送者的用户
* @param command 指令名 ( 不包含指令参数 )
* @param args 指令参数 ( 不包含指令名 )
* @return 发送回去的消息 ( 当然也可以手动发送然后返回空 )
*/
@Override
public String run(EventMessage event, User sender, String command, ArrayList<String> args) {
if (null == args || args.size() == 0) {
return ConstantQRCode.EXPLAIN;
}
//二维码内容
String text = args.get(0);
//图片内容处理
if (text.contains("[CQ:image")) {
//此时内容是网络图片链接
text = StringUtil.getCQImageUrl(text);
}
String bgColor = null;
String fgColor = null;
//由于需要网络图片链接,目前没有可用的图床,只好直接用酷Q的,无法对图片进行修正
String logo = null;
//其他设定
int paramSize = args.size();
if (paramSize >= 2) {
bgColor = args.get(1);
}
if (paramSize >= 3) {
fgColor = args.get(2);
}
if (paramSize >= 4) {
logo = args.get(3);
if (!logo.contains("[CQ:image")) {
return ConstantQRCode.QRCODE_LOGO_NOT_IMAGE;
}
logo = StringUtil.getCQImageUrl(logo);
}
String result = "";
try {
result = QRCodeService.doQRCodeRequest(text, bgColor, fgColor, logo);
} catch (Exception ex) {
LoggerRabbit.logger().error(ConstantQRCode.QRCODE_ERROR + ex.toString(), ex);
result = ConstantQRCode.QRCODE_ERROR;
}
return result;
}
@Override
public CommandProperties properties() {
return new CommandProperties("生成二维码", "二维码", "qrcode");
}
}
| 27.987342 | 96 | 0.589326 |
09567414fd9dfab0fc1936185ffb97c23d052956 | 1,590 | package atUniProMaven.inheritance;
import static atUniProMaven.inheritance.MessageType.*;
public class Main {
public static void main(String[] args) {
final Text text1 = new Text("Mary Key", "01.01.2020", "This is a new text about fast cars", POST, false);
final Media media1 = new Media("Gary Key", "02.01.2020", "This is a new media", REPOST, 200);
final Picture picture1 = new Picture("Tom Key", "03.01.2020", "This is a picture", COMMENT, 300, 2, 4, 6);
final Audio audio1 = new Audio("Max Key", "04.01.2020", "This is an audio", POST, 400, true);
final Video video1 = new Video("Kate Key", "05.01.2020", "This is a video", COMMENT, 500, "AVI");
//Text
text1.maxMessageSizeInMb(10);
text1.displayContent();
text1.isCopyRightProtected(true);
text1.printSomething();
//Media
media1.maxMessageSizeInMb(200);
media1.displayContent();
media1.isMediaSizeAcceptable(300000);
//Picture
picture1.maxMessageSizeInMb(12);
picture1.displayContent();
picture1.square(6, 6);
picture1.printSomething();
//Audio
audio1.maxMessageSizeInMb(3000);
audio1.displayContent();
audio1.isHighQualityFormat(true);
audio1.isHighQualityFormat(false);
audio1.playSomething();
//Video
video1.maxMessageSizeInMb(40000);
video1.displayContent();
video1.isVideoFormatAcceptable("AVI");
video1.isVideoFormatAcceptable("AVI-1");
video1.playSomething();
}
}
| 34.565217 | 114 | 0.628931 |
37fd11835d514974ad15880be574fdc17c3da325 | 850 | package com.voting_app.util.sanitizer;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.voting_app.models.CandidateVote;
/**
********************************************************************
* @implements ICandidateVoteListSanitizer
*
* Bean for sanitizing CandidateVote lists
*
* @author Kyle Williamson
* @version 1.0.0
********************************************************************
*/
@Component
public class CandidateVotesListSanitizer implements ICandidateVoteListSanitizer {
@Override
public List<CandidateVote> sanitizeList(List<CandidateVote> votes) {
List<CandidateVote> sanitizedList = new ArrayList<CandidateVote>();
for(CandidateVote vote: votes) {
if(vote.getRank() != 0) {
sanitizedList.add(vote);
}
}
return sanitizedList;
}
}
| 24.285714 | 81 | 0.634118 |
b780563491662a65f81d3bea3978d321d9861510 | 1,414 | package com.hackedcube.kontact;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import com.gabrielittner.auto.value.cursor.ColumnAdapter;
import com.gabrielittner.auto.value.cursor.ColumnName;
import com.google.auto.value.AutoValue;
import com.hackedcube.kontact.columnadapters.EventTypeIntAdapter;
@AutoValue
public abstract class Event {
@Nullable
@ColumnName(ContactsContract.CommonDataKinds.Event.START_DATE)
public abstract String startDate();
@Nullable
@ColumnAdapter(EventTypeIntAdapter.class)
@ColumnName(ContactsContract.CommonDataKinds.Event.TYPE)
public abstract Event.Type type();
@Nullable
@ColumnName(ContactsContract.CommonDataKinds.Event.LABEL)
public abstract String label();
public static Event create(Cursor cursor) {
return AutoValue_Event.createFromCursor(cursor);
}
public enum Type {
CUSTOM(ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM),
ANNIVERSARY(ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY),
OTHER(ContactsContract.CommonDataKinds.Event.TYPE_OTHER),
BIRTHDAY(ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
int typeMap;
Type(int columnName) {
this.typeMap = columnName;
}
public int getTypeMap() {
return typeMap;
}
}
}
| 28.28 | 77 | 0.739745 |
5ce90dd4ed8448f77d770ff885ab620c1e7de4f6 | 2,961 | package AllClasses;
import javafx.scene.layout.AnchorPane;
import javafx.scene.shape.Rectangle;
import java.util.ArrayList;
public class Cat extends Rectangle {
public static ArrayList<Cat> cats=new ArrayList<>();
public static ArrayList<CatAnimation> catAnimation =new ArrayList<>();
double theta;
public boolean collect=false;
public Cat(int x, int y, AnchorPane anchorPane,WareHouse wareHouse){
super(x,y,82,68);
theta=-90;
cats.add(this);
catAnimation.add(new CatAnimation(this,anchorPane,wareHouse));
catAnimation.get(catAnimation.size()-1).play();
}
public void catMove(double dx,double dy){
this.setX(this.getX()+dx);
this.setY(this.getY()+dy);
}
public double[] catMoveP(double dx,double dy,double xp,double yp)
{
if(dx==0)
dx=0.5;
if(dy==0)
dy=0.5;
if(Math.abs(this.getX()-xp)<1.5) {
dx = 0;
dy = 1;
}
if(Math.abs(this.getY()-yp)<1.5) {
dy = 0;
dx = 1;
}
double[] xy=new double[2];
double spy;
double spx;
if(Math.abs(xp-(this.getX()+dx))<=Math.abs(xp-(this.getX()-dx)))
spx=dx;
else
spx=-dx;
if(Math.abs(yp-(this.getY()+dy))<=Math.abs(yp-(this.getY()-dy)))
spy=dy;
else
spy=-dy;
xy[0]=spx;xy[1]=spy;
return xy;
}
public double[] nearestGood(ArrayList<Product> products,double x,double y)
{
double[] xy=new double[2];
double xn=0,yn=0;
double min=100000;
for (int i = 0; i < products.size(); i++) {
if(!products.get(i).isRemoved())
{
if(Math.pow(x-products.get(i).getX(),2)+Math.pow(y-products.get(i).getY(),2)<min)
{
xn=products.get(i).getX();
yn=products.get(i).getY();
min=Math.pow(x-products.get(i).getX(),2)+Math.pow(y-products.get(i).getY(),2);
}
}
}
xy[0]=xn;
xy[1]=yn;
return xy;
}
public int[] findProduct(ArrayList<Product> products,double x,double y)
{
int[] find=new int[3];
for (int i = 0; i < products.size(); i++) {
if(!products.get(i).isRemoved() && Math.abs(products.get(i).getX()-x)<2 && Math.abs(products.get(i).getY()-y)<2)
{
find[0]=1;
find[1]=i;
break;
}
}
return find;
}
public boolean hitTop(double y) { return y<=210; }
public boolean hitFloor(double y) {
return y+80 >= 750;
}
public boolean hitLeftWall(double x) {
return x <= 230;
}
public boolean hitRightWall(double x) { return x+85 >= 835;}
} | 30.84375 | 125 | 0.494765 |
587875abdaaf3716a1392e7d41990c22b346a183 | 5,305 | package com.github.skrethel.simple.config.retrofit;
import com.github.skrethel.simple.config.retrofit.constraint.DefaultSchemaConstraintValidator;
import com.github.skrethel.simple.config.retrofit.exception.ValidationException;
import com.github.skrethel.simple.config.retrofit.schema.ConfigSchema;
import com.github.skrethel.simple.config.retrofit.schema.Constraint;
import org.ini4j.Ini;
import org.junit.Test;
import java.util.Arrays;
import static com.github.skrethel.simple.config.retrofit.TestUtils.*;
public class DefaultSchemaConstraintValidatorTest {
@Test
public void testValidBool() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("bool");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "true");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test(expected = ValidationException.class)
public void testInvalidBool() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("bool");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "asdf");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test
public void testValidInt() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, 3, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "3");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test(expected = ValidationException.class)
public void testInvalidInt() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "asdf");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test
public void testValidMin() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
constraint.addParam("min", "3");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, 3, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "3");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test(expected = ValidationException.class)
public void testInvalidMin() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
constraint.addParam("min", "3");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "2");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test
public void testValidMax() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
constraint.addParam("max", "3");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, 3, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "3");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test(expected = ValidationException.class)
public void testInvalidMax() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
constraint.addParam("max", "3");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.put(group, name, "5");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
@Test(expected = ValidationException.class)
public void testValidateMultiValuedMax() throws Exception {
ConfigSchema schema = new ConfigSchema();
Constraint constraint = new Constraint();
constraint.setType("int");
constraint.addParam("max", "3");
String group = "group";
String name = "name";
addSchemaItem(schema, group, name, true, "desc", Arrays.asList(constraint));
Ini ini = new Ini();
ini.add(group, name, "3");
ini.add(group, name, "5");
DefaultSchemaConstraintValidator validator = new DefaultSchemaConstraintValidator();
validator.validate(schema, ini);
}
} | 32.151515 | 94 | 0.73459 |
1c9c755ec72f86dc80fa02360d95f97cd662cba5 | 141 | package com.bstek.ureport.echarts.options.prop;
/**
* @author Jacky.gao
* @since 2017年12月27日
*/
public enum Trigger {
item,axis,none;
}
| 14.1 | 47 | 0.702128 |
79b179974a978f08e8c6df8a719c1ec31e27bd77 | 292 | package com.coolcompany.Beshstore.controller;
import com.coolcompany.Beshstore.domain.Product;
import java.util.List;
public interface ProductController {
Product findById(int id);
List<Product> findAll();
void add(Product product);
void updateName (String name, int id);
}
| 24.333333 | 48 | 0.753425 |
80886312dbd91a85cc1ef330843d6cddd62015af | 5,285 | package npc.model.residences.clanhall;
import l2f.gameserver.dao.SiegeClanDAO;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.entity.events.impl.ClanHallMiniGameEvent;
import l2f.gameserver.model.entity.events.objects.CMGSiegeClanObject;
import l2f.gameserver.model.entity.events.objects.SiegeClanObject;
import l2f.gameserver.model.entity.residence.ClanHall;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.model.pledge.Clan;
import l2f.gameserver.network.serverpackets.NpcHtmlMessage;
import l2f.gameserver.templates.npc.NpcTemplate;
import l2f.gameserver.utils.ItemFunctions;
import l2f.gameserver.utils.TimeUtils;
/**
* @author VISTALL
* @date 8:01/07.05.2011
*/
public class RainbowMessengerInstance extends NpcInstance
{
public static final int ITEM_ID = 8034;
public RainbowMessengerInstance(int objectId, NpcTemplate template)
{
super(objectId, template);
}
@Override
public void onBypassFeedback(final Player player, final String command)
{
if (!canBypassCheck(player, this))
return;
ClanHall clanHall = getClanHall();
ClanHallMiniGameEvent miniGameEvent = clanHall.getSiegeEvent();
if (command.equalsIgnoreCase("register"))
{
if (miniGameEvent.isRegistrationOver())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti014.htm");
return;
}
Clan clan = player.getClan();
if (clan == null || clan.getLevel() < 3 || clan.getAllSize() <= 5)
{
showChatWindow(player, "residence2/clanhall/messenger_yetti011.htm");
return;
}
if (clan.getLeaderId() != player.getObjectId())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti010.htm");
return;
}
if (clan.getHasHideout() > 0)
{
showChatWindow(player, "residence2/clanhall/messenger_yetti012.htm");
return;
}
if (miniGameEvent.getSiegeClan(ClanHallMiniGameEvent.ATTACKERS, clan) != null)
{
showChatWindow(player, "residence2/clanhall/messenger_yetti013.htm");
return;
}
long count = player.getInventory().getCountOf(ITEM_ID);
if (count == 0)
showChatWindow(player, "residence2/clanhall/messenger_yetti008.htm");
else
{
if (!player.consumeItem(ITEM_ID, count))
return;
CMGSiegeClanObject siegeClanObject = new CMGSiegeClanObject(ClanHallMiniGameEvent.ATTACKERS, clan, count);
miniGameEvent.addObject(ClanHallMiniGameEvent.ATTACKERS, siegeClanObject);
SiegeClanDAO.getInstance().insert(clanHall, siegeClanObject);
showChatWindow(player, "residence2/clanhall/messenger_yetti009.htm");
}
}
else if (command.equalsIgnoreCase("cancel"))
{
if (miniGameEvent.isRegistrationOver())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti017.htm");
return;
}
Clan clan = player.getClan();
if (clan == null || clan.getLevel() < 3)
{
showChatWindow(player, "residence2/clanhall/messenger_yetti011.htm");
return;
}
if (clan.getLeaderId() != player.getObjectId())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti010.htm");
return;
}
SiegeClanObject siegeClanObject = miniGameEvent.getSiegeClan(ClanHallMiniGameEvent.ATTACKERS, clan);
if (siegeClanObject == null)
showChatWindow(player, "residence2/clanhall/messenger_yetti016.htm");
else
{
miniGameEvent.removeObject(ClanHallMiniGameEvent.ATTACKERS, siegeClanObject);
SiegeClanDAO.getInstance().delete(clanHall, siegeClanObject);
ItemFunctions.addItem(player, ITEM_ID, siegeClanObject.getParam() / 2L, true, "RainbowMessenger");
showChatWindow(player, "residence2/clanhall/messenger_yetti005.htm");
}
}
else if (command.equalsIgnoreCase("refund"))
{
if (miniGameEvent.isRegistrationOver())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti010.htm");
return;
}
Clan clan = player.getClan();
if (clan == null || clan.getLevel() < 3)
{
showChatWindow(player, "residence2/clanhall/messenger_yetti011.htm");
return;
}
if (clan.getLeaderId() != player.getObjectId())
{
showChatWindow(player, "residence2/clanhall/messenger_yetti010.htm");
return;
}
SiegeClanObject siegeClanObject = miniGameEvent.getSiegeClan(ClanHallMiniGameEvent.REFUND, clan);
if (siegeClanObject == null)
showChatWindow(player, "residence2/clanhall/messenger_yetti020.htm");
else
{
miniGameEvent.removeObject(ClanHallMiniGameEvent.REFUND, siegeClanObject);
SiegeClanDAO.getInstance().delete(clanHall, siegeClanObject);
ItemFunctions.addItem(player, ITEM_ID, siegeClanObject.getParam(), true, "RainbowMessenger");
showChatWindow(player, "residence2/clanhall/messenger_yetti019.htm");
}
}
else
super.onBypassFeedback(player, command);
}
@Override
public void showChatWindow(Player player, int val, Object... arg)
{
ClanHall clanHall = getClanHall();
Clan clan = clanHall.getOwner();
NpcHtmlMessage msg = new NpcHtmlMessage(player, this);
if (clan != null)
{
msg.setFile("residence2/clanhall/messenger_yetti001.htm");
msg.replace("%owner_name%", clan.getName());
}
else
msg.setFile("residence2/clanhall/messenger_yetti001a.htm");
msg.replace("%siege_date%", TimeUtils.toSimpleFormat(clanHall.getSiegeDate()));
player.sendPacket(msg);
}
}
| 30.906433 | 110 | 0.736235 |
76a3ab918e63050ebf875322574c74a8b6924dbc | 1,271 | package qea.benchmark.rovers;
import qea.properties.rovers.ResourceLifecycle_QVar01_FVar_Det_QEA;
import qea.properties.rovers.ResourceLifecycle_QVar01_FVar_NonDet_QEA;
import qea.properties.rovers.ResourceLifecycle_QVar01_NoFVar_NonDet_QEA;
import qea.properties.rovers.RoverCaseStudy;
import qea.benchmark.rovers.qea.QeaDoEval.QeaDoWork;
public class ResourceLifecycleQeaDoEval extends DoEval {
@Override
public DoWork makeWork() {
return new QeaDoWork();
}
public static void main(String[] args) {
ResourceLifecycleQeaDoEval eval = new ResourceLifecycleQeaDoEval();
QeaDoWork.print = false;
// Worst case
eval.eval_for_ResourceLifecycle(
RoverCaseStudy.makeResourceLifecycleGeneral(),
"ResourceLifecycle");
// Intermediate cases
eval.eval_for_ResourceLifecycle(
new ResourceLifecycle_QVar01_FVar_NonDet_QEA(),
"ResourceLifecycle");
eval.eval_for_ResourceLifecycle(
new ResourceLifecycle_QVar01_FVar_Det_QEA(),
"ResourceLifecycle");
eval.eval_for_ResourceLifecycle(
new ResourceLifecycle_QVar01_NoFVar_NonDet_QEA(),
"ResourceLifecycle");
// Best case
eval.eval_for_ResourceLifecycle(RoverCaseStudy.makeResourceLifecycle(),
"ResourceLifecycle");
}
}
| 27.630435 | 74 | 0.771833 |
8b16b397966ee311f3c7618ac3db437d53303689 | 47 | package ComplexCommands;
public class If {
}
| 7.833333 | 24 | 0.744681 |
78949ee0cb4fc8b3e75069d7f413c5e8c2e750cf | 156 | package introduction;
import oops.Student;
public class MainClass {
public static void main(String[] args) {
Student obj = new Student("Sid");
}
}
| 12 | 41 | 0.698718 |
5b4c609e2dfef906073d4428b8139116f04f0814 | 3,409 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import Hash.Hash;
import HeapMax.HeapMax;
import Pessoas.Advogado;
import Pessoas.Funcionario;
import Pessoas.Juiz;
import Pilha.Pilha;
import Processo.Processo;
public class Teste {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Hash h = new Hash();
HeapMax heap = new HeapMax();
Pilha<Processo> pilha = new Pilha<>();
Pilha pProcessos = new Pilha();
Funcionario davi = new Advogado("Davi Wesley", "daviwesley", "Dr.", true, 1234548);
Funcionario b = new Advogado("Daniel", "daniel", "Dr.", true, 123456);
Funcionario c = new Advogado("Vitor Oliveira", "voliveira", "Dr.", true, 168641);
Funcionario d = new Juiz("Vitor Oliveira", "voliveira", "Dr.", true, 168641);
h.put(davi);
h.put(b);
h.put(c);
Processo processo;
HeapMax filaPrioridade = new HeapMax();
InputStreamReader a = new InputStreamReader(System.in);
BufferedReader ler = new BufferedReader(a);
Scanner input = new Scanner(System.in);
int opcao = -1;
do {
System.out.println("____________________________________");
System.out.println(" 1 - Cadastrar Processo");
System.out.println(" 2- Analisar Processo");
System.out.println(" 3- Julgar Processso");
System.out.println(" 4- Sair");
System.out.println("____________________________________");
System.out.println("Digite sua opção");
opcao = input.nextInt();
switch (opcao) {
case 1:
int choice = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.println(" Digite o nome da Vitima");
String nomeVitima = ler.readLine();
System.out.println(" Digite o nome do Acusado");
String nomeAcusado = ler.readLine();
System.out.println(" Digite a descricao do Processo");
String descricao = ler.readLine();
processo = new Processo(0, nomeVitima, nomeAcusado, "", descricao);
pilha.adicionar(processo);
System.out.println("Digite 1 para continuar e 0 para sair");
choice = scan.nextInt();
} while (choice != 0);
break;
case 2:
int escolha = 0;
if(h.verificarUsuario()){
Scanner scanner = new Scanner(System.in);
do {
Processo procAnalisado = pilha.remover();
System.out.println("Digite o nome do advogado");
String nomeAdvogado = ler.readLine();
procAnalisado.setNomeAdvogado(nomeAdvogado);
System.out.println("Digite um inteiro para representar a prioridade");
String aux = ler.readLine();
int prioridade = Integer.parseInt(aux);
procAnalisado.setPrioridade(prioridade);
filaPrioridade.adicionar(procAnalisado);
System.out.println("Digite 1 para continuar e 0 para sair");
escolha = scanner.nextInt();
} while (escolha != 0);
}
break;
case 3:
if(h.verificarUsuario()){
Processo pJulgado = filaPrioridade.removerHeap();
pJulgado.Imprimir();
System.out.println("Processo Removido");
}else{
System.out.println("Senha Incorreta");
}
break;
case 4:
System.exit(1);
break;
default:
System.out.println("Opção Inválida");
}
} while (opcao != 0);
}
}
| 32.466667 | 86 | 0.638017 |
ea90ed7f0a15fd9c8f64e7d3cea29459641f1e19 | 1,983 | /**
*
*/
package org.societies.rfid.server;
import java.util.Hashtable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.societies.api.osgi.event.CSSEvent;
import org.societies.api.osgi.event.EventListener;
import org.societies.api.osgi.event.IEventMgr;
import org.societies.api.osgi.event.InternalEvent;
/**
* @author Eliza
*
*/
public class RfidWebAppEventListener extends EventListener{
private Logger logging = LoggerFactory.getLogger(this.getClass());
private static final String RFID_SERVER_EVENT_TYPE = "org/societies/rfid/server";
private RfidServer server;
private IEventMgr eventMgr;
public RfidWebAppEventListener(RfidServer server){
this.server = server;
eventMgr = server.getEventMgr();
eventMgr.subscribeInternalEvent(this, new String[]{RFID_SERVER_EVENT_TYPE}, null);
logging.debug("registered for events!");
}
@Override
public void handleExternalEvent(CSSEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void handleInternalEvent(InternalEvent event) {
if(logging.isDebugEnabled()) logging.debug("Received event: "+event.geteventType()+" name: "+event.geteventName());
if (event.geteventType().equalsIgnoreCase(RFID_SERVER_EVENT_TYPE)){
Hashtable<String, String> payload = (Hashtable<String, String>) event.geteventInfo();
if (event.geteventName().equalsIgnoreCase("addNewTag")){
if(logging.isDebugEnabled()) logging.debug("adding new tag");
if (payload.containsKey("tag")){
if (payload.containsKey("password")){
this.server.addTag(payload.get("tag"), payload.get("password"));
}else{
String password = this.server.getPassword();
this.server.addTag(payload.get("tag"), password);
}
}
}else if (event.geteventName().equalsIgnoreCase("deleteTag")){
if (payload.containsKey("tag")){
this.server.requestDeleteTag(payload.get("tag"));
}
}
}
}
}
| 30.045455 | 118 | 0.704488 |
737f9a9d5c31550ca03f145724ded134fb2cfe87 | 2,918 | package no.uib.ii.inf102.f18.mandatory1;
/**
* A client for solving the problem https://uib.kattis.com/problems/uib.indexpq
* using an implementation of the IIndexPQ interface (implementation MUST be a min-PQ)
*
* @author Torstein Strømme
*/
public class IndexMinPQClient {
public static void main(String[] args) {
Kattio io = new Kattio(System.in);
solve(io);
io.close();
}
private static void solve(Kattio io) {
final int m = io.getInt();
final int q = io.getInt();
int idx, key;
// Change the line below to initialize with your IndexMinPQ class
IIndexPQ<Integer> pq = new IndexMinPQ<>(m); // new IndexMinPQ<>(m);
for (int i = 0; i < q; i++) {
switch (io.getWord().charAt(0)) {
case 'A': // add
idx = io.getInt();
key = io.getInt();
if (pq.contains(idx)) {
io.print("error\n");
return;
}
pq.add(idx, key);
break;
case 'C': // changeKey
idx = io.getInt();
key = io.getInt();
if (!pq.contains(idx)) {
io.print("error\n");
return;
}
pq.changeKey(idx, key);
break;
case 'E': // peek
if (pq.isEmpty()) {
io.print("error\n");
return;
}
io.print(String.format("%d\n", pq.peek()));
break;
case 'G': // getKey
idx = io.getInt();
if (!pq.contains(idx)) {
io.print("error\n");
return;
}
io.print(String.format("%d\n", pq.getKey(idx)));
break;
case 'R': // remove (delete)
idx = io.getInt();
if (!pq.contains(idx)) {
io.print("error\n");
return;
}
pq.delete(idx);
break;
case 'P': // poll
if (pq.isEmpty()) {
io.print("error\n");
return;
}
io.print(String.format("%d\n", pq.poll()));
break;
case 'S': // size
io.print(String.format("%d\n", pq.size()));
break;
default:
throw new RuntimeException("Unknown operator");
}
}
}
}
| 32.065934 | 87 | 0.362234 |
2aaebbb1bfb83ce214953b0cbd6bb1908b520b7f | 802 | package bg.softuni.web.beans.list;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import bg.softuni.entity.model.UserModel;
import bg.softuni.service.UserServiceLocal;
@ManagedBean(name = "listAllUsersUnpaidBillBean")
@ViewScoped
public class ListAllUsersUnpaidBillBean implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
UserServiceLocal<UserModel> userService;
@PostConstruct
public void init() {
}
/**
* Get all users with unpaid bills
*
* @return list of users
*/
public List<UserModel> getAllUsersUnpaidBills() {
return userService.allUsersUnpaidBillCounter();
}
} | 22.914286 | 65 | 0.744389 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.