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
|
---|---|---|---|---|---|
849478f06b930fc68cf9a5fe7df612d2be2b4b21 | 6,477 | package com.ft.sdk.tests;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import com.ft.sdk.garble.bean.DataType;
import com.ft.sdk.garble.bean.LineProtocolBean;
import com.ft.sdk.garble.bean.ObjectBean;
import com.ft.sdk.garble.bean.SyncJsonData;
import com.ft.sdk.garble.manager.SyncDataHelper;
import com.ft.sdk.garble.utils.Constants;
import com.ft.sdk.garble.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* BY huangDianHua
* DATE:2019-12-16 18:06
* Description:
*/
public class UtilsTest {
private static final String TEST_MEASUREMENT_INFLUX_DB_LINE = "TestInfluxDBLine";
private static final String KEY_TAGS = "tags1";
private static final String KEY_TAGS_EMPTY = "tagEmpty";
private static final String KEY_FIELD = "field1";
private static final String KEY_FIELD_EMPTY = "fieldEmpty";
private static final String VALUE_TAGS = "tags1-value";
private static final Object VALUE_TAGS_EMPTY = "";
private static final String VALUE_FIELD = "field1-value";
private static final Object VALUE_FIELD_EMPTY = "";
public static final long VALUE_TIME = 1598512145640000000L;
private static final String SINGLE_LINE_NORMAL_DATA = TEST_MEASUREMENT_INFLUX_DB_LINE + ","
+ KEY_TAGS + "=" + VALUE_TAGS + " "
+ KEY_FIELD + "=\"" + VALUE_FIELD + "\" " +
"" + VALUE_TIME + "\n";
private static final String SINGLE_LINE_EMPTY_DATA = TEST_MEASUREMENT_INFLUX_DB_LINE + ","
+ KEY_TAGS_EMPTY + "=" + Constants.UNKNOWN + " "
+ KEY_FIELD_EMPTY + "=\"" + Constants.UNKNOWN + "\" " +
"" + VALUE_TIME + "\n";
private static final String LOG_EXPECT_DATA = SINGLE_LINE_NORMAL_DATA + SINGLE_LINE_NORMAL_DATA + SINGLE_LINE_NORMAL_DATA;
private Context getContext() {
return InstrumentationRegistry.getInstrumentation().getTargetContext();
}
@Test
public void isNetworkAvailable() {
assertTrue(Utils.isNetworkAvailable(getContext()));
}
@Test
public void contentMD5Encode() {
assertEquals("M1QEWjl2Ic2SQG8fmM3ikg==", Utils.contentMD5EncodeWithBase64("1122334455"));
}
@Test
public void getHMacSha1() {
//String value = Utils.getHMacSha1("screct", "POST" + "\n" + "xrKOMvb4g+/lSVHoW8XcaA==" + "\n" + "application/json" + "\n" + "Wed, 02 Sep 2020 09:41:24 GMT");
assertEquals("4me5NXJallTGFmZiO3csizbWI90=", Utils.getHMacSha1("screct", "123456"));
}
/**
* ๅค่ก่กๆฐๆฎ้ช่ฏ
*
* @throws JSONException
* @throws InterruptedException
*/
@Test
public void multiLineProtocolFormatTest() throws JSONException, InterruptedException {
SyncJsonData recordData = new SyncJsonData(DataType.LOG);
recordData.setTime(VALUE_TIME);
JSONObject jsonObject = new JSONObject();
jsonObject.put(Constants.MEASUREMENT, TEST_MEASUREMENT_INFLUX_DB_LINE);
JSONObject tags = new JSONObject();
tags.put(KEY_TAGS, VALUE_TAGS);
JSONObject fields = new JSONObject();
fields.put(KEY_FIELD, VALUE_FIELD);
jsonObject.put(Constants.TAGS, tags);
jsonObject.put(Constants.FIELDS, fields);
recordData.setDataString(jsonObject.toString());
List<SyncJsonData> recordDataList = new ArrayList<>();
recordDataList.add(recordData);
recordDataList.add(recordData);
recordDataList.add(recordData);
String content = new SyncDataHelper().getBodyContent(DataType.LOG, recordDataList);
Assert.assertEquals(LOG_EXPECT_DATA, content);
}
/**
* ๅๆฐๆฎ้ช่ฏ๏ผ็ฉบๅผๆฐๆฎ
*
* @throws JSONException
*/
@Test
public void singleLineProtocolFormatTest() throws JSONException {
JSONObject tags = new JSONObject();
tags.put(KEY_TAGS, VALUE_TAGS);
JSONObject fields = new JSONObject();
fields.put(KEY_FIELD, VALUE_FIELD);
LineProtocolBean trackBean = new LineProtocolBean(TEST_MEASUREMENT_INFLUX_DB_LINE, tags, fields, VALUE_TIME);
SyncJsonData data = SyncJsonData.getSyncJsonData(DataType.TRACK, trackBean);
List<SyncJsonData> recordDataList = new ArrayList<>();
recordDataList.add(data);
String content = new SyncDataHelper().getBodyContent(DataType.TRACK, recordDataList);
Assert.assertTrue(content.contains(TEST_MEASUREMENT_INFLUX_DB_LINE));
Assert.assertTrue(content.contains(SINGLE_LINE_NORMAL_DATA.replace(TEST_MEASUREMENT_INFLUX_DB_LINE, "")));
JSONObject tagsEmpty = new JSONObject();
tagsEmpty.put(KEY_TAGS_EMPTY, VALUE_TAGS_EMPTY);
JSONObject fieldsEmpty = new JSONObject();
fieldsEmpty.put(KEY_FIELD_EMPTY, VALUE_FIELD_EMPTY);
LineProtocolBean trackBeanEmpty = new LineProtocolBean(TEST_MEASUREMENT_INFLUX_DB_LINE, tagsEmpty, fieldsEmpty, VALUE_TIME);
SyncJsonData dataEmpty = SyncJsonData.getSyncJsonData(DataType.TRACK, trackBeanEmpty);
List<SyncJsonData> emptyRecordDataList = new ArrayList<>();
emptyRecordDataList.add(dataEmpty);
String contentEmpty = new SyncDataHelper().getBodyContent(DataType.TRACK, emptyRecordDataList);
Assert.assertTrue(contentEmpty.contains(SINGLE_LINE_EMPTY_DATA.replace(TEST_MEASUREMENT_INFLUX_DB_LINE, "")));
}
/**
* ๅฏน่ฑกๆฐๆฎๅ
ๅฎนๆ ก้ช
*
* @throws JSONException
*/
@Test
public void objectDataTest() throws JSONException {
String objectName = "objectTest";
ObjectBean objectBean = new ObjectBean(objectName);
ArrayList<SyncJsonData> list = new ArrayList<>();
list.add(SyncJsonData.getFromObjectData(objectBean));
String content = new SyncDataHelper().getBodyContent(DataType.OBJECT, list);
JSONArray array = new JSONArray(content);
Assert.assertTrue(array.length() > 0);
JSONObject jsonObject = array.optJSONObject(0);
String name = jsonObject.optString(ObjectBean.INNER_NAME);
Assert.assertEquals(name, objectName);
JSONObject tags = jsonObject.optJSONObject(ObjectBean.INNER_CONTENT);
String clazz = tags.optString(ObjectBean.INNER_CLASS);
Assert.assertEquals(clazz, Constants.DEFAULT_OBJECT_CLASS);
}
}
| 37.877193 | 166 | 0.702795 |
744db27dd3f32fdd9ba575e1e33aa51078bfcec4 | 14,082 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*/
package org.netbeans.modules.doap;
import java.awt.EventQueue;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.ListIterator;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.turtle.TurtleWriter;
import javax.swing.JFileChooser;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.StatusDisplayer;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle;
import org.openide.util.NbPreferences;
import org.openide.util.RequestProcessor;
import org.openrdf.model.Resource;
import org.openrdf.model.ValueFactory;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.sail.SailRepositoryConnection;
import org.openrdf.repository.util.RDFInserter;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.rdfxml.RDFXMLParser;
import org.openrdf.sail.memory.MemoryStore;
/**
* Fetches a DOAP file from a dropped URL, and if the user agrees, checks
* it out from CVS or SVN.
*
* The dropped URL is parsed and its resource downloaded on a background
* thread; if successful, on the event thread we ask the user if the project
* should be downloaded/opened; if so, we ask them to choose a destination
* directory; if they choose one, we then go back to a background thread
* to actually pull the content down from SVN or CVS.
*
* @author Tim Boudreau
*/
final class DoapFetcher implements Runnable {
private final java.net.URL url;
MemoryStore mem;
SailRepositoryConnection sailconn;
final static String doap = "http://usefulinc.com/ns/doap#";
final static String rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
ValueFactory vf;
public DoapFetcher(java.net.URL url) {
System.err.println("creating doap fetcher");
this.url = url;
try {
org.openrdf.sail.memory.MemoryStore mem = new org.openrdf.sail.memory.MemoryStore();
// mem.initialize();
org.openrdf.repository.sail.SailRepository sail = new org.openrdf.repository.sail.SailRepository(mem);
sailconn = sail.getConnection();
vf = sail.getValueFactory();
} catch (RepositoryException ex) { //mhh. the whole thing should stop right now! So I should throw the exception...
Exceptions.printStackTrace(ex);
}
System.err.println("finished creating doap fetcher");
}
//clearly using http://sommer.dev.java.net would be a lot easier. But I need to update it for Sesame 2 beta 3
class RepoInfo {
Resource repo;
String location;
Resource type;
ArrayList<String> modules = new ArrayList<String>(); //only for cvs repos
String anonroot; //only for cvs repos
}
//HENRY: Stuff for you:
// - Implement tryToGetTheDoap() to make a connection, fetch the DOAP file,
// parse it, and if valid, return its text (or whatever you want)
// - Implement createCheckoutHandler() - either create a CVS or SVN
// one as appropriate (code is copied from remote projects modules and mostly
// works), using the data d/l'd earlier in tryToGetTheDoap())
private CheckoutHandler createCheckoutHandler() {
System.err.println("using the doap file");
java.util.ArrayList<org.netbeans.modules.doap.DoapFetcher.RepoInfo> results = new java.util.ArrayList<org.netbeans.modules.doap.DoapFetcher.RepoInfo>();
try {
TurtleWriter wr = new TurtleWriter(System.out);
sailconn.export(wr);
org.openrdf.repository.RepositoryResult<org.openrdf.model.Statement> res = sailconn.getStatements(null, vf.createURI(doap, "repository"), null, false);
org.openrdf.model.Resource repo = null;
while (res.hasNext()) {
repo = (org.openrdf.model.Resource) res.next().getObject();
org.netbeans.modules.doap.DoapFetcher.RepoInfo info = new org.netbeans.modules.doap.DoapFetcher.RepoInfo();
info.repo = repo;
results.add(info);
}
for (ListIterator<RepoInfo> li = results.listIterator(); li.hasNext();) {
RepoInfo info =li.next();
res = sailconn.getStatements(info.repo, vf.createURI(doap, "location"), null, false);
while (res.hasNext()) {
info.location = res.next().getObject().toString();
}
res = sailconn.getStatements(info.repo, vf.createURI(rdf, "type"), null, false);
while (res.hasNext()) {
info.type = (org.openrdf.model.Resource) res.next().getObject();
}
if (info.type.equals(vf.createURI(doap,"CVSRepository"))) {
res = sailconn.getStatements(info.repo, vf.createURI(doap,"module"), null, false);
while(res.hasNext()) {
info.modules.add(res.next().getObject().toString());
}
res = sailconn.getStatements(info.repo, vf.createURI(doap,"anon-root"), null, false);
while(res.hasNext()) {
info.anonroot = res.next().getObject().toString();
}
} else if (info.type.equals(vf.createURI(doap,"SVNRepository"))) {
res = sailconn.getStatements(info.repo, vf.createURI(doap,"module"), null, false);
while(res.hasNext()) {
info.modules.add(res.next().getObject().toString());
}
res = sailconn.getStatements(info.repo, vf.createURI(doap,"location"), null, false);
while(res.hasNext()) {
info.location = res.next().getObject().toString();
}
}
if (info.location == null) li.remove();
}
} catch (RepositoryException ex) {
Exceptions.printStackTrace(ex);
} catch (RDFHandlerException ex) {
Exceptions.printStackTrace(ex);
}
System.err.println("found |results|="+results.size());
for (RepoInfo info: results) {
if (info.type.equals(vf.createURI(doap,"CVSRepository"))) {
System.err.println("creating a CVSCheckoutHandler");
System.err.println("anonroot="+info.anonroot);
String module =null;
if (info.modules != null && info.modules.size() > 0) {
module = info.modules.get(0);
System.err.println("module="+module);
}
System.err.println("destinationdir="+destination);
return new CvsCheckoutHandler(info.anonroot,info.modules.get(0),"HEAD",destination);
} else if (info.type.equals(vf.createURI(doap,"SVNRepository"))) {
System.err.println("creating a CVSCheckoutHandler");
System.err.println("anonroot="+info.anonroot);
if (info.modules != null && info.modules.size() > 0) {
System.err.println("modules="+info.modules.get(0));
}
System.err.println("destinationdir="+destination);
//todo: the svn checkout handler should allow more than one module to be checked out...
SvnCheckoutHandler h = new SvnCheckoutHandler(info.location, null, null, info.modules,destination);
return h;
}
}
return null;
}
private boolean tryToGetTheDoap() {
System.err.println("trying to get the doap at "+url);
boolean success = false;
try {
assert !java.awt.EventQueue.isDispatchThread();
//there is a bug in rio: it does not parse rdf files that are not wrapped with <RDF ...></RDF>
//sailconn.add(url, (String)null, RDFFormat.RDFXML);
URLConnection conn = url.openConnection();
conn.connect();
//todo: should get the content encoding
RDFXMLParser parser = new RDFXMLParser();
parser.setParseStandAloneDocuments(true);
RDFInserter inserter = new RDFInserter(sailconn);
parser.setRDFHandler(inserter);
parser.setVerifyData(true);
parser.setStopAtFirstError(true);
parser.setDatatypeHandling(RDFParser.DatatypeHandling.VERIFY);
InputStream str = conn.getInputStream();
URL url = conn.getURL();
String base = conn.getURL().toString().substring(0,url.toString().length()-url.getFile().length());
parser.parse(str, base);
success = !sailconn.isEmpty();
if (success)
System.err.println("got the doap.");
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
} catch (RDFHandlerException ex) {
Exceptions.printStackTrace(ex);
} catch (RDFParseException ex) {
NotifyDescriptor.Message msg = new NotifyDescriptor.Message(
NbBundle.getMessage(DoapFetcher.class, "MSG_BAD_DOPE"));
DialogDisplayer.getDefault().notify(msg);
} catch (RepositoryException ex) {
Exceptions.printStackTrace(ex);
}
return success;
}
boolean gotDoap = false;
public void run() {
if (!EventQueue.isDispatchThread()) {
try {
gotDoap = tryToGetTheDoap();
} finally {
if (gotDoap) {
EventQueue.invokeLater(this);
}
}
} else {
useTheDoapFile();
}
}
File destination;
private void useTheDoapFile() {
assert EventQueue.isDispatchThread();
assert sailconn != null;
//Ask the user the project sources should be downloaded, etc.
//if they say yes
boolean userSaidYes = askUserIfProjectShouldBeOpened();
if (userSaidYes) {
destination = askUserForDestinationDir();
if (destination != null) {
CheckoutHandler handler = createCheckoutHandler();
if (handler != null) {
ProgressHandle progress = ProgressHandleFactory.createHandle(
NbBundle.getMessage(DoapFetcher.class,
"MSG_DOWNLOADING")); //NOI18N
//Run the checkout on a background thread
RequestProcessor.getDefault().post(new CheckerOuter(handler,
progress));
} else {
StatusDisplayer.getDefault().setStatusText(NbBundle.getMessage(
DoapFetcher.class, "LBL_CANT_CHECKOUT")); //NOI18N
}
}
}
}
private boolean askUserIfProjectShouldBeOpened() {
//Show a dialog asking if the project should be opened
NotifyDescriptor.Message md = new NotifyDescriptor.Message(NbBundle.getMessage(
DoapFetcher.class, "LBL_FETCH", url), NotifyDescriptor.YES_NO_OPTION); //NOI18N
return (NotifyDescriptor.YES_OPTION.equals(DialogDisplayer.getDefault().notify(md)));
}
private File askUserForDestinationDir() {
JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(false);
jfc.setDialogTitle(NbBundle.getMessage(DoapFetcher.class,
"TTL_DEST_DIR")); //NOI18N
jfc.setFileSelectionMode(jfc.DIRECTORIES_ONLY);
String dir = NbPreferences.forModule(DoapFetcher.class).get("destdir", null);
if (dir != null) {
File f = new File(dir);
if (f.exists() && f.isDirectory()) {
jfc.setSelectedFile(f);
}
}
File result = null;
if (jfc.showOpenDialog(Frame.getFrames()[0]) == jfc.APPROVE_OPTION) {
result = jfc.getSelectedFile();
NbPreferences.forModule(DoapFetcher.class).put("destdir", result.getPath());
}
return result;
}
private static class CheckerOuter implements Runnable {
private final CheckoutHandler handler;
private final ProgressHandle progress;
CheckerOuter(CheckoutHandler handler, ProgressHandle progress) {
this.handler = handler;
this.progress = progress;
}
public void run() {
handler.checkout(progress);
}
}
}
| 44.422713 | 163 | 0.614117 |
3d594659c1f32ff0e6dbc6f75cddff8d9e776199 | 599 | package dao;
import models.Config;
import models.Log;
import models.NodeInfoLog;
import play.db.jpa.JPA;
/**
* Created by sunsai on 2016/4/11 - 12:29.
*/
public class NodeInfoLogDao {
public static NodeInfoLog findById(Long id) {
return JPA.em().find(NodeInfoLog.class, id);
}
public static void add(NodeInfoLog nodeInfoLog) {
JPA.em().persist(nodeInfoLog);
}
public static void update(NodeInfoLog nodeInfoLog) {
JPA.em().merge(nodeInfoLog);
}
public static void delete(Long id) {
NodeInfoLog nodeInfoLog = findById(id);
JPA.em().remove(nodeInfoLog);
}
}
| 19.966667 | 54 | 0.69783 |
c50d051d50cb09a59c1367a608f675143238345d | 2,105 | package pro.taskana.monitor.api.reports;
import java.util.List;
import pro.taskana.common.api.TimeInterval;
import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.monitor.api.CombinedClassificationFilter;
import pro.taskana.monitor.api.TaskTimestamp;
import pro.taskana.monitor.api.reports.header.ColumnHeader;
import pro.taskana.monitor.api.reports.header.TimeIntervalColumnHeader;
import pro.taskana.monitor.api.reports.item.MonitorQueryItem;
import pro.taskana.monitor.api.reports.row.Row;
import pro.taskana.task.api.models.Task;
import pro.taskana.workbasket.api.models.Workbasket;
/**
* A WorkbasketReport aggregates {@linkplain Task} related data.
*
* <p>Each {@linkplain Row} represents a {@linkplain Workbasket}.
*
* <p>Each {@linkplain ColumnHeader} represents a {@linkplain TimeInterval}.
*/
public class WorkbasketReport extends Report<MonitorQueryItem, TimeIntervalColumnHeader> {
public WorkbasketReport(List<TimeIntervalColumnHeader> timeIntervalColumnHeaders) {
super(timeIntervalColumnHeaders, new String[] {"WORKBASKET"});
}
/** Builder for {@link WorkbasketReport}. */
public interface Builder
extends TimeIntervalReportBuilder<Builder, MonitorQueryItem, TimeIntervalColumnHeader> {
@Override
WorkbasketReport buildReport() throws NotAuthorizedException, InvalidArgumentException;
@Override
WorkbasketReport buildReport(TaskTimestamp timestamp)
throws NotAuthorizedException, InvalidArgumentException;
/**
* Adds a list of {@link CombinedClassificationFilter} to the builder. The created report
* contains only tasks with a pair of a classificationId for a task and a classificationId for
* the corresponding attachment in this list.
*
* @param combinedClassificationFilter a list of combinedClassificationFilter
* @return the WorkbasketReportBuilder
*/
WorkbasketReport.Builder combinedClassificationFilterIn(
List<CombinedClassificationFilter> combinedClassificationFilter);
}
}
| 39.716981 | 98 | 0.790974 |
1cb6594cfae9b6661f0dd02b9cedacdc47520877 | 1,373 | package ql.typechecker;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(value = Parameterized.class)
public class TestCompatibility {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ Arrays.asList(true, true, true, true), true },
{ Arrays.asList(true, true, true, false), false },
{ Arrays.asList(false, true, true, true), false }
});
}
private List<Boolean> list;
private boolean expected;
public TestCompatibility(List<Boolean> list, boolean expected) {
System.out.println("Testing: " + list);
this.expected = expected;
this.list = list;
}
@BeforeClass
public static void printHeader() {
System.out.println("=============================");
System.out.println("*** Testing Compatibility ***");
System.out.println("=============================");
}
@Test
public void testCompatibility() {
boolean result = list
.stream()
.allMatch(a -> a);
assertEquals(expected, result);
}
}
| 26.403846 | 69 | 0.616897 |
2394b524e9ddd47f145c2b525730b1eae40d6a53 | 5,375 | package ghareeb.smsplus.helper;
import ghareeb.smsplus.Activity_Chat;
import ghareeb.smsplus.Activity_Main;
import ghareeb.smsplus.R;
import ghareeb.smsplus.database.SmsPlusDatabaseHelper;
import ghareeb.smsplus.database.entities.ReceivedMessage;
import ghareeb.smsplus.database.entities.ThreadEntity;
import java.util.ArrayList;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v4.app.NotificationCompat.Builder;
public class NotificationsHelper
{
private final static int NOTIFICATION_ID_RECEIVED = 2;
public static Notification buildNotification(Context cntxt, String title, String text, int icon, PendingIntent pi,
boolean vibrate, Uri ring, boolean lights, Bitmap largeIcon)
{
Builder builder = new Builder(cntxt);
builder.setContentTitle(title);
CharSequence textCHS = SmiliesHelper.removeAllSmiliesPtterns(text);
builder.setContentText(textCHS);
builder.setTicker(textCHS);
builder.setContentIntent(pi);
builder.setAutoCancel(true);
builder.setSmallIcon(icon);
if (ring != null)
builder.setSound(ring);
if (largeIcon != null)
builder.setLargeIcon(largeIcon);
int defaults = 0;
if (vibrate)
defaults = Notification.DEFAULT_VIBRATE;
if (lights)
{
defaults |= Notification.DEFAULT_LIGHTS;
builder.setLights(0xff00ff00, 300, 1000);
}
if (defaults != 0)
builder.setDefaults(defaults);
return builder.build();
}
public static Notification buildNotification(Context cntxt, String title, String text, int icon, PendingIntent pi,
boolean vibrate, boolean lights, Bitmap largeIcon)
{
Uri tone = SharedPreferencesHelper.getUri(cntxt, SharedPreferencesHelper.PREF_NOTIFICATIONS_RING_TONE);
return buildNotification(cntxt, title, text, icon, pi, vibrate, tone, lights, largeIcon);
}
private static ArrayList<ThreadEntity> getThreadsOfMessages(ArrayList<ReceivedMessage> messages, Context cntxt)
{
SmsPlusDatabaseHelper helper = new SmsPlusDatabaseHelper(cntxt);
ArrayList<ThreadEntity> all = helper.Thread_getAllThreadsFilled(false);
ArrayList<ThreadEntity> result = new ArrayList<ThreadEntity>();
ThreadEntity temp;
for (ReceivedMessage msg : messages)
{
for (int i = 0; i < all.size(); i++)
{
temp = all.get(i);
if (msg.getThreadId() == temp.getId())
{
if (!result.contains(temp))
{
temp.getContact().loadContactBasicContractInformation(cntxt);
result.add(temp);
}
all.remove(i);
break;
}
}
}
return result;
}
public static void refreshMessageReceivedNotification(Context cntxt, boolean notificationEffects)
{
boolean notify = SharedPreferencesHelper.getBoolean(cntxt, SharedPreferencesHelper.PREF_NOTIFICATIONS);
if (!notify)
return;
NotificationManager manager = (NotificationManager) cntxt.getSystemService(Context.NOTIFICATION_SERVICE);
String title;
String text;
Intent intent;
Bitmap largeIcon = null;
SmsPlusDatabaseHelper helper = new SmsPlusDatabaseHelper(cntxt);
ArrayList<ReceivedMessage> unseen = helper.ReceivedMessage_getAllUnseenMessages();
if (unseen.size() == 0)
{
manager.cancel(NOTIFICATION_ID_RECEIVED);
return;
}
ArrayList<ThreadEntity> threads = getThreadsOfMessages(unseen, cntxt);
// threads list might be 0 in case of deletion
if (threads.size() > 0)
{
if (unseen.size() == 1)// single message from single contact
{
title = threads.get(0).getContact().toString();
largeIcon = threads.get(0).getContact().getPhoto();
text = unseen.get(0).getBody();
intent = new Intent(cntxt, Activity_Chat.class);
intent.putExtra(Activity_Chat.KEY_CONTACT_PHONE_NUMBER, threads.get(0).getContact().getNumber().toString());
intent.putExtra(Activity_Chat.KEY_THREAD_ID, threads.get(0).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else
{
text = String.format("%d %s", unseen.size(),
cntxt.getResources().getString(R.string.notification_text_unread_messages));
if (threads.size() == 1)// multiple messages from single
// contact
{
title = threads.get(0).getContact().toString();
largeIcon = threads.get(0).getContact().getPhoto();
intent = new Intent(cntxt, Activity_Chat.class);
intent.putExtra(Activity_Chat.KEY_CONTACT_PHONE_NUMBER, threads.get(0).getContact().getNumber().toString());
intent.putExtra(Activity_Chat.KEY_THREAD_ID, threads.get(0).getId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else
{
title = cntxt.getResources().getString(R.string.notification_title_unread_messages);
intent = new Intent(cntxt, Activity_Main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
}
PendingIntent pi = PendingIntent.getActivity(cntxt, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
int icon = R.drawable.ic_message_received;
Notification notification = null;
if(notificationEffects)
notification = buildNotification(cntxt, title, text, icon, pi, true,
true, largeIcon);
else
notification = buildNotification(cntxt, title, text, icon, pi, false, null,
false, largeIcon);
manager.notify(NOTIFICATION_ID_RECEIVED, notification);
}
}
}
| 30.714286 | 115 | 0.738233 |
b20e551d16bc878181381acfae69cf8a55927143 | 11,363 | package io.github.shiruka.protocol.data;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.crypto.ECDSAVerifier;
import io.github.shiruka.protocol.data.skin.Skin;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.text.ParseException;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* a record class that represents client chain data.
*
* @param chainData the chain data.
* @param skinData the skin data.
*/
public record ClientChainData(
@NotNull ChainData chainData,
@NotNull SkinData skinData
) {
/**
* the mapper.
*/
private static final ObjectMapper MAPPER = new ObjectMapper();
/**
* the map type.
*/
private static final TypeReference<Map<String, List<String>>> MAP_TYPE = new TypeReference<>() {
};
/**
* the Mojang's public key.
*/
private static final PublicKey MOJANG_PUBLIC_KEY;
/**
* the Mojang's public key as base 64.
*/
private static final String MOJANG_PUBLIC_KEY_BASE64 =
"MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAE8ELkixyLcwlZryUQcu1TvPOmI2B7vX83ndnWRUaXm74wFfa5f/lwQNTfrLVHa2PmenpGI6JhIMUJaWZrjmMj90NoKNFSNBuKdm8rYiXsfaz3K36x/1U26HpG0ZxK/V1V";
static {
try {
MOJANG_PUBLIC_KEY = ClientChainData.generateKey(ClientChainData.MOJANG_PUBLIC_KEY_BASE64);
} catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
throw new IllegalStateException("An error occurs when generating Mojang's public key", e);
}
}
/**
* creates a chain data.
*
* @param chainData the chain data to create.
* @param skinData the skin data to create.
*
* @return chain data.
*/
@NotNull
public static ClientChainData from(@NotNull final String chainData, @NotNull final String skinData) {
return new ClientChainData(
ChainData.decode(chainData),
SkinData.decode(skinData));
}
/**
* decodes the token.
*
* @param token the token to decode.
*
* @return decoded token.
*/
@NotNull
private static JsonNode decodeToken(@NotNull final String token) {
final var base = token.split("\\.");
Preconditions.checkArgument(base.length >= 2, "Invalid token length!");
final var json = new String(Base64.getDecoder().decode(base[1]), StandardCharsets.UTF_8);
try {
return ClientChainData.MAPPER.readTree(json);
} catch (final IOException e) {
throw new IllegalArgumentException("Invalid token JSON", e);
}
}
/**
* generates a EC key.
*
* @param base64 the base 64 to create.
*
* @return public EC key.
*
* @throws NoSuchAlgorithmException if no {@code Provider} supports a {@code KeyFactorySpi} implementation for
* the specified algorithm.
* @throws InvalidKeySpecException if the given key specification is inappropriate for this key factory to produce a
* public key.
*/
@NotNull
private static ECPublicKey generateKey(@NotNull final String base64) throws NoSuchAlgorithmException,
InvalidKeySpecException {
return (ECPublicKey) KeyFactory.getInstance("EC")
.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(base64)));
}
/**
* verifies the key.
*
* @param key the key to verify.
* @param object the object to verify.
*
* @return {@code true} if the key verified.
*
* @throws JOSEException if the JWS object couldn't be verified, or if the elliptic curve of key is not supported.
*/
private static boolean verify(@NotNull final ECPublicKey key, @NotNull final JWSObject object) throws JOSEException {
return object.verify(new ECDSAVerifier(key));
}
/**
* verifies the chain.
*
* @param chains the chains to verify.
*
* @return {@code true} if the chain verified.
*
* @throws ParseException if the chains couldn't be parsed to a JWS object.
* @throws NoSuchAlgorithmException if no {@code Provider} supports a {@code KeyFactorySpi} implementation for
* the specified algorithm.
* @throws InvalidKeySpecException if the given key specification is inappropriate for this key factory to produce a
* public key.
* @throws JOSEException if the JWS object couldn't be verified, or if the elliptic curve of key is not supported.
*/
private static boolean verifyChain(@NotNull final List<String> chains) throws ParseException, NoSuchAlgorithmException,
InvalidKeySpecException, JOSEException {
ECPublicKey lastKey = null;
var mojangKeyVerified = false;
final var iterator = chains.iterator();
while (iterator.hasNext()) {
final var jws = JWSObject.parse(iterator.next());
final var x5u = jws.getHeader().getX509CertURL();
if (x5u == null) {
return false;
}
final var expectedKey = ClientChainData.generateKey(x5u.toString());
if (lastKey == null) {
lastKey = expectedKey;
} else if (!lastKey.equals(expectedKey)) {
return false;
}
if (!ClientChainData.verify(lastKey, jws)) {
return false;
}
if (mojangKeyVerified) {
return !iterator.hasNext();
}
if (lastKey.equals(ClientChainData.MOJANG_PUBLIC_KEY)) {
mojangKeyVerified = true;
}
final var payload = jws.getPayload().toJSONObject();
final var base64key = payload.get("identityPublicKey");
if (!(base64key instanceof String)) {
throw new RuntimeException("No key found");
}
lastKey = ClientChainData.generateKey((String) base64key);
}
return mojangKeyVerified;
}
/**
* a record class that represents chain data.
*
* @param clientUUID the client unique id.
* @param identityPublicKey the identify public key.
* @param username the username.
* @param xboxAuthed the xbox authed.
* @param xuid the xuid.
*/
private record ChainData(
boolean xboxAuthed,
@Nullable String username,
@Nullable UUID clientUUID,
@Nullable String xuid,
@Nullable String identityPublicKey
) {
/**
* decodes the chain data.
*
* @param chainData the chain data to decode.
*
* @return chain data.
*/
@NotNull
private static ChainData decode(@NotNull final String chainData) {
final Map<String, List<String>> map;
try {
map = ClientChainData.MAPPER.readValue(chainData, ClientChainData.MAP_TYPE);
} catch (final IOException e) {
throw new IllegalArgumentException("Invalid JSON!", e);
}
Preconditions.checkArgument(!map.isEmpty() && map.containsKey("chain") && !map.get("chain").isEmpty(),
"Something goes wrong when reading the chain data!");
final var chains = map.get("chain");
var xboxAuthed = false;
try {
xboxAuthed = ClientChainData.verifyChain(chains);
} catch (final Exception ignored) {
}
String username = null;
UUID clientUUID = null;
String xuid = null;
String identityPublicKey = null;
for (final var chain : chains) {
final var chainMap = ClientChainData.decodeToken(chain);
if (chainMap.has("extraData")) {
final var extra = chainMap.get("extraData");
if (extra.has("displayName")) {
username = extra.get("displayName").textValue();
}
if (extra.has("identity")) {
clientUUID = UUID.fromString(extra.get("identity").textValue());
}
if (extra.has("XUID")) {
xuid = extra.get("XUID").textValue();
}
}
if (chainMap.has("identityPublicKey")) {
identityPublicKey = chainMap.get("identityPublicKey").textValue();
}
}
if (!xboxAuthed) {
xuid = null;
}
return new ChainData(xboxAuthed, username, clientUUID, xuid, identityPublicKey);
}
}
/**
* a record class that represents skin data.
*
* @param clientId the client id.
* @param currentInputMode the current input mode.
* @param defaultInputMode the default input mode.
* @param deviceId the device id.
* @param deviceModel the device model.
* @param deviceOS the device os.
* @param gameVersion the game version.
* @param guiScale the gui scale.
* @param languageCode the language code.
* @param skin the skin.
* @param serverAddress the server address.
* @param uiProfile the ui profile.
*/
private record SkinData(
long clientId,
@Nullable String serverAddress,
@Nullable String deviceModel,
int deviceOS,
@Nullable String deviceId,
@Nullable String gameVersion,
int guiScale,
@Nullable String languageCode,
int currentInputMode,
int defaultInputMode,
int uiProfile,
@NotNull Skin skin
) {
/**
* decodes the skin data.
*
* @param skinData the skin data to decode.
*
* @return skin data.
*/
@NotNull
private static SkinData decode(@NotNull final String skinData) {
final var skinToken = ClientChainData.decodeToken(skinData);
var clientId = 0L;
String serverAddress = null;
String deviceModel = null;
var deviceOS = 0;
String deviceId = null;
String gameVersion = null;
var guiScale = 0;
String languageCode = null;
var currentInputMode = 0;
var defaultInputMode = 0;
var uiProfile = 0;
if (skinToken.has("ClientRandomId")) {
clientId = skinToken.get("ClientRandomId").longValue();
}
if (skinToken.has("ServerAddress")) {
serverAddress = skinToken.get("ServerAddress").textValue();
}
if (skinToken.has("DeviceModel")) {
deviceModel = skinToken.get("DeviceModel").textValue();
}
if (skinToken.has("DeviceOS")) {
deviceOS = skinToken.get("DeviceOS").intValue();
}
if (skinToken.has("DeviceId")) {
deviceId = skinToken.get("DeviceId").textValue();
}
if (skinToken.has("GameVersion")) {
gameVersion = skinToken.get("GameVersion").textValue();
}
if (skinToken.has("GuiScale")) {
guiScale = skinToken.get("GuiScale").intValue();
}
if (skinToken.has("LanguageCode")) {
languageCode = skinToken.get("LanguageCode").textValue();
}
if (skinToken.has("CurrentInputMode")) {
currentInputMode = skinToken.get("CurrentInputMode").intValue();
}
if (skinToken.has("DefaultInputMode")) {
defaultInputMode = skinToken.get("DefaultInputMode").intValue();
}
if (skinToken.has("UIProfile")) {
uiProfile = skinToken.get("UIProfile").intValue();
}
return new SkinData(clientId, serverAddress, deviceModel, deviceOS, deviceId, gameVersion, guiScale, languageCode,
currentInputMode, defaultInputMode, uiProfile, Skin.from(skinToken));
}
}
}
| 33.031977 | 167 | 0.669894 |
10390dd1d2c8c447ab330f6b9d7a03cc843a6099 | 2,058 | /*
* Copyright ยฉ 2019 Dominokit
*
* 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.dominokit.domino.api.server;
import io.vertx.core.Launcher;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import java.util.ServiceLoader;
public class DominoLauncher extends Launcher {
protected static final ConfigHolder configHolder = new ConfigHolder();
protected static final RouterHolder routerHolder = new RouterHolder();
protected static class ConfigHolder {
protected JsonObject config;
}
protected static class RouterHolder {
protected Router router;
}
public static void main(String[] args) {
new DominoLauncher().dispatch(args);
}
@Override
public void afterStartingVertx(Vertx vertx) {
RouterConfigurator routerConfigurator =
new RouterConfigurator(vertx, configHolder.config, SecretKey.generate());
routerHolder.router =
PROCESS_ARGS.contains("-cluster")
? routerConfigurator.configuredClusteredRouter()
: routerConfigurator.configuredRouter();
}
@Override
public void beforeStartingVertx(VertxOptions options) {
ServiceLoader.load(VertxOptionsHandler.class)
.iterator()
.forEachRemaining(
vertxOptionsHandler -> {
vertxOptionsHandler.onBeforeVertxStart(options, configHolder.config);
});
}
@Override
public void afterConfigParsed(JsonObject config) {
configHolder.config = config;
}
}
| 30.264706 | 83 | 0.728863 |
14c2bc71ae9d0937059cfad0d622854d538eae81 | 355 | package com.nukkitx.protocol.bedrock.data;
public enum Ability {
BUILD,
MINE,
DOORS_AND_SWITCHES,
OPEN_CONTAINERS,
ATTACK_PLAYERS,
ATTACK_MOBS,
OPERATOR_COMMANDS,
TELEPORT,
INVULNERABLE,
FLYING,
MAY_FLY,
INSTABUILD,
LIGHTNING,
FLY_SPEED,
WALK_SPEED,
MUTED,
WORLD_BUILDER,
NO_CLIP
}
| 15.434783 | 42 | 0.656338 |
ca3efade8eb757043732e383a2891dadabf57d2c | 469 | package com.accenture.javamos.service;
import com.accenture.javamos.entity.Airline;
import com.accenture.javamos.repository.AirlineRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AirlineService {
@Autowired
private AirlineRepository amadeusRepository;
public List<Airline> getAirlines() {
return this.amadeusRepository.findAll();
}
}
| 24.684211 | 62 | 0.812367 |
1283d6116ccb8390b8efa186c5501f991b4d9429 | 2,369 | /*
* Copyright 2019 Qameta Software Oร
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.qameta.allure.attachment;
import io.qameta.allure.AllureLifecycle;
import io.qameta.allure.attachment.http.HttpRequestAttachment;
import io.qameta.allure.test.AllureFeatures;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static io.qameta.allure.attachment.testdata.TestData.randomAttachmentContent;
import static io.qameta.allure.attachment.testdata.TestData.randomHttpRequestAttachment;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* @author charlie (Dmitry Baev).
*/
class DefaultAttachmentProcessorTest {
@SuppressWarnings("unchecked")
@AllureFeatures.Attachments
@Test
void shouldProcessAttachments() {
final HttpRequestAttachment attachment = randomHttpRequestAttachment();
final AllureLifecycle lifecycle = mock(AllureLifecycle.class);
final AttachmentRenderer<AttachmentData> renderer = mock(AttachmentRenderer.class);
final AttachmentContent content = randomAttachmentContent();
doReturn(content)
.when(renderer)
.render(attachment);
new DefaultAttachmentProcessor(lifecycle)
.addAttachment(attachment, renderer);
verify(renderer, times(1)).render(attachment);
verify(lifecycle, times(1))
.addAttachment(
eq(attachment.getName()),
eq(content.getContentType()),
eq(content.getFileExtension()),
eq(content.getContent().getBytes(StandardCharsets.UTF_8))
);
}
}
| 37.603175 | 91 | 0.708316 |
de86b6d95c9d03fd27aaa7ffd111b6573575455e | 9,470 | package org.ovirt.engine.core.bll;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.quota.QuotaManager;
import org.ovirt.engine.core.bll.snapshots.SnapshotsManager;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.common.action.IdParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VmManagementParametersBase;
import org.ovirt.engine.core.common.action.VmOperationParameterBase;
import org.ovirt.engine.core.common.action.VmPoolSimpleUserParameters;
import org.ovirt.engine.core.common.businessentities.Snapshot;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmPayload;
import org.ovirt.engine.core.common.businessentities.VmPool;
import org.ovirt.engine.core.common.businessentities.VmPoolType;
import org.ovirt.engine.core.common.businessentities.VmWatchdog;
import org.ovirt.engine.core.common.businessentities.aaa.DbUser;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.utils.VmDeviceCommonUtils;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.VmPoolDAO;
import org.ovirt.engine.core.utils.log.Log;
import org.ovirt.engine.core.utils.log.LogFactory;
@InternalCommandAttribute
@NonTransactiveCommandAttribute
public class ProcessDownVmCommand<T extends IdParameters> extends CommandBase<T> {
private static final Log log = LogFactory.getLog(ProcessDownVmCommand.class);
protected ProcessDownVmCommand(Guid commandId) {
super(commandId);
}
public ProcessDownVmCommand(T parameters) {
this(parameters, null);
}
public ProcessDownVmCommand(T parameters, CommandContext cmdContext) {
super(parameters, cmdContext);
setVmId(getParameters().getId());
}
@Override
protected boolean canDoAction() {
if (getVm() == null) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND);
}
return true;
}
@Override
protected void executeCommand() {
boolean removedStatelessSnapshot = detachUsers();
if (!removedStatelessSnapshot) {
// If we are dealing with a prestarted Vm or a regular Vm - clean stateless images
// Otherwise this was already done in DetachUserFromVmFromPoolCommand
removeVmStatelessImages();
}
QuotaManager.getInstance().rollbackQuotaByVmId(getVmId());
removeStatelessVmUnmanagedDevices();
applyNextRunConfiguration();
}
private boolean detachUsers() {
// check if this is a VM from a VM pool
if (getVm().getVmPoolId() == null) {
return false;
}
List<DbUser> users = getDbUserDAO().getAllForVm(getVmId());
// check if this VM is attached to a user
if (users == null || users.isEmpty()) {
// if not, check if new version or need to restore stateless
runInternalActionWithTasksContext(VdcActionType.RestoreStatelessVm,
new VmOperationParameterBase(getVmId()),
getLock());
return true;
}
VmPool pool = getVmPoolDAO().get(getVm().getVmPoolId());
if (pool != null && pool.getVmPoolType() == VmPoolType.Automatic) {
// should be only one user in the collection
for (DbUser dbUser : users) {
runInternalActionWithTasksContext(VdcActionType.DetachUserFromVmFromPool,
new VmPoolSimpleUserParameters(getVm().getVmPoolId(), dbUser.getId(), getVmId()), getLock());
}
return true;
}
return false;
}
private VmPoolDAO getVmPoolDAO() {
return DbFacade.getInstance().getVmPoolDao();
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
return Collections.emptyList();
}
/**
* remove VMs unmanaged devices that are created during run-once or stateless run.
*
* @param vmId
*/
private void removeStatelessVmUnmanagedDevices() {
if (getVm().isStateless() || isRunOnce()) {
final List<VmDevice> vmDevices =
DbFacade.getInstance()
.getVmDeviceDao()
.getUnmanagedDevicesByVmId(getVmId());
for (VmDevice device : vmDevices) {
// do not remove device if appears in white list
if (!VmDeviceCommonUtils.isInWhiteList(device.getType(), device.getDevice())) {
DbFacade.getInstance().getVmDeviceDao().remove(device.getId());
}
}
}
}
/**
* This method checks if we are stopping a VM that was started by run-once In such case we will may have 2 devices,
* one managed and one unmanaged for CD or Floppy This is not supported currently by libvirt that allows only one
* CD/Floppy This code should be removed if libvirt will support in future multiple CD/Floppy
*/
private boolean isRunOnce() {
List<VmDevice> cdList =
DbFacade.getInstance()
.getVmDeviceDao()
.getVmDeviceByVmIdTypeAndDevice(getVmId(),
VmDeviceGeneralType.DISK,
VmDeviceType.CDROM.getName());
List<VmDevice> floppyList =
DbFacade.getInstance()
.getVmDeviceDao()
.getVmDeviceByVmIdTypeAndDevice(getVmId(),
VmDeviceGeneralType.DISK,
VmDeviceType.FLOPPY.getName());
return (cdList.size() > 1 || floppyList.size() > 1);
}
/**
* Update vm configuration with NEXT_RUN configuration, if exists
* @param vmId
*/
private void applyNextRunConfiguration() {
// Remove snpashot first, in case other update is in progress, it will block this one with exclusive lock
// and any newer update should be preffered to this one.
Snapshot runSnap = getSnapshotDAO().get(getVmId(), SnapshotType.NEXT_RUN);
if (runSnap != null) {
getSnapshotDAO().remove(runSnap.getId());
Date originalCreationDate = getVm().getVmCreationDate();
new SnapshotsManager().updateVmFromConfiguration(getVm(), runSnap.getVmConfiguration());
// override creation date because the value in the config is the creation date of the config, not the vm
getVm().setVmCreationDate(originalCreationDate);
runInternalAction(VdcActionType.UpdateVm, createUpdateVmParameters());
}
}
private VmManagementParametersBase createUpdateVmParameters() {
// clear non updateable fields got from config
getVm().setExportDate(null);
getVm().setOvfVersion(null);
VmManagementParametersBase updateVmParams = new VmManagementParametersBase(getVm());
updateVmParams.setUpdateWatchdog(true);
updateVmParams.setSoundDeviceEnabled(false);
updateVmParams.setBalloonEnabled(false);
updateVmParams.setVirtioScsiEnabled(false);
updateVmParams.setClearPayload(true);
for (VmDevice device : getVm().getManagedVmDeviceMap().values()) {
switch (device.getType()) {
case WATCHDOG:
updateVmParams.setWatchdog(new VmWatchdog(device));
break;
case SOUND:
updateVmParams.setSoundDeviceEnabled(true);
break;
case BALLOON:
updateVmParams.setBalloonEnabled(true);
break;
case CONTROLLER:
if (VmDeviceType.VIRTIOSCSI.getName().equals(device.getDevice())) {
updateVmParams.setVirtioScsiEnabled(true);
}
break;
case DISK:
if (VmPayload.isPayload(device.getSpecParams())) {
updateVmParams.setVmPayload(new VmPayload(device));
}
break;
case CONSOLE:
updateVmParams.setConsoleEnabled(true);
break;
default:
}
}
// clear these fields as these are non updatable
getVm().getManagedVmDeviceMap().clear();
getVm().getVmUnamagedDeviceList().clear();
return updateVmParams;
}
private void removeVmStatelessImages() {
if (getSnapshotDAO().exists(getVmId(), SnapshotType.STATELESS)) {
log.infoFormat("Deleting snapshot for stateless vm {0}", getVmId());
runInternalAction(VdcActionType.RestoreStatelessVm,
new VmOperationParameterBase(getVmId()),
ExecutionHandler.createDefaultContextForTasks(getContext(), getLock()));
}
}
}
| 40.643777 | 119 | 0.641183 |
ee688438b9bc25c367723cf72b8527186d79d169 | 6,526 | package OOD;
import jdk.swing.interop.SwingInterOpUtils;
import java.util.*;
// Copyright 2021 The KeepTry Open Source Project
//
// 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.
//
/*
/*
You have been tasked with
parsing menus from a large restaurant group. Each menu is streamed to clients via a provided interface.
You must design object(s) that represents a menu and can be instantiated with data from the provided interface
Your design should contain an appropriate class structure to contain the parsed data, as well as a function
or set of functions to perform the parsing.
Consumers will use your object(s) to access a complete representation of the data sent by the menu
stream after it has finished loading. Your objects should provide easy access to the full representation
of the menu.
It should be possible to reconstruct the menu stream from your object.
The menu stream represents a list of menu items. Each item in the stream is a menu item, and each item will
be separated by an empty string. The attributes of each item are as follows:
Line 0: The ID of the item
Line 1: The item type, either CATEGORY, ENTREE or OPTION
Line 2: The name of the item
Line 3: The price of the item for ENTREE and OPTION. Not present for CATEGORY items.
Any other line: A list of item IDs that are linked to the current item. OPTIONs do not have any linked items.
E.g.:
4
ENTREE
Spaghetti
10.95
2
3
------ empty line
1
CATEGORY
Pasta
4
5
------
2
OPTION
Meatballs
1.00
------
3
OPTION
Chicken
2.00
------
5
ENTREE
Lasagna
12.00
------
6
ENTREE
Caesar Salad
9.75
3
------
*/
abstract class Menu {
double ID;
String name;
public Menu(double ID, String name) {
this.ID = ID;
this.name = name;
}
abstract String getType();
@Override
public String toString() {
StringBuilder b = new StringBuilder();
return b.append(ID)
.append("\n")
.append(getType())
.append("\n")
.append(name)
.append("\n")
.toString();
}
}
abstract class WithNext extends Menu {
List<Menu> list;
public WithNext(double ID, String name) {
super(ID, name);
}
public void put(List<Menu> list) {
this.list = list;
}
@Override
public String toString() {
StringBuilder b = new StringBuilder();
for (Menu n : list) {
b.append(n.ID).append("\n");
}
return super.toString() + b;
}
}
class Category extends WithNext {
public Category(double ID, String name) {
super(ID, name);
}
@Override
String getType() {
return Category.class.getSimpleName().toUpperCase();
}
}
interface Price {
void put(float price);
}
class Entree extends WithNext implements Price {
float price;
public Entree(double ID, String name) {
super(ID, name);
}
@Override
String getType() {
return Entree.class.getSimpleName().toUpperCase();
}
@Override
public void put(float price) {
this.price = price;
}
}
class Option extends Menu implements Price {
float price;
public Option(double ID, String name) {
super(ID, name);
}
@Override
String getType() {
return Option.class.getSimpleName().toUpperCase();
}
@Override
public void put(float price) {
this.price = price;
}
@Override
public String toString() {
return super.toString() + price + "\n";
}
}
interface Parser {
Set<Menu> parsing(MenuStream stream);
List<String> parsing(Set<Menu> categorySet);
}
interface MenuStream {
String nextLine();
}
enum Type {
CATEGORY,
ENTREE,
OPTION
}
public class MenuParserImp implements Parser {
public Set<Menu> parsing(MenuStream stream) {
Set<Menu> result = new HashSet<>();
Map<Double, List<Double>> nexts = new HashMap<>();
Map<Double, Menu> map = new HashMap<>();
double ID;
Type type;
String name;
float price = 0;
String cur = null;
List<Double> list = null;
while (true) {
ID = Double.valueOf(stream.nextLine());
type = Type.valueOf(stream.nextLine());
name = stream.nextLine();
if (!type.equals(Category.class.getSimpleName().toUpperCase()))
price = Float.valueOf(stream.nextLine());
if (!type.equals(Option.class.getSimpleName().toUpperCase())) {
list = new ArrayList<>();
while (true) {
cur = stream.nextLine();
if (!(cur == null || cur.isEmpty())) {
list.add(Double.valueOf(stream.nextLine()));
} else break;
}
} else {
cur = stream.nextLine(); // empty line or null
}
Menu m = null;
switch (type) {
case CATEGORY:
m = new Category(ID, name);
break;
case ENTREE:
Entree e = new Entree(ID, name);
e.put(price);
m = e;
break;
case OPTION:
Option o = new Option(ID, name);
o.put(price);
m = o;
break;
default:
// todo
}
if (m instanceof Category) result.add(m);
map.put(ID, m);
if (!type.equals(Option.class.getSimpleName().toUpperCase())) {
nexts.put(ID, list);
if (cur == null) break;
}
}
for (double id : nexts.keySet()) {
WithNext withn = (WithNext) map.get(id);
List<Menu> l = new ArrayList<>();
withn.put(l);
for (double n : nexts.get(id)) l.add(map.get(n));
}
return result;
}
// Category set
@Override
public List<String> parsing(Set<Menu> menus) {
List<String> ans = new ArrayList<>();
Set<Menu> vis = new HashSet<>();
for (Menu m : menus) {
f(m, ans, vis);
}
ans.remove(ans.size() - 1);
ans.add(null);
return ans;
}
private void f(Menu m, List<String> ans, Set<Menu> vis) {
if (vis.contains(m)) return;
vis.add(m);
ans.add(m.toString() + "\n");
if (m instanceof WithNext) {
WithNext wn = (WithNext) m;
for (Menu n : wn.list) {
f(n, ans, vis);
}
}
}
public static void main(String[] args) {
// Todo
}
}
| 22.349315 | 111 | 0.629329 |
ce8a942dbf19b929e6d7c820514a06d2edd50967 | 1,366 | // This file is licensed under the Elastic License 2.0. Copyright 2021 StarRocks Limited.
package com.starrocks.sql.optimizer.rule.implementation;
import com.google.common.collect.Lists;
import com.starrocks.sql.optimizer.OptExpression;
import com.starrocks.sql.optimizer.OptimizerContext;
import com.starrocks.sql.optimizer.operator.OperatorType;
import com.starrocks.sql.optimizer.operator.logical.LogicalProjectOperator;
import com.starrocks.sql.optimizer.operator.pattern.Pattern;
import com.starrocks.sql.optimizer.operator.physical.PhysicalProjectOperator;
import com.starrocks.sql.optimizer.rule.RuleType;
import java.util.List;
public class ProjectImplementationRule extends ImplementationRule {
public ProjectImplementationRule() {
super(RuleType.IMP_PROJECT,
Pattern.create(OperatorType.LOGICAL_PROJECT, OperatorType.PATTERN_LEAF));
}
@Override
public List<OptExpression> transform(OptExpression input, OptimizerContext context) {
LogicalProjectOperator projectOperator = (LogicalProjectOperator) input.getOp();
PhysicalProjectOperator physicalProject = new PhysicalProjectOperator(
projectOperator.getColumnRefMap(),
projectOperator.getCommonSubOperatorMap());
return Lists.newArrayList(OptExpression.create(physicalProject, input.getInputs()));
}
}
| 44.064516 | 92 | 0.785505 |
72ed4511c847afe7d935c2255b38bb87eb35bae6 | 538 | package org.cloudfoundry.identity.uaa.account;
import org.cloudfoundry.identity.uaa.test.JsonTranslation;
import org.junit.jupiter.api.BeforeEach;
class EmailChangeResponseTest extends JsonTranslation<EmailChangeResponse> {
@BeforeEach
void setUp() {
EmailChangeResponse subject = new EmailChangeResponse();
subject.setUsername("aaaa");
subject.setUserId("bbbb");
subject.setRedirectUrl("cccc");
subject.setEmail("dddd");
super.setUp(subject, EmailChangeResponse.class);
}
} | 29.888889 | 76 | 0.72119 |
7ea2449d3d47b8cfd148f4211fc7b60e5707ff8d | 2,087 | package io.getmedusa.medusa.core.annotation;
import io.getmedusa.medusa.core.registry.EventHandlerRegistry;
import io.getmedusa.medusa.core.registry.RouteRegistry;
import io.getmedusa.medusa.core.util.FilenameHandler;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
/**
* This class triggers the post-processing. This is extensively relied upon to setup the registry at startup. <br/>
* Note: This is post-processing <i>before</i> initialization of all beans. So it happens before any bean has started up.
*/
@Component
class UIEventPostProcessor implements BeanPostProcessor {
private final boolean hydraEnabled;
public UIEventPostProcessor(@Value("${hydra.enabled:false}") Boolean hydraEnabled) {
if(hydraEnabled == null) hydraEnabled = false;
this.hydraEnabled = hydraEnabled;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
final UIEventPage uiEventPage = bean.getClass().getAnnotation(UIEventPage.class);
if(uiEventPage != null) {
final String path = uiEventPage.path();
final String htmlFile = FilenameHandler.removeExtension(FilenameHandler.normalize(uiEventPage.file()));
RouteRegistry.getInstance().add(path, htmlFile);
if(hydraEnabled) {
final HydraMenu menu = bean.getClass().getAnnotation(HydraMenu.class);
if(null != menu) RouteRegistry.getInstance().addMenuItem(menu.value(), menu.label(), path);
}
EventHandlerRegistry.getInstance().add(path, bean);
}
return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
}
}
| 44.404255 | 121 | 0.737422 |
dbc4b063c5c5abaa2198c4e4ed3d4c1ffbaa3898 | 1,550 | package my_cargonaut.utility.data_classes.offers;
import my_cargonaut.utility.data_classes.Measurements;
import my_cargonaut.utility.data_classes.Tour;
import my_cargonaut.utility.data_classes.user.User;
import my_cargonaut.utility.data_classes.Vehicle;
import java.util.Optional;
public class Offer implements java.io.Serializable {
private static long numberOfOffers = 0L;
// use userid here instead?
private User user;
private Tour tour;
private long offerID;
private Measurements freeSpace;
private Vehicle vic;
public User offerAcceptor;
public Offer(User user, Tour tour, Measurements freeSpace, Vehicle vehicle) {
this.user = user;
this.tour = tour;
this.offerID = numberOfOffers++;
this.freeSpace = freeSpace;
this.vic = vehicle;
this.offerAcceptor = null;
}
public User getUser() {
return user;
}
public Tour getRoute() {
return tour;
}
public Optional<Vehicle> getVehicle() {
return Optional.ofNullable(vic);
}
public Optional<Measurements> getFreeSpace() {
return Optional.ofNullable(freeSpace);
}
public Optional<User> getOfferAcceptor() {
return Optional.ofNullable(offerAcceptor);
}
public long getOfferID() {
return this.offerID;
}
public boolean hasOfferAcceptor() {
return getOfferAcceptor().isPresent();
}
public Offer setOfferAcceptor(User user) {
this.offerAcceptor = user;
return this;
}
}
| 23.846154 | 81 | 0.673548 |
2b9c72e269fbe63ad2bf0080975b7991c778cbb7 | 2,725 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/enums/account_budget_status.proto
package com.google.ads.googleads.v10.enums;
public final class AccountBudgetStatusProto {
private AccountBudgetStatusProto() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_ads_googleads_v10_enums_AccountBudgetStatusEnum_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_ads_googleads_v10_enums_AccountBudgetStatusEnum_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n:google/ads/googleads/v10/enums/account" +
"_budget_status.proto\022\036google.ads.googlea" +
"ds.v10.enums\032\034google/api/annotations.pro" +
"to\"x\n\027AccountBudgetStatusEnum\"]\n\023Account" +
"BudgetStatus\022\017\n\013UNSPECIFIED\020\000\022\013\n\007UNKNOWN" +
"\020\001\022\013\n\007PENDING\020\002\022\014\n\010APPROVED\020\003\022\r\n\tCANCELL" +
"ED\020\004B\362\001\n\"com.google.ads.googleads.v10.en" +
"umsB\030AccountBudgetStatusProtoP\001ZCgoogle." +
"golang.org/genproto/googleapis/ads/googl" +
"eads/v10/enums;enums\242\002\003GAA\252\002\036Google.Ads." +
"GoogleAds.V10.Enums\312\002\036Google\\Ads\\GoogleA" +
"ds\\V10\\Enums\352\002\"Google::Ads::GoogleAds::V" +
"10::Enumsb\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.AnnotationsProto.getDescriptor(),
});
internal_static_google_ads_googleads_v10_enums_AccountBudgetStatusEnum_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_ads_googleads_v10_enums_AccountBudgetStatusEnum_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_ads_googleads_v10_enums_AccountBudgetStatusEnum_descriptor,
new java.lang.String[] { });
com.google.api.AnnotationsProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 44.672131 | 99 | 0.755963 |
f988333c18cc6866d02df63a3782a2fbe00a6229 | 387 | package com.ss.ssmall.coupon.dao;
import com.ss.ssmall.coupon.entity.SeckillPromotionEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* ็งๆๆดปๅจ
*
* @author fangsheng
* @email [email protected]
* @date 2020-09-03 11:34:09
*/
@Mapper
public interface SeckillPromotionDao extends BaseMapper<SeckillPromotionEntity> {
}
| 21.5 | 81 | 0.77261 |
6d0162c222d29292df533f702d57ddd4fd6a8ccd | 992 | package io.gamemachine.core;
import io.gamemachine.messages.Character;
import io.gamemachine.messages.CombatLog;
import io.gamemachine.messages.ItemSlots;
import io.gamemachine.messages.StatusEffect;
import io.gamemachine.messages.Vitals;
import plugins.core.combat.VitalsProxy;
public interface GameEntityManager {
Vitals getBaseVitals(String characterId);
Vitals getBaseVitals(String entityId, Vitals.VitalsType vitalsType, String zone);
void OnCharacterCreated(Character character, Object data);
void OnPlayerConnected(String playerId);
void OnPlayerDisConnected(String playerId);
int getEffectValue(StatusEffect statusEffect, String playerSkillId, String characterId);
void skillUsed(String playerSkillId, String characterId);
void combatDamage(VitalsProxy originProxy, VitalsProxy targetProxy, int damage, CombatLog.Type type);
void ItemSlotsUpdated(String playerId, String characterId, ItemSlots itemSlots);
}
| 33.066667 | 106 | 0.785282 |
0ac20695fae802addf8699571063c8be806d3572 | 4,566 | package org.jiffy.util;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
public class Dollar implements Comparable<Dollar>, Serializable
{
public static final Dollar ZERO = new Dollar("0.00");
private static final long serialVersionUID = 893832762897563929L;
protected BigDecimal amount;
protected Currency currency;
protected RoundingMode roundingMode;
// in situations that carry more than 2 decimal spots for cents
// like in tax situations or currency trading
public Dollar(BigDecimal dollarAmount, int centDigits)
{
this.amount = dollarAmount.setScale(centDigits, RoundingMode.HALF_EVEN);
this.currency = Currency.getInstance("USD");
}
public Dollar(BigDecimal dollarAmount)
{
this(dollarAmount, 2);
}
public Dollar(String amount)
{
this(new BigDecimal(amount));
}
public BigDecimal getAmount()
{
return amount;
}
public double doubleValue()
{
return amount.doubleValue();
}
public Dollar plus(Dollar d)
{
return new Dollar(amount.add(d.getAmount()));
}
public Dollar minus(Dollar d)
{
return new Dollar(amount.subtract(d.getAmount()));
}
public static Dollar sum(Dollar...d)
{
Dollar sum = ZERO;
for (int i=0; i<d.length; i++)
{
sum = sum.plus(d[i]);
}
return sum;
}
public Dollar times(double multiple)
{
return new Dollar(amount.multiply(new BigDecimal(multiple)));
}
public Dollar divide(double dividend)
{
return new Dollar(amount.divide(new BigDecimal(dividend)));
}
public Dollar afterTax(double taxRate)
{
return times(1 + taxRate);
}
// return % in decimal terms, e.g. 0.825 or 1.35
public static double percentDifference(Dollar d1, Dollar d2, int decimal)
{
return d1.getAmount().divide(d2.getAmount(), decimal, RoundingMode.HALF_UP).doubleValue();
}
public boolean isGreaterThan(Dollar d)
{
return amount.compareTo(d.getAmount()) > 0;
}
public boolean isGreaterThanEquals(Dollar d)
{
return amount.compareTo(d.getAmount()) >= 0;
}
public boolean isLessThan(Dollar d)
{
return amount.compareTo(d.getAmount()) < 0;
}
public boolean isLessThanEquals(Dollar d)
{
return amount.compareTo(d.getAmount()) <= 0;
}
public boolean isPositive()
{
return isGreaterThan(ZERO);
}
public boolean isNegative()
{
return isLessThan(ZERO);
}
public boolean isZero()
{
return equals(ZERO);
}
public Dollar inverse()
{
return times(-1);
}
public Dollar roundToNearest(Dollar d)
{
return new Dollar(new BigDecimal(MathUtil.roundToNearest(amount.doubleValue(), d.doubleValue())));
}
public Dollar roundToSigDigits(int sigDigits)
{
return new Dollar(new BigDecimal(MathUtil.roundToSigDigits(amount.doubleValue(), sigDigits, RoundingMode.HALF_EVEN.ordinal())));
}
public String toString()
{
return currency.getSymbol() + amount.toPlainString();
}
public String toString(String format)
{
DecimalFormat formatter = (DecimalFormat)NumberFormat.getInstance(Locale.getDefault());
formatter.applyPattern(format);
return formatter.format(doubleValue());
}
public static Dollar parseDollar(String dollarString) throws Exception
{
if (StringUtils.isEmpty(dollarString))
{
return ZERO;
}
double unrounded = 0.0;
DecimalFormat formatter = (DecimalFormat)NumberFormat.getInstance(Locale.getDefault());
// the price one isn't very tolerant when the currency is excluded, so for this we try it with the currency
// one in case they did type it, and then fail to a normal one if they didn't type it, and then fail
// to a thrown exception
try
{
formatter.applyPattern("$#,###.00");
unrounded = formatter.parse(dollarString.trim()).doubleValue();
}
catch (Exception ex)
{
try
{
formatter.applyPattern("#,###.00");
unrounded = formatter.parse(dollarString.trim()).doubleValue();
}
catch (Exception e)
{
throw new Exception(Text.get("error.invalidPriceFormat"));
}
}
return new Dollar(new BigDecimal(unrounded));
}
public int compareTo(Dollar d)
{
return amount.compareTo(d.getAmount());
}
public boolean equals(Dollar d)
{
return amount.equals(d.getAmount());
}
}
| 23.060606 | 131 | 0.678055 |
fbe163b45e57c4435f8de522ea7b247d245387cb | 388 | package com.jfeat.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.Data;
/**
* Created on 2020/6/28.
*
* @author Wen Hao
*/
@Data
@Component
@ConfigurationProperties(prefix = "fs")
public class FSProperties {
private String fileUploadPath;
private String fileHost;
}
| 16.166667 | 75 | 0.760309 |
a75b3abb0609c464f4a10c276450be15d01a32f8 | 400 | package com.study.spring;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created on 2018-01-07
*
* @author liuzhaoyuan
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootShiroApplication.class)// ๆๅฎspring-boot็ๅฏๅจ็ฑป
public class BaseTest {
}
| 23.529412 | 79 | 0.8025 |
6defe19f39cccd7dc73a12e8c7c5c774cf478cef | 971 | package datamodel.ex1.service;
import datamodel.ex1.entity.Person;
import io.jmix.core.DataManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
@Service(PersonApiService.NAME)
public class PersonApiServiceBean implements PersonApiService{
@Autowired
private DataManager dataManager;
@Override
public List<Person> getPersons() {
return dataManager.load(Person.class).all().list();
}
@Override
public void addNewPerson(String firstName, BigDecimal height, String passportNumber) {
Person person = dataManager.create(Person.class);
person.setFirstName(firstName);
person.setHeight(height);
person.setPassportNumber(passportNumber);
dataManager.save(person);
}
@Override
public String validatePerson(String comment, Person person) {
return null;
}
}
| 26.972222 | 90 | 0.733265 |
8455948043840578e61291458e3a77687672ea1e | 77 | package com.julianjupiter.addressbook.core;
public interface Controller {
}
| 15.4 | 43 | 0.818182 |
e250d3bcd0002f7dde9d08c7e406484445aa90b9 | 8,647 | package com.mysql.cj.jdbc;
import com.mysql.cj.Messages;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping;
import com.mysql.cj.log.Log;
import com.mysql.cj.util.StringUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.XAConnection;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
public class MysqlXAConnection extends MysqlPooledConnection implements XAConnection, XAResource {
private static final int MAX_COMMAND_LENGTH = 300;
private JdbcConnection underlyingConnection;
private static final Map<Integer, Integer> MYSQL_ERROR_CODES_TO_XA_ERROR_CODES;
private Log log;
protected boolean logXaCommands;
static {
HashMap<Integer, Integer> temp = new HashMap<>();
temp.put(Integer.valueOf(1397), Integer.valueOf(-4));
temp.put(Integer.valueOf(1398), Integer.valueOf(-5));
temp.put(Integer.valueOf(1399), Integer.valueOf(-7));
temp.put(Integer.valueOf(1400), Integer.valueOf(-9));
temp.put(Integer.valueOf(1401), Integer.valueOf(-3));
temp.put(Integer.valueOf(1402), Integer.valueOf(100));
temp.put(Integer.valueOf(1440), Integer.valueOf(-8));
temp.put(Integer.valueOf(1613), Integer.valueOf(106));
temp.put(Integer.valueOf(1614), Integer.valueOf(102));
MYSQL_ERROR_CODES_TO_XA_ERROR_CODES = Collections.unmodifiableMap(temp);
}
protected static MysqlXAConnection getInstance(JdbcConnection mysqlConnection, boolean logXaCommands) throws SQLException {
return new MysqlXAConnection(mysqlConnection, logXaCommands);
}
public MysqlXAConnection(JdbcConnection connection, boolean logXaCommands) {
super(connection);
this.underlyingConnection = connection;
this.log = connection.getSession().getLog();
this.logXaCommands = logXaCommands;
}
public XAResource getXAResource() throws SQLException {
try {
return this;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException);
}
}
public int getTransactionTimeout() throws XAException {
return 0;
}
public boolean setTransactionTimeout(int arg0) throws XAException {
return false;
}
public boolean isSameRM(XAResource xares) throws XAException {
if (xares instanceof MysqlXAConnection)
return this.underlyingConnection.isSameResource(((MysqlXAConnection)xares).underlyingConnection);
return false;
}
public Xid[] recover(int flag) throws XAException {
return recover(this.underlyingConnection, flag);
}
protected static Xid[] recover(Connection c, int flag) throws XAException {
boolean startRscan = ((flag & 0x1000000) > 0);
boolean endRscan = ((flag & 0x800000) > 0);
if (!startRscan && !endRscan && flag != 0)
throw new MysqlXAException(-5, Messages.getString("MysqlXAConnection.001"), null);
if (!startRscan)
return new Xid[0];
ResultSet rs = null;
Statement stmt = null;
List<MysqlXid> recoveredXidList = new ArrayList<>();
try {
stmt = c.createStatement();
rs = stmt.executeQuery("XA RECOVER");
while (rs.next()) {
int formatId = rs.getInt(1);
int gtridLength = rs.getInt(2);
int bqualLength = rs.getInt(3);
byte[] gtridAndBqual = rs.getBytes(4);
byte[] gtrid = new byte[gtridLength];
byte[] bqual = new byte[bqualLength];
if (gtridAndBqual.length != gtridLength + bqualLength)
throw new MysqlXAException(105, Messages.getString("MysqlXAConnection.002"), null);
System.arraycopy(gtridAndBqual, 0, gtrid, 0, gtridLength);
System.arraycopy(gtridAndBqual, gtridLength, bqual, 0, bqualLength);
recoveredXidList.add(new MysqlXid(gtrid, bqual, formatId));
}
} catch (SQLException sqlEx) {
throw mapXAExceptionFromSQLException(sqlEx);
} finally {
if (rs != null)
try {
rs.close();
} catch (SQLException sqlEx) {
throw mapXAExceptionFromSQLException(sqlEx);
}
if (stmt != null)
try {
stmt.close();
} catch (SQLException sqlEx) {
throw mapXAExceptionFromSQLException(sqlEx);
}
}
int numXids = recoveredXidList.size();
Xid[] asXids = new Xid[numXids];
Object[] asObjects = recoveredXidList.toArray();
for (int i = 0; i < numXids; i++)
asXids[i] = (Xid)asObjects[i];
return asXids;
}
public int prepare(Xid xid) throws XAException {
StringBuilder commandBuf = new StringBuilder(300);
commandBuf.append("XA PREPARE ");
appendXid(commandBuf, xid);
dispatchCommand(commandBuf.toString());
return 0;
}
public void forget(Xid xid) throws XAException {}
public void rollback(Xid xid) throws XAException {
StringBuilder commandBuf = new StringBuilder(300);
commandBuf.append("XA ROLLBACK ");
appendXid(commandBuf, xid);
try {
dispatchCommand(commandBuf.toString());
} finally {
this.underlyingConnection.setInGlobalTx(false);
}
}
public void end(Xid xid, int flags) throws XAException {
StringBuilder commandBuf = new StringBuilder(300);
commandBuf.append("XA END ");
appendXid(commandBuf, xid);
switch (flags) {
case 67108864:
break;
case 33554432:
commandBuf.append(" SUSPEND");
break;
case 536870912:
break;
default:
throw new XAException(-5);
}
dispatchCommand(commandBuf.toString());
}
public void start(Xid xid, int flags) throws XAException {
StringBuilder commandBuf = new StringBuilder(300);
commandBuf.append("XA START ");
appendXid(commandBuf, xid);
switch (flags) {
case 2097152:
commandBuf.append(" JOIN");
break;
case 134217728:
commandBuf.append(" RESUME");
break;
case 0:
break;
default:
throw new XAException(-5);
}
dispatchCommand(commandBuf.toString());
this.underlyingConnection.setInGlobalTx(true);
}
public void commit(Xid xid, boolean onePhase) throws XAException {
StringBuilder commandBuf = new StringBuilder(300);
commandBuf.append("XA COMMIT ");
appendXid(commandBuf, xid);
if (onePhase)
commandBuf.append(" ONE PHASE");
try {
dispatchCommand(commandBuf.toString());
} finally {
this.underlyingConnection.setInGlobalTx(false);
}
}
private ResultSet dispatchCommand(String command) throws XAException {
Statement stmt = null;
try {
if (this.logXaCommands)
this.log.logDebug("Executing XA statement: " + command);
stmt = this.underlyingConnection.createStatement();
stmt.execute(command);
ResultSet rs = stmt.getResultSet();
return rs;
} catch (SQLException sqlEx) {
throw mapXAExceptionFromSQLException(sqlEx);
} finally {
if (stmt != null)
try {
stmt.close();
} catch (SQLException sQLException) {}
}
}
protected static XAException mapXAExceptionFromSQLException(SQLException sqlEx) {
Integer xaCode = MYSQL_ERROR_CODES_TO_XA_ERROR_CODES.get(Integer.valueOf(sqlEx.getErrorCode()));
if (xaCode != null)
return (XAException)(new MysqlXAException(xaCode.intValue(), sqlEx.getMessage(), null)).initCause(sqlEx);
return (XAException)(new MysqlXAException(-7, Messages.getString("MysqlXAConnection.003"), null)).initCause(sqlEx);
}
private static void appendXid(StringBuilder builder, Xid xid) {
byte[] gtrid = xid.getGlobalTransactionId();
byte[] btrid = xid.getBranchQualifier();
if (gtrid != null)
StringUtils.appendAsHex(builder, gtrid);
builder.append(',');
if (btrid != null)
StringUtils.appendAsHex(builder, btrid);
builder.append(',');
StringUtils.appendAsHex(builder, xid.getFormatId());
}
public synchronized Connection getConnection() throws SQLException {
try {
Connection connToWrap = getConnection(false, true);
return connToWrap;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException);
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\MysqlXAConnection.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/ | 33.515504 | 138 | 0.680583 |
019ba8b57dd375dad5942c60439da963db26cc60 | 1,655 | /*******************************************************************************
* Copyright 2018 Samsung Electronics 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
*
* 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.edgexfoundry.support.dataprocessing.runtime.task;
import org.edgexfoundry.support.dataprocessing.runtime.task.model.QueryModel;
import org.junit.Assert;
import org.junit.Test;
public class QueryModelTest {
@Test
public void testGetProcessingType() {
QueryModel model = new QueryModel();
Assert.assertEquals(TaskType.QUERY, model.getType());
}
@Test
public void testGetName() {
TaskModel model1 = new QueryModel();
Assert.assertEquals("query", model1.getName());
QueryModel model2 = new QueryModel();
Assert.assertEquals("query", model2.getName());
}
@Test
public void testSetParam() {
TaskModel model1 = new QueryModel();
TaskModelParam params = new TaskModelParam();
params.put("request", "helloworld");
model1.setParam(params);
}
}
| 29.553571 | 81 | 0.632024 |
18bca88026a1f2112a61e1569ab8ec51ee66a469 | 397 | package com.java110.api.bmo.demo.impl;
import com.java110.api.bmo.ApiBaseBMO;
import com.java110.api.bmo.demo.IDemoBMO;
import org.springframework.stereotype.Service;
/**
* @ClassName DemoBMOImpl
* @Description TODO
* @Author wuxw
* @Date 2020/3/9 22:20
* @Version 1.0
* add by wuxw 2020/3/9
**/
@Service("demoBMOImpl")
public class DemoBMOImpl extends ApiBaseBMO implements IDemoBMO {
}
| 22.055556 | 65 | 0.745592 |
e7e628b1c4c5aa6648e645375e95c5a8cde4f65c | 775 | package io.bank.api.transactions.model.dto;
import io.bank.api.transactions.model.Account;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AccountDTO {
private String id;
private String created;
private String currency;
private long balance;
public static AccountDTO fromAccount(Account account) {
return AccountDTO.builder()
.id(account.getId())
.created(account.getCreated().toString())
.currency(account.getBalance().getCurrency().getCurrencyCode())
.balance(account.getBalance().getNumber().longValueExact())
.build();
}
}
| 27.678571 | 79 | 0.682581 |
0f30d43f3173b0afbbc5a9409ed8ebde0ba22c2a | 324 |
import java.util.*;
public class NullTest
{
public static void main(String[] args)
{
Date d = null;
try
{
System.out.println(d.after(new Date()));
}
catch (NullPointerException ne)
{
System.out.println("NullPointerException");
}
catch (Exception e)
{
System.out.println("Exception");
}
}
}
| 14.086957 | 46 | 0.638889 |
6a78b632a765366b0e98e3c25a4f2a3cc99c7cae | 4,072 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.android.tv;
import static com.android.tv.common.feature.EngOnlyFeature.ENG_ONLY_FEATURE;
import static com.android.tv.common.feature.FeatureUtils.AND;
import static com.android.tv.common.feature.FeatureUtils.ON;
import static com.android.tv.common.feature.FeatureUtils.OR;
import android.content.Context;
import android.os.Build;
import android.support.annotation.VisibleForTesting;
import android.support.v4.os.BuildCompat;
import com.android.tv.common.feature.Feature;
import com.android.tv.common.feature.GServiceFeature;
import com.android.tv.common.feature.PackageVersionFeature;
import com.android.tv.common.feature.PropertyFeature;
import com.android.tv.util.PermissionUtils;
/**
* List of {@link Feature} for the Live TV App.
*
* <p>Remove the {@code Feature} once it is launched.
*/
public final class Features {
/**
* UI for opting in to analytics.
*
* <p>Do not turn this on until the splash screen asking existing users to opt-in is launched.
* See <a href="http://b/20228119">b/20228119</a>
*/
public static final Feature ANALYTICS_OPT_IN = ENG_ONLY_FEATURE;
/**
* Analytics that include sensitive information such as channel or program identifiers.
*
* <p>See <a href="http://b/22062676">b/22062676</a>
*/
public static final Feature ANALYTICS_V2 = AND(ON, ANALYTICS_OPT_IN);
public static final Feature EPG_SEARCH =
new PropertyFeature("feature_tv_use_epg_search", false);
public static final Feature USB_TUNER = new Feature() {
/**
* This is special handling just for USB Tuner.
* It does not require any N API's but relies on a improvements in N for AC3 support
* After release, change class to this to just be
* {@link BuildCompat#isAtLeastN()}.
*/
@Override
public boolean isEnabled(Context context) {
return Build.VERSION.SDK_INT > Build.VERSION_CODES.M || BuildCompat.isAtLeastN();
}
};
private static final String PLAY_STORE_PACKAGE_NAME = "com.android.vending";
private static final int PLAY_STORE_ZIMA_VERSION_CODE = 80441186;
private static final Feature PLAY_STORE_LINK =
new PackageVersionFeature(PLAY_STORE_PACKAGE_NAME, PLAY_STORE_ZIMA_VERSION_CODE);
public static final Feature ONBOARDING_PLAY_STORE = PLAY_STORE_LINK;
/**
* A flag which indicates that the on-boarding experience is used or not.
*
* <p>See <a href="http://b/24070322">b/24070322</a>
*/
public static final Feature ONBOARDING_EXPERIENCE = ONBOARDING_PLAY_STORE;
private static final String GSERVICE_KEY_UNHIDE = "live_channels_unhide";
/**
* A flag which indicates that LC app is unhidden even when there is no input.
*/
public static final Feature UNHIDE = AND(ONBOARDING_EXPERIENCE,
OR(new GServiceFeature(GSERVICE_KEY_UNHIDE, false), new Feature() {
@Override
public boolean isEnabled(Context context) {
// If LC app runs as non-system app, we unhide the app.
return !PermissionUtils.hasAccessAllEpg(context);
}
}));
@VisibleForTesting
public static Feature TEST_FEATURE = new PropertyFeature("test_feature", false);
public static final Feature FETCH_EPG = new PropertyFeature("live_channels_fetch_epg", false);
private Features() {
}
}
| 37.357798 | 98 | 0.70334 |
abb01e576ba45b4ab889e04c1c608ad9cca384fa | 886 | package com.maximka.gifsearcher;
import android.app.Application;
import com.maximka.gifsearcher.DI.DaggerGiphyAppComponent;
import com.maximka.gifsearcher.DI.GiphyAppComponent;
import proxypref.ProxyPreferences;
/**
* Created by maximka on 15.11.16.
*/
public class GiphyApp extends Application {
public static final String PREFERENCES_NAME = "preferences";
private static GiphyAppComponent component;
private static Preferences preferences;
public static GiphyAppComponent getInjector() {
return component;
}
public static Preferences getPreferences() {
return preferences;
}
@Override
public void onCreate() {
super.onCreate();
component = DaggerGiphyAppComponent.create();
preferences = ProxyPreferences.build(Preferences.class,
getSharedPreferences(PREFERENCES_NAME, 0));
}
}
| 25.314286 | 64 | 0.722348 |
5b8bc9914dff6102b0f7d8d5965b9bfb4dae8cf7 | 302 | package com.kang.codetool.controller.request;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Data
public class GetDbDataConditionReq {
private String name;
private String value;
}
| 18.875 | 45 | 0.81457 |
771e080ddb2a312a7a821692bbf024d7da727c2f | 959 | /**
* Project Name: wine
* Package Name: top.guhanjie.wine.msic
* File Name: TestPrint.java
* Create Date: 2017ๅนด7ๆ9ๆฅ ไธๅ12:08:56
* Author: Administrator
* Copyright (c) 2014-2017, guhanjie All Rights Reserved.
*/
package top.guhanjie.wine.msic;
import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;
public class TestStringFormat {
@Test
public void testBinaryPrint() {
System.out.printf("%#016x\n", 127);
System.out.println(String.format("%16s", Integer.toBinaryString(7)));
System.out.println(0x01<<2 | 0x01<<1 | 0x01);
Integer i = null;
if(0 != i) {
System.out.println(i);
}
String total_fee = "1185";
System.out.println(Double.valueOf(total_fee)/100);
}
@Test
public void TestRandCodeFormat() {
int rcode = 151;
String randcode = String.format("%03d", rcode);
System.out.println(randcode);
}
}
| 24.589744 | 77 | 0.626694 |
d67dd87d76e7e417de80d407aeb2af8c46547af2 | 5,497 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_package
DECL|package|org.jabref.gui.externalfiletype
package|package
name|org
operator|.
name|jabref
operator|.
name|gui
operator|.
name|externalfiletype
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Comparator
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|javafx
operator|.
name|collections
operator|.
name|FXCollections
import|;
end_import
begin_import
import|import
name|javafx
operator|.
name|collections
operator|.
name|ObservableList
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jabref
operator|.
name|gui
operator|.
name|icon
operator|.
name|IconTheme
import|;
end_import
begin_import
import|import
name|org
operator|.
name|jabref
operator|.
name|logic
operator|.
name|l10n
operator|.
name|Localization
import|;
end_import
begin_class
DECL|class|CustomizeExternalFileTypesViewModel
specifier|public
class|class
name|CustomizeExternalFileTypesViewModel
block|{
DECL|field|fileTypes
specifier|private
specifier|final
name|ObservableList
argument_list|<
name|ExternalFileType
argument_list|>
name|fileTypes
decl_stmt|;
DECL|method|CustomizeExternalFileTypesViewModel ()
specifier|public
name|CustomizeExternalFileTypesViewModel
parameter_list|()
block|{
name|Set
argument_list|<
name|ExternalFileType
argument_list|>
name|types
init|=
name|ExternalFileTypes
operator|.
name|getInstance
argument_list|()
operator|.
name|getExternalFileTypeSelection
argument_list|()
decl_stmt|;
name|fileTypes
operator|=
name|FXCollections
operator|.
name|observableArrayList
argument_list|(
name|types
argument_list|)
expr_stmt|;
name|fileTypes
operator|.
name|sort
argument_list|(
name|Comparator
operator|.
name|comparing
argument_list|(
name|ExternalFileType
operator|::
name|getName
argument_list|)
argument_list|)
expr_stmt|;
block|}
comment|/** * Stores the list of external entry types in the preferences. */
DECL|method|storeSettings ()
specifier|public
name|void
name|storeSettings
parameter_list|()
block|{
name|ExternalFileTypes
operator|.
name|getInstance
argument_list|()
operator|.
name|setExternalFileTypes
argument_list|(
name|fileTypes
argument_list|)
expr_stmt|;
block|}
DECL|method|resetToDefaults ()
specifier|public
name|void
name|resetToDefaults
parameter_list|()
block|{
name|List
argument_list|<
name|ExternalFileType
argument_list|>
name|list
init|=
name|ExternalFileTypes
operator|.
name|getDefaultExternalFileTypes
argument_list|()
decl_stmt|;
name|fileTypes
operator|.
name|setAll
argument_list|(
name|list
argument_list|)
expr_stmt|;
name|fileTypes
operator|.
name|sort
argument_list|(
name|Comparator
operator|.
name|comparing
argument_list|(
name|ExternalFileType
operator|::
name|getName
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|addNewType ()
specifier|public
name|void
name|addNewType
parameter_list|()
block|{
name|CustomExternalFileType
name|type
init|=
operator|new
name|CustomExternalFileType
argument_list|(
literal|""
argument_list|,
literal|""
argument_list|,
literal|""
argument_list|,
literal|""
argument_list|,
literal|"new"
argument_list|,
name|IconTheme
operator|.
name|JabRefIcons
operator|.
name|FILE
argument_list|)
decl_stmt|;
name|fileTypes
operator|.
name|add
argument_list|(
name|type
argument_list|)
expr_stmt|;
name|showEditDialog
argument_list|(
name|type
argument_list|,
name|Localization
operator|.
name|lang
argument_list|(
literal|"Add new file type"
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|getFileTypes ()
specifier|public
name|ObservableList
argument_list|<
name|ExternalFileType
argument_list|>
name|getFileTypes
parameter_list|()
block|{
return|return
name|fileTypes
return|;
block|}
DECL|method|showEditDialog (ExternalFileType type, String dialogTitle)
specifier|private
name|void
name|showEditDialog
parameter_list|(
name|ExternalFileType
name|type
parameter_list|,
name|String
name|dialogTitle
parameter_list|)
block|{
name|CustomExternalFileType
name|typeForEdit
decl_stmt|;
if|if
condition|(
name|type
operator|instanceof
name|CustomExternalFileType
condition|)
block|{
name|typeForEdit
operator|=
operator|(
name|CustomExternalFileType
operator|)
name|type
expr_stmt|;
block|}
else|else
block|{
name|typeForEdit
operator|=
operator|new
name|CustomExternalFileType
argument_list|(
name|type
argument_list|)
expr_stmt|;
block|}
name|EditExternalFileTypeEntryDialog
name|dlg
init|=
operator|new
name|EditExternalFileTypeEntryDialog
argument_list|(
name|typeForEdit
argument_list|,
name|dialogTitle
argument_list|)
decl_stmt|;
name|dlg
operator|.
name|showAndWait
argument_list|()
expr_stmt|;
block|}
DECL|method|edit (ExternalFileType type)
specifier|public
name|void
name|edit
parameter_list|(
name|ExternalFileType
name|type
parameter_list|)
block|{
name|showEditDialog
argument_list|(
name|type
argument_list|,
name|Localization
operator|.
name|lang
argument_list|(
literal|"Edit file type"
argument_list|)
argument_list|)
expr_stmt|;
block|}
DECL|method|remove (ExternalFileType type)
specifier|public
name|void
name|remove
parameter_list|(
name|ExternalFileType
name|type
parameter_list|)
block|{
name|fileTypes
operator|.
name|remove
argument_list|(
name|type
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
| 14.776882 | 86 | 0.819356 |
2260ae8cc81534b1e8b3de53d52262e77da44fd3 | 1,282 | package com.github.base.widget.toast;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.github.base.R;
/**
* @author liji
*/
public class CenterToast extends Toast {
private TextView tvContent;
private String text;
private int duration;
public CenterToast(Context context, String content) {
this(context, content, Toast.LENGTH_SHORT);
}
public CenterToast(Context context, String content, int duration) {
super(context);
this.text = content;
this.duration = duration;
init(context);
}
private void init(Context context) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.base_center_toast, null);
setGravity(Gravity.CENTER, 0, 0);
//setGravity็จๆฅ่ฎพ็ฝฎToastๆพ็คบ็ไฝ็ฝฎ๏ผ็ธๅฝไบxmlไธญ็android:gravityๆandroid:layout_gravity
tvContent = (TextView) view.findViewById(R.id.tv_content);
tvContent.setText("" + text);
setDur(duration);
setView(view);
}
public CenterToast setDur(int duration) {
this.setDuration(duration);
return this;
}
}
| 25.64 | 81 | 0.684867 |
5969c94cbdb21b8ce9d2f0a07ea5fe2e0a6fca4e | 413 | package io.github.benzwreck.wykop4j.exceptions;
/**
* This exception is thrown when you are trying to send a pm to the user that blocked you.
*/
public class UserBlockedByAnotherUserException extends WykopException {
public UserBlockedByAnotherUserException() {
super(102, "Uลผytkownik nie chce odbieraฤ wiadomoลci prywatnych od Ciebie", "User does not want to receive messages from you.");
}
}
| 37.545455 | 135 | 0.760291 |
65a15e5224308d7b60e73ec7862a33f8664ab0fb | 8,620 | package me.opkarol.oppets;
/*
= Copyright (c) 2021-2022.
= [OpPets] ThisKarolGajda
= 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.
*/
import me.opkarol.oppets.cache.NamespacedKeysCache;
import me.opkarol.oppets.collections.map.OpMap;
import me.opkarol.oppets.commands.builder.OpCommandBuilder;
import me.opkarol.oppets.commands.OpSubCommand;
import me.opkarol.oppets.commands.OpPetsCommandExecutor;
import me.opkarol.oppets.databases.Database;
import me.opkarol.oppets.entities.manager.IEntityManager;
import me.opkarol.oppets.files.manager.FileManager;
import me.opkarol.oppets.files.MessagesHolder;
import me.opkarol.oppets.graphic.GraphicInterface;
import me.opkarol.oppets.interfaces.IUtils;
import me.opkarol.oppets.inventory.OpInventories;
import me.opkarol.oppets.listeners.*;
import me.opkarol.oppets.misc.external.bstats.Metrics;
import me.opkarol.oppets.versions.ServerVersion;
import me.opkarol.oppets.packets.IPacketPlayInSteerVehicleEvent;
import me.opkarol.oppets.packets.PacketManager;
import me.opkarol.oppets.pets.Pet;
import me.opkarol.oppets.utils.external.MathUtils;
import me.opkarol.oppets.utils.OpUtils;
import me.opkarol.oppets.utils.external.PDCUtils;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID;
public class PetPluginController {
private final Database database = Database.getInstance();
private final OpPets instance;
private IPacketPlayInSteerVehicleEvent packetEvent;
private String version;
private OpPetsCommandExecutor executor;
public PetPluginController(OpPets opPets) {
this.instance = opPets;
init();
}
public OpPets getInstance() {
return instance;
}
public void init() {
getInstance().saveDefaultConfig();
registerCommands();
bStatsActivation(13211);
}
public void bStatsActivation(int pluginId) {
Metrics metrics = new Metrics(getInstance(), pluginId);
metrics.addCustomChart(new Metrics.SingleLineChart("pets", () -> database.getDatabase().getPetsMap().keySet().stream().mapToInt(uuid -> database.getDatabase().getPetList(uuid).size()).sum()));
}
public void saveFiles() {
executor.getCommandListener().unregister();
Bukkit.getOnlinePlayers().forEach(player -> database.getDatabase().databaseUUIDSaver(player.getUniqueId(), false));
new FileManager<OpMap<UUID, List<Pet>>>("database/Pets.txt").saveObject(database.getDatabase().getPetsMap());
new FileManager<OpMap<UUID, Pet>>("database/ActivePets.txt").saveObject(database.getDatabase().getActivePetMap());
killAllPets();
}
public void registerEvents() {
PluginManager manager = instance.getServer().getPluginManager();
manager.registerEvents(new PlayerListeners(), instance);
manager.registerEvents(new SkillsListeners(), instance);
manager.registerEvents(new PetListeners(), instance);
manager.registerEvents(new ChatReceiver(), instance);
manager.registerEvents(new PetAbilities(), instance);
manager.registerEvents(new GraphicInterface(), instance);
}
public void registerCommands() {
OpMap<String, OpSubCommand> builder = new OpCommandBuilder().addKey("Addons").addKey("Admin").addKey("Booster").addKey("Call").addKey("Create").addKey("Delete").addKey("Eggs").addKey("Gift").addKey("Help").addKey("Leaderboard").addKey("Preferences").addKey("Prestige").addKey("Rename").addKey("Ride").addKey("Shop").addKey("Summon")
.addDummyKey("respawn", (commandSender, strings) -> {
//TODO add cooldown
if (commandSender instanceof Player player) {
Pet pet = database.getDatabase().getCurrentPet(player.getUniqueId());
database.getUtils().respawnPet(pet, player);
player.sendMessage(MessagesHolder.getInstance().getString("Commands.respawnedSuccessfully"));
}
})
.addDummyKey("settings", (commandSender, strings) -> {
if (commandSender instanceof Player player) {
Pet pet = database.getDatabase().getCurrentPet(player.getUniqueId());
player.openInventory(new OpInventories.SettingsInventory(pet).buildInventory());
}
})
.getMap();
executor = new OpPetsCommandExecutor(builder);
}
public void killAllPets() {
database.getDatabase().getActivePetMap().keySet().forEach(uuid -> {
if (uuid != null) {
OpUtils.killPetFromPlayerUUID(uuid);
}
});
Bukkit.getWorlds()
.forEach(world -> world.getLivingEntities().stream()
.filter(entity -> (!(entity instanceof Player)))
.filter(entity -> PDCUtils.hasNBT(entity, NamespacedKeysCache.petKey))
.forEach(LivingEntity::remove));
}
public boolean setupVersion() {
String version;
try {
version = Bukkit.getBukkitVersion().split("-")[0];
this.setVersion(version);
} catch (ArrayIndexOutOfBoundsException exception) {
instance.disablePlugin(exception.getCause().getMessage());
return false;
}
this.instance.getLogger().info("Your server is running version " + version);
PluginManager manager = this.instance.getServer().getPluginManager();
String versionR;
switch (getVersion()) {
case "1.16", "1.16.1", "1.16.2" -> versionR = "v1_16_1R.";
case "1.16.3", "1.16.4" -> versionR = "v1_16_3R.";
case "1.16.5" -> versionR = "v1_16_5R.";
case "1.17" -> versionR = "v1_17R.";
case "1.17.1" -> versionR = "v1_17_1R.";
case "1.18", "1.18.1" -> versionR = "v1_18_1R.";
case "1.18.2" -> versionR = "v1_18_2R.";
default -> throw new IllegalStateException("Unexpected value: " + getVersion());
}
String substring = MathUtils.substringFromEnd(versionR, 2);
try {
ServerVersion.setSeverVersion(MathUtils.substringFromEnd(versionR, 1));
versionR = "me.opkarol.oppets." + versionR;
IUtils utils = (IUtils) Class.forName(versionR + "Utils").newInstance();
instance.setUtils(utils);
PacketManager.setUtils(utils);
instance.setEntityManager((IEntityManager) Class.forName(versionR + "entities.EntityManager").newInstance());
this.setPacketEvent((IPacketPlayInSteerVehicleEvent) Class.forName(versionR + "PacketPlayInSteerVehicleEvent_" + substring).newInstance());
manager.registerEvents((Listener) Class.forName(versionR + "PlayerSteerVehicleEvent_" + substring).newInstance(), instance);
PacketManager.setEvent(getPacketEvent());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return true;
}
public IPacketPlayInSteerVehicleEvent getPacketEvent() {
return this.packetEvent;
}
public void setPacketEvent(IPacketPlayInSteerVehicleEvent packetEvent) {
this.packetEvent = packetEvent;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public @Nullable Object setupEconomy() {
if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) {
return null;
}
RegisteredServiceProvider<Economy> rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
if (rsp == null) {
return null;
}
return rsp.getProvider();
}
}
| 45.851064 | 340 | 0.668097 |
29c8b7217cc399e7479d2fabfaa04e98fedaa6d2 | 357 | package com.example.ashi.irrigatedmanager.util;
/**
* Created by ashi on 8/29/2018.
*/
public class CreateDate {
public long nanos;
public long time;
public long minutes;
public long seconds;
public long hours;
public long month;
public long year;
public long timezoneOffset;
public long day;
public long date;
}
| 18.789474 | 47 | 0.677871 |
53c13532c6aec022c4524d6686d5f2036a0145e5 | 2,025 | package org.jumpmind.db.alter;
/*
* 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.
*/
import org.jumpmind.db.model.Database;
import org.jumpmind.db.model.IIndex;
import org.jumpmind.db.model.Table;
import org.jumpmind.db.platform.DdlException;
/**
* Represents the addition of an index to a table.
*/
public class AddIndexChange extends TableChangeImplBase
{
/** The new index. */
private IIndex _newIndex;
/**
* Creates a new change object.
*
* @param table The table to add the index to
* @param newIndex The new index
*/
public AddIndexChange(Table table, IIndex newIndex)
{
super(table);
_newIndex = newIndex;
}
/**
* Returns the new index.
*
* @return The new index
*/
public IIndex getNewIndex()
{
return _newIndex;
}
/**
* {@inheritDoc}
*/
public void apply(Database database, boolean caseSensitive)
{
IIndex newIndex = null;
try
{
newIndex = (IIndex)_newIndex.clone();
}
catch (CloneNotSupportedException ex)
{
throw new DdlException(ex);
}
database.findTable(getChangedTable().getName(), caseSensitive).addIndex(newIndex);
}
}
| 27 | 90 | 0.662222 |
b15b3762d8f562a56a993d2104bc0603f75d1c58 | 2,165 | package com.insightfullogic.slab.implementation;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.objectweb.asm.ClassWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.insightfullogic.slab.SlabOptions;
class GeneratedClassLoader extends ClassLoader {
private static final String DUMP_DIR = System.getProperty("user.home") + File.separator + "dump" + File.separator;
private static final Logger LOGGER = LoggerFactory.getLogger(GeneratedClassLoader.class);
private final boolean debugEnabled;
GeneratedClassLoader(SlabOptions options) {
debugEnabled = options.isDebugEnabled();
}
synchronized Class<?> defineClass(final String binaryName, final ClassWriter cw) {
final byte[] bytecode = cw.toByteArray();
logDebugInfo(binaryName, bytecode);
return defineClass(binaryName, bytecode, 0, bytecode.length);
}
private void logDebugInfo(final String binaryName, final byte[] bytecode) {
if (!debugEnabled)
return;
final File file = new File(DUMP_DIR + makeFilename(binaryName));
if (!dumpDirExists(file.getParentFile()))
throw new IllegalStateException("Unable to create directory: " + file.getParent());
writeBytecodeToFile(bytecode, file);
}
private void writeBytecodeToFile(final byte[] bytecode, final File file) {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(bytecode);
out.flush();
} catch (IOException e) {
LOGGER.error("Error logging debug information", e);
} finally {
closeStream(out);
}
}
private boolean dumpDirExists(final File dumpDir) {
return (dumpDir.exists() && dumpDir.isDirectory()) || dumpDir.mkdirs();
}
private String makeFilename(final String binaryName) {
return binaryName.replace('.', File.separatorChar) + ".class";
}
private void closeStream(OutputStream out) {
if (out == null)
return;
try {
out.close();
} catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
| 28.486842 | 118 | 0.689607 |
51436097c23f58e91ada56a0f7aeb68dce30d47c | 388 | package de.as.garde_sheet_generator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import de.as.garde_sheet_generator.dao.SchulferienDeutschlandProvider;
@Configuration
public class AppConfig {
@Bean
public SchulferienDeutschlandProvider holidayProvider() {
return new SchulferienDeutschlandProvider("");
}
}
| 22.823529 | 70 | 0.829897 |
049b4e924cceeed397be393671b276a5710e159b | 2,375 | /**
* Project Name:CommonApp
* File Name:DemoService2
* Package Name:cn.cloudwalk.commonapp.services
* Date:2017/2/14 001411:38
* Copyright @ 2010-2017 Cloudwalk Information Technology Co.Ltd All Rights Reserved.
*/
package cn.cloudwalk.commonapp.services;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import java.lang.ref.WeakReference;
/**
* ClassName:DemoService2 <br/>
* Description: TODO Description. <br/>
* Date: 2017ๅนด02ๆ14ๆฅ 11:38 <br/>
* @author 284891377
* @version
* @since JDK 1.7
*/
class DemoService {
// //TODO ็คบไพๅ้ๆณจ้ livetemplate filtem
// /**
// * :{TODO}(็จไธๅฅ่ฏๆ่ฟฐ่ฟไธชๅ้่กจ็คบไปไน).
// * create by:284891377
// * @since JDK 1.7
// */
// public String filed="XXXXX";
// //TODO ็คบไพๆนๆณๆณจ้ livetemplate mettem
// /**
// * method:(ไธๅฅ่ฏๆ่ฟฐๆนๆณไฝ็จ). <br/>
// * ้็จๆกไปถ:(ๅฏ้).<br/>
// * ๆง่กๆต็จ:(ๅฏ้).<br/>
// * ไฝฟ็จๆนๆณ:(ๅฏ้).<br/>
// * ไฝฟ็จๆนๆณ:(ๅฏ้).<br/>
// * @param param xxx
// * @return retu xxxx
// *
// * @author:284891377 Date: 2017/1/16 0016 16:16
// *
// * @since JDK 1.7
// */
// public void method(String param){
//
// }
//TODO ------------handler้ฒๆญขๅ
ๅญๆณๆผ
DemoService mReference;
public static class MyHandler extends Handler {
//ๅฃฐๆไธไธชๅผฑๅผ็จๅฏน่ฑก
WeakReference<DemoService> mReference;
MyHandler(DemoService activity) {
//ๅจๆ้ ๅจไธญไผ ๅ
ฅActivity,ๅๅปบๅผฑๅผ็จๅฏน่ฑก
mReference = new WeakReference<DemoService>(activity);
}
public void handleMessage(Message msg) {
//ๅจไฝฟ็จactivityไนๅๅ
ๅค็ฉบๅค็
if (mReference != null && mReference.get() != null) {
//mReference.get().text.setText("hello word");
}
}
}
//TODO ------------handler้ฒๆญขๅ
ๅญๆณๆผ
//TODO ------------้ๆ็ๅ
้จ็ฑป้ฒๆญขๅ
ๅญๆณๆผ
TestResource mTestResource;
private void initData() {
if (mTestResource == null) {
mTestResource = new TestResource();
}
}
public void onClick(View v) {
initData();
}
//้้ๆๅ
้จ็ฑป้ป่ฎคไผๆๆๅค้จ็ฑป็ๅผ็จ
//ไฟฎๆนๆๅฐฑๅคชไนๅๆญฃๅธธ่ขซๅๆถ,ๆฏๅ ไธบ้ๆ็ๅ
้จ็ฑปไธไผๅฏนActivityๆๅผ็จ
private static class TestResource {
}
//TODO ------------้ๆ็ๅ
้จ็ฑป้ฒๆญขๅ
ๅญๆณๆผ
//TODO ------ๅ
้จ็บฟ็จ้ฒๆญขๅ
ๅญๆณๆผ
private static class MyThread implements Runnable {
public void run() {
SystemClock.sleep(20000);
}
}
}
| 23.989899 | 85 | 0.585263 |
60b95b08c0783e0f606427a01ae75d8844c88976 | 4,573 | package net.minecraftforge.event.world;
import java.util.ArrayList;
import cpw.mods.fml.common.eventhandler.Cancelable;
import cpw.mods.fml.common.eventhandler.Event;
import net.minecraft.block.Block;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeHooks;
public class BlockEvent extends Event {
public final int x;
public final int y;
public final int z;
public final World world;
public final Block block;
public final int blockMetadata;
public BlockEvent(int x, int y, int z, World world, Block block, int blockMetadata)
{
this.x = x;
this.y = y;
this.z = z;
this.world = world;
this.block = block;
this.blockMetadata = blockMetadata;
}
/**
* Fired when a block is about to drop it's harvested items. The {@link #drops} array can be amended, as can the {@link #dropChance}.
* <strong>Note well:</strong> the {@link #harvester} player field is null in a variety of scenarios. Code expecting null.
*
* The {@link #dropChance} is used to determine which items in this array will actually drop, compared to a random number. If you wish, you
* can pre-filter yourself, and set {@link #dropChance} to 1.0f to always drop the contents of the {@link #drops} array.
*
* {@link #isSilkTouching} is set if this is considered a silk touch harvesting operation, vs a normal harvesting operation. Act accordingly.
*
* @author cpw
*/
public static class HarvestDropsEvent extends BlockEvent {
public final int fortuneLevel;
public final ArrayList<ItemStack> drops;
public final boolean isSilkTouching;
public float dropChance; // Change to e.g. 1.0f, if you manipulate the list and want to guarantee it always drops
public final EntityPlayer harvester; // May be null for non-player harvesting such as explosions or machines
public HarvestDropsEvent(int x, int y, int z, World world, Block block, int blockMetadata, int fortuneLevel, float dropChance, ArrayList<ItemStack> drops, EntityPlayer harvester, boolean isSilkTouching)
{
super(x, y, z, world, block, blockMetadata);
this.fortuneLevel = fortuneLevel;
this.dropChance = dropChance;
this.drops = drops;
this.isSilkTouching = isSilkTouching;
this.harvester = harvester;
}
}
/**
* Event that is fired when an Block is about to be broken by a player
* Canceling this event will prevent the Block from being broken.
*/
@Cancelable
public static class BreakEvent extends BlockEvent
{
/** Reference to the Player who broke the block. If no player is available, use a EntityFakePlayer */
private final EntityPlayer player;
private int exp;
public BreakEvent(int x, int y, int z, World world, Block block, int blockMetadata, EntityPlayer player)
{
super(x, y, z, world, block, blockMetadata);
this.player = player;
if (block == null || !ForgeHooks.canHarvestBlock(block, player, blockMetadata) || // Handle empty block or player unable to break block scenario
block.canSilkHarvest(world, player, x, y, z, blockMetadata) && EnchantmentHelper.getSilkTouchModifier(player)) // If the block is being silk harvested, the exp dropped is 0
{
this.exp = 0;
}
else
{
int meta = block.func_149643_k(world, x, y, z);
int bonusLevel = EnchantmentHelper.getFortuneModifier(player);
this.exp = block.getExpDrop(world, meta, bonusLevel);
}
}
public EntityPlayer getPlayer()
{
return player;
}
/**
* Get the experience dropped by the block after the event has processed
*
* @return The experience to drop or 0 if the event was canceled
*/
public int getExpToDrop()
{
return this.isCanceled() ? 0 : exp;
}
/**
* Set the amount of experience dropped by the block after the event has processed
*
* @param exp 1 or higher to drop experience, else nothing will drop
*/
public void setExpToDrop(int exp)
{
this.exp = exp;
}
}
}
| 39.765217 | 210 | 0.638093 |
207c421cf93fd732d8aa1645ebe6a22c50aafd15 | 692 | package com.tibco.tgdb.test;
import com.tibco.tgdb.connection.TGConnection;
import com.tibco.tgdb.connection.TGConnectionFactory;
import com.tibco.tgdb.model.TGGraphObjectFactory;
public class MaxConnection {
public static void main(String[] args) throws Exception {
String url = "tcp://localhost:8222";
TGConnection conn = null;
try {
conn = TGConnectionFactory.getInstance().createConnection(url, "scott", "scott", null);
conn.connect();
TGGraphObjectFactory gof = conn.getGraphObjectFactory();
if (gof == null)
System.out.println("GOF is null");
}
finally {
System.out.println("THE END");
//conn.disconnect();
}
}
}
| 24.714286 | 91 | 0.683526 |
20f80d49d0273a108ac4da6f92a24f23a25e7145 | 6,685 | package com.analisis.numericsapp.app.OneVarEquation;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.analisis.numericsapp.app.AnswerTable;
import com.analisis.numericsapp.app.Funcion;
import com.analisis.numericsapp.app.R;
import com.analisis.numericsapp.app.WrapperMatrix;
public class FalseRule extends ActionBarActivity {
double xInf;
double xSup;
int iterations;
double tolerance;
private static int contadorFilas=0;
public static Funcion f= null;
public static String respuesta;
public static TextView response;
public static double [][] matrix;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_false_rule);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.false_rule, menu);
setupButtonTableButton();
return true;
}
private void setupButtonTableButton()
{
Button bt1 =(Button) findViewById(R.id.TableButton);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent();
Bundle b = new Bundle();
b.putSerializable("clase", "FalseRule");
myIntent.setClass(getApplicationContext(), AnswerTable.class);
myIntent.putExtras(b);
startActivity(myIntent);
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void CalculateFalseRule(View v)
{
response = (TextView)findViewById(R.id.textView7);
GetValues();
//reglaFalsa(xInf, xSup, iterations, tolerance);
matrix = reglaFalsa(xInf, xSup, iterations, tolerance);
WrapperMatrix.matrix = matrix;
}
public void GetValues()
{
EditText xvalueText = (EditText)findViewById(R.id.editText2);
xInf = Double.parseDouble(xvalueText.getText().toString());
EditText iterationsText = (EditText)findViewById(R.id.editText5);
iterations = Integer.parseInt(iterationsText.getText().toString());
EditText XsValueText = (EditText)findViewById(R.id.editText3);
xSup = Double.parseDouble(XsValueText.getText().toString());
EditText ToleranceText = (EditText)findViewById(R.id.editText4);
tolerance = Double.parseDouble(ToleranceText.getText().toString());
f = WrapperMatrix.GlobalFunction;
}
public static double [][]reglaFalsa(double xInf, double xSup, int iteraciones, double tolerancia) {
double i[][] = new double[iteraciones][6];
double yInf = f.evaluarFuncion(xInf);
double ySup = f.evaluarFuncion(xSup);
if (yInf == 0) {
System.out.println(xInf + "es raiz");
respuesta=xInf + "es raiz";
response.setText(respuesta);
} else if (ySup == 0) {
System.out.println(xSup + "es raiz");
respuesta=xSup + "es raiz";
response.setText(respuesta);
} else if ((yInf * ySup) > 0) {
System.out.println("El intervalo no tiene raices");
respuesta="El intervalo no tiene raices";
response.setText(respuesta);
} else {
int contador=0;
double xMedio = xInf - ((yInf * (xSup - xInf)) / (ySup - yInf));
double yMedio = f.evaluarFuncion(xMedio);
double E = (tolerancia + 1);
i[contador][0] = (double)contador;
i[contador][1] = xInf;
i[contador][2] = xSup;
i[contador][3] = xMedio;
i[contador][4] = yMedio;
i[contador][5] = E;
contadorFilas++;
contador = 1;
while (yMedio != 0 && E > tolerancia && contador < iteraciones) {
double xAuxiliar = xMedio;
if (yInf * yMedio > 0) {
xInf = xMedio;
yInf = yMedio;
} else {
xSup = xMedio;
ySup = yMedio;
}
xMedio = xInf - ((yInf * (xInf - xSup)) / (yInf - ySup));
yMedio = f.evaluarFuncion(xMedio);
E = Math.abs(xMedio - xAuxiliar);
contador = contador + 1;
i[contador][0] = contador;
i[contador][1] = xInf;
i[contador][2] = xSup;
i[contador][3] = xMedio;
i[contador][4] = yMedio;
i[contador][5] = E;
contadorFilas++;
}
for (int j = 0; j < iteraciones; j++) {
for (int k = 0; k < 6; k++) {
System.out.print(i[j][k] + " ");
}
System.out.println("");
}
if (yMedio == 0)
{
System.out.println("xMedio=" + xMedio + "es una raiz");
respuesta="xMedio=" + xMedio + "es una raiz";
response.setText(respuesta);
}
else if (E <= tolerancia) {
System.out.println("xMedio=" + xMedio + "es una raiz con tolerancia" + tolerancia);
respuesta="xMedio=" + xMedio + "es una raiz con tolerancia" + tolerancia;
response.setText(respuesta);
} else {
System.out.println("No dio :S ");
respuesta="No dio :S ";
response.setText(respuesta);
}
}
return i ;
}
public static int getContador(){
return contadorFilas;
}
public static String SetRespuesta(){
return respuesta;
}
public static void SetContador(){
contadorFilas=0;
}
public static void SetFuncion(Funcion funcion){
f=funcion;
}
}
| 28.088235 | 103 | 0.558863 |
b2a935d4b1a0885ea2c514d70c8667eeff4dcb81 | 202 | package de.jdynameta.base.value;
public interface WrappedValueObject<TWrappedObject extends TypedValueObject> extends ChangeableTypedValueObject
{
public TWrappedObject getWrappedValueObject();
}
| 25.25 | 111 | 0.846535 |
3be834948e222fd1d609b6e4071f54cd0a4cd261 | 896 | package com.jpeony.algorithm.sorts;
import java.util.Arrays;
/**
* ใๅๆณกๆๅบใ
* ๆฏๆฌกๅพช็ฏไธไธชๅ
็ด ๏ผๆพๅฐๅ้็ไฝ็ฝฎ่ฟ่กๆพ็ฝฎ๏ผ้ๅค n ๆฌก๏ผๅฎๆๆๅบใ
*
* @author yihonglei
*/
public class BubbleSort {
/**
* ๆถ้ดๅคๆๅบฆ๏ผO(n^2)
* ็ฉบ้ดๅคๆๅบฆ๏ผO(1)
*/
private static void bubbleSort(int[] arr, int n) {
if (n <= 1) {
return;
}
// ๅพช็ฏ่ฝฎๆฌก
for (int i = 0; i < n; i++) {
// ๆฏไธ่ฝฎๆฏ่พๅบไธไธชๆๅคงๅผๅบๅฎ๏ผๅทฒ็ปๅๅฐไธๅฑ็ๅ
็ด ๏ผๆ ้ๅๆฏ่พ๏ผไผๅๆฏ่พๆง่ฝ
for (int j = 0; j < n - 1 - i; j++) {
// ๆฏ่พ&ไบคๆข
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 4, 1, 3};
bubbleSort(arr, arr.length);
System.out.println(Arrays.toString(arr));
}
}
| 22.4 | 54 | 0.421875 |
38b4788668d0dca0d2b112278012f7e7e64dc148 | 694 | package de.jottyfan.camporganizer.rss;
import java.util.Date;
/**
*
* @author jotty
*
*/
public class RssBean {
public final Integer pk;
public String recipient;
public String message;
public Date pubdate;
public RssBean(Integer pk) {
this.pk = pk;
}
public Integer getPk() {
return pk;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getPubdate() {
return pubdate;
}
public void setPubdate(Date pubdate) {
this.pubdate = pubdate;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
}
| 14.458333 | 45 | 0.690202 |
0d3e5d7bfc56fd80c47b342980960f60025e4ed3 | 1,675 | /* 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.camunda.bpm.engine.impl.pvm;
import java.util.List;
/**
* @author Tom Baeyens
* @author Daniel Meyer
*/
public interface PvmActivity extends PvmScope {
boolean isAsync();
/**
* Indicates whether this activity is interrupting. If true, the activity
* will interrupt and cancel all other activities inside the same scope
* before it is executed.
*
* @return true if this activity is interrupting. False otherwise.
*/
boolean isCancelScope();
/**
* Indicates whether this activity is concurrent. If true, the activity
* will be executed concurrently to other activities which are part of
* the same scope.
*
* @return true if this activity is concurrent. False otherwise.
*/
boolean isConcurrent();
/** returns the scope of this activity. Must contain this activity but may or
* may not be the direct parent. */
PvmScope getScope();
boolean isScope();
PvmScope getParent();
List<PvmTransition> getIncomingTransitions();
List<PvmTransition> getOutgoingTransitions();
PvmTransition findOutgoingTransition(String transitionId);
}
| 28.389831 | 79 | 0.727164 |
383498c3280aafdd25fcc3ec05f1f4fa9bd35d13 | 9,048 | /**
* Copyright (c) Lambda Innovation Team, 2013
* ็ๆ่ฎธๅฏ๏ผLambdaCraft ๅถไฝๅฐ็ป๏ผ 2013.
* http://lambdacraft.cn/
*
* The mod is open-source. It is distributed under the terms of the
* Lambda Innovation Open Source License. It grants rights to read, modify, compile
* or run the code. It does *NOT* grant the right to redistribute this software
* or its modifications in any form, binary or source, except if expressively
* granted by the copyright holder.
*
* ๆฌModๆฏๅฎๅ
จๅผๆบ็๏ผไฝ ๅ
่ฎธๅ่ใไฝฟ็จใๅผ็จๅ
ถไธญ็ไปปไฝไปฃ็ ๆฎต๏ผไฝไธๅ
่ฎธๅฐๅ
ถ็จไบๅไธ็จ้๏ผๅจๅผ็จ็ๆถๅ๏ผๅฟ
้กปๆณจๆๅไฝ่
ใ
*/
package cn.weaponmod.api;
import java.util.List;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.DamageSource;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.util.MovingObjectPosition.MovingObjectType;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import cn.liutils.api.util.GenericUtils;
import cn.liutils.api.util.Motion3D;
import cn.weaponmod.api.weapon.WeaponGenericBase;
/**
* @author WeAthFolD
*
*/
public class WeaponHelper {
/**
* Tries to consume a specific amount of ammo in player's inventory.
*
* @return how many are left to be consumed
*/
public static int consumeAmmo(EntityPlayer player, WeaponGenericBase item, int amount) {
return tryConsume(player, item.ammoItem, amount);
}
/**
* Tries to consume one specific item in player's inventory.
*
* @return how many are left to be consumed
*/
public static int tryConsume(EntityPlayer player, Item item, int amount) {
int left = amount;
ItemStack is;
if (item.getItemStackLimit() > 1) {
for (int i = 0; i < player.inventory.mainInventory.length; i++) {
is = player.inventory.mainInventory[i];
if (is != null && is.getItem() == item) {
if (is.stackSize > left) {
player.inventory.decrStackSize(i, left);
return 0;
} else {
left -= is.stackSize;
player.inventory.decrStackSize(i, is.stackSize);
}
}
}
return left;
} else {
for (int i = 0; i < player.inventory.mainInventory.length; i++) {
is = player.inventory.mainInventory[i];
int stackCap;
if (is != null && is.getItem() == item) {
stackCap = is.getMaxDamage() - is.getItemDamage() - 1;
if (stackCap > left) {
is.damageItem(left, player);
return 0;
} else {
left -= stackCap;
is.setItemDamage(is.getMaxDamage() - 1);
}
}
}
return left;
}
}
/**
* determine if player have any ammo for reloading/energy weapon shooting.
*/
public static boolean hasAmmo(WeaponGenericBase is, EntityPlayer player) {
for (ItemStack i : player.inventory.mainInventory) {
if (i == null)
continue;
if (i.getItem() == is.ammoItem) {
if (i.isStackable())
return true;
else if (i.getItemDamage() < i.getMaxDamage() - 1)
return true;
}
}
return false;
}
public static int getAmmoCapacity(Item item, InventoryPlayer inv) {
int cnt = 0;
for(ItemStack s : inv.mainInventory) {
if(s != null && s.getItem() == item) {
cnt += s.getMaxStackSize() == 1 ? s.getMaxDamage() - s.getItemDamage() - 1 : s.stackSize;
}
}
return cnt;
}
public static boolean hasAmmo(Item itemID, EntityPlayer player) {
return player.inventory.hasItem(itemID);
}
public static int consumeInventoryItem(ItemStack[] inv, Item item,
int count) {
int left = count;
ItemStack is;
if (item.getItemStackLimit() > 1) {
for (int i = 0; i < inv.length; i++) {
is = inv[i];
if (is != null && is.getItem() == item) {
if (is.stackSize > left) {
inv[i].splitStack(left);
return 0;
} else {
left -= is.stackSize;
inv[i] = null;
}
}
}
return left;
} else
return left;
}
public static int consumeInventoryItem(ItemStack[] inv, Item item,
int count, int startFrom) {
int left = count;
ItemStack is;
if (item.getItemStackLimit() > 1) {
for (int i = startFrom; i < inv.length; i++) {
is = inv[i];
if (is != null && is.getItem() == item) {
if (is.stackSize > left) {
inv[i].splitStack(left);
return 0;
} else {
left -= is.stackSize;
inv[i] = null;
}
}
}
return left;
} else
return left;
}
/**
* ๆไนไฝๅจ๏ผ
* @param ent
* @param ds
* @param damage
* @param dx
* @param dy
* @param dz
*/
public static void doEntityAttack(Entity ent, DamageSource ds, float damage, double dx, double dy, double dz) {
ent.attackEntityFrom(ds, damage);
}
public static void doEntityAttack(Entity ent, DamageSource ds, float damage) {
doEntityAttack(ent, ds, damage, 0, 0, 0);
}
public static void doPlayerAttack(EntityPlayer player, float damage) {
Motion3D mot = new Motion3D(player, true);
MovingObjectPosition mop = GenericUtils.rayTraceBlocksAndEntities(GenericUtils.selectorLiving,
player.worldObj, mot.getPosVec(player.worldObj), mot.move(1.4).getPosVec(player.worldObj), player);
if(mop != null && mop.typeOfHit == MovingObjectType.ENTITY) {
mop.entityHit.attackEntityFrom(DamageSource.causePlayerDamage(player), damage);
}
}
public static void Explode(World world, Entity entity, float strengh,
double radius, double posX, double posY, double posZ,
int additionalDamage) {
Explode(world, entity, strengh, radius, posX, posY, posZ, additionalDamage, 1.0, 1.0F);
}
public static AxisAlignedBB getBoundingBox(double minX, double minY,double minZ,double maxX,double maxY, double maxZ) {
double i;
if(minX > maxX) {
i = maxX;
maxX = minX;
minX = i;
}
if(minY > maxY) {
i = maxY;
maxY = minY;
minY = i;
}
if(minZ > maxZ) {
i = maxZ;
maxZ = minZ;
minZ = i;
}
return AxisAlignedBB.getBoundingBox(minX, minY, minZ, maxX, maxY, maxZ);
}
public static void Explode(World world, Entity entity, float strengh,
double radius, double posX, double posY, double posZ,
int additionalDamage, double velocityRadius, float soundRadius) {
if(world.isRemote) //Ignore client operations
return;
Explosion explosion = world.createExplosion(entity, posX, posY, posZ, strengh, true);
if (additionalDamage <= 0)
return;
doRangeDamage(world, DamageSource.setExplosionSource(explosion), Vec3.createVectorHelper(posX, posY, posZ), additionalDamage, radius, entity);
}
public static void doRangeDamage(World world, DamageSource src, Vec3 pos, float strengh, double radius, Entity... exclusion) {
AxisAlignedBB par2 = AxisAlignedBB.getBoundingBox(pos.xCoord - 4, pos.yCoord - 4,
pos.zCoord - 4, pos.xCoord + 4, pos.yCoord + 4, pos.zCoord + 4);
List entitylist = world
.getEntitiesWithinAABBExcludingEntity(null, par2);
if (entitylist.size() > 0) {
for (int i = 0; i < entitylist.size(); i++) {
Entity ent = (Entity) entitylist.get(i);
if (ent instanceof EntityLivingBase) {
double distance = pos.distanceTo(Vec3.createVectorHelper(ent.posX, ent.posY, ent.posZ));
int damage = (int) ((1 - distance / 6.928) * strengh);
// System.out.println("Attacking " + ent + " " + damage);
ent.attackEntityFrom(src , damage);
}
}
}
}
}
| 34.666667 | 150 | 0.547745 |
7c3446cd63f2231c43c5aa4e354315272cc6c9b2 | 16,827 | class WvyFL8Zjk {
public static void YaVzRxW8 (String[] wPniG) {
U8roqPS6Y().ll5osBUCL;
if ( na8Z()[ !( true[ !!!-!true[ new LmujQ3_().balcV3TOe1()]]).SZCRtpbYGduUT()]) return;else if ( !--null.ZSa5) true.wNwCXsUA7oJ3b9;
j9g6AeCs QS885mm = !null[ d0S4QoGgK53fGS[ z_e8bjAUco8d.vsJCTFITdKC]];
return -new boolean[ --false[ null.D3KaR9P5OiTYI()]][ ---true.A5fUP];
boolean[] ott_mU;
{
while ( this.DSMAJO8yrRiA()) if ( yUBIre6O()[ -this[ !-!!false[ K[ new IJ55YN6dCeZxnG().D6]]]]) return;
{
if ( !RpqrklU7aXWNWO[ false[ 391[ !!false.I9lmyoUXEuG()]]]) if ( ( new void[ y3okg3TEmoyvz().PFIHsjFjo0J5][ -new int[ null.Gu].buD6lkc0cxt]).J2CGj7) if ( null.V) while ( B8Juy7BLFb.H7Cz()) if ( L_BNhX3vAsS.eFtH3pN8THq) this[ ( !--true.g1GTxlajtuDT6()).Zs()];
}
;
int[][][][] ibg1Mnd58h;
{
return;
}
void[][][][] Cs1pQoYdY;
if ( !new boolean[ !-------true.jAgoK()].VvqlvT0Z) hfDzxjbg6yDlZK().elOk();
!true.SF9f3D;
void ya;
xaJQ_FYLq[] w1JDYW;
}
void j6oD50h84A;
J6kQYs0Z xR8QRogfT49g0 = new boolean[ -!!!!true.VtL7MckCVJN].bgpsJwYVkoeyf();
void[] rd0N8b5kaISY;
if ( 72200.yx0XPKVce) ;
boolean[][][][][] Jun8 = -new void[ this[ false.EZ()]][ --x0NNsm8kse.utj4BI()] = ---!this[ null.B_ZJWnNCnm];
;
}
}
class LPsVd {
}
class Ge_Mo7 {
}
class x {
public static void hDTFOWb (String[] idywLmNH7ZC) throws amQVdq2kO {
int[] RTtsHvD0rDe3Uv;
}
public int[] blqeb;
public boolean nZMPAf (int[] nfQ2, TJdhR[][][] J286, H k4) {
;
boolean[][] m = new yR9Ngt1K[ -!--false[ !!yk8VnVgpnkQ8n().Iia4fM8EsY]][ !( -!-( this.NGIfzcAdUPk1W())[ !!( --Iq8Ui().Efd2wPks()).DR0aYSABr__m]).HwN722DV4xQ()] = ag2hboaVG9T().lb3xA();
void[][][] RS;
tzpXGt8JI[][] s;
boolean HOz2UF0xEI4Tx = !new DyWYXSWc5().kBhoWQ() = !new alG1cu07xP()[ !new boolean[ -!new int[ !!!!( !-!-new boolean[ true.usYqazY][ --xY3IUKR85crFR().pAYjDc()]).ZeL3][ --6691284[ new Lo9VCkIK7s().tLc_TSJ59]]].oTMjzlg8V];
void[][][] UCPZi;
QN2j5rJ[][] C;
if ( -!-WuuJZHSNK().x()) while ( mC().PSit8MEpsS4WKQ()) return;
int[] QtNas5;
}
public void[] _qSenzQA;
public int swYE67Gr;
public a_NiScmekwsz[] X16 (int h, int[][][][][] u1uE2JF, int[][] EwrTZQL4, void F5liZZg0VlH) {
;
--false._CUCBG;
void[] s_k;
B[][] n3fGytz = new void[ 389479.OSULOwHO].sgkz3BKXGl;
void[][][][][] WeVOsn;
int[][] AqbEnI = !!new dynxW6jV[ -!!!1737.ajE9VKEOOU()][ !-LBnmXnQisNM._Wiv_YIGnkf4hJ] = !-NSunDXlV7EDM().bu_AtwqXrHAD;
l_w8_h6egtCnTD Rb6nPt4EH;
--this.T;
!false.qPmtTf2xx3qR;
boolean[][][][][][][] lPQ5;
boolean[] rn6SLI_IIBE6h;
void[][][][][][][][][][][] BZFA;
int K7YLsuWFQ = false[ _P6bzt()[ ( !mYQzEmWCCpey[ 2721.YMXrev]).CxwO]] = amVE3w2yrcCD5[ -4.gzQfc9];
boolean[][][][][][] JEnIDe4;
return new b5tOP()._iJfrH97OuTVa();
boolean[][][][] tZF4zDI = null.VJlzh5Ft_6JPsi() = this[ new boolean[ new tfA1j3vm9mjEu().zUroSPrs7()].h1qn09Bo()];
while ( --new boolean[ this[ -!-( -RbwZ.OX0XRW)[ !-QoqyV3eeEivIPi()[ new boolean[ 37268.C7Ebr5vXC8l].w1Nb_X3xKx1O7()]]]].gMBBaq) return;
if ( --( new jX().H8YjyPLBNDKm).PAQTQMQLXwoT) false.hltR3Xk();
void gcIuibdBdu1M2 = !-!!U0MHw9i1Uhf.YUUn2;
}
public static void eoc (String[] GtDSA0InR65) {
while ( !new FQcjU().dr2RL) if ( -new tcRgZn7y5znO().MI()) while ( !-this.dGE) !TXcQ14S.faTysfvwMTWA();
return;
int[] JVM = oFh().rALBuJ7E();
a9Nz[][] pZKt2bRnpYDciL = -!!--!-H().bZRMAu0E1msi7y() = !!false.o6T6MvC0Fg_l();
if ( 8.s44r2Qx()) {
while ( !!-true._5) ;
}
while ( -!!!false[ !-QR.RXX34B()]) return;
void[] BgwTdnt95nj2 = !Ilodoowt().Y();
if ( -new YeFglBbLPiB0q()[ null.sGmYhBGj]) return;
LXTRZKHlhW[] l11;
return;
}
public int[] m71 () {
int[][] d_b = -!!!null[ -true.gBXtTAGg()];
{
boolean gyb;
boolean[] P5a_H;
}
boolean[][][][] O;
802.a1L_tay;
CF9X[] h;
( !-this[ !true.EEMg0])[ !--!-this.oEtmMl2h3iCf];
;
xY nQ;
return;
this.A;
;
;
{
int MD71Z0;
if ( -( -!new MdNISKmN6j2()[ qu_F[ null.RnRFNotp()]]).ARR) return;
;
boolean Lc6;
return;
boolean dQLP;
boolean LGW0J;
{
;
}
{
void xoDq;
}
isfXmRKQZ65f14 uIzca;
uffZFzR DkqpmRaVnn;
int[] wY9ggrL8zWjA;
boolean NlJn;
return;
boolean xYc4g6Yo;
{
void iWnuWn3_E;
}
}
Jg[][] qHEDzDPlT = !R5Kp4WFRbR2L.yvit2 = !-true.Kifnlb7();
_InnQRqKe4leqb lzDPgIam = this.bz4n;
33975480[ null.LcyR5I3L];
;
if ( yjG.Wgq02CG9C67j) {
boolean[][][] DeMK;
}else ;
boolean EkHXlEMMv = !58195265.yV8PS5DwwbA1J;
}
public static void MXO (String[] BFENiVxqkJSW) throws CtR0ugXLzfcOeK {
int[] ZImiIMX1257 = 699.FfJVv;
boolean[][][] o3V;
while ( 4785[ 6203.TJ()]) {
PTARY XJ6MMFwMNy;
}
int R9lgroSe = !!!this.A1uz4F4uNbL9E5();
dp8M9Z5[][] hPUtwSNz;
int M2WAJ9hpaoFfc;
boolean PSSxrxXgNkwNe7;
void ItthQZrHVod = null.hqZ1Ep6 = !-false.BCT9fIZ2v6i;
int wlqrPMQ = 2684466.iQOtNBsd;
void qOSW7Iaa5s7u;
return -5.Lab8fdB;
return !!LCF2Psy039km.qCzTmib7d;
;
;
return true[ new uYja9_3NLQY5().I49V5HPbF3tOX];
if ( !-!( -_OE141_Ab[ ( ---!IVNUchdF.VHAcUgD1)[ !new boolean[ -WjQ6y()[ null.c2JizUV7QPT()]].X7ep1SV_8t5l]])[ -!-new int[ z7[ new XZSrN().BP()]].vdOIV()]) ;
}
}
class zg5Gdr37Ty {
public HT yh;
public y[][] b0Evzh (Zr t3d, UUsmPGXB2Dh0[][] UjcIaIsAkA_J0) throws jXSVJ {
!!null[ 7942959.IRFJQM63W28N()];
{
return;
if ( d5hg3YkmiKzCeZ.d) ;
{
while ( --94201567.bfh) while ( -( -YKmTmtaf.MesSztcZD67U).mLxNa_50Q6j81) while ( false[ --!232920864.Fo_34RN]) -!-!!this.OH4jN9FSp6NAW;
}
void ysTIv3uQDBBA5;
{
boolean[][][][][] jE_BroDSp;
}
int O;
{
void[][] p0bBl7K;
}
HDn3ZkUqtFB()[ --new void[ !f5SSnK6rl._v()].Qi_];
boolean[] TGS_Qh6vIRG;
void[][][][] qH;
if ( !!!7657464[ !70.XRs6jCCCB]) ;
boolean hMmh46F6a64JJ;
;
while ( -!-!q5o2yYqc7PqPI().XE5YYzRtXej) {
return;
}
void[] L9;
}
return !-Jdgn2P75f().c();
;
}
public static void mHUHCMBrHzH9 (String[] DF6I4vER_d_RQ) {
if ( !ZxzFar65()[ -!this[ -false.QUHi4YTkVQ3X]]) if ( null.jdBeYcIIAr87) -new rQcC5pbi[ -!!-302.fSdsWf].XECWjWA9exN();else 3913[ !Rnu7un.ekt];
}
public int lKhAma8;
public static void iTApA1 (String[] p809IgD6t9) throws xA18t1ZMI_HkG {
{
boolean[] yBprI8TiXPBaX;
}
boolean[][][] vd5Vu;
if ( new boolean[ !this.AqVfAWqb].ZVOP3iurx) if ( null[ GGOegsaiysRX()[ woptLHo5kFnqPS.k()]]) g2()[ ( !-null[ !new _().RloM]).G];else return;
U[] sXd0VE6bC;
void[][][][][][][] LUsd0;
BhSUufK[] L;
null.tjzcK_Q();
boolean z2cGL6;
boolean[] zhNff;
t6d5Zox j1W_XM3ilGn = wEF()[ null.w7vS1nPZO7] = false[ XTQiBZpYwse().PgNDC];
while ( bSf12XHaQfCcK8.SXQxF()) {
--u7VAnILCJn2y().T65();
}
void wATcdYEP6epKzL;
DYa DJTULZW6 = !BYW().FZJyRBMT() = ----!!false.yqEAhoO5elTv;
void[] h = !true.i56U0i4GxTWO() = KXknF5HerV.ZwGSMYPcbN;
pa2GWnh0[] JLfcvYaHOfZ7 = -DmszWxG().Is2SXf6pQ4pjz7() = !-!916668[ ( !qlzxpJB2Q().gt()).Iw6];
{
return;
int XsTbZkgZHr;
if ( false.I6AMF85wTl2()) this.zmjql8LY;
boolean[] Mws_pYAUydw08q;
boolean qV63;
}
if ( !( !true.P0qycke()).B3uPfQEZvO) new XwduL0PPm9().qPVFXFNl5Cd;
}
public static void NKILL (String[] x1OEUr9T) {
;
while ( -e_().CtIPEDhoT5t_3) if ( _gxitKw.Nfs()) false.cEFc7();
void[] K_Jo9XURUQAjc = -this.r_aWAx();
{
;
xCl7yowPmi[][][][][] tpBo5O;
boolean aYIM;
void[] G_uoZOkW5Hr3;
void[][][][][] nDWwJCOs3;
boolean DXE;
zXta4WiA3[] RHpA;
int[] gn1zjju;
return;
int[][] qP;
return;
sw2huDh6l XHdy6OIFz;
void[][] s_DfPd;
-LsF()[ true.gZjH7sf4e3gTWl];
}
;
void[] zc9p6 = false.jUpWUOLjY();
int[][][] Jca6ScogPR = ( null[ --false.BXl19uL()]).UN = VERKio5RI().NV;
while ( 97278003.Is3_dwZgI08()) -true.R;
boolean _SE8UAb6o4yQ;
boolean[] LuJd3hK87uj6nS = false.KgykybIGKW() = null[ -621919214[ -!52455316.QLS]];
}
public void j0Lov9CmLq (PyIZE9eZPH2Gpu q7WVC7IDOwj29p, qb908nDwppSA[][] WPioaWQ3TcDem, void AeuDVb, int[][] SVw4, int H) throws a {
r g = --false.rLp() = YzDwoaUw6tw().ae8tfo5pJiAa();
new P48yS()[ false.K8ggtzzT8FiEO];
if ( false.fb3zrA6kjZ) if ( --!-oCFo1cKJoH()[ false.ptqEqlPBviSF()]) ;
boolean[][] qUUXSUH2WL_n2G = 11175[ 2393[ null[ !this.ctnk7BK8f()]]];
int[][][] W;
;
void LtGqfryWpd9jDb;
void BJFuq6O4IbWgvb;
boolean CJkSddPav;
return -this.Gjynoi;
}
public boolean k9F;
}
class sjznFMItF {
public static void yMuGDjWktN (String[] cwbF5hH) {
return;
int[] a9Ua;
int[] M3NXWqp = 203738757.mwXJyrzw3();
if ( false.WaA55umeNABrX) false[ --new void[ -true[ --!false.qOLPFm2ZJTsvsh()]].gLOmehEhdZ];else !!!PAizwEdNjNR[ null.QdISiiLzK];
m KLhM;
W5_c0HX1 o;
void[][][] bXTrFXemo01 = !true.EJUt = !!-43374.G;
if ( 51997028.zNAvD9kKpqO) !null.Rg();
return;
V5ScxwPpP0 V_sGRjrS = null[ !null[ -!new f3VHHRghXlxog().u065r30g7pKP0t()]];
{
void CtJl_qgqkbNJ1;
{
;
}
;
while ( false[ this.MJImjvD()]) {
;
}
return;
void[] GV;
return;
if ( ( -xu[ GD.Nin14EIT74q()]).SSnI) return;
int[] ER2wq;
-null.DZSVe0ZGhs();
this[ null.muKEcnGl()];
zg35X3tFq rqAQTSZc;
void CpfJkL;
( !!!-!null[ --!false[ false.uWDii]])[ !-!( !---!( -this.pyz())[ -70603864.yffRLvft59gU]).N16kP];
boolean RZlv;
void C;
z[] Cr2R83SlK5Li56;
o0R7exX[][] ypARxxpP6mhK6;
{
void NF4C0DQtsgprgJ;
}
}
}
public VnYqPwD HscrEZ1DZS0aOj (M0Bf[][][] pj5cB4iORVIS) throws GOS3gn6pU7 {
boolean cWbLEZtLv;
;
void ySimQ4nnAs = !-86[ h9Bl8DuMgiiI8()[ -!!w0HBL_MYRw9EL.dwFDDTdoCLe()]];
!oHWKqUSZL9N6p()[ false[ 9[ !-1053.QI()]]];
;
int[] LcIahe3;
fSEg1heGQZ6x y6uz3ar;
int lVANzMXjwgT;
void[][][][] X57t4z = !null[ this[ false.e()]] = ( new z0I1dpcXVN().Moobb0T8Vkre())[ --!!-null.BUUPk];
int P6r0bPyi;
return false.nG8cXr0;
boolean[][] B9L;
}
public static void t (String[] garj3N1YpK) {
return;
int[][] LB = -new wK42cS9yte_n().y;
( this.ILoB0l5f4u6()).igqML7Wdaqv75();
{
void OtSUGce_Tz9tK;
boolean uPEb;
eYQx[][][][][] DRb2E;
if ( AnYFtYI72g4O().r_1ydm1S6Gfh1) return;
{
!!-true.xH1pmj3Y();
}
while ( 81230625.Wi0az) if ( true[ -true.iqWx4x8mv()]) !!!!new boolean[ null[ -( null.rG).oia8G9Op]][ -tQdeSh()[ -IxoV.v()]];
{
return;
}
}
return;
while ( 522953.X8NgY) while ( new NysEv5Qvss().XqZ2) if ( M[ --!true.Zm()]) ;
boolean hCn5Kg;
}
public int[][] xrj36Yq5ZuFMva;
}
class JnMlYMBio {
}
class tEOwlUiCq {
public static void B2wXCbYTb46GWa (String[] iz7j) {
boolean[][][][] bP0h1H12SkeL = false[ !-new PUkK7lRHd30RM().PRObB];
;
int[][][] m = new boolean[ O9P0oHbWjx().N()][ k3fWeevrOv.cG5nse3()] = new boolean[ this.AIZPeTVLPk06o()].I4_E9VrpHBX;
int[] jMjBIQPb;
;
int[] FJLbsrZQmvz = -!!--!!37979863.Q5dLzBeHWDl() = -this[ !!-( -!-true.KF_9)[ !true.r]];
nFHVt9jFppUqR_ aE51VipFeR6 = -null.JJDNk();
}
public void IlVCh6hBH;
public _XsdiBHb[] MNIi8tLNq (void DXSGMOzyy, NatR[][] CV9qh4dj5r, boolean[] PRNWZXWLTia, void Zx) throws tKByDsO4 {
if ( new XJUs2AyFHUh5ht()[ !-!!this[ true.CXmlpNG()]]) while ( null.kuTRjc8jCEKXg) -!-Epsj2IE_IZD().S1NaF();else !--!!!new boolean[ ---rEAMo_WXhuYAIu.Ap07H0JreC].po;
void[][] drAboakWDaPva = 96[ this.iQHx()] = !false.iJc6utfTCIAq();
}
public int[] ULkYAI;
public static void vU0vA (String[] kNPN3vuWpfA) throws f {
int[] dBFC3PAUAK1Tn = !false.GlTVl() = new BpOX8vm().f8K0kJ();
int[][] ngMkyoApnh = uzI2d3YlEC1YhK()[ FncbrIr9[ true.ROnu]];
{
;
;
void jvfr;
h0sVUaqH1 c5taNX;
yHXOGXv A_3qTc;
;
void UuFANOi;
;
boolean[][] Cec4H;
if ( !true.v6RYnHVsN8L) while ( !!-BXKH0i5p9R()[ new On3TO().lHNBeGvxKbLVDW()]) while ( null.Xfz) return;
void[] W58xpz;
uoLV8VfbH RHSCejmJ2tx2_;
{
int eIr;
}
boolean[] OiD7ykuSB32aqp;
!null.dv5nWx();
}
{
;
int[] ld1f4qD;
while ( -34900[ null[ true.n9g62qXjdaEn]]) ;
Xv1bEu_ bU;
return;
}
new uPKcP7IyGC9().Yb;
while ( ---null[ 780244243.BrJr3eM845K]) while ( false.C()) while ( ( true[ new fFDI().om()])[ -!-true[ !938198.uXs9YwjfZ()]]) while ( !!-!0994.aQd) while ( !vr5P6Kvu.jK()) {
{
boolean Soa8oVZrb;
}
}
;
boolean sy33MIR = false[ false[ null.rcW3LGW_iVn()]] = mu0Q.ePNbCr2J();
void[] oaNLC;
!this.ur9();
boolean KkqgNUNuiEeA = --376.nfWES4HRcyovuS;
return --!YbwD().m();
int G3u = this[ new uF4TmsGz()[ !new boolean[ false.xwAz_s].TE]] = new npxg_3()[ false.mAgrEfp1rf()];
}
public XKXWE4qA[][] bjNDeUtjgvc;
public int[] GsDS0uBEBX () throws P1K {
void[] j = !!!null.iZHiHfoPqMo1() = -!!8336384[ --true.WlJQ9JnEGkGFM];
return;
int[][][][][] i0_TiBu = YX.w3t;
int[][][][] g92AJn = -!!-( !false.C)._seVUiIz96DhBK;
boolean[][][] Gv;
if ( q7iwc4OeS0Z().moDQ68) if ( -new s().Opc7yhk81urN()) {
R_PZiiQMVfEX7 JXHoWeDbbj;
}else ;
int[][][] q_;
return ( -true.PJ3S7R6).SRkuvCjA524();
{
boolean iAoqNMVgXH0XdH;
}
void[] XTFA82O;
return;
HEiDAVGl LqHmnc_8Ir = null[ -( !-new TeS().Z0G).g2pltt8Q62];
;
if ( !true.rQyqb7XGOE5DZ) !new bgpOo0Zt1r().U;
int iV0sEHfEA;
void[] A0jErv_QXr = !1.iKu8EOw2fC() = true.rX_ZrpzCptB;
if ( !!false.k6ISVf7R427()) while ( U74h9XaggNUS().ZjMAMbMr()) return;else ;
while ( -!-!-this.Pt8f()) return;
boolean[][] OVK6jHxd1;
if ( --!( ( null.D)[ !( --null[ new i9eYjq2pM().VDAed15vJi]).wOap]).zNkQ2B) while ( !null.WNhVVN3U()) {
if ( !!true[ BUJijUm7CFHr5()[ C8Djo8nO_auMXv.l]]) 628828030.K5YUjJ;
}else if ( ( -null.n5vz0grCT8t()).AzFa()) !!true[ !gUmH5adMF()[ -true.xz]];
}
public boolean[] GysSaI9 (CGskjz9mR[][] LIyu3LOwZj, void M4) throws n29EBhn {
;
return;
-null.KiF4BwSFsrx();
boolean OQlGp;
boolean bQmd;
boolean[][] Cns1Pnx;
while ( !!!!-!new oq().n_rrKv()) if ( this.baRKpxsl45Lg) this[ null.S4miBpPHR];
int[] DW2RWi2FSr;
int[] DBPhibRRaI3ykn;
void lEvxodaQcI;
}
}
class YV3YvX_Sa3pX {
}
| 36.660131 | 275 | 0.508825 |
12c5c24b7967977aec78a88e1848a7c0cf93fd18 | 1,295 | package org.innovateuk.ifs.finance.handler;
import org.innovateuk.ifs.competition.domain.Competition;
import org.innovateuk.ifs.competition.repository.CompetitionRepository;
import org.innovateuk.ifs.organisation.resource.OrganisationTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static org.innovateuk.ifs.commons.error.CommonErrors.notFoundError;
import static org.innovateuk.ifs.util.EntityLookupCallbacks.find;
@Component
public class OrganisationFinanceDelegate {
@Autowired
private CompetitionRepository competitionRepository;
@Autowired
private IndustrialCostFinanceHandler organisationFinanceDefaultHandler;
@Autowired
private JesFinanceHandler organisationJESFinance;
public OrganisationTypeFinanceHandler getOrganisationFinanceHandler(Long competitionId, Long organisationType) {
Competition competition = find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)).getSuccess();
if (competition.applicantShouldUseJesFinances(OrganisationTypeEnum.getFromId(organisationType))) {
return organisationJESFinance;
} else {
return organisationFinanceDefaultHandler;
}
}
}
| 39.242424 | 148 | 0.810811 |
9476595f5c9a4d08d38d90517705d6a0bd34e7fe | 3,754 | package ca.uhn.fhir.jpa.dao;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import ca.uhn.fhir.jpa.entity.ResourceTable;
import ca.uhn.fhir.jpa.util.StopWatch;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.rest.server.IBundleProvider;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
public abstract class BaseFhirSystemDao<T> extends BaseFhirDao implements IFhirSystemDao<T> {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseFhirSystemDao.class);
@Transactional(propagation=Propagation.REQUIRED)
@Override
public void deleteAllTagsOnServer() {
myEntityManager.createQuery("DELETE from ResourceTag t").executeUpdate();
}
@PersistenceContext()
protected EntityManager myEntityManager;
protected boolean hasValue(InstantDt theInstantDt) {
return theInstantDt != null && theInstantDt.isEmpty() == false;
}
protected ResourceTable tryToLoadEntity(IdDt nextId) {
ResourceTable entity;
try {
Long pid = translateForcedIdToPid(nextId);
entity = myEntityManager.find(ResourceTable.class, pid);
} catch (ResourceNotFoundException e) {
entity = null;
}
return entity;
}
protected ResourceTable loadFirstEntityFromCandidateMatches(Set<Long> candidateMatches) {
return myEntityManager.find(ResourceTable.class, candidateMatches.iterator().next());
}
@Override
public IBundleProvider history(Date theSince) {
StopWatch w = new StopWatch();
IBundleProvider retVal = super.history(null, null, theSince);
ourLog.info("Processed global history in {}ms", w.getMillisAndRestart());
return retVal;
}
@Override
public TagList getAllTags() {
StopWatch w = new StopWatch();
TagList retVal = super.getTags(null, null);
ourLog.info("Processed getAllTags in {}ms", w.getMillisAndRestart());
return retVal;
}
@Override
public Map<String, Long> getResourceCounts() {
CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = builder.createTupleQuery();
Root<?> from = cq.from(ResourceTable.class);
cq.multiselect(from.get("myResourceType").as(String.class), builder.count(from.get("myResourceType")).as(Long.class));
cq.groupBy(from.get("myResourceType"));
TypedQuery<Tuple> q = myEntityManager.createQuery(cq);
Map<String, Long> retVal = new HashMap<String, Long>();
for (Tuple next : q.getResultList()) {
String resourceName = next.get(0, String.class);
Long count = next.get(1, Long.class);
retVal.put(resourceName, count);
}
return retVal;
}
}
| 32.929825 | 120 | 0.763452 |
be01a7f697f3b0b588cbea3c237fa53043a55235 | 1,264 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package de.uros.citlab.errorrate.kws.measures;
import de.uros.citlab.errorrate.types.KWS.Match;
import de.uros.citlab.errorrate.types.KWS.MatchList;
import static de.uros.citlab.errorrate.types.KWS.Type.TRUE_POSITIVE;
/**
*
* @author tobias
*/
public abstract class AveragePrecision implements IRankingMeasure {
public static double calcAveragePrecision(MatchList matches) {
double cntTP = 0.0;
double ap = 0.0;
int gt = matches.getRefSize();
if (gt == 0) {
if (matches.matches.isEmpty()) {
return 1.0;
} else {
return 0.0;
}
}
matches.sort();
int cntTPandFP = 0;
for (Match match : matches.matches) {
switch (match.type) {
case TRUE_POSITIVE:
cntTP++;
cntTPandFP++;
ap += cntTP / cntTPandFP;
break;
case FALSE_POSITIVE:
cntTPandFP++;
}
}
return ap / gt;
}
}
| 26.893617 | 79 | 0.550633 |
5260cafa08e3b88d262a088e3abd2b83369bfa89 | 2,058 | package net.ausiasmarch.factory;
import com.google.gson.Gson;
import net.ausiasmarch.bean.BeanInterface;
import net.ausiasmarch.bean.CompraBean;
import net.ausiasmarch.bean.FacturaBean;
import net.ausiasmarch.bean.ProductoBean;
import net.ausiasmarch.bean.TipoProductoBean;
import net.ausiasmarch.bean.TipoUsuarioBean;
import net.ausiasmarch.bean.UsuarioBean;
public class BeanFactory {
public static BeanInterface getBean(String ob) {
BeanInterface oBean = null;
switch (ob) {
case "producto":
oBean = new ProductoBean();
break;
case "compra":
oBean = new CompraBean();
break;
case "factura":
oBean = new FacturaBean();
break;
case "tipo_producto":
oBean = new TipoProductoBean();
break;
case "tipo_usuario":
oBean = new TipoUsuarioBean();
break;
case "usuario":
oBean = new UsuarioBean();
break;
}
return oBean;
}
public static BeanInterface getBeanFromJson(String ob, String data) {
BeanInterface oBean = null;
Gson oGson = GsonFactory.getGson();
switch (ob) {
case "producto":
oBean = oGson.fromJson(data, ProductoBean.class);
break;
case "usuario":
oBean = oGson.fromJson(data, UsuarioBean.class);
break;
case "compra":
oBean = oGson.fromJson(data, ProductoBean.class);
break;
case "factura":
oBean = oGson.fromJson(data, CompraBean.class);
break;
case "tipo_producto":
oBean = oGson.fromJson(data, TipoProductoBean.class);
break;
case "tipo_usuario":
oBean = oGson.fromJson(data, TipoUsuarioBean.class);
break;
}
return oBean;
}
}
| 31.181818 | 73 | 0.539845 |
fcb217ab80c3848593d2aad943e2f1e0eb31d435 | 382 | package store.roll.CostStrategy;
public class SpringRollStrategy implements CostStrategy {
//override cost of extras for given specific roll
@Override
public double getFillingCost() {
return 3.33;
}
@Override
public double getSauceCost() {
return 4.44;
}
@Override
public double getToppingCost() {
return 5.55;
}
}
| 19.1 | 57 | 0.643979 |
f12e3e39535bf5e9ae8ef2002dbe6938e0bb3944 | 4,105 | package com.inHere.entity;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* ็จๆทๅฎไฝ
*/
public class User {
private String userId;
private String passwd;
private String saltKey;
private String userName;
private String headImg;
private String contactWay;
private Integer sex;
private String area;
private Integer schoolId;
private Integer roleId;
private Date createTime;
private Date updateTime;
private Integer is_admin;
private Integer available;
// schoolๅฏน่ฑก
private School school;
// ่ง่ฒ้ๅ
private List<Roles> roles;
public School getSchool() {
return school;
}
public void setSchool(School school) {
this.school = school;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId == null ? null : userId.trim();
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd == null ? null : passwd.trim();
}
public String getSaltKey() {
return saltKey;
}
public void setSaltKey(String saltKey) {
this.saltKey = saltKey == null ? null : saltKey.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getHeadImg() throws IOException {
return headImg == null ? null : new String(headImg.getBytes("ISO-8859-1"), "UTF-8");
}
public void setHeadImg(String headImg) {
this.headImg = headImg == null ? null : headImg.trim();
}
public String getContactWay() throws IOException {
return contactWay == null ? null : new String(contactWay.getBytes("ISO-8859-1"), "UTF-8");
}
public void setContactWay(String contactWay) {
this.contactWay = contactWay == null ? null : contactWay.trim();
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area == null ? null : area.trim();
}
public Integer getSchoolId() {
return schoolId;
}
public void setSchoolId(Integer schoolId) {
this.schoolId = schoolId;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public List<Roles> getRoles() {
return roles;
}
public void setRoles(List<Roles> roles) {
this.roles = roles;
}
public Integer getIs_admin() {
return is_admin;
}
public void setIs_admin(Integer is_admin) {
this.is_admin = is_admin;
}
public Integer getAvailable() {
return available;
}
public void setAvailable(Integer available) {
this.available = available;
}
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", passwd='" + passwd + '\'' +
", saltKey='" + saltKey + '\'' +
", userName='" + userName + '\'' +
", headImg='" + headImg + '\'' +
", contactWay='" + contactWay + '\'' +
", sex=" + sex +
", area='" + area + '\'' +
", schoolId=" + schoolId +
", roleId=" + roleId +
", createTime=" + createTime +
", updateTime=" + updateTime +
", school=" + school +
", roles=" + roles +
'}';
}
}
| 22.554945 | 98 | 0.558831 |
fd741f6771784eba8d1158961f5b14bc30f90089 | 961 | package br.com.ordemdeev.quizzes.usuario;
import java.util.List;
import br.com.ordemdeev.quizzes.util.DAOFactory;
public class UsuarioRN {
private UsuarioDAO usuarioDAO;
public UsuarioRN() {
this.usuarioDAO = DAOFactory.criarUsuarioDAO();
}
public Usuario carregar(Integer codigo) {
return this.usuarioDAO.carregar(new Usuario(), codigo);
}
public Usuario buscarPorLogin(String login) {
return this.usuarioDAO.buscarPorLogin(login);
}
public void salvar(Usuario usuario) {
Integer codigo = usuario.getCodigo();
if (codigo == null || codigo == 0) {
//sempre que for criado um usuario, ele vai ter o papel de usuario nas permssรตes
usuario.getPermissao().add("ROLE_USUARIO");
this.usuarioDAO.salvar(usuario);
} else {
this.usuarioDAO.salvar(usuario);
}
}
public void excluir(Usuario usuario) {
this.usuarioDAO.excluir(usuario);
}
public List<Usuario> listar() {
return this.usuarioDAO.listar(new Usuario());
}
}
| 23.439024 | 83 | 0.729448 |
05c6a5d1f9e2257307193250a166ab639b8e4b6c | 708 | package com.instaclustr.operations;
public abstract class OperationCoordinator<T extends OperationRequest> {
public static final int MAX_NUMBER_OF_CONCURRENT_OPERATIONS = Integer.parseInt(System.getProperty("instaclustr.coordinator.operations.executor.size", "100"));
public abstract void coordinate(final Operation<T> operation) throws OperationCoordinatorException;
public static class OperationCoordinatorException extends Exception {
public OperationCoordinatorException(final String message) {
super(message);
}
public OperationCoordinatorException(final String message, final Throwable cause) {
super(message, cause);
}
}
}
| 35.4 | 162 | 0.75 |
ccc04599a0068974f879c36f0dae269bf6e79541 | 2,824 | import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdDraw;
import edu.princeton.cs.algs4.StdOut;
import java.util.ArrayList;
import java.util.Arrays;
/**
*
*/
public class FastCollinearPoints {
private final ArrayList<LineSegment> _segments = new ArrayList<LineSegment>();
public FastCollinearPoints(Point[] points) {
if (points == null) {
throw new IllegalArgumentException();
}
for (Point point : points) {
if (point == null) {
throw new IllegalArgumentException();
}
}
Point[] sortedPoints = new Point[points.length];
System.arraycopy(points, 0, sortedPoints, 0, sortedPoints.length);
Arrays.sort(sortedPoints);
for (int i = 0; i < sortedPoints.length - 1; i++) {
if (sortedPoints[i].compareTo(sortedPoints[i + 1]) == 0) {
throw new IllegalArgumentException();
}
}
for (Point originPoint : sortedPoints) {
Point[] pointsBySlope = sortedPoints.clone();
Arrays.sort(pointsBySlope, originPoint.slopeOrder());
for (int j = 1; j < sortedPoints.length;) {
ArrayList<Point> candidates = new ArrayList<>();
double slopScore = originPoint.slopeTo(pointsBySlope[j]);
do {
candidates.add(pointsBySlope[j++]);
} while (j < sortedPoints.length && Double.compare(originPoint.slopeTo(pointsBySlope[j]), slopScore) == 0);
if (candidates.size() > 2 && originPoint.compareTo(candidates.get(0)) < 0) {
_segments.add(new LineSegment(originPoint, candidates.get(candidates.size() - 1)));
}
}
}
}
public int numberOfSegments() {
return _segments.size();
}
public LineSegment[] segments() {
return _segments.toArray(new LineSegment[0]);
}
public static void main(String[] args) {
// In in = new In(args[0]);
In in = new In("data/input6.txt");
int n = in.readInt();
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
points[i] = new Point(x, y);
}
// draw the points
StdDraw.enableDoubleBuffering();
StdDraw.setXscale(0, 32768);
StdDraw.setYscale(0, 32768);
for (Point p : points) {
p.draw();
}
StdDraw.show();
// print and draw the line segments
FastCollinearPoints collinear = new FastCollinearPoints(points);
for (LineSegment segment : collinear.segments()) {
StdOut.println(segment);
segment.draw();
}
StdDraw.show();
}
}
| 30.365591 | 123 | 0.553824 |
cdd153f8b0a1ea1a748ab72749268b51bfb1f273 | 37,376 | /*
* 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.ignite.internal.processors.cache.distributed.dht.preloader;
import org.apache.ignite.*;
import org.apache.ignite.cache.affinity.*;
import org.apache.ignite.cluster.*;
import org.apache.ignite.events.*;
import org.apache.ignite.internal.*;
import org.apache.ignite.internal.cluster.*;
import org.apache.ignite.internal.managers.discovery.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.distributed.dht.*;
import org.apache.ignite.internal.processors.cache.version.*;
import org.apache.ignite.internal.processors.timeout.*;
import org.apache.ignite.internal.util.*;
import org.apache.ignite.internal.util.future.*;
import org.apache.ignite.internal.util.tostring.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jdk8.backport.*;
import org.jetbrains.annotations.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.concurrent.locks.*;
import static org.apache.ignite.internal.managers.communication.GridIoPolicy.*;
/**
* Future for exchanging partition maps.
*/
public class GridDhtPartitionsExchangeFuture extends GridFutureAdapter<Long>
implements Comparable<GridDhtPartitionsExchangeFuture>, GridDhtTopologyFuture {
/** */
private static final long serialVersionUID = 0L;
/** Dummy flag. */
private final boolean dummy;
/** Force preload flag. */
private final boolean forcePreload;
/** Dummy reassign flag. */
private final boolean reassign;
/** Discovery event. */
private volatile DiscoveryEvent discoEvt;
/** */
@GridToStringInclude
private final Collection<UUID> rcvdIds = new GridConcurrentHashSet<>();
/** Remote nodes. */
private volatile Collection<ClusterNode> rmtNodes;
/** Remote nodes. */
@GridToStringInclude
private volatile Collection<UUID> rmtIds;
/** Oldest node. */
@GridToStringExclude
private final AtomicReference<ClusterNode> oldestNode = new AtomicReference<>();
/** ExchangeFuture id. */
private final GridDhtPartitionExchangeId exchId;
/** Init flag. */
@GridToStringInclude
private final AtomicBoolean init = new AtomicBoolean(false);
/** Ready for reply flag. */
@GridToStringInclude
private final AtomicBoolean ready = new AtomicBoolean(false);
/** Replied flag. */
@GridToStringInclude
private final AtomicBoolean replied = new AtomicBoolean(false);
/** Timeout object. */
@GridToStringExclude
private volatile GridTimeoutObject timeoutObj;
/** Cache context. */
private final GridCacheSharedContext<?, ?> cctx;
/** Busy lock to prevent activities from accessing exchanger while it's stopping. */
private ReadWriteLock busyLock;
/** */
private AtomicBoolean added = new AtomicBoolean(false);
/** Event latch. */
@GridToStringExclude
private CountDownLatch evtLatch = new CountDownLatch(1);
/** */
private GridFutureAdapter<Boolean> initFut;
/** Topology snapshot. */
private AtomicReference<GridDiscoveryTopologySnapshot> topSnapshot =
new AtomicReference<>();
/** Last committed cache version before next topology version use. */
private AtomicReference<GridCacheVersion> lastVer = new AtomicReference<>();
/**
* Messages received on non-coordinator are stored in case if this node
* becomes coordinator.
*/
private final Map<UUID, GridDhtPartitionsSingleMessage> singleMsgs = new ConcurrentHashMap8<>();
/** Messages received from new coordinator. */
private final Map<UUID, GridDhtPartitionsFullMessage> fullMsgs = new ConcurrentHashMap8<>();
/** */
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
@GridToStringInclude
private volatile IgniteInternalFuture<?> partReleaseFut;
/** */
private final Object mux = new Object();
/** Logger. */
private IgniteLogger log;
/**
* Dummy future created to trigger reassignments if partition
* topology changed while preloading.
*
* @param cctx Cache context.
* @param reassign Dummy reassign flag.
* @param discoEvt Discovery event.
* @param exchId Exchange id.
*/
public GridDhtPartitionsExchangeFuture(
GridCacheSharedContext cctx,
boolean reassign,
DiscoveryEvent discoEvt,
GridDhtPartitionExchangeId exchId
) {
dummy = true;
forcePreload = false;
this.exchId = exchId;
this.reassign = reassign;
this.discoEvt = discoEvt;
this.cctx = cctx;
onDone(exchId.topologyVersion());
}
/**
* Force preload future created to trigger reassignments if partition
* topology changed while preloading.
*
* @param cctx Cache context.
* @param discoEvt Discovery event.
* @param exchId Exchange id.
*/
public GridDhtPartitionsExchangeFuture(GridCacheSharedContext cctx, DiscoveryEvent discoEvt,
GridDhtPartitionExchangeId exchId) {
dummy = false;
forcePreload = true;
this.exchId = exchId;
this.discoEvt = discoEvt;
this.cctx = cctx;
reassign = true;
onDone(exchId.topologyVersion());
}
/**
* @param cctx Cache context.
* @param busyLock Busy lock.
* @param exchId Exchange ID.
*/
public GridDhtPartitionsExchangeFuture(GridCacheSharedContext cctx, ReadWriteLock busyLock,
GridDhtPartitionExchangeId exchId) {
assert busyLock != null;
assert exchId != null;
dummy = false;
forcePreload = false;
reassign = false;
this.cctx = cctx;
this.busyLock = busyLock;
this.exchId = exchId;
log = cctx.logger(getClass());
// Grab all nodes with order of equal or less than last joined node.
oldestNode.set(CU.oldest(cctx, exchId.topologyVersion()));
assert oldestNode.get() != null;
initFut = new GridFutureAdapter<>();
if (log.isDebugEnabled())
log.debug("Creating exchange future [localNode=" + cctx.localNodeId() +
", fut=" + this + ']');
}
/** {@inheritDoc} */
@Override public GridDiscoveryTopologySnapshot topologySnapshot() throws IgniteCheckedException {
get();
if (topSnapshot.get() == null)
topSnapshot.compareAndSet(null, new GridDiscoveryTopologySnapshot(discoEvt.topologyVersion(),
discoEvt.topologyNodes()));
return topSnapshot.get();
}
/**
* @return Dummy flag.
*/
public boolean dummy() {
return dummy;
}
/**
* @return Force preload flag.
*/
public boolean forcePreload() {
return forcePreload;
}
/**
* @return Dummy reassign flag.
*/
public boolean reassign() {
return reassign;
}
/**
* @return {@code True} if dummy reassign.
*/
public boolean dummyReassign() {
return (dummy() || forcePreload()) && reassign();
}
/**
* Rechecks topology.
*/
private void initTopology(GridCacheContext cacheCtx) throws IgniteCheckedException {
if (canCalculateAffinity(cacheCtx)) {
if (log.isDebugEnabled())
log.debug("Will recalculate affinity [locNodeId=" + cctx.localNodeId() + ", exchId=" + exchId + ']');
cacheCtx.affinity().calculateAffinity(exchId.topologyVersion(), discoEvt);
}
else {
if (log.isDebugEnabled())
log.debug("Will request affinity from remote node [locNodeId=" + cctx.localNodeId() + ", exchId=" +
exchId + ']');
// Fetch affinity assignment from remote node.
GridDhtAssignmentFetchFuture fetchFut =
new GridDhtAssignmentFetchFuture(cacheCtx, exchId.topologyVersion(), CU.affinityNodes(cacheCtx));
fetchFut.init();
List<List<ClusterNode>> affAssignment = fetchFut.get();
if (log.isDebugEnabled())
log.debug("Fetched affinity from remote node, initializing affinity assignment [locNodeId=" +
cctx.localNodeId() + ", topVer=" + exchId.topologyVersion() + ']');
cacheCtx.affinity().initializeAffinity(exchId.topologyVersion(), affAssignment);
}
}
/**
* @return {@code True} if local node can calculate affinity on it's own for this partition map exchange.
*/
private boolean canCalculateAffinity(GridCacheContext cacheCtx) {
CacheAffinityFunction affFunc = cacheCtx.config().getAffinity();
// Do not request affinity from remote nodes if affinity function is not centralized.
if (!U.hasAnnotation(affFunc, CacheCentralizedAffinityFunction.class))
return true;
// If local node did not initiate exchange or local node is the only cache node in grid.
Collection<ClusterNode> affNodes = CU.affinityNodes(cacheCtx, exchId.topologyVersion());
return !exchId.nodeId().equals(cctx.localNodeId()) ||
(affNodes.size() == 1 && affNodes.contains(cctx.localNode()));
}
/**
* @return {@code True}
*/
public boolean onAdded() {
return added.compareAndSet(false, true);
}
/**
* Event callback.
*
* @param exchId Exchange ID.
* @param discoEvt Discovery event.
*/
public void onEvent(GridDhtPartitionExchangeId exchId, DiscoveryEvent discoEvt) {
assert exchId.equals(this.exchId);
this.discoEvt = discoEvt;
evtLatch.countDown();
}
/**
* @return Discovery event.
*/
public DiscoveryEvent discoveryEvent() {
return discoEvt;
}
/**
* @return Exchange id.
*/
GridDhtPartitionExchangeId key() {
return exchId;
}
/**
* @return Oldest node.
*/
ClusterNode oldestNode() {
return oldestNode.get();
}
/**
* @return Exchange ID.
*/
public GridDhtPartitionExchangeId exchangeId() {
return exchId;
}
/**
* @return Init future.
*/
IgniteInternalFuture<?> initFuture() {
return initFut;
}
/**
* @return {@code true} if entered to busy state.
*/
private boolean enterBusy() {
if (busyLock.readLock().tryLock())
return true;
if (log.isDebugEnabled())
log.debug("Failed to enter busy state (exchanger is stopping): " + this);
return false;
}
/**
*
*/
private void leaveBusy() {
busyLock.readLock().unlock();
}
/**
* Starts activity.
*
* @throws IgniteInterruptedCheckedException If interrupted.
*/
public void init() throws IgniteInterruptedCheckedException {
assert oldestNode.get() != null;
if (init.compareAndSet(false, true)) {
if (isDone())
return;
try {
// Wait for event to occur to make sure that discovery
// will return corresponding nodes.
U.await(evtLatch);
assert discoEvt != null;
assert exchId.nodeId().equals(discoEvt.eventNode().id());
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
// Update before waiting for locks.
if (!cacheCtx.isLocal())
cacheCtx.topology().updateTopologyVersion(exchId, this);
}
// Grab all alive remote nodes with order of equal or less than last joined node.
rmtNodes = new ConcurrentLinkedQueue<>(CU.aliveRemoteCacheNodes(cctx, exchId.topologyVersion()));
rmtIds = Collections.unmodifiableSet(new HashSet<>(F.nodeIds(rmtNodes)));
for (Map.Entry<UUID, GridDhtPartitionsSingleMessage> m : singleMsgs.entrySet())
// If received any messages, process them.
onReceive(m.getKey(), m.getValue());
for (Map.Entry<UUID, GridDhtPartitionsFullMessage> m : fullMsgs.entrySet())
// If received any messages, process them.
onReceive(m.getKey(), m.getValue());
long topVer = exchId.topologyVersion();
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (cacheCtx.isLocal())
continue;
// Must initialize topology after we get discovery event.
initTopology(cacheCtx);
cacheCtx.preloader().updateLastExchangeFuture(this);
}
IgniteInternalFuture<?> partReleaseFut = cctx.partitionReleaseFuture(topVer);
// Assign to class variable so it will be included into toString() method.
this.partReleaseFut = partReleaseFut;
if (log.isDebugEnabled())
log.debug("Before waiting for partition release future: " + this);
partReleaseFut.get();
if (log.isDebugEnabled())
log.debug("After waiting for partition release future: " + this);
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (cacheCtx.isLocal())
continue;
// Notify replication manager.
if (cacheCtx.isDrEnabled())
cacheCtx.dr().beforeExchange(topVer, exchId.isLeft());
// Partition release future is done so we can flush the write-behind store.
cacheCtx.store().forceFlush();
// Process queued undeploys prior to sending/spreading map.
cacheCtx.preloader().unwindUndeploys();
GridDhtPartitionTopology top = cacheCtx.topology();
assert topVer == top.topologyVersion() :
"Topology version is updated only in this class instances inside single ExchangeWorker thread.";
top.beforeExchange(exchId);
}
for (GridClientPartitionTopology top : cctx.exchange().clientTopologies()) {
top.updateTopologyVersion(exchId, this);
top.beforeExchange(exchId);
}
}
catch (IgniteInterruptedCheckedException e) {
onDone(e);
throw e;
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to reinitialize local partitions (preloading will be stopped): " + exchId, e);
onDone(e);
return;
}
if (F.isEmpty(rmtIds)) {
onDone(exchId.topologyVersion());
return;
}
ready.set(true);
initFut.onDone(true);
if (log.isDebugEnabled())
log.debug("Initialized future: " + this);
if (!U.hasCaches(discoEvt.node()))
onDone(exchId.topologyVersion());
else {
// If this node is not oldest.
if (!oldestNode.get().id().equals(cctx.localNodeId()))
sendPartitions();
else {
boolean allReceived = allReceived();
if (allReceived && replied.compareAndSet(false, true)) {
if (spreadPartitions())
onDone(exchId.topologyVersion());
}
}
scheduleRecheck();
}
}
else
assert false : "Skipped init future: " + this;
}
/**
* @param node Node.
* @param id ID.
* @throws IgniteCheckedException If failed.
*/
private void sendLocalPartitions(ClusterNode node, @Nullable GridDhtPartitionExchangeId id) throws IgniteCheckedException {
GridDhtPartitionsSingleMessage m = new GridDhtPartitionsSingleMessage(id, cctx.versions().last());
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (!cacheCtx.isLocal())
m.addLocalPartitionMap(cacheCtx.cacheId(), cacheCtx.topology().localPartitionMap());
}
if (log.isDebugEnabled())
log.debug("Sending local partitions [nodeId=" + node.id() + ", exchId=" + exchId + ", msg=" + m + ']');
cctx.io().send(node, m, SYSTEM_POOL);
}
/**
* @param nodes Nodes.
* @param id ID.
* @throws IgniteCheckedException If failed.
*/
private void sendAllPartitions(Collection<? extends ClusterNode> nodes, GridDhtPartitionExchangeId id)
throws IgniteCheckedException {
GridDhtPartitionsFullMessage m = new GridDhtPartitionsFullMessage(id,
lastVer.get(),
id.topologyVersion());
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (!cacheCtx.isLocal())
m.addFullPartitionsMap(cacheCtx.cacheId(), cacheCtx.topology().partitionMap(true));
}
for (GridClientPartitionTopology top : cctx.exchange().clientTopologies())
m.addFullPartitionsMap(top.cacheId(), top.partitionMap(true));
if (log.isDebugEnabled())
log.debug("Sending full partition map [nodeIds=" + F.viewReadOnly(nodes, F.node2id()) +
", exchId=" + exchId + ", msg=" + m + ']');
cctx.io().safeSend(nodes, m, SYSTEM_POOL, null);
}
/**
*
*/
private void sendPartitions() {
ClusterNode oldestNode = this.oldestNode.get();
try {
sendLocalPartitions(oldestNode, exchId);
}
catch (ClusterTopologyCheckedException ignore) {
if (log.isDebugEnabled())
log.debug("Oldest node left during partition exchange [nodeId=" + oldestNode.id() +
", exchId=" + exchId + ']');
}
catch (IgniteCheckedException e) {
scheduleRecheck();
U.error(log, "Failed to send local partitions to oldest node (will retry after timeout) [oldestNodeId=" +
oldestNode.id() + ", exchId=" + exchId + ']', e);
}
}
/**
* @return {@code True} if succeeded.
*/
private boolean spreadPartitions() {
try {
sendAllPartitions(rmtNodes, exchId);
return true;
}
catch (IgniteCheckedException e) {
scheduleRecheck();
if (!X.hasCause(e, InterruptedException.class))
U.error(log, "Failed to send full partition map to nodes (will retry after timeout) [nodes=" +
F.nodeId8s(rmtNodes) + ", exchangeId=" + exchId + ']', e);
return false;
}
}
/** {@inheritDoc} */
@Override public boolean onDone(Long res, Throwable err) {
if (err == null) {
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (!cacheCtx.isLocal())
cacheCtx.affinity().cleanUpCache(res - 10);
}
}
cctx.exchange().onExchangeDone(this);
if (super.onDone(res, err) && !dummy && !forcePreload) {
if (log.isDebugEnabled())
log.debug("Completed partition exchange [localNode=" + cctx.localNodeId() + ", exchange= " + this + ']');
initFut.onDone(err == null);
GridTimeoutObject timeoutObj = this.timeoutObj;
// Deschedule timeout object.
if (timeoutObj != null)
cctx.kernalContext().timeout().removeTimeoutObject(timeoutObj);
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (exchId.event() == EventType.EVT_NODE_FAILED || exchId.event() == EventType.EVT_NODE_LEFT)
cacheCtx.config().getAffinity().removeNode(exchId.nodeId());
}
return true;
}
return dummy;
}
/**
* Cleans up resources to avoid excessive memory usage.
*/
public void cleanUp() {
topSnapshot.set(null);
singleMsgs.clear();
fullMsgs.clear();
rcvdIds.clear();
rmtNodes.clear();
oldestNode.set(null);
partReleaseFut = null;
}
/**
* @return {@code True} if all replies are received.
*/
private boolean allReceived() {
Collection<UUID> rmtIds = this.rmtIds;
assert rmtIds != null : "Remote Ids can't be null: " + this;
synchronized (rcvdIds) {
return rcvdIds.containsAll(rmtIds);
}
}
/**
* @param nodeId Sender node id.
* @param msg Single partition info.
*/
public void onReceive(final UUID nodeId, final GridDhtPartitionsSingleMessage msg) {
assert msg != null;
assert msg.exchangeId().equals(exchId);
// Update last seen version.
while (true) {
GridCacheVersion old = lastVer.get();
if (old == null || old.compareTo(msg.lastVersion()) < 0) {
if (lastVer.compareAndSet(old, msg.lastVersion()))
break;
}
else
break;
}
if (isDone()) {
if (log.isDebugEnabled())
log.debug("Received message for finished future (will reply only to sender) [msg=" + msg +
", fut=" + this + ']');
try {
ClusterNode n = cctx.node(nodeId);
if (n != null)
sendAllPartitions(F.asList(n), exchId);
}
catch (IgniteCheckedException e) {
scheduleRecheck();
U.error(log, "Failed to send full partition map to node (will retry after timeout) [node=" + nodeId +
", exchangeId=" + exchId + ']', e);
}
}
else {
initFut.listen(new CI1<IgniteInternalFuture<Boolean>>() {
@Override public void apply(IgniteInternalFuture<Boolean> t) {
try {
if (!t.get()) // Just to check if there was an error.
return;
ClusterNode loc = cctx.localNode();
singleMsgs.put(nodeId, msg);
boolean match = true;
// Check if oldest node has changed.
if (!oldestNode.get().equals(loc)) {
match = false;
synchronized (mux) {
// Double check.
if (oldestNode.get().equals(loc))
match = true;
}
}
if (match) {
boolean allReceived;
synchronized (rcvdIds) {
if (rcvdIds.add(nodeId))
updatePartitionSingleMap(msg);
allReceived = allReceived();
}
// If got all replies, and initialization finished, and reply has not been sent yet.
if (allReceived && ready.get() && replied.compareAndSet(false, true)) {
spreadPartitions();
onDone(exchId.topologyVersion());
}
else if (log.isDebugEnabled())
log.debug("Exchange future full map is not sent [allReceived=" + allReceived() +
", ready=" + ready + ", replied=" + replied.get() + ", init=" + init.get() +
", fut=" + this + ']');
}
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to initialize exchange future: " + this, e);
}
}
});
}
}
/**
* @param nodeId Sender node ID.
* @param msg Full partition info.
*/
public void onReceive(final UUID nodeId, final GridDhtPartitionsFullMessage msg) {
assert msg != null;
if (isDone()) {
if (log.isDebugEnabled())
log.debug("Received message for finished future [msg=" + msg + ", fut=" + this + ']');
return;
}
ClusterNode curOldest = oldestNode.get();
if (!nodeId.equals(curOldest.id())) {
if (log.isDebugEnabled())
log.debug("Received full partition map from unexpected node [oldest=" + curOldest.id() +
", unexpectedNodeId=" + nodeId + ']');
ClusterNode sender = cctx.discovery().node(nodeId);
if (sender == null) {
if (log.isDebugEnabled())
log.debug("Sender node left grid, will ignore message from unexpected node [nodeId=" + nodeId +
", exchId=" + msg.exchangeId() + ']');
return;
}
// Will process message later if sender node becomes oldest node.
if (sender.order() > curOldest.order())
fullMsgs.put(nodeId, msg);
return;
}
assert msg.exchangeId().equals(exchId);
if (log.isDebugEnabled())
log.debug("Received full partition map from node [nodeId=" + nodeId + ", msg=" + msg + ']');
assert exchId.topologyVersion() == msg.topologyVersion();
initFut.listen(new CI1<IgniteInternalFuture<Boolean>>() {
@Override public void apply(IgniteInternalFuture<Boolean> t) {
assert msg.lastVersion() != null;
cctx.versions().onReceived(nodeId, msg.lastVersion());
updatePartitionFullMap(msg);
onDone(exchId.topologyVersion());
}
});
}
/**
* Updates partition map in all caches.
*
* @param msg Partitions full messages.
*/
private void updatePartitionFullMap(GridDhtPartitionsFullMessage msg) {
for (Map.Entry<Integer, GridDhtPartitionFullMap> entry : msg.partitions().entrySet()) {
Integer cacheId = entry.getKey();
GridCacheContext cacheCtx = cctx.cacheContext(cacheId);
if (cacheCtx != null)
cacheCtx.topology().update(exchId, entry.getValue());
else if (CU.oldest(cctx).isLocal())
cctx.exchange().clientTopology(cacheId, exchId).update(exchId, entry.getValue());
}
}
/**
* Updates partition map in all caches.
*
* @param msg Partitions single message.
*/
private void updatePartitionSingleMap(GridDhtPartitionsSingleMessage msg) {
for (Map.Entry<Integer, GridDhtPartitionMap> entry : msg.partitions().entrySet()) {
Integer cacheId = entry.getKey();
GridCacheContext cacheCtx = cctx.cacheContext(cacheId);
GridDhtPartitionTopology top = cacheCtx != null ? cacheCtx.topology() :
cctx.exchange().clientTopology(cacheId, exchId);
top.update(exchId, entry.getValue());
}
}
/**
* @param nodeId Left node id.
*/
public void onNodeLeft(final UUID nodeId) {
if (isDone())
return;
if (!enterBusy())
return;
try {
// Wait for initialization part of this future to complete.
initFut.listen(new CI1<IgniteInternalFuture<?>>() {
@Override public void apply(IgniteInternalFuture<?> f) {
if (isDone())
return;
if (!enterBusy())
return;
try {
// Pretend to have received message from this node.
rcvdIds.add(nodeId);
Collection<UUID> rmtIds = GridDhtPartitionsExchangeFuture.this.rmtIds;
assert rmtIds != null;
ClusterNode oldest = oldestNode.get();
if (oldest.id().equals(nodeId)) {
if (log.isDebugEnabled())
log.debug("Oldest node left or failed on partition exchange " +
"(will restart exchange process)) [oldestNodeId=" + oldest.id() +
", exchangeId=" + exchId + ']');
boolean set = false;
ClusterNode newOldest = CU.oldest(cctx, exchId.topologyVersion());
// If local node is now oldest.
if (newOldest.id().equals(cctx.localNodeId())) {
synchronized (mux) {
if (oldestNode.compareAndSet(oldest, newOldest)) {
// If local node is just joining.
if (exchId.nodeId().equals(cctx.localNodeId())) {
try {
for (GridCacheContext cacheCtx : cctx.cacheContexts()) {
if (!cacheCtx.isLocal())
cacheCtx.topology().beforeExchange(exchId);
}
}
catch (IgniteCheckedException e) {
onDone(e);
return;
}
}
set = true;
}
}
}
else {
synchronized (mux) {
set = oldestNode.compareAndSet(oldest, newOldest);
}
if (set && log.isDebugEnabled())
log.debug("Reassigned oldest node [this=" + cctx.localNodeId() +
", old=" + oldest.id() + ", new=" + newOldest.id() + ']');
}
if (set) {
// If received any messages, process them.
for (Map.Entry<UUID, GridDhtPartitionsSingleMessage> m : singleMsgs.entrySet())
onReceive(m.getKey(), m.getValue());
for (Map.Entry<UUID, GridDhtPartitionsFullMessage> m : fullMsgs.entrySet())
onReceive(m.getKey(), m.getValue());
// Reassign oldest node and resend.
recheck();
}
}
else if (rmtIds.contains(nodeId)) {
if (log.isDebugEnabled())
log.debug("Remote node left of failed during partition exchange (will ignore) " +
"[rmtNode=" + nodeId + ", exchangeId=" + exchId + ']');
assert rmtNodes != null;
for (Iterator<ClusterNode> it = rmtNodes.iterator(); it.hasNext(); )
if (it.next().id().equals(nodeId))
it.remove();
if (allReceived() && ready.get() && replied.compareAndSet(false, true))
if (spreadPartitions())
onDone(exchId.topologyVersion());
}
}
finally {
leaveBusy();
}
}
});
}
finally {
leaveBusy();
}
}
/**
*
*/
private void recheck() {
// If this is the oldest node.
if (oldestNode.get().id().equals(cctx.localNodeId())) {
Collection<UUID> remaining = remaining();
if (!remaining.isEmpty()) {
try {
cctx.io().safeSend(cctx.discovery().nodes(remaining),
new GridDhtPartitionsSingleRequest(exchId), SYSTEM_POOL, null);
}
catch (IgniteCheckedException e) {
U.error(log, "Failed to request partitions from nodes [exchangeId=" + exchId +
", nodes=" + remaining + ']', e);
}
}
// Resend full partition map because last attempt failed.
else {
if (spreadPartitions())
onDone(exchId.topologyVersion());
}
}
else
sendPartitions();
// Schedule another send.
scheduleRecheck();
}
/**
*
*/
private void scheduleRecheck() {
if (!isDone()) {
GridTimeoutObject old = timeoutObj;
if (old != null)
cctx.kernalContext().timeout().removeTimeoutObject(old);
GridTimeoutObject timeoutObj = new GridTimeoutObjectAdapter(
cctx.gridConfig().getNetworkTimeout() * cctx.gridConfig().getCacheConfiguration().length) {
@Override public void onTimeout() {
if (isDone())
return;
if (!enterBusy())
return;
try {
U.warn(log,
"Retrying preload partition exchange due to timeout [done=" + isDone() +
", dummy=" + dummy + ", exchId=" + exchId + ", rcvdIds=" + F.id8s(rcvdIds) +
", rmtIds=" + F.id8s(rmtIds) + ", remaining=" + F.id8s(remaining()) +
", init=" + init + ", initFut=" + initFut.isDone() +
", ready=" + ready + ", replied=" + replied + ", added=" + added +
", oldest=" + U.id8(oldestNode.get().id()) + ", oldestOrder=" +
oldestNode.get().order() + ", evtLatch=" + evtLatch.getCount() +
", locNodeOrder=" + cctx.localNode().order() +
", locNodeId=" + cctx.localNode().id() + ']',
"Retrying preload partition exchange due to timeout.");
recheck();
}
finally {
leaveBusy();
}
}
};
this.timeoutObj = timeoutObj;
cctx.kernalContext().timeout().addTimeoutObject(timeoutObj);
}
}
/**
* @return Remaining node IDs.
*/
Collection<UUID> remaining() {
if (rmtIds == null)
return Collections.emptyList();
return F.lose(rmtIds, true, rcvdIds);
}
/** {@inheritDoc} */
@Override public int compareTo(GridDhtPartitionsExchangeFuture fut) {
return exchId.compareTo(fut.exchId);
}
/** {@inheritDoc} */
@Override public boolean equals(Object o) {
if (this == o)
return true;
GridDhtPartitionsExchangeFuture fut = (GridDhtPartitionsExchangeFuture)o;
return exchId.equals(fut.exchId);
}
/** {@inheritDoc} */
@Override public int hashCode() {
return exchId.hashCode();
}
/** {@inheritDoc} */
@Override public String toString() {
ClusterNode oldestNode = this.oldestNode.get();
return S.toString(GridDhtPartitionsExchangeFuture.class, this,
"oldest", oldestNode == null ? "null" : oldestNode.id(),
"oldestOrder", oldestNode == null ? "null" : oldestNode.order(),
"evtLatch", evtLatch == null ? "null" : evtLatch.getCount(),
"remaining", remaining(),
"super", super.toString());
}
}
| 34.258478 | 127 | 0.531437 |
7bccdd047367ede5a2e93bebed7e83b2e4e0dae6 | 1,822 | package com.domgarr.concetto;
import com.domgarr.concetto.models.Concept;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
/*
Since all the getter/setters are now generated via Lombok I don't think testing the Model is necessary,
I will the tests here for now and will rethink again in the future if testings getters/setters is necessary.
TODO: Re-think if testing Concept is necessary.
*/
public class ConceptTests {
private Concept concept;
@BeforeEach
void initBefore() {
concept = new Concept();
}
// (Name of method) / (action) / expectation
@Test
void setName_nameSetWithREST_shouldSetNameToREST() {
concept.setName("REST");
assertEquals("REST", concept.getName());
}
@Test
void setName_nameSetWithREST_shouldNotBeNull() {
concept.setName("REST");
assertNotNull(concept.getName());
}
@Test
@DisplayName("should return violation error message 'size must be between 1 and 20'")
void setName_nameSetWithEmptyString_shouldReturnViolationError() {
concept.setName("");
}
@Test
@DisplayName("should return violation error message 'size must be between 1 and 20'")
void setName_nameSetStringLength21_shouldReturnViolationError() {
concept.setName("SportSportSportSportSport"); //25 length
}
@Test
void getName_nameSetWithRest_shouldReturnREST() {
concept.setName("REST");
assertEquals("REST", concept.getName());
}
@Test
void concept_emptyConstructor_shouldInitializeDateCreated() {
assertNotNull(concept.getDateCreated());
}
}
| 30.366667 | 112 | 0.70966 |
74ce271e32facde86a1feea5e753f96686213d49 | 2,879 | package jp.sourceforge.reflex;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jp.sourceforge.reflex.core.ResourceMapper;
import jp.sourceforge.reflex.exception.JSONException;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import model.Array;
import model.Element;
/**
* Unit test for simple App.
*/
public class JSONArrayTest extends TestCase {
/**
* Create the test case
*
* @param testName
* name of the test case
*/
public JSONArrayTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(JSONArrayTest.class);
}
/**
* Rigourous Test :-)
*/
public void test() {
// ใขใใซใใผใณใฎใใใฑใผใธๅใๆๅฎใใฆmapperใnewใใ
Map nsmap = new HashMap();
nsmap.put("model", ""); // ""ใฏใใใฉใซใใฎๅๅ็ฉบ้
IResourceMapper mapper = new ResourceMapper(nsmap);
// ้
ๅ
List elementList = new ArrayList();
Element element1 = new Element();
element1._$$text = "XYZ\\<>'\"";
elementList.add(element1);
Element element2 = new Element();
element2._$$text = "102";
elementList.add(element2);
Element element3 = new Element();
element3._$$text = "103";
elementList.add(element3);
Element element4 = new Element();
element4._$$text = "104";
elementList.add(element4);
Element element5 = new Element();
element5._$$text = "105";
elementList.add(element5);
Element element6 = new Element();
element6._$$text = "ABC";
elementList.add(element6);
Array array = new Array();
array._element = elementList;
// XMLใซใทใชใขใฉใคใบ
String toXML = mapper.toXML(array);
System.out.println("\nใXML(array)ใใทใชใขใฉใคใบใในใใ:");
System.out.println(toXML);
// JSONใซใทใชใขใฉใคใบ
String toJSON = mapper.toJSON(array);
System.out.println("\nใJSON(array)ใใทใชใขใฉใคใบใในใใ:");
System.out.println(toJSON);
try {
// ่ฉฆใใซใใทใชใขใฉใคใบใใฆใฟใ
Array arrayFromXML = (Array) mapper.fromXML(toXML);
toXML = mapper.toXML(arrayFromXML);
System.out.println("\nไธใใใทใชใขใฉใคใบ(XML):");
System.out.println(toXML);
} catch (Exception e) {
e.printStackTrace();
}
try {
// ่ฉฆใใซใใทใชใขใฉใคใบใใฆใฟใ(ใจใฉใผใๅบใ๏ผ
Array arrayFromJSON = (Array) mapper.fromJSON(toJSON);
toJSON = mapper.toJSON(arrayFromJSON);
System.out.println("\nไธใใใทใชใขใฉใคใบ(JSON):");
System.out.println(toJSON);
/*
* // ้ ๅบใ้ใซใใ ReflexJSONTest me = new ReflexJSONTest(); List
* oppsiteElement = me.opposite(arrayFromJSON.element);
* arrayFromJSON.element = oppsiteElement; toJSON =
* mapper.toJSON(arrayFromJSON);
* System.out.println("\nไธใฎ้ ๅบใ้ใซใใฆใใทใชใขใฉใคใบ:");
* System.out.println(toJSON);
*/
} catch (JSONException e) {
e.printStackTrace();
}
}
}
| 24.818966 | 64 | 0.656131 |
d9087ae9bf949643e594565b89097b987c732b96 | 3,806 | package com.sxquan.manage.generator.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sxquan.core.entity.LayuiPage;
import com.sxquan.core.entity.RequestPage;
import com.sxquan.core.entity.ServerResponse;
import com.sxquan.core.exception.ShopException;
import com.sxquan.core.pojo.generator.GeneratorConfig;
import com.sxquan.core.util.ShopUtil;
import com.sxquan.manage.common.annotation.ControllerEndpoint;
import com.sxquan.manage.common.constant.GeneratorConstant;
import com.sxquan.manage.common.util.FileUtil;
import com.sxquan.manage.generator.helper.GeneratorHelper;
import com.sxquan.manage.generator.pojo.Column;
import com.sxquan.manage.generator.pojo.Table;
import com.sxquan.manage.generator.service.IGeneratorConfigService;
import com.sxquan.manage.generator.service.IGeneratorService;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* @author sxquan
* @since 2020/5/21 1:07
*/
@RestController
@Validated
@RequestMapping("generator")
public class GeneratorController {
private static final String SUFFIX = "_code.zip";
@Autowired
private IGeneratorConfigService generatorConfigService;
@Autowired
private IGeneratorService generatorService;
@Autowired
private GeneratorHelper generatorHelper;
@GetMapping("table/list")
public ServerResponse getTableList(String tableName, RequestPage requestPage) {
IPage<Table> page = generatorService.findTableList(tableName,requestPage);
return ServerResponse.success(new LayuiPage<>(page.getRecords(),page.getTotal()));
}
@GetMapping("code")
@ControllerEndpoint(exceptionMessage = "ไปฃ็ ็ๆๅคฑ่ดฅ")
@RequiresPermissions("generator:generate")
public void generate(@NotBlank(message = "{required}") String name, String remark, HttpServletResponse response) throws Exception {
GeneratorConfig generatorConfig = generatorConfigService.findGeneratorConfig();
if (generatorConfig == null) {
throw new ShopException("ไปฃ็ ็ๆ้
็ฝฎไธบ็ฉบ");
}
String className = name;
if (GeneratorConfig.TRIM_YES.equals(generatorConfig.getIsTrim())) {
className = RegExUtils.replaceFirst(name, generatorConfig.getTrimValue(), StringUtils.EMPTY);
}
generatorConfig.setTableName(name);
generatorConfig.setClassName(ShopUtil.underscoreToCamel(className));
generatorConfig.setTableComment(remark);
// ็ๆไปฃ็ ๅฐไธดๆถ็ฎๅฝ
List<Column> columns = generatorService.getColumns(GeneratorConstant.DATABASE_NAME, name);
generatorHelper.generateEntityFile(columns, generatorConfig);
generatorHelper.generateMapperFile(columns, generatorConfig);
generatorHelper.generateMapperXmlFile(columns, generatorConfig);
generatorHelper.generateServiceFile(columns, generatorConfig);
generatorHelper.generateServiceImplFile(columns, generatorConfig);
generatorHelper.generateControllerFile(columns, generatorConfig);
// ๆๅ
String zipFile = System.currentTimeMillis() + SUFFIX;
FileUtil.compress(GeneratorConstant.TEMP_PATH + "src", zipFile);
// ไธ่ฝฝ
FileUtil.download(zipFile, name + SUFFIX, true, response);
// ๅ ้คไธดๆถ็ฎๅฝ
FileUtil.delete(GeneratorConstant.TEMP_PATH);
}
}
| 40.924731 | 135 | 0.769312 |
40b314fb3038f25dd1f41927836f062bede0b033 | 1,816 | /**
* Copyright (C) 2009 - present by OpenGamma Inc. and other contributors.
*
* 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.fudgemsg.types.secondary;
import javax.time.calendar.DateProvider;
import javax.time.calendar.LocalDate;
import org.fudgemsg.types.DateFieldType;
import org.fudgemsg.types.FudgeDate;
import org.fudgemsg.types.SecondaryFieldTypeBase;
/**
* Secondary type for JSR-310 object conversion.
*
* @author Andrew Griffin
*/
public class JSR310LocalDateFieldType extends SecondaryFieldTypeBase<LocalDate,DateProvider,FudgeDate> {
/**
* Singleton instance of the type.
*/
public static final JSR310LocalDateFieldType INSTANCE = new JSR310LocalDateFieldType ();
private JSR310LocalDateFieldType () {
super (DateFieldType.INSTANCE, LocalDate.class);
}
/**
* {@inheritDoc}
*/
@Override
public FudgeDate secondaryToPrimary(final LocalDate object) {
return new FudgeDate (object);
}
/**
* {@inheritDoc}
*/
@Override
public LocalDate primaryToSecondary (final DateProvider object) {
return object.toLocalDate ();
}
/**
* {@inheritDoc}
*/
@Override
public boolean canConvertPrimary (final Class<? extends DateProvider> clazz) {
return DateProvider.class.isAssignableFrom (clazz);
}
} | 27.938462 | 104 | 0.727974 |
eb79befadd1ae8bf23bb153f2fddc5ab7be5ee71 | 921 | package com.mirhoseini.fyber.util;
/**
* Created by Mohsen on 30/09/2016.
*/
public abstract class Constants {
public static final String BASE_URL = "http://api.fyber.com/";
public static final String CODE_OK = "OK";
public static final String CODE_NO_CONTENT = "NO_CONTENT";
public static final String FORMAT_JSON = "json";
public static final int OFFER_TYPES = 112;
public static final String SAMPLE_USER_ID = "spiderman";
public static final String SAMPLE_API_KEY = "1c915e3b5d42d05136185030892fbb846c278927";
public static final int SAMPLE_APPLICATION_ID = 2070;
public static final String SAMPLE_PUB0 = "campaign2";
public static final int NETWORK_CONNECTION_TIMEOUT = 30; // 30 sec
public static final long CACHE_SIZE = 10 * 1024 * 1024; // 10 MB
public static final int CACHE_MAX_AGE = 2; // 2 min
public static final int CACHE_MAX_STALE = 7; // 7 day
}
| 35.423077 | 91 | 0.724213 |
6f587d7ec0fd35043cb28589c6da2346073fdffa | 6,425 | package com.quandoo.quandootest.domain.interactor;
import android.arch.paging.DataSource;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.quandoo.quandootest.domain.entities.Customer;
import com.quandoo.quandootest.domain.entities.Table;
import com.quandoo.quandootest.domain.entities.TableAndCustomer;
import com.quandoo.quandootest.shadows.CompletableShadow;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import io.reactivex.Completable;
import static junit.framework.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
public class TablesInteractorTest {
@Mock
private Repository repository;
private TablesInteractor subject;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
subject = spy(new TablesInteractor(repository));
}
@Test
public void getTablesAndCustomers_shouldReturnFactoryFromRepository() throws Exception {
final DataSource.Factory mockedFactory = mock(DataSource.Factory.class);
when(repository.getTablesAndCustomers()).thenReturn(mockedFactory);
final DataSource.Factory factory = subject.getTablesAndCustomers();
verify(repository).getTablesAndCustomers();
assertEquals(factory, mockedFactory);
}
@Test
public void softUpdate_ifCacheIsNotValid_shouldCallUpdate() throws Exception {
when(repository.isTablesCacheValid(anyLong())).thenReturn(false);
when(repository.isTablesCacheValid(anyLong())).thenReturn(false);
when(repository.updateTables()).thenReturn(Completable.complete());
subject.softUpdate();
verify(subject).update();
}
@Config(shadows = CompletableShadow.class)
@Test
public void softUpdate_ifCacheIsValid_shouldReturnEmptyCompletable() throws Exception {
final Completable mockedCompletable = mock(Completable.class);
CompletableShadow.mockCompletable(mockedCompletable);
when(repository.isTablesCacheValid(anyLong())).thenReturn(true);
assertEquals(subject.softUpdate(), mockedCompletable);
verify(subject, never()).update();
}
@Test
public void update_shouldCallUpdateTables_andScheduleCleanDbOnComplete() throws Exception {
when(repository.updateTables()).thenReturn(Completable.complete());
subject.update().subscribe();
verify(repository).updateTables();
verify(repository).scheduleCleanDb(anyLong());
}
@Test
public void getLastUpdateTime_shouldReturnTablesLastUpdateTime() throws Exception {
final long testTime = 999;
when(repository.getTablesLastUpdateTime()).thenReturn(testTime);
assertEquals(subject.getLastUpdateTime(), testTime);
}
@Config(shadows = CompletableShadow.class)
@Test
public void updateTableWithNewCustomer_ifTableIsReserved_shouldReturnEmptyCompletable() throws Exception {
final Completable mockedCompletable = mock(Completable.class);
CompletableShadow.mockCompletable(mockedCompletable);
final Table mockedTable = mock(Table.class);
when(mockedTable.isReserved()).thenReturn(true);
final TableAndCustomer mockedTandC = mock(TableAndCustomer.class);
when(mockedTandC.getTable()).thenReturn(mockedTable);
assertEquals(subject.updateTableWithNewCustomer(mockedTandC, 0L), mockedCompletable);
verify(repository, never()).updateTableWithNewCustomer(anyLong(), anyBoolean(), anyLong());
}
@Config(shadows = CompletableShadow.class)
@Test
public void updateTableWithNewCustomer_ifTableHasCustomer_shouldReturnEmptyCompletable() throws Exception {
final Completable mockedCompletable = mock(Completable.class);
CompletableShadow.mockCompletable(mockedCompletable);
final Table mockedTable = mock(Table.class);
when(mockedTable.isReserved()).thenReturn(false);
final Customer mockedCustomer = mock(Customer.class);
final TableAndCustomer mockedTandC = mock(TableAndCustomer.class);
when(mockedTandC.getTable()).thenReturn(mockedTable);
when(mockedTandC.getCustomer()).thenReturn(mockedCustomer);
assertEquals(subject.updateTableWithNewCustomer(mockedTandC, 0L), mockedCompletable);
verify(repository, never()).updateTableWithNewCustomer(anyLong(), anyBoolean(), anyLong());
}
@Config(shadows = CompletableShadow.class)
@Test
public void updateTableWithNewCustomer_ifNewCustomerIdIsNull_shouldReturnEmptyCompletable() throws Exception {
final Completable mockedCompletable = mock(Completable.class);
CompletableShadow.mockCompletable(mockedCompletable);
final Table mockedTable = mock(Table.class);
when(mockedTable.isReserved()).thenReturn(false);
final TableAndCustomer mockedTandC = mock(TableAndCustomer.class);
when(mockedTandC.getTable()).thenReturn(mockedTable);
assertEquals(subject.updateTableWithNewCustomer(mockedTandC, null), mockedCompletable);
verify(repository, never()).updateTableWithNewCustomer(anyLong(), anyBoolean(), anyLong());
}
@Config(shadows = CompletableShadow.class)
@Test
public void updateTableWithNewCustomer_shouldCallRepositoryUpdateTableWithNewCustomer() throws Exception {
final long testTableId = 100L;
final Long testCustomerId = 200L;
final Table mockedTable = mock(Table.class);
when(mockedTable.isReserved()).thenReturn(false);
when(mockedTable.getId()).thenReturn(testTableId);
final TableAndCustomer mockedTandC = mock(TableAndCustomer.class);
when(mockedTandC.getTable()).thenReturn(mockedTable);
subject.updateTableWithNewCustomer(mockedTandC, testCustomerId);
verify(repository).updateTableWithNewCustomer(eq(testTableId), eq(true), eq(testCustomerId));
}
}
| 42.269737 | 114 | 0.752529 |
7baf11ea5b9cfe4a00f8c6afaf8014a935972b28 | 1,136 | package com.bingstar.bingmall.order.OrderApplyAfter;
import java.util.List;
/**
* Created by John on 2017/3/28.
*/
public class OrderApplayEditBeanInfo {
private String afterSaleType;
private String zorderinfo_id;
private String afterSaleReason;
public List<AfterSaleOrderInfo> afterSaleOrderList;
public String getAfterSaleType() {
return afterSaleType;
}
public void setAfterSaleType(String afterSaleType) {
this.afterSaleType = afterSaleType;
}
public String getZorderinfo_id() {
return zorderinfo_id;
}
public void setZorderinfo_id(String zorderinfo_id) {
this.zorderinfo_id = zorderinfo_id;
}
public String getAfterSaleReason() {
return afterSaleReason;
}
public void setAfterSaleReason(String afterSaleReason) {
this.afterSaleReason = afterSaleReason;
}
public List<AfterSaleOrderInfo> getAfterSaleOrderList() {
return afterSaleOrderList;
}
public void setAfterSaleOrderList(List<AfterSaleOrderInfo> afterSaleOrderList) {
this.afterSaleOrderList = afterSaleOrderList;
}
}
| 23.666667 | 84 | 0.711268 |
7467a3cb121e786a8d8fb21b6f74e10db276bcbc | 950 | package org.joder.stock.core.domain;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* @author Joder 2020/8/14 21:36
*/
@Data
public class ProcessQuery {
private double initMoney;
private String strategyCode;
private List<StockData> stockList;
/**
* ๅฏนๅบๆฏไธช็ญ็ฅ้่ฆ็ๅๆฐ
*/
private Map<String, Object> hyperParams;
public ProcessQuery(String strategyCode, List<StockData> stockList) {
this(100000, strategyCode, stockList);
}
public ProcessQuery(double initMoney, String strategyCode, List<StockData> stockList) {
this(initMoney, strategyCode, stockList, null);
}
public ProcessQuery(double initMoney, String strategyCode, List<StockData> stockList, Map<String, Object> hyperParams) {
super();
this.initMoney = initMoney;
this.strategyCode = strategyCode;
this.stockList = stockList;
this.hyperParams = hyperParams;
}
}
| 25.675676 | 124 | 0.686316 |
60973c27d2620e0bac15b702089ba832cd275cbe | 6,089 | package com.anton46.stepsview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
public class StepsViewIndicator extends View {
private static final int THUMB_SIZE = 50;
private static final int CIRCLERADIUS_SIZE = 100;
private Paint paint = new Paint();
private Paint paint2 = new Paint();
private Paint selectedPaint = new Paint();
private int mNumOfStep = 2;
private float mLineHeight;
private float mThumbRadius;
private float mCircleRadius;
private float mPadding;
private int mProgressColor = Color.YELLOW;
private int mBarColor = Color.BLACK;
private float mCenterY;
private float mLeftX;
private float mLeftY;
private float mRightX;
private float mRightY;
private float mDelta;
private List<Float> mThumbContainerXPosition = new ArrayList<>();
private int mCompletedPosition;
private OnDrawListener mDrawListener;
public StepsViewIndicator(Context context) {
this(context, null);
}
public StepsViewIndicator(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public StepsViewIndicator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
mLineHeight = 0.2f * THUMB_SIZE;
mThumbRadius = 0.4f * CIRCLERADIUS_SIZE;
mCircleRadius = 0.5f * mThumbRadius;
mPadding = 0.5f * CIRCLERADIUS_SIZE;
}
public void setStepSize(int size) {
mNumOfStep = size;
invalidate();
}
public void setDrawListener(OnDrawListener drawListener) {
mDrawListener = drawListener;
}
public List<Float> getThumbContainerXPosition() {
return mThumbContainerXPosition;
}
@Override
public void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mCenterY = 0.5f * getHeight();
mLeftX = mPadding;
mLeftY = mCenterY - (mLineHeight / 2);
mRightX = getWidth() - mPadding;
mRightY = 0.5f * (getHeight() + mLineHeight);
mDelta = (mRightX - mLeftX) / (mNumOfStep - 1);
mThumbContainerXPosition.add(mLeftX);
for (int i = 1; i < mNumOfStep - 1; i++) {
mThumbContainerXPosition.add(mLeftX + (i * mDelta));
}
mThumbContainerXPosition.add(mRightX);
mDrawListener.onReady();
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = 200;
if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) {
width = MeasureSpec.getSize(widthMeasureSpec);
}
int height = THUMB_SIZE + 20;
if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) {
height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
}
setMeasuredDimension(width, height);
}
public void setCompletedPosition(int position) {
mCompletedPosition = position;
}
public void reset() {
setCompletedPosition(0);
}
public void setProgressColor(int progressColor) {
mProgressColor = progressColor;
}
public void setBarColor(int barColor) {
mBarColor = barColor;
}
@Override
protected synchronized void onDraw(Canvas canvas) {
super.onDraw(canvas);
mDrawListener.onReady();
// Draw rect bounds
paint.setAntiAlias(true);
paint.setColor(mBarColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint2.setAntiAlias(true);
paint2.setColor(Color.WHITE);
paint2.setStyle(Paint.Style.FILL);
paint2.setStrokeWidth(2);
selectedPaint.setAntiAlias(true);
selectedPaint.setColor(mProgressColor);
selectedPaint.setStyle(Paint.Style.STROKE);
selectedPaint.setStrokeWidth(2);
// Draw rest of the circle'Bounds
for (int i = 0; i < mThumbContainerXPosition.size(); i++) {
canvas.drawCircle(mThumbContainerXPosition.get(i), mCenterY,(i == mCompletedPosition) ? mCircleRadius+10 : mCircleRadius, (i <= mCompletedPosition) ? selectedPaint : paint);
}
paint.setStyle(Paint.Style.FILL);
selectedPaint.setStyle(Paint.Style.FILL);
for (int i = 0; i < mThumbContainerXPosition.size() - 1; i++) {
final float pos = mThumbContainerXPosition.get(i);
final float pos2 = mThumbContainerXPosition.get(i + 1);
canvas.drawRect(pos, mLeftY, pos2, mRightY, (i < mCompletedPosition) ? selectedPaint : paint);
}
// Draw rest of circle
for (int i = 0; i < mThumbContainerXPosition.size(); i++) {
final float pos = mThumbContainerXPosition.get(i);
canvas.drawCircle(pos, mCenterY, mCircleRadius, (i <= mCompletedPosition) ? selectedPaint : paint);
if (i == mCompletedPosition) {
selectedPaint.setColor(getColorWithAlpha(mProgressColor, 0.2f));
canvas.drawCircle(pos, mCenterY, mCircleRadius * 1.8f, selectedPaint);
}
}
for (int i = 0; i < mThumbContainerXPosition.size(); i++) {
canvas.drawCircle(mThumbContainerXPosition.get(i), mCenterY, (i == mCompletedPosition) ? mCircleRadius : mCircleRadius-5, paint2);
}
}
public int getCompletedPosition() {
return mCompletedPosition;
}
public static int getColorWithAlpha(int color, float ratio) {
int newColor = 0;
int alpha = Math.round(Color.alpha(color) * ratio);
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
newColor = Color.argb(alpha, r, g, b);
return newColor;
}
public interface OnDrawListener {
void onReady();
}
}
| 32.216931 | 185 | 0.643948 |
ac56d8fdbdde5a0b987e14506b2d4524ca5b02a4 | 400 | package io.subutai.common.security.objects;
/**
*
*/
public enum UserStatus
{
ACTIVE(1,"ACTIVE"),
DISABLED(2,"Disabled");
private String name;
private int id;
UserStatus( int id, String name)
{
this.id = id;
this.name = name;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
}
| 12.121212 | 43 | 0.53 |
c1ea3fedf4fb8a2a7ad0e2ded1c3599f2091885f | 2,058 | package com.nsqre.insquare.Utilities;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nsqre.insquare.R;
import java.util.ArrayList;
/**
* unused
*/
public class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
@Override
public int getCount() {
return mNavItems.size();
}
@Override
public Object getItem(int position) {
return mNavItems.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.drawer_title);
TextView subtitleView = (TextView) view.findViewById(R.id.drawer_subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.drawer_icon);
TextView counterView = (TextView) view.findViewById(R.id.drawer_counter);
NavItem temp = mNavItems.get(position);
titleView.setText(temp.getmTitle());
subtitleView.setText(temp.getmSubtitle());
iconView.setImageResource(temp.getmIcon());
if (temp.getmNotificationCounter() == 0) {
counterView.setVisibility(View.INVISIBLE);
} else {
String counter = Integer.toString(temp.getmNotificationCounter());
counterView.setText(counter);
}
return view;
}
} | 27.44 | 114 | 0.667153 |
0122d8fb24782cc9f78fcbfd0aed6d8c23a845c2 | 940 | package com.br.antbridge.severino.resource.mod_controleponto.diasemana;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import com.br.antbridge.core.resource.ResourceCRUD;
import com.br.antbridge.severino.entity.mod_controleponto.DiaSemana;
public class DiaSemanaResource extends ResourceCRUD<DiaSemana> {
public DiaSemanaResource() {
}
@Override
public Class<DiaSemana> getModelClass() {
return DiaSemana.class;
}
public DiaSemana buscaPorNome(String nomeDiaSemana) throws Exception {
TypedQuery<DiaSemana> queryDiaSemana = this.getEm().createQuery("select d from DiaSemana d where d.nome = :nomeDiaSemana", DiaSemana.class);
queryDiaSemana.setParameter("nomeDiaSemana", nomeDiaSemana);
DiaSemana daisemana = new DiaSemana();
try {
daisemana = queryDiaSemana.getSingleResult();
} catch (NoResultException e) {
daisemana = null;
}
return daisemana;
}
} | 26.111111 | 142 | 0.770213 |
52dc277ead244fc4c29133ffcb40533cb7e5def7 | 2,521 | package com.macro.mall.portal.component.trade.alipay.utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
/**
* Created by liuyangkly on 15/6/27.
* ไฝฟ็จไบgoogle zxingไฝไธบไบ็ปด็ ็ๆๅทฅๅ
ท
*/
public class ZxingUtils {
private static Log log = LogFactory.getLog(ZxingUtils.class);
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
}
private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
if (!ImageIO.write(image, format, file)) {
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}
/** ๅฐๅ
ๅฎนcontents็ๆ้ฟๅฎฝๅไธบwidth็ๅพ็๏ผๅพ็่ทฏๅพ็ฑimgPathๆๅฎ
*/
public static File getQRCodeImge(String contents, int width, String imgPath) {
return getQRCodeImge(contents, width, width, imgPath);
}
/** ๅฐๅ
ๅฎนcontents็ๆ้ฟไธบwidth๏ผๅฎฝไธบwidth็ๅพ็๏ผๅพ็่ทฏๅพ็ฑimgPathๆๅฎ
*/
public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
try {
Map<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
File imageFile = new File(imgPath);
writeToFile(bitMatrix, "png", imageFile);
return imageFile;
} catch (Exception e) {
log.error("create QR code error!", e);
return null;
}
}
}
| 34.067568 | 111 | 0.687426 |
60ee48e5d86b17687e0ef79d1b1191e7ee727f85 | 4,077 | /*
* Copyright ConsenSys AG.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods;
import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTrace;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.DebugTraceTransactionResult;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.core.Block;
import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions;
import org.hyperledger.besu.ethereum.debug.TraceOptions;
import org.hyperledger.besu.ethereum.rlp.RLP;
import org.hyperledger.besu.ethereum.rlp.RLPException;
import org.hyperledger.besu.ethereum.vm.DebugOperationTracer;
import java.util.Collection;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tuweni.bytes.Bytes;
public class DebugTraceBlock implements JsonRpcMethod {
private static final Logger LOG = LogManager.getLogger();
private final BlockTracer blockTracer;
private final BlockHeaderFunctions blockHeaderFunctions;
private final BlockchainQueries blockchain;
public DebugTraceBlock(
final BlockTracer blockTracer,
final BlockHeaderFunctions blockHeaderFunctions,
final BlockchainQueries blockchain) {
this.blockTracer = blockTracer;
this.blockHeaderFunctions = blockHeaderFunctions;
this.blockchain = blockchain;
}
@Override
public String getName() {
return RpcMethod.DEBUG_TRACE_BLOCK.getMethodName();
}
@Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
final String input = requestContext.getRequiredParameter(0, String.class);
final Block block;
try {
block = Block.readFrom(RLP.input(Bytes.fromHexString(input)), this.blockHeaderFunctions);
} catch (final RLPException e) {
LOG.debug("Failed to parse block RLP", e);
return new JsonRpcErrorResponse(
requestContext.getRequest().getId(), JsonRpcError.INVALID_PARAMS);
}
final TraceOptions traceOptions =
requestContext
.getOptionalParameter(1, TransactionTraceParams.class)
.map(TransactionTraceParams::traceOptions)
.orElse(TraceOptions.DEFAULT);
if (this.blockchain.blockByHash(block.getHeader().getParentHash()).isPresent()) {
final Collection<DebugTraceTransactionResult> results =
blockTracer
.trace(block, new DebugOperationTracer(traceOptions))
.map(BlockTrace::getTransactionTraces)
.map(DebugTraceTransactionResult::of)
.orElse(null);
return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), results);
} else {
return new JsonRpcErrorResponse(
requestContext.getRequest().getId(), JsonRpcError.PARENT_BLOCK_NOT_FOUND);
}
}
}
| 43.83871 | 118 | 0.773853 |
0410108bacabc3681333e7c9b26ce20165cbf868 | 1,483 | package Services;
import java.util.ArrayList;
/* Singleton Service for finding longest cons chain */
public class FinderService {
private static FinderService ourInstance = new FinderService();
public static FinderService getInstance() {
return ourInstance;
}
private FinderService() {
}
public static ArrayList<String> findLongestConsonantChain(final ArrayList<String> words){
for(String word: words){
if(word.matches(".*[^a-zA-Z].*")) // Not a word
throw new IllegalArgumentException("Word '" + word + "' contains not only letters.");
}
// Getting Iterable array
String[] wordsArray = new String[words.size()];
words.toArray(wordsArray);
int[] longestChain = new int[words.size()];
int maxLength = 0;
// Finding max cons chain length
for (int i = 0; i < words.size(); i++) {
longestChain[i] = CounterService.getLongestChain(wordsArray[i]);
if(longestChain[i]>maxLength)
maxLength = longestChain[i];
}
// Now maxLength value is our longest consonant chain length
ArrayList<String> maxChainArray = new ArrayList<>();
for (int i = 0; i < words.size(); i++) {
if(longestChain[i]==maxLength && !maxChainArray.contains(wordsArray[i])) // Add only unique words
maxChainArray.add(wordsArray[i]);
}
return maxChainArray;
}
}
| 30.265306 | 109 | 0.608227 |
230edec1baf57f9e056e6f9f33cb53b3edd47bc8 | 457 | package com.brandon.snake.game;
public enum Direction {
UP(0),
DOWN(1),
LEFT(2),
RIGHT(3),
NONE(4);
private int value;
private Direction(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public Direction opposite() {
switch (this) {
case UP: return DOWN;
case DOWN: return UP;
case LEFT: return RIGHT;
case RIGHT: return LEFT;
default:
throw new IllegalArgumentException(toString());
}
}
}
| 14.741935 | 50 | 0.656455 |
10ac3bb0494e41bdbd4c1c232572c8c61368b074 | 1,268 | package pl.vgtworld.imagedraw.filters.gaussianblur;
class MatrixGenerator {
float[][] createMatrix(int radius, double standardDeviation) {
if (radius < 1) {
throw new IllegalArgumentException("Radius must be greater than 0.");
}
int matrixSize = radius * 2 + 1;
float[][] matrix = new float[matrixSize][matrixSize];
populateMatrixWithValues(matrix, radius, standardDeviation);
return matrix;
}
private void populateMatrixWithValues(float[][] matrix, int radius, double standardDeviation) {
int matrixSize = matrix.length;
for (int j = 0; j < matrixSize; ++j) {
for (int i = 0; i < matrixSize; ++i) {
int xDistanceFromCenter = Math.abs(i - radius);
int yDistanceFromCenter = Math.abs(j - radius);
float value = calculateGaussianBlurCellValue(
xDistanceFromCenter,
yDistanceFromCenter,
standardDeviation
);
matrix[i][j] = value;
}
}
}
private float calculateGaussianBlurCellValue(int xDistance, int yDistance, double standardDeviation) {
double result = 1.0 / (2 * Math.PI * Math.pow(standardDeviation, 2));
double ePower = -((Math.pow(xDistance, 2) + Math.pow(yDistance, 2)) / (2 * Math.pow(standardDeviation, 2)));
result = result * Math.exp(ePower);
return (float) result;
}
}
| 32.512821 | 110 | 0.690852 |
304985f559e1ee68f2ea24f1f205459ea8a38ff5 | 2,671 | package me.dylanmullen.weightchallenge.util.config;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author Dylan
* @date 27 Sep 2021
* @project drinkersbot
* @file beer.drinkers.drinkersbot.modules.io.IOController.java
*/
public class IOManager
{
private Map<String, File> folders;
private ConfigManager configManager;
public IOManager()
{
this.folders = new HashMap<>();
init();
}
private void init()
{
loadFolders();
this.configManager = new ConfigManager(folders.get("configs"));
}
private void loadFolders()
{
loadFolder("configs", "configs");
}
private void loadFolder(String folder, String resourcePath)
{
File file = new File(folder);
if (!file.exists())
file.mkdirs();
loadFolderContents(file, resourcePath);
folders.put(folder, file);
System.out.println("[INFO] Loaded resource folder: " + folder);
}
private void loadFolderContents(File diskFolder, String folderPath)
{
JarFile jar = null;
try
{
jar = new JarFile(getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith(folderPath))
{
createFile(jar, entry, diskFolder, name.split(folderPath)[1]);
}
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (jar != null)
jar.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
private void createFile(JarFile jar, JarEntry entry, File diskFolder, String fileName)
{
File file = new File(diskFolder.getPath() + File.separator + fileName);
if (file.exists())
return;
InputStream is = null;
FileOutputStream fs = null;
try
{
file.createNewFile();
is = jar.getInputStream(entry);
fs = new FileOutputStream(file);
while (is.available() > 0)
fs.write(is.read());
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try
{
if (is != null)
is.close();
if (fs != null)
fs.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
public File getFolder(String name)
{
return folders.get(name);
}
public boolean folderExists(String name)
{
return folders.get(name) != null;
}
/**
* @return the controller
*/
public ConfigManager getConfigController()
{
return configManager;
}
}
| 18.678322 | 95 | 0.665668 |
965c449b163fe334a03e4a9ea5bc6cc139702326 | 604 | package io.mindjet.jetgear.mvvm.viewmodel.item;
import android.view.View;
import io.mindjet.jetgear.R;
import io.mindjet.jetgear.databinding.ItemLoadingBinding;
import io.mindjet.jetgear.mvvm.base.BaseViewModel;
import io.mindjet.jetgear.mvvm.viewinterface.ViewInterface;
/**
* Common loading view model.
* <p>
* Created by Mindjet on 2017/4/16.
*/
public class LoadingViewModel extends BaseViewModel<ViewInterface<ItemLoadingBinding>> {
@Override
public int getLayoutId() {
return R.layout.item_loading;
}
@Override
public void onViewAttached(View view) {
}
}
| 21.571429 | 88 | 0.743377 |
89ec9ae38fb7130171b008e202b417b99c484a66 | 5,516 | package com.interview.codingblocks.week7Greedy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class BusyMan {
private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> unsortMap ) {
List<Map.Entry<K, V>> list =
new LinkedList<>(unsortMap.entrySet());
list.sort(Comparator.comparing(o -> (o.getValue())));
Map<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}
private static void solve() throws IOException {
FastScanner scanner = new FastScanner(System.in);
int testCases = scanner.br.read();
while (testCases-- > 0) {
int numOfActivities = scanner.nextInt();
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 0; i < numOfActivities; i++) {
int key = scanner.nextInt();
int value = scanner.nextInt();
hashMap.put(key, value);
}
hashMap = sortByValue(hashMap);
System.out.println(Collections.singletonList(hashMap));
int count = 1;
Iterator<Map.Entry<Integer, Integer>> data = hashMap.entrySet().iterator();
if (data.hasNext()) {
Map.Entry<Integer, Integer> entry = data.next();
int nextActivity = entry.getValue();
while (data.hasNext()) {
if (data.hasNext())
data.next();
if (data.next().getKey() >= nextActivity) {
nextActivity = data.next().getValue();
count++;
}
}
}
System.out.println(count);
// System.out.println(Collections.singletonList(hashMap));
// int count = 1, nextActivity = mapValues.get(0);
/* int count = 1, nextActivity = activityList.get(0).endTime;
for (int i = 1; i < activityList.size(); i++) {
if (activityList.get(i).startTime >= nextActivity) {
nextActivity = activityList.get(i).endTime;
count++;
}
}*/
// System.out.println(count);
}
}
//https://www.spoj.com/problems/BUSYMAN/
//We are sorting the values according to ending time.
//Then we are checking if that ending is overlap with other's starting time or not.
public static void main( String[] args ) throws IOException {
solve();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner( InputStream stream ) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
static class Activity {
int startTime;
int endTime;
}
/*
import java.util.*;
import java.lang.*;
import java.io.*;
class Main
{
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner( InputStream stream ) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
StringProblem next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
static class Activity {
int startTime;
int endTime;
}
public static void main (StringProblem[] args) throws java.lang.Exception
{
FastScanner scanner = new FastScanner(System.in);
int testCases = scanner.nextInt();
while (testCases-- > 0){
int numOfActivities = scanner.nextInt();
List<Activity> activityList = new ArrayList<>();
for (int i = 0; i < numOfActivities; i++) {
Activity activity = new Activity();
activity.startTime = scanner.nextInt();
activity.endTime = scanner.nextInt();
activityList.add(activity);
}
activityList.sort(Comparator.comparingInt(o -> o.endTime));
int count = 1, nextActivity = activityList.get(0).endTime;
for (int i = 1; i < activityList.size(); i++) {
if (activityList.get(i).startTime >= nextActivity) {
nextActivity = activityList.get(i).endTime;
count++;
}
}
System.out.println(count);
}
}
}
*/
}
| 26.14218 | 102 | 0.506889 |
98b8606eb19233898edc0544a449b01b5787cbc3 | 1,139 | package controllers;
import models.Fachada;
import models.entity.Usuario;
import models.entity.Voluntario;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.info_usuario;
import views.html.perfil_usuario;
public class VoluntarioDetailController extends Controller{
public Result loadPage(){
String user_type = session().get("user_type");
if (user_type != null && user_type.equals("VOLUNTARIO")){
String voluntario_id = session().get("voluntario_id");
String usuario_id = session().get("user_id");
if(voluntario_id != null && usuario_id != null){
long id_voluntario = Long.parseLong(voluntario_id);
long id_usuario = Long.parseLong(usuario_id);
Voluntario voluntario = Fachada.CONTROLADOR_VOLUNTARIO.show(id_voluntario);
Usuario usuario = Fachada.CONTROLADOR_USUARIO.show(id_usuario);
return ok(info_usuario.render(voluntario, usuario));
}else{
return redirect(routes.Application.login());
}
}else{
return redirect(routes.Application.login());
}
}
public Result edit(){
// Voluntario voluntario = Fachada.CONTROLADOR_VOLUNTARIO.show(id);
return null;
}
}
| 30.783784 | 79 | 0.744513 |
b42d9edaa0989fd619b2f15d4f84ab842dd0bf6a | 1,188 | package cz.app.restauracka.demo.logika.Data;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cz.app.restauracka.demo.logika.obj.Jidlo;
import cz.app.restauracka.demo.logika.obj.MenuJidla;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Set;
@Component
public class NactiDataMenu {
private static final String SAVE_FILE_NAME = "src/main/resources/LocalData/menu.json";
@Autowired
MenuJidla menuJidla;
private final Gson gson = new Gson();
public void loadData() {
try {
List<String> lines = Files.readAllLines(Paths.get(SAVE_FILE_NAME));
String jsonRaw = String.join("\n", lines);
Type listOfPersonsType = new TypeToken<Set<Jidlo>>() {
}.getType();
menuJidla.setMenuSet(gson.fromJson(jsonRaw, listOfPersonsType));
} catch (IOException e) {
System.out.println("Error while saving data: " + e.getMessage());
}
}
}
| 29.7 | 90 | 0.701178 |
c7e2ff1e0e455f7b084284fc3d2a41dd45712659 | 2,800 | /*
* Copyright 2020-2021 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.canal.support.converter.record.header.mapper;
import com.alibaba.otter.canal.protocol.CanalEntry;
import org.springframework.canal.support.converter.record.header.CanalMessageHeaderAccessor;
import java.util.HashMap;
import java.util.Map;
/**
* @author ๆฉๅญ
* @since 2020/12/11
*/
public class DefaultCanalHeaderMapper implements CanalHeaderMapper {
@Override
public void toHeaders(CanalEntry.Header src, Map<String, Object> dest) {
dest.put(CanalMessageHeaderAccessor.G_TID, src.hasGtid() ? src.getGtid() : null);
dest.put(CanalMessageHeaderAccessor.EXECUTE_TIME, src.hasExecuteTime() ? src.getExecuteTime() : null);
dest.put(CanalMessageHeaderAccessor.EVENT_TYPE, src.hasEventType() ? src.getEventType() : null);
dest.put(CanalMessageHeaderAccessor.EVENT_LENGTH, src.hasEventLength() ? src.getEventLength() : null);
dest.put(CanalMessageHeaderAccessor.LOGFILE_NAME, src.hasLogfileName() ? src.getLogfileName() : null);
dest.put(CanalMessageHeaderAccessor.LOGFILE_OFFSET, src.hasLogfileOffset() ? src.getLogfileOffset() : null);
dest.put(CanalMessageHeaderAccessor.SOURCE_TYPE, src.hasSourceType() ? src.getSourceType() : null);
dest.put(CanalMessageHeaderAccessor.SERVER_ID, src.hasServerId() ? src.getServerId() : null);
dest.put(CanalMessageHeaderAccessor.SERVER_CODE, src.hasServerenCode() ? src.getServerenCode() : null);
dest.put(CanalMessageHeaderAccessor.SCHEMA_NAME, src.hasSchemaName() ? src.getSchemaName() : null);
dest.put(CanalMessageHeaderAccessor.TABLE_NAME, src.hasTableName() ? src.getTableName() : null);
dest.put(CanalMessageHeaderAccessor.VERSION, src.hasVersion() ? src.getVersion() : null);
Map<String, String> propertiesMap = new HashMap<>(src.getPropsCount());
for (CanalEntry.Pair pair : src.getPropsList())
propertiesMap.put(pair.getKey(), pair.getValue());
dest.put(CanalMessageHeaderAccessor.PROPERTIES, propertiesMap);
dest.put(CanalMessageHeaderAccessor.HEADER_UNKNOWN_FIELD_SET, src.getUnknownFields());
}
}
| 53.846154 | 117 | 0.728214 |
3a3215202e40d79afa3be5ca1e95d805f3df697b | 1,610 | package org.zalando.nakadi.domain;
import org.zalando.nakadi.plugin.api.authz.AuthorizationAttribute;
import org.zalando.nakadi.plugin.api.authz.AuthorizationService;
import javax.annotation.concurrent.Immutable;
import java.util.Objects;
@Immutable
public class Permission {
private final String resource;
private final AuthorizationService.Operation operation;
private final AuthorizationAttribute authorizationAttribute;
public Permission(final String resource, final AuthorizationService.Operation operation,
final AuthorizationAttribute authorizationAttribute) {
this.resource = resource;
this.operation = operation;
this.authorizationAttribute = authorizationAttribute;
}
public String getResource() {
return resource;
}
public AuthorizationService.Operation getOperation() {
return operation;
}
public AuthorizationAttribute getAuthorizationAttribute() {
return authorizationAttribute;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Permission that = (Permission) o;
return Objects.equals(resource, that.resource) &&
Objects.equals(operation, that.operation) &&
Objects.equals(authorizationAttribute, that.authorizationAttribute);
}
@Override
public int hashCode() {
return Objects.hash(resource, operation, authorizationAttribute);
}
}
| 29.814815 | 92 | 0.68323 |
228090c0687de8cfd3b6ab57f8065e9125deaea3 | 1,510 | package com.qayratsultan.quizforfun.data;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.room.Embedded;
import androidx.room.Relation;
public class UserWithAttempts implements Parcelable {
@Embedded
private User user;
@Relation(
parentColumn = "email",
entityColumn = "email",
entity = Attempt.class
)
private Attempt attempt;
public UserWithAttempts(User user, Attempt attempt) {
this.user = user;
this.attempt = attempt;
}
protected UserWithAttempts(Parcel in) {
user = in.readParcelable(User.class.getClassLoader());
attempt = in.readParcelable(Attempt.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(user, flags);
dest.writeParcelable(attempt, flags);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<UserWithAttempts> CREATOR = new Creator<UserWithAttempts>() {
@Override
public UserWithAttempts createFromParcel(Parcel in) {
return new UserWithAttempts(in);
}
@Override
public UserWithAttempts[] newArray(int size) {
return new UserWithAttempts[size];
}
};
public User getUser() {
return user;
}
public Attempt getAttempt() {
return attempt;
}
}
| 24.754098 | 94 | 0.611258 |
e8b1446dd791f60556e1f6fc9d9eda49ac3a91d6 | 1,089 | package Windows;
import CoolFeatures.WindowDynamics;
import Interfaces.FadeDelay;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Introduction extends Application {
// Load the Introduction.fxml file
@Override
public void start(Stage introStage) throws Exception{
Parent introParent = FXMLLoader.load(getClass().getResource("/SceneBuilderFXML/Introduction.fxml"));
introStage.initStyle(StageStyle.UNDECORATED); // Remove the menubar and shut down button
introStage.setScene(new Scene(introParent, 500, 200));
introStage.show();
// Close with a delay and open MainWindow
FadeDelay fadeDelay = new WindowDynamics();
fadeDelay.OpenWithDelay(3000, new MainWindow()); // Open MainWindow after 3000
fadeDelay.CloseStageWithFade(introStage, 3000);
}
@FXML
public void initialize() {
}
} | 30.25 | 109 | 0.708907 |
5695b7fcde3f1bd6d78aafa01c819c322911450f | 397 | package io.choerodon.devops.app.service;
import java.util.List;
import io.choerodon.devops.api.dto.GitlabGroupMemberDTO;
/**
* Created by Zenger on 2018/3/28.
*/
public interface GitlabGroupMemberService {
void createGitlabGroupMemberRole(List<GitlabGroupMemberDTO> gitlabGroupMemberDTOList);
void deleteGitlabGroupMemberRole(List<GitlabGroupMemberDTO> gitlabGroupMemberDTOList);
}
| 24.8125 | 90 | 0.811083 |
813acf4694e575f01ba4abacd56a35de8373084a | 927 | package org.smartregister.domain;
import org.smartregister.domain.jsonmapping.LoginResponseData;
public enum LoginResponse {
SUCCESS("Login successful."),
NO_INTERNET_CONNECTIVITY("No internet connection. Please ensure data connectivity"),
MALFORMED_URL("Incorrect url"),
UNKNOWN_RESPONSE("Dristhi login failed. Try later"),
UNAUTHORIZED("Please check the credentials"),
TIMEOUT("The server could not be reached. Try again"),
EMPTY_REPONSE("The server returned an empty response. Try Again");
private LoginResponseData payload;
private String message;
LoginResponse(String message) {
this.message = message;
}
public String message() {
return message;
}
public LoginResponseData payload() {
return payload;
}
public LoginResponse withPayload(LoginResponseData payload) {
this.payload = payload;
return this;
}
}
| 27.264706 | 88 | 0.703344 |
d44d9e6cc53ffe0066336dd1f4a43389f8fd5937 | 3,317 | package org.bndly.common.app.provisioning.model;
/*-
* #%L
* App Provisioning
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.bndly.common.json.api.ConversionContext;
import org.bndly.common.json.api.ConversionContextBuilder;
import org.bndly.common.json.model.JSArray;
import org.bndly.common.json.model.JSBoolean;
import org.bndly.common.json.model.JSMember;
import org.bndly.common.json.model.JSNull;
import org.bndly.common.json.model.JSNumber;
import org.bndly.common.json.model.JSObject;
import org.bndly.common.json.model.JSString;
import org.bndly.common.json.model.JSValue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author cybercon <[email protected]>
*/
public class Config {
private final String name;
private final Map<String, Object> properties;
Config(String configName, JSObject properties) {
Set<JSMember> members = properties.getMembers();
if (members != null && !members.isEmpty()) {
Map<String, Object> tmp = new LinkedHashMap<>();
for (JSMember member : members) {
String propertyName = member.getName().getValue();
JSValue val = member.getValue();
Object valJava = convert(val);
tmp.put(propertyName, valJava);
}
this.properties = Collections.unmodifiableMap(tmp);
} else {
this.properties = Collections.EMPTY_MAP;
}
this.name = configName;
}
public JSValue toJsValue() {
ConversionContext context = new ConversionContextBuilder().initDefaults().build();
final JSObject jsObject = new JSObject();
for (Map.Entry<String, Object> entry : properties.entrySet()) {
Object val = entry.getValue();
if (val == null) {
jsObject.createMember(entry.getKey()).setValue(JSNull.INSTANCE);
} else {
jsObject.createMember(entry.getKey()).setValue(context.serialize(val.getClass(), val));
}
}
return jsObject;
}
public String getName() {
return name;
}
public Map<String, Object> getProperties() {
return properties;
}
private Object convert(JSValue val) {
if (JSArray.class.isInstance(val)) {
List<Object> converted = new ArrayList<>();
JSArray arr = (JSArray) val;
for (JSValue arrayItem : arr) {
converted.add(convert(arrayItem));
}
return converted.toArray();
} else if (JSString.class.isInstance(val)) {
return ((JSString) val).getValue();
} else if (JSNull.class.isInstance(val)) {
return null;
} else if (JSNumber.class.isInstance(val)) {
return ((JSNumber) val).getValue();
} else if (JSBoolean.class.isInstance(val)) {
return ((JSBoolean) val).isValue();
} else {
throw new IllegalArgumentException("unsupported value: " + val);
}
}
}
| 30.154545 | 91 | 0.713295 |
62d8828701d5fafbb374fa6e685f138ea25ab885 | 7,740 | package com.hubspot.jinjava.lib.tag.eager;
import com.google.common.collect.ImmutableMap;
import com.hubspot.jinjava.el.ext.ExtendedParser;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.interpret.TemplateSyntaxException;
import com.hubspot.jinjava.lib.tag.CycleTag;
import com.hubspot.jinjava.tree.parse.TagToken;
import com.hubspot.jinjava.util.EagerExpressionResolver;
import com.hubspot.jinjava.util.EagerReconstructionUtils;
import com.hubspot.jinjava.util.HelperStringTokenizer;
import com.hubspot.jinjava.util.WhitespaceUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class EagerCycleTag extends EagerStateChangingTag<CycleTag> {
public EagerCycleTag() {
super(new CycleTag());
}
public EagerCycleTag(CycleTag cycleTag) {
super(cycleTag);
}
@SuppressWarnings("unchecked")
@Override
public String getEagerTagImage(TagToken tagToken, JinjavaInterpreter interpreter) {
HelperStringTokenizer tk = new HelperStringTokenizer(tagToken.getHelpers());
List<String> helper = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (String token : tk.allTokens()) {
sb.append(token);
if (!token.endsWith(",")) {
helper.add(sb.toString());
sb = new StringBuilder();
}
}
if (sb.length() > 0) {
helper.add(sb.toString());
}
String expression = '[' + helper.get(0) + ']';
EagerExecutionResult eagerExecutionResult = EagerReconstructionUtils.executeInChildContext(
eagerInterpreter ->
EagerExpressionResolver.resolveExpression(expression, interpreter),
interpreter,
true,
false,
interpreter.getContext().isDeferredExecutionMode()
);
StringBuilder prefixToPreserveState = new StringBuilder();
if (interpreter.getContext().isDeferredExecutionMode()) {
prefixToPreserveState.append(eagerExecutionResult.getPrefixToPreserveState());
} else {
interpreter.getContext().putAll(eagerExecutionResult.getSpeculativeBindings());
}
String resolvedExpression;
List<String> resolvedValues; // can only be retrieved if the EagerExpressionResult are fully resolved.
if (
eagerExecutionResult
.getResult()
.toString()
.equals(EagerExpressionResolver.JINJAVA_EMPTY_STRING)
) {
resolvedExpression = normalizeResolvedExpression(expression); // Cycle tag defaults to input on null
resolvedValues =
new HelperStringTokenizer(resolvedExpression).splitComma(true).allTokens();
} else {
resolvedExpression =
normalizeResolvedExpression(eagerExecutionResult.getResult().toString());
if (!eagerExecutionResult.getResult().isFullyResolved()) {
resolvedValues =
new HelperStringTokenizer(resolvedExpression).splitComma(true).allTokens();
prefixToPreserveState.append(
EagerReconstructionUtils.reconstructFromContextBeforeDeferring(
eagerExecutionResult.getResult().getDeferredWords(),
interpreter
)
);
} else {
List<?> objects = eagerExecutionResult.getResult().toList();
if (objects.size() == 1 && objects.get(0) instanceof List) {
// because we may have wrapped in an extra set of brackets
objects = (List<?>) objects.get(0);
}
resolvedValues =
objects.stream().map(interpreter::getAsString).collect(Collectors.toList());
for (int i = 0; i < resolvedValues.size(); i++) {
resolvedValues.set(
i,
interpreter.resolveString(
resolvedValues.get(i),
tagToken.getLineNumber(),
tagToken.getStartPosition()
)
);
}
}
}
if (helper.size() == 1) {
// The helpers get printed out
return (
prefixToPreserveState.toString() +
interpretPrintingCycle(
tagToken,
interpreter,
resolvedValues,
resolvedExpression,
eagerExecutionResult.getResult().isFullyResolved()
)
);
} else if (helper.size() == 3) {
// The helpers get set to a new variable
return (
prefixToPreserveState.toString() +
interpretSettingCycle(
interpreter,
resolvedValues,
helper,
resolvedExpression,
eagerExecutionResult.getResult().isFullyResolved()
)
);
} else {
throw new TemplateSyntaxException(
tagToken.getImage(),
"Tag 'cycle' expects 1 or 3 helper(s), was: " + helper.size(),
tagToken.getLineNumber(),
tagToken.getStartPosition()
);
}
}
private String normalizeResolvedExpression(String resolvedExpression) {
resolvedExpression = resolvedExpression.replace(", ", ",");
resolvedExpression = resolvedExpression.substring(1, resolvedExpression.length() - 1);
if (WhitespaceUtils.isWrappedWith(resolvedExpression, "[", "]")) {
resolvedExpression =
resolvedExpression.substring(1, resolvedExpression.length() - 1);
}
return resolvedExpression;
}
private String interpretSettingCycle(
JinjavaInterpreter interpreter,
List<String> values,
List<String> helper,
String resolvedExpression,
boolean fullyResolved
) {
String var = helper.get(2);
if (!fullyResolved) {
return EagerReconstructionUtils.buildSetTag(
ImmutableMap.of(
var,
String.format("[%s]", resolvedExpression.replace(",", ", "))
),
interpreter,
true
);
}
interpreter.getContext().put(var, values);
return "";
}
private String interpretPrintingCycle(
TagToken tagToken,
JinjavaInterpreter interpreter,
List<String> values,
String resolvedExpression,
boolean fullyResolved
) {
if (interpreter.getContext().isDeferredExecutionMode()) {
return reconstructCycleTag(resolvedExpression, tagToken);
}
Integer forindex = (Integer) interpreter.retraceVariable(
CycleTag.LOOP_INDEX,
tagToken.getLineNumber(),
tagToken.getStartPosition()
);
if (forindex == null) {
forindex = 0;
}
if (values.size() == 1) {
String var = values.get(0);
if (!fullyResolved) {
return getIsIterable(var, forindex, tagToken);
} else {
return var;
}
}
String item = values.get(forindex % values.size());
if (!fullyResolved && EagerExpressionResolver.shouldBeEvaluated(item, interpreter)) {
return String.format("{{ %s }}", values.get(forindex % values.size()));
}
return item;
}
private String reconstructCycleTag(String expression, TagToken tagToken) {
return String.format(
"%s cycle %s %s",
tagToken.getSymbols().getExpressionStartWithTag(),
expression,
tagToken.getSymbols().getExpressionEndWithTag()
);
}
private static String getIsIterable(String var, int forIndex, TagToken tagToken) {
String tokenStart = tagToken.getSymbols().getExpressionStartWithTag();
String tokenEnd = tagToken.getSymbols().getExpressionEndWithTag();
return (
String.format(
"%s if exptest:iterable.evaluate(%s, %s) %s",
tokenStart,
var,
ExtendedParser.INTERPRETER,
tokenEnd
) +
// modulo indexing
String.format(
"{{ %s[%d %% filter:length.filter(%s, %s)] }}",
var,
forIndex,
var,
ExtendedParser.INTERPRETER
) +
String.format("%s else %s", tokenStart, tokenEnd) +
String.format("{{ %s }}", var) +
String.format("%s endif %s", tokenStart, tokenEnd)
);
}
}
| 32.79661 | 106 | 0.652972 |
4ede8fbbbe07719e1edd91bb16c1601c5d5d1bd9 | 2,423 | /*
* 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.yarn.submarine.runtimes.yarnservice.command;
import org.apache.hadoop.yarn.service.api.records.Component;
import org.apache.hadoop.yarn.submarine.client.cli.param.runjob.RunJobParameters;
import org.apache.hadoop.yarn.submarine.runtimes.yarnservice.HadoopEnvironmentSetup;
import java.io.IOException;
/**
* Abstract base class for Launch command implementations for Services.
* Currently we have launch command implementations
* for TensorFlow PS, worker and Tensorboard instances.
*/
public abstract class AbstractLaunchCommand {
private final LaunchScriptBuilder builder;
public AbstractLaunchCommand(HadoopEnvironmentSetup hadoopEnvSetup,
Component component, RunJobParameters parameters,
String launchCommandPrefix) throws IOException {
this.builder = new LaunchScriptBuilder(launchCommandPrefix, hadoopEnvSetup,
parameters, component);
}
protected LaunchScriptBuilder getBuilder() {
return builder;
}
/**
* Subclasses need to defined this method and return a valid launch script.
* Implementors can utilize the {@link LaunchScriptBuilder} using
* the getBuilder method of this class.
* @return The contents of a script.
* @throws IOException If any IO issue happens.
*/
public abstract String generateLaunchScript() throws IOException;
/**
* Subclasses need to provide a service-specific launch command
* of the service.
* Please note that this method should only return the launch command
* but not the whole script.
* @return The launch command
*/
public abstract String createLaunchCommand();
}
| 39.080645 | 84 | 0.767231 |
f2cdfe653b495e34129251f72bd4a730ba35059d | 928 | package com.kamron.drx.service;
import com.kamron.drx.model.Delivery;
import com.kamron.drx.repository.DeliveryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* The type Delivery service.
*
* @author Kamron Sultanov
* @date July 18, 2020
*/
@Service
public class DeliveryServiceImpl implements DeliveryService {
private final DeliveryRepository deliveryRepository;
/**
* Instantiates a new Delivery service.
*
* @param deliveryRepository the delivery repository
*/
@Autowired
public DeliveryServiceImpl(DeliveryRepository deliveryRepository) {
this.deliveryRepository = deliveryRepository;
}
/**
* Finds all Deliveries.
*
* @return Deliveries
*/
@Override
public Iterable<Delivery> findAllDeliveryTypes() {
return deliveryRepository.findAll();
}
}
| 23.794872 | 71 | 0.716595 |
24a001a313097e815b24ece7834dabae9b738f11 | 19,722 | /*
* Copyright 2014 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.roaster.model.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ServiceLoader;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;
import org.jboss.forge.roaster.ParserException;
import org.jboss.forge.roaster.model.Annotation;
import org.jboss.forge.roaster.model.JavaType;
import org.jboss.forge.roaster.model.SyntaxError;
import org.jboss.forge.roaster.model.Type;
import org.jboss.forge.roaster.model.Visibility;
import org.jboss.forge.roaster.model.ast.AnnotationAccessor;
import org.jboss.forge.roaster.model.ast.ModifierAccessor;
import org.jboss.forge.roaster.model.source.AnnotationSource;
import org.jboss.forge.roaster.model.source.Import;
import org.jboss.forge.roaster.model.source.JavaDocSource;
import org.jboss.forge.roaster.model.source.JavaPackageInfoSource;
import org.jboss.forge.roaster.model.source.JavaSource;
import org.jboss.forge.roaster.model.util.Formatter;
import org.jboss.forge.roaster.model.util.Strings;
import org.jboss.forge.roaster.model.util.Types;
import org.jboss.forge.roaster.spi.WildcardImportResolver;
public class JavaPackageInfoImpl implements JavaPackageInfoSource
{
protected final Document document;
protected final CompilationUnit unit;
protected final PackageDeclaration pkg;
protected final JavaSource<?> enclosingType;
private final AnnotationAccessor<JavaPackageInfoSource, JavaPackageInfoSource> annotations = new AnnotationAccessor<JavaPackageInfoSource, JavaPackageInfoSource>();
private final ModifierAccessor modifiers = new ModifierAccessor();
private static List<WildcardImportResolver> resolvers;
public JavaPackageInfoImpl(JavaSource<?> enclosingType, Document document,
CompilationUnit unit, PackageDeclaration pkg)
{
this.enclosingType = enclosingType == null ? this : enclosingType;
this.document = document;
this.unit = unit;
this.pkg = pkg;
}
@Override
public String getName()
{
return "package-info";
}
@Override
public JavaSource<?> getEnclosingType()
{
return enclosingType;
}
/*
* Annotation modifiers
*/
@Override
public AnnotationSource<JavaPackageInfoSource> addAnnotation()
{
return annotations.addAnnotation(this, getPackageDeclaration());
}
@Override
public AnnotationSource<JavaPackageInfoSource> addAnnotation(
final Class<? extends java.lang.annotation.Annotation> clazz)
{
return annotations.addAnnotation(this, getPackageDeclaration(), clazz.getName());
}
@Override
public AnnotationSource<JavaPackageInfoSource> addAnnotation(final String className)
{
return annotations.addAnnotation(this, getPackageDeclaration(), className);
}
@Override
public List<AnnotationSource<JavaPackageInfoSource>> getAnnotations()
{
return annotations.getAnnotations(this, getPackageDeclaration());
}
@Override
public boolean hasAnnotation(final Class<? extends java.lang.annotation.Annotation> type)
{
return annotations.hasAnnotation(this, getPackageDeclaration(), type.getName());
}
@Override
public boolean hasAnnotation(final String type)
{
return annotations.hasAnnotation(this, getPackageDeclaration(), type);
}
@Override
public JavaPackageInfoSource removeAnnotation(final Annotation<JavaPackageInfoSource> annotation)
{
return annotations.removeAnnotation(this, getPackageDeclaration(), annotation);
}
@Override
public void removeAllAnnotations()
{
annotations.removeAllAnnotations(getPackageDeclaration());
}
@Override
public AnnotationSource<JavaPackageInfoSource> getAnnotation(
final Class<? extends java.lang.annotation.Annotation> type)
{
return annotations.getAnnotation(this, getPackageDeclaration(), type);
}
@Override
public AnnotationSource<JavaPackageInfoSource> getAnnotation(final String type)
{
return annotations.getAnnotation(this, getPackageDeclaration(), type);
}
/*
* Import modifiers
*/
@Override
public Import addImport(final Class<?> type)
{
return addImport(type.getCanonicalName());
}
@Override
public <T extends JavaType<?>> Import addImport(final T type)
{
String qualifiedName = type.getQualifiedName();
return this.addImport(qualifiedName);
}
@Override
public Import addImport(final Import imprt)
{
return addImport(imprt.getQualifiedName()).setStatic(imprt.isStatic());
}
@Override
@SuppressWarnings("unchecked")
public Import addImport(final String className)
{
String strippedClassName = Types.stripGenerics(Types.stripArray(className));
Import imprt;
if (Types.isSimpleName(strippedClassName) && !hasImport(strippedClassName))
{
throw new IllegalArgumentException("Cannot import class without a package [" + strippedClassName + "]");
}
if (!hasImport(strippedClassName) && validImport(strippedClassName))
{
imprt = new ImportImpl(this).setName(strippedClassName);
unit.imports().add(imprt.getInternal());
}
else if (hasImport(strippedClassName))
{
imprt = getImport(strippedClassName);
}
else
{
throw new IllegalArgumentException("Attempted to import the illegal type [" + strippedClassName + "]");
}
return imprt;
}
@Override
public Import getImport(final String className)
{
List<Import> imports = getImports();
for (Import imprt : imports)
{
if (imprt.getQualifiedName().equals(className) || imprt.getSimpleName().equals(className))
{
return imprt;
}
}
return null;
}
@Override
public Import getImport(final Class<?> type)
{
return getImport(type.getName());
}
@Override
public <T extends JavaType<?>> Import getImport(final T type)
{
return getImport(type.getQualifiedName());
}
@Override
public Import getImport(final Import imprt)
{
return getImport(imprt.getQualifiedName());
}
@Override
@SuppressWarnings("unchecked")
public List<Import> getImports()
{
List<Import> results = new ArrayList<Import>();
for (ImportDeclaration i : (List<ImportDeclaration>) unit.imports())
{
results.add(new ImportImpl(this, i));
}
return Collections.unmodifiableList(results);
}
@Override
public boolean hasImport(final Class<?> type)
{
return hasImport(type.getName());
}
@Override
public <T extends JavaType<T>> boolean hasImport(final T type)
{
return hasImport(type.getQualifiedName());
}
@Override
public boolean hasImport(final Import imprt)
{
return hasImport(imprt.getQualifiedName());
}
@Override
public boolean hasImport(final String type)
{
String resultType = type;
if (Types.isArray(type))
{
resultType = Types.stripArray(type);
}
if (Types.isGeneric(type))
{
resultType = Types.stripGenerics(type);
}
return getImport(resultType) != null;
}
@Override
public boolean requiresImport(final Class<?> type)
{
return requiresImport(type.getName());
}
@Override
public boolean requiresImport(final String type)
{
String resultType = type;
if (Types.isArray(resultType))
{
resultType = Types.stripArray(type);
}
if (Types.isGeneric(resultType))
{
resultType = Types.stripGenerics(resultType);
}
return !(!validImport(resultType)
|| hasImport(resultType)
|| Types.isJavaLang(resultType));
}
@Override
public String resolveType(final String type)
{
String original = type;
String result = type;
// Strip away any characters that might hinder the type matching process
if (Types.isArray(result))
{
original = Types.stripArray(result);
result = Types.stripArray(result);
}
if (Types.isGeneric(result))
{
original = Types.stripGenerics(result);
result = Types.stripGenerics(result);
}
if (Types.isPrimitive(result))
{
return result;
}
// Check for direct import matches first since they are the fastest and least work-intensive
if (Types.isSimpleName(result))
{
if (!hasImport(type) && Types.isJavaLang(type))
{
result = "java.lang." + result;
}
if (result.equals(original))
{
for (Import imprt : getImports())
{
if (Types.areEquivalent(result, imprt.getQualifiedName()))
{
result = imprt.getQualifiedName();
break;
}
}
}
}
// If we didn't match any imports directly, we might have a wild-card/on-demand import.
if (Types.isSimpleName(result))
{
for (Import imprt : getImports())
{
if (imprt.isWildcard())
{
// TODO warn if no wild-card resolvers are configured
// TODO Test wild-card/on-demand import resolving
for (WildcardImportResolver r : getImportResolvers())
{
result = r.resolve(this, result);
if (Types.isQualified(result))
break;
}
}
}
}
// No import matches and no wild-card/on-demand import matches means this class is in the same package.
if (Types.isSimpleName(result))
{
if (getPackage() != null)
result = getPackage() + "." + result;
}
return result;
}
private List<WildcardImportResolver> getImportResolvers()
{
if (resolvers == null)
{
resolvers = new ArrayList<WildcardImportResolver>();
for (WildcardImportResolver r : ServiceLoader.load(WildcardImportResolver.class, getClass().getClassLoader()))
{
resolvers.add(r);
}
}
if (resolvers.size() == 0)
{
throw new IllegalStateException("No instances of [" + WildcardImportResolver.class.getName()
+ "] were found on the classpath.");
}
return resolvers;
}
private boolean validImport(final String type)
{
return !Strings.isNullOrEmpty(type) && !Types.isPrimitive(type);
}
@Override
public JavaPackageInfoSource removeImport(final String name)
{
for (Import i : getImports())
{
if (i.getQualifiedName().equals(name))
{
removeImport(i);
break;
}
}
return this;
}
@Override
public JavaPackageInfoSource removeImport(final Class<?> clazz)
{
return removeImport(clazz.getName());
}
@Override
public <T extends JavaType<?>> JavaPackageInfoSource removeImport(final T type)
{
return removeImport(type.getQualifiedName());
}
@Override
public JavaPackageInfoSource removeImport(final Import imprt)
{
Object internal = imprt.getInternal();
if (unit.imports().contains(internal))
{
unit.imports().remove(internal);
}
return this;
}
protected PackageDeclaration getPackageDeclaration()
{
if (pkg instanceof PackageDeclaration)
return pkg;
throw new ParserException("Source body was not of the expected type (PackageDeclaration).");
}
@Override
public JavaPackageInfoSource setName(final String name)
{
throw new UnsupportedOperationException("Changing name of [" + getQualifiedName() + "] not supported.");
}
@Override
public String getCanonicalName()
{
String result = getName();
JavaType<?> enclosingTypeLocal = this;
while (enclosingTypeLocal != enclosingTypeLocal.getEnclosingType())
{
enclosingTypeLocal = getEnclosingType();
result = enclosingTypeLocal.getEnclosingType().getName() + "." + result;
enclosingTypeLocal = enclosingTypeLocal.getEnclosingType();
}
if (!Strings.isNullOrEmpty(getPackage()))
result = getPackage() + "." + result;
return result;
}
@Override
public String getQualifiedName()
{
String result = getName();
JavaType<?> enclosingTypeLocal = this;
while (enclosingTypeLocal != enclosingTypeLocal.getEnclosingType())
{
enclosingTypeLocal = getEnclosingType();
result = enclosingTypeLocal.getEnclosingType().getName() + "$" + result;
enclosingTypeLocal = enclosingTypeLocal.getEnclosingType();
}
if (!Strings.isNullOrEmpty(getPackage()))
result = getPackage() + "." + result;
return result;
}
/*
* Package modifiers
*/
@Override
public String getPackage()
{
PackageDeclaration pkgLocal = unit.getPackage();
if (pkgLocal != null)
{
return pkgLocal.getName().getFullyQualifiedName();
}
else
{
return null;
}
}
@Override
public JavaPackageInfoSource setPackage(final String name)
{
if (unit.getPackage() == null)
{
unit.setPackage(unit.getAST().newPackageDeclaration());
}
unit.getPackage().setName(unit.getAST().newName(name));
return this;
}
@Override
public JavaPackageInfoSource setDefaultPackage()
{
unit.setPackage(null);
return this;
}
@Override
public boolean isDefaultPackage()
{
return unit.getPackage() == null;
}
/*
* Visibility modifiers
*/
@Override
public boolean isPackagePrivate()
{
return !isPublic() && !isPrivate() && !isProtected();
}
@Override
public JavaPackageInfoSource setPackagePrivate()
{
modifiers.clearVisibility(getPackageDeclaration());
return this;
}
@Override
public boolean isPublic()
{
return modifiers.hasModifier(getPackageDeclaration(), ModifierKeyword.PUBLIC_KEYWORD);
}
@Override
public JavaPackageInfoSource setPublic()
{
modifiers.clearVisibility(getPackageDeclaration());
modifiers.addModifier(getPackageDeclaration(), ModifierKeyword.PUBLIC_KEYWORD);
return this;
}
@Override
public boolean isPrivate()
{
return modifiers.hasModifier(getPackageDeclaration(), ModifierKeyword.PRIVATE_KEYWORD);
}
@Override
public JavaPackageInfoSource setPrivate()
{
modifiers.clearVisibility(getPackageDeclaration());
modifiers.addModifier(getPackageDeclaration(), ModifierKeyword.PRIVATE_KEYWORD);
return this;
}
@Override
public boolean isProtected()
{
return modifiers.hasModifier(getPackageDeclaration(), ModifierKeyword.PROTECTED_KEYWORD);
}
@Override
public JavaPackageInfoSource setProtected()
{
modifiers.clearVisibility(getPackageDeclaration());
modifiers.addModifier(getPackageDeclaration(), ModifierKeyword.PROTECTED_KEYWORD);
return this;
}
@Override
public Visibility getVisibility()
{
return Visibility.getFrom(this);
}
@Override
public JavaPackageInfoSource setVisibility(final Visibility scope)
{
return Visibility.set(this, scope);
}
/*
* Non-manipulation methods.
*/
/**
* Return this {@link JavaType} file as a String
*/
@Override
public String toString()
{
return Formatter.format(toUnformattedString());
}
@Override
public String toUnformattedString()
{
Document documentLocal = new Document(this.document.get());
try
{
TextEdit edit = unit.rewrite(documentLocal, null);
edit.apply(documentLocal);
}
catch (Exception e)
{
throw new ParserException("Could not modify source: " + unit.toString(), e);
}
return documentLocal.get();
}
@Override
public Object getInternal()
{
return unit;
}
@Override
public JavaPackageInfoSource getOrigin()
{
return this;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((pkg == null) ? 0 : pkg.hashCode());
result = prime * result + ((document == null) ? 0 : document.hashCode());
result = prime * result + ((enclosingType == null) ? 0 : enclosingType.hashCode());
result = prime * result + ((unit == null) ? 0 : unit.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JavaPackageInfoImpl other = (JavaPackageInfoImpl) obj;
if (pkg == null)
{
if (other.pkg != null)
return false;
}
else if (!pkg.equals(other.pkg))
return false;
if (document == null)
{
if (other.document != null)
return false;
}
else if (!document.equals(other.document))
return false;
if (enclosingType == null)
{
if (other.enclosingType != null)
return false;
}
else if (!enclosingType.equals(other.enclosingType))
return false;
if (unit == null)
{
if (other.unit != null)
return false;
}
else if (!unit.equals(other.unit))
return false;
return true;
}
@Override
public List<SyntaxError> getSyntaxErrors()
{
List<SyntaxError> result = new ArrayList<SyntaxError>();
IProblem[] problems = unit.getProblems();
if (problems != null)
{
for (IProblem problem : problems)
{
result.add(new SyntaxErrorImpl(this, problem));
}
}
return result;
}
@Override
public boolean hasSyntaxErrors()
{
return !getSyntaxErrors().isEmpty();
}
@Override
public boolean isClass()
{
return false;
}
@Override
public boolean isEnum()
{
return false;
}
@Override
public boolean isInterface()
{
return false;
}
@Override
public boolean isAnnotation()
{
return false;
}
@Override
public Import addImport(Type<?> type)
{
return addImport(type.getQualifiedName());
}
@Override
public JavaDocSource<JavaPackageInfoSource> getJavaDoc()
{
Javadoc javadoc = pkg.getJavadoc();
if (javadoc == null)
{
javadoc = pkg.getAST().newJavadoc();
pkg.setJavadoc(javadoc);
}
return new JavaDocImpl<JavaPackageInfoSource>(this, javadoc);
}
@Override
public JavaPackageInfoSource removeJavaDoc()
{
pkg.setJavadoc(null);
return this;
}
@Override
public boolean hasJavaDoc()
{
return pkg.getJavadoc() != null;
}
public CompilationUnit getUnit()
{
return unit;
}
public PackageDeclaration getPkg()
{
return pkg;
}
} | 25.713168 | 167 | 0.63954 |
dd4bda67a9ae1634858ecfafc68dc102bcd3080f | 777 | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.aws.greengrass.util.platforms;
import com.aws.greengrass.testcommons.testutilities.GGExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.is;
@ExtendWith({GGExtension.class})
class WindowsPlatformTest {
@Test
void GIVEN_command_WHEN_decorate_THEN_is_decorated() {
assertThat(new WindowsPlatform.CmdDecorator()
.decorate("echo", "hello"),
is(arrayContaining("cmd.exe", "/C", "echo", "hello")));
}
}
| 29.884615 | 71 | 0.725869 |
192ce322a00ae0308fae22315b486428f0894cd8 | 214 | package ru.kontur.vostok.hercules.partitioner;
import ru.kontur.vostok.hercules.protocol.Event;
/**
* @author Gregory Koshelev
*/
public interface Hasher {
int hash(Event event, ShardingKey shardingKey);
}
| 19.454545 | 51 | 0.757009 |
e811def40fdeb4e972fc497551c735ae7174bfdf | 2,265 | package info.bfly.pay.bean.order;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
/**
* 3.15ๅๅปบๆน้ไปฃไปๅฐๆ็ฐๅกไบคๆ on 2017/2/17 0017.
*/
public class CreateBatchHostingPayToCardTradeSinaEntity extends OrderSinaEntity implements Serializable {
private static final long serialVersionUID = 1579613108970386312L;
/**
* ๆฏไป่ฏทๆฑๅท
*/
@NotNull
private String out_pay_no;
/**
* ไบคๆ็
*/
@NotNull
private String out_trade_code;
/**
* ไบคๆๅ่กจ
*/
@NotNull
private String trade_list;
/**
* ้็ฅๆนๅผ
*/
@NotNull
private String notify_method;
/**
* ๅฐ่ดฆ็ฑปๅ
*/
private String payto_type;
/**
* ็จๆทIPๅฐๅ
*/
@NotNull
private String user_ip;
public String getOut_pay_no() {
return out_pay_no;
}
public void setOut_pay_no(String out_pay_no) {
this.out_pay_no = out_pay_no;
}
public String getOut_trade_code() {
return out_trade_code;
}
public void setOut_trade_code(String out_trade_code) {
this.out_trade_code = out_trade_code;
}
public String getTrade_list() {
return trade_list;
}
public void setTrade_list(String trade_list) {
this.trade_list = trade_list;
}
public String getNotify_method() {
return notify_method;
}
public void setNotify_method(String notify_method) {
this.notify_method = notify_method;
}
public String getPayto_type() {
return payto_type;
}
public void setPayto_type(String payto_type) {
this.payto_type = payto_type;
}
public String getUser_ip() {
return user_ip;
}
public void setUser_ip(String user_ip) {
this.user_ip = user_ip;
}
@Override
public String toString() {
return "CreateBatchHostingPayToCardTradeSinaEntity{" +
"out_pay_no='" + out_pay_no + '\'' +
", out_trade_code='" + out_trade_code + '\'' +
", trade_list=" + trade_list +
", notify_method='" + notify_method + '\'' +
", payto_type='" + payto_type + '\'' +
", user_ip='" + user_ip + '\'' +
"} " + super.toString();
}
}
| 22.425743 | 105 | 0.592053 |
07ed757138bb61d193a3dee10d7a28ee6985d4f2 | 5,996 | package ltd.beihu.core.web.boot.http;
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;
public class HttpLogInterceptor implements Interceptor {
private static final Logger logger = LoggerFactory.getLogger(HttpLogInterceptor.class);
private static final String T_HEAD = "โ ";
private static final String F_BREAK = " %n";
private static final String F_URL = " %s";
private static final String F_TIME = T_HEAD + "Elapsed Time: %.1fms";
private static final String F_HEADERS = T_HEAD + "Headers: %s";
private static final String F_RESPONSE = "Response: %d";
private static final String F_BODY = "Body: %s";
private static final String U_BREAKER = F_BREAK + "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ" + F_BREAK + T_HEAD;
private static final String D_BREAKER = "โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ" + F_BREAK;
private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_BREAK + F_TIME + F_BREAK + F_HEADERS + F_BREAK + T_HEAD;
private static final String F_REQUEST_WITH_BODY = F_URL + F_BREAK + F_TIME + F_BREAK + F_HEADERS + F_BREAK + T_HEAD + F_BODY + F_BREAK;
private static final String F_RESPONSE_WITH_BODY = T_HEAD + F_BREAK + T_HEAD + F_RESPONSE + F_BREAK + F_HEADERS + F_BODY + F_BREAK + D_BREAKER;
private static String slimString(String source) {
int end = source.length() >= 1000 ? 1000 : source.length();
return source.substring(0, end).concat(" ใใใใใใ [ log print char max length = 1000 ] ");
}
private static void processeLog(Request request, double elapsedTime, Response response, String content) {
if (request.method().equals("GET")) {
logger.info(String.format(U_BREAKER + "GET: " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), elapsedTime, ConverterHeaders(request.headers().toString()), response.code(), ConverterHeaders(response.headers().toString()), content));
} else {
logger.info(String.format(U_BREAKER + request.method() + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url().toString(), elapsedTime, ConverterHeaders(request.headers().toString()), stringifyRequestBody(request), response.code(), ConverterHeaders(response.headers().toString()), content));
}
}
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.nanoTime();
Response response = chain.proceed(request);
double elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
String content = "";
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
//todo:!check,how it works
bodyEncoded(request.headers());
} catch (UnsupportedCharsetException e) {
content = "Couldn't decode the response body; charset is likely malformed.";
processeLog(request, elapsedTime, response, slimString(content));
return response;
}
}
if (!isPlaintext(buffer)) {
content = "HTTP (binary " + buffer.size() + "-byte body omitted)";
processeLog(request, elapsedTime, response, slimString(content));
return response;
}
if (contentLength != 0) {
// ไฝฟ็จๅคๅถBuffer็ๆนๅผ
// content = buffer.clone().readString(charset);
//้ๆResponse็ๆนๅผ
content = responseBody.string();
response = response.newBuilder()
.body(ResponseBody.create(contentType, content))
.build();
}
processeLog(request, elapsedTime, response, slimString(content));
return response;
}
private static String ConverterHeaders(String str) {
return StringUtils.replace(str, "\n", "\n" + T_HEAD);
}
private static boolean isPlaintext(Buffer buffer) {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
private static String stringifyRequestBody(Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
RequestBody requestBody = copy.body();
if (requestBody != null) {
requestBody.writeTo(buffer);
return buffer.readUtf8();
} else {
return "";
}
} catch (final IOException e) {
return "IOException! Cannot format requestBody";
}
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}
}
| 40.789116 | 307 | 0.61024 |
6c2212110b7f5e62959c354d737e0e37427e67ab | 4,144 | package com.atguigu.gulimall.pms.service.impl;
import com.atguigu.gulimall.pms.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.pms.dao.AttrDao;
import com.atguigu.gulimall.pms.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.pms.entity.AttrEntity;
import com.atguigu.gulimall.pms.entity.CategoryEntity;
import com.atguigu.gulimall.pms.vo.AttrGroupWithAttrsVo;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.commons.bean.PageVo;
import com.atguigu.gulimall.commons.bean.Query;
import com.atguigu.gulimall.commons.bean.QueryCondition;
import com.atguigu.gulimall.pms.dao.AttrGroupDao;
import com.atguigu.gulimall.pms.entity.AttrGroupEntity;
import com.atguigu.gulimall.pms.service.AttrGroupService;
@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
@Autowired
AttrGroupDao attrGroupDao;
@Autowired
AttrAttrgroupRelationDao relationDao;
@Autowired
AttrDao attrDao;
@Override
public PageVo queryPage(QueryCondition params) {
IPage<AttrGroupEntity> page = this.page(
new Query<AttrGroupEntity>().getPage(params),
new QueryWrapper<AttrGroupEntity>()
);
return new PageVo(page);
}
@Override
public PageVo queryPageAttrGroupsByCatId(QueryCondition queryCondition, Long catId) {
//1ใ่ทๅๅฐ่ฃ
็ๅ้กตๆกไปถ
IPage<AttrGroupEntity> page = new Query<AttrGroupEntity>().getPage(queryCondition);
//2ใ่ทๅๆฅ่ฏขๆกไปถ
QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<AttrGroupEntity>()
.eq("catelog_id", catId);
IPage<AttrGroupEntity> data = this.page(page, wrapper);
//ๆฅๅบ็ๆๆๅ็ป 3
List<AttrGroupEntity> records = data.getRecords();
//ๅฐ่ฆ่ฟๅๅบๅป็ๅธฆๅ็ปไฟกๆฏไปฅๅไป็ๅฑๆงไฟกๆฏ็ๅฏน่ฑก
List<AttrGroupWithAttrsVo> groupWithAttrs = new ArrayList<AttrGroupWithAttrsVo>(records.size());
for (AttrGroupEntity record : records) {
//1ใๅๅปบไธไธชvoๅๅคๆถ้ๆๆ้่ฆ็ๆฐๆฎ
AttrGroupWithAttrsVo vo = new AttrGroupWithAttrsVo();
BeanUtils.copyProperties(record,vo);
Long groupId = record.getAttrGroupId();
//่ทๅๅฝๅๅ็ป็ๆๆๅฑๆง๏ผ
List<AttrAttrgroupRelationEntity> relationEntities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", groupId));
if(relationEntities!=null && relationEntities.size()>0){
List<Long> attrIds = new ArrayList<>();
for (AttrAttrgroupRelationEntity entity : relationEntities) {
attrIds.add(entity.getAttrId());
}
//ๆฅๅบๅฝๅๅ็ปๆๆ็ๆญฃ็ๅฑๆง
List<AttrEntity> attrEntities = attrDao.selectList(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));
vo.setAttrEntities(attrEntities);
}
//ๆ่ฟไธชvoๆพๅจ้ๅไธญ
groupWithAttrs.add(vo);
}
//(List<?> list, Long totalCount, Long pageSize, Long currPage)
PageVo vo = new PageVo(groupWithAttrs, (int)data.getTotal(), (int) data.getSize(), (int)data.getCurrent());
return vo;
}
@Override
public AttrGroupEntity getGroupInfoByAttrId(Long attrId) {
AttrGroupEntity attrGroupEntity = null;
//1.ๆ นๆฎattrIdๅปๅ
ณ่ๅ
ณ็ณป่กจๆพๅฐ้ฃไธช็ป
AttrAttrgroupRelationEntity one = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
.eq("attr_id", attrId));
//2,ๅๆ นๆฎๅ็ป็idๆพๅฐๅ็ปไฟกๆฏ
if( one != null){
Long attrGroupId = one.getAttrGroupId();
attrGroupEntity = attrGroupDao.selectById(attrGroupId);
}
return attrGroupEntity;
}
} | 36.034783 | 166 | 0.698359 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.