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
|
---|---|---|---|---|---|
0276ee14723fb0709c03a7cc9be6f5da8a8dde72 | 230 | package de.uniba.dsg.concurrency.exercises.documentation;
public class Class7 {
private final int x;
public Class7(int x) {
super();
this.x = x;
}
public int getX() {
return x;
}
}
| 13.529412 | 57 | 0.565217 |
69cd683dd182b2d055f716be03f92c293f4c7ff5 | 1,479 | package net.enigmablade.lol.lolitem.ui.models;
import java.util.*;
import javax.swing.*;
public class MovableListModel<E> extends DefaultListModel<E>
{
//Physical up, indices decrease
public int[] moveUp(int[] indecies)
{
int[] newIndecies = new int[indecies.length];
Arrays.sort(indecies);
for(int n = 0; n < indecies.length; n++)
newIndecies[n] = moveUp(indecies[n]);
return newIndecies;
}
public int moveUp(int index)
{
if(index < 0 || index >= getSize())
throw new IllegalArgumentException("Bad index");
int index2 = index-1;
if(index2 >= 0)
swap(index, index2);
return index2;
}
//Physical down, indices increase
public int[] moveDown(int[] indecies)
{
int[] newIndecies = new int[indecies.length];
Arrays.sort(indecies);
for(int n = indecies.length-1; n >= 0 ; n--)
newIndecies[n] = moveDown(indecies[n]);
return newIndecies;
}
public int moveDown(int index)
{
if(index < 0 || index >= getSize())
throw new IllegalArgumentException("Bad index");
int index2 = index+1;
if(index2 < getSize())
swap(index, index2);
return index2;
}
//Helpers
private void swap(int i1, int i2)
{
if(i1 < 0 || i1 >= getSize() || i2 < 0 || i2 >= getSize() || i1 == i2)
throw new IllegalArgumentException("Bad indecies");
E e1 = getElementAt(i1);
setElementAt(getElementAt(i2), i1);
setElementAt(e1, i2);
}
}
| 21.434783 | 73 | 0.616633 |
92e4d6ce1eacd136281c86f182f9805bdfb91be3 | 4,774 | package sch.frog.learn.spring.mybatis.gen.mapper;
import sch.frog.learn.spring.mybatis.gen.model.GCoffee;
import sch.frog.learn.spring.mybatis.gen.model.GCoffeeExample;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.session.RowBounds;
public interface GCoffeeMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
long countByExample(GCoffeeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
int deleteByExample(GCoffeeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
@Delete({
"delete from T_GCOFFEE",
"where ID = #{id,jdbcType=BIGINT}"
})
int deleteByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
@Insert({
"insert into T_GCOFFEE (NAME, PRICE, ",
"CREATE_TIME, UPDATE_TIME)",
"values (#{name,jdbcType=VARCHAR}, #{price,jdbcType=BIGINT,typeHandler=sch.frog.learn.spring.mybatis.common.typehandler.MoneyTypeHandler}, ",
"#{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP})"
})
@SelectKey(statement="CALL IDENTITY()", keyProperty="id", before=false, resultType=Long.class)
int insert(GCoffee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
int insertSelective(GCoffee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
List<GCoffee> selectByExampleWithRowbounds(GCoffeeExample example, RowBounds rowBounds);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
List<GCoffee> selectByExample(GCoffeeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
@Select({
"select",
"ID, NAME, PRICE, CREATE_TIME, UPDATE_TIME",
"from T_GCOFFEE",
"where ID = #{id,jdbcType=BIGINT}"
})
@ResultMap("frog.learn.spring.mybatis.gen.mapper.GCoffeeMapper.BaseResultMap")
GCoffee selectByPrimaryKey(Long id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
int updateByExampleSelective(@Param("record") GCoffee record, @Param("example") GCoffeeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
int updateByExample(@Param("record") GCoffee record, @Param("example") GCoffeeExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
int updateByPrimaryKeySelective(GCoffee record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table T_GCOFFEE
*
* @mbg.generated Thu Apr 02 13:06:42 CST 2020
*/
@Update({
"update T_GCOFFEE",
"set NAME = #{name,jdbcType=VARCHAR},",
"PRICE = #{price,jdbcType=BIGINT,typeHandler=sch.frog.learn.spring.mybatis.common.typehandler.MoneyTypeHandler},",
"CREATE_TIME = #{createTime,jdbcType=TIMESTAMP},",
"UPDATE_TIME = #{updateTime,jdbcType=TIMESTAMP}",
"where ID = #{id,jdbcType=BIGINT}"
})
int updateByPrimaryKey(GCoffee record);
} | 34.846715 | 149 | 0.675744 |
c65001d18d225bf79518e773db8eeeaf1974877b | 3,117 | package io.reactivex.internal.operators.flowable;
import io.reactivex.Flowable;
import io.reactivex.FlowableSubscriber;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.Exceptions;
import io.reactivex.internal.disposables.EmptyDisposable;
import io.reactivex.internal.functions.ObjectHelper;
import io.reactivex.internal.fuseable.FuseToFlowable;
import io.reactivex.internal.subscriptions.SubscriptionHelper;
import io.reactivex.internal.util.ArrayListSupplier;
import io.reactivex.plugins.RxJavaPlugins;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.reactivestreams.Subscription;
public final class FlowableToListSingle<T, U extends Collection<? super T>> extends Single<U> implements FuseToFlowable<U> {
final Callable<U> collectionSupplier;
final Flowable<T> source;
static final class ToListSubscriber<T, U extends Collection<? super T>> implements FlowableSubscriber<T>, Disposable {
final SingleObserver<? super U> actual;
Subscription f2605s;
U value;
ToListSubscriber(SingleObserver<? super U> actual, U collection) {
this.actual = actual;
this.value = collection;
}
public void onSubscribe(Subscription s) {
if (SubscriptionHelper.validate(this.f2605s, s)) {
this.f2605s = s;
this.actual.onSubscribe(this);
s.request(Long.MAX_VALUE);
}
}
public void onNext(T t) {
this.value.add(t);
}
public void onError(Throwable t) {
this.value = null;
this.f2605s = SubscriptionHelper.CANCELLED;
this.actual.onError(t);
}
public void onComplete() {
this.f2605s = SubscriptionHelper.CANCELLED;
this.actual.onSuccess(this.value);
}
public void dispose() {
this.f2605s.cancel();
this.f2605s = SubscriptionHelper.CANCELLED;
}
public boolean isDisposed() {
return this.f2605s == SubscriptionHelper.CANCELLED;
}
}
public FlowableToListSingle(Flowable<T> source) {
this(source, ArrayListSupplier.asCallable());
}
public FlowableToListSingle(Flowable<T> source, Callable<U> collectionSupplier) {
this.source = source;
this.collectionSupplier = collectionSupplier;
}
protected void subscribeActual(SingleObserver<? super U> s) {
try {
this.source.subscribe(new ToListSubscriber(s, (Collection) ObjectHelper.requireNonNull(this.collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources.")));
} catch (Throwable e) {
Exceptions.throwIfFatal(e);
EmptyDisposable.error(e, (SingleObserver) s);
}
}
public Flowable<U> fuseToFlowable() {
return RxJavaPlugins.onAssembly(new FlowableToList(this.source, this.collectionSupplier));
}
}
| 35.420455 | 255 | 0.676933 |
8b754bdd0aff028bbf3e96283785580589354c1c | 546 | package basics.exceptionHandling;
public class G
{
public static void main(String[] args)
{
int[] arr1={10,20,30,40,50,60,70,80};
int[] arr2={10,0,30,0,50};
for(int i=0;i<arr1.length;i++)
{
try
{
System.out.println(arr1[i]/arr2[i]);
//arr[5]/arr[5];
//60/no values
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("No such index");
}catch(Exception e) {
//genetic exception
}
}
}
}
| 16.545455 | 42 | 0.591575 |
0f11df4f9dbcaa3f536362e8d0bc832eb215acf2 | 3,404 | /*
###############################################################################
# #
# Copyright 2016, AdeptJ (http://www.adeptj.com) #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License. #
# You may obtain a copy of the License at #
# #
# http://www.apache.org/licenses/LICENSE-2.0 #
# #
# Unless required by applicable law or agreed to in writing, software #
# distributed under the License is distributed on an "AS IS" BASIS, #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
# See the License for the specific language governing permissions and #
# limitations under the License. #
# #
###############################################################################
*/
package com.adeptj.runtime.common;
import com.adeptj.runtime.exception.ServerException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
import static javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE;
/**
* Utils for {@link HttpServletResponse}
*
* @author Rakesh.Kumar, AdeptJ
*/
public final class ResponseUtil {
private ResponseUtil() {
}
public static void serverError(HttpServletResponse resp) {
try {
resp.sendError(SC_INTERNAL_SERVER_ERROR);
} catch (IOException ex) {
// Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
}
}
public static void sendError(HttpServletResponse resp, int errorCode) {
try {
resp.sendError(errorCode);
} catch (IOException ex) {
// Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
}
}
public static void unavailable(HttpServletResponse resp) {
try {
resp.sendError(SC_SERVICE_UNAVAILABLE);
} catch (IOException ex) {
// Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
}
}
public static void redirect(HttpServletResponse resp, String redirectUrl) {
try {
resp.sendRedirect(resp.encodeRedirectURL(redirectUrl));
} catch (IOException ex) {
// Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
}
}
public static void write(HttpServletResponse resp, String content) {
try {
resp.getWriter().write(content);
} catch (IOException ex) {
// Now what? may be wrap and re-throw. Let the container handle it.
throw new ServerException(ex);
}
}
}
| 39.581395 | 79 | 0.515276 |
d72840e3a086d958a49347eaafd7e659c797a196 | 1,232 | //
// ========================================================================
// Copyright (c) Webtide LLC and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package net.webtide.github.releasedrafter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public final class IO
{
public static final String toString(Path path) throws IOException
{
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
Files.copy(path, out);
return out.toString(StandardCharsets.UTF_8);
}
}
}
| 32.421053 | 75 | 0.633929 |
c620f89c257f1f0f6cfb15a4fdf9c553493874c1 | 1,160 | package eu.epfc.cours3449.LibrarySQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MySQL {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection connx = DriverManager.getConnection("jdbc:mysql://localhost/library", "root", "");
Statement statement = connx.createStatement();
statement.executeUpdate("create table if not exists Temp (col1 char(5), col2 char(5))");
ResultSet resultSet = statement.executeQuery("SELECT * FROM BOOKS");
while (resultSet.next()) {
System.out.println( resultSet.getString(1)
+ "\t" + resultSet.getString(2)
+ "\t" + resultSet.getString(3)
+ "\t" + resultSet.getString(4)
+ "\t" + resultSet.getString(5)
+ "\t" + resultSet.getString(6)
);
}
}
}
| 34.117647 | 102 | 0.557759 |
d9f975631149beba1467046e57623bfaccde9f37 | 8,275 | /*
* Copyright 2001-2014 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Words. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package programmingwithdocuments.workingwithimages.compressimages.java;
import com.aspose.words.*;
import com.aspose.words.Shape;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.MessageFormat;
import java.util.Iterator;
public class Resampler
{
/**
* Resamples all images in the document that are greater than the specified PPI (pixels per inch) to the specified PPI
* and converts them to JPEG with the specified quality setting.
*
* @param doc The document to process.
* @param desiredPpi Desired pixels per inch. 220 high quality. 150 screen quality. 96 email quality.
* @param jpegQuality 0 - 100% JPEG quality.
*/
public static int resample(Document doc, int desiredPpi, int jpegQuality) throws Exception
{
int count = 0;
// Convert VML shapes.
for (Shape vmlShape : (Iterable<Shape>) doc.getChildNodes(NodeType.SHAPE, true, false))
{
// It is important to use this method to correctly get the picture shape size in points even if the picture is inside a group shape.
Point2D.Float shapeSizeInPoints = vmlShape.getSizeInPoints();
if (resampleCore(vmlShape.getImageData(), shapeSizeInPoints, desiredPpi, jpegQuality))
count++;
}
// Convert DrawingML shapes.
for (DrawingML dmlShape : (Iterable<DrawingML>) doc.getChildNodes(NodeType.DRAWING_ML, true, false))
{
// In MS Word the size of a DrawingML shape is always in points at the moment.
Point2D.Float shapeSizeInPoints = dmlShape.getSize();
if (resampleCore(dmlShape.getImageData(), shapeSizeInPoints, desiredPpi, jpegQuality))
count++;
}
return count;
}
/**
* Resamples one VML or DrawingML image
*/
private static boolean resampleCore(IImageData imageData, Point2D.Float shapeSizeInPoints, int ppi, int jpegQuality) throws Exception
{
// The are actually several shape types that can have an image (picture, ole object, ole control), let's skip other shapes.
if (imageData == null)
return false;
// An image can be stored in the shape or linked from somewhere else. Let's skip images that do not store bytes in the shape.
byte[] originalBytes = imageData.getImageBytes();
if (originalBytes == null)
return false;
// Ignore metafiles, they are vector drawings and we don't want to resample them.
int imageType = imageData.getImageType();
if ((imageType == ImageType.WMF) || (imageType == ImageType.EMF))
return false;
try
{
double shapeWidthInches = ConvertUtil.pointToInch(shapeSizeInPoints.getX());
double shapeHeightInches = ConvertUtil.pointToInch(shapeSizeInPoints.getY());
// Calculate the current PPI of the image.
ImageSize imageSize = imageData.getImageSize();
double currentPpiX = imageSize.getWidthPixels() / shapeWidthInches;
double currentPpiY = imageSize.getHeightPixels() / shapeHeightInches;
System.out.print(MessageFormat.format("Image PpiX:{0}, PpiY:{1}. ", (int) currentPpiX, (int) currentPpiY));
// Let's resample only if the current PPI is higher than the requested PPI (e.g. we have extra data we can get rid of).
if ((currentPpiX <= ppi) || (currentPpiY <= ppi))
{
System.out.println("Skipping.");
return false;
}
BufferedImage srcImage = imageData.toImage();
// Create a new image of such size that it will hold only the pixels required by the desired ppi.
int dstWidthPixels = (int)(shapeWidthInches * ppi);
int dstHeightPixels = (int)(shapeHeightInches * ppi);
BufferedImage dstImage = new BufferedImage(dstWidthPixels, dstHeightPixels, getResampledImageType(srcImage.getType()));
// Drawing the source image to the new image scales it to the new size.
Graphics2D g = (Graphics2D)dstImage.getGraphics();
try
{
// Setting any other interpolation or rendering value can increase the time taken extremely.
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(
srcImage,
0, 0, dstWidthPixels, dstHeightPixels,
0, 0, srcImage.getWidth(), srcImage.getHeight(),
null);
}
finally
{
g.dispose();
}
// Create JPEG encoder parameters with the quality setting.
Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)writers.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(jpegQuality / 100.0f);
// Save the image as JPEG to a memory stream.
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(dstStream);
writer.setOutput(ios);
IIOImage ioImage = new IIOImage(dstImage, null, null);
writer.write(null, ioImage, param);
// This is required, otherwise not all data might be written to our stream.
ios.flush();
// The Java documentation recommends disposing image readers and writers asap.
writer.dispose();
// If the image saved as JPEG is smaller than the original, store it in the shape.
System.out.println(MessageFormat.format("Original size {0}, new size {1}.", originalBytes.length, dstStream.size()));
if (dstStream.size() < originalBytes.length)
{
imageData.setImageBytes(dstStream.toByteArray());
return true;
}
}
catch (Exception e)
{
// Catch an exception, log an error and continue if cannot process one of the images for whatever reason.
System.out.println("Error processing an image, ignoring. " + e.getMessage());
}
return false;
}
private static int getResampledImageType(int srcImageType)
{
// In general, we want to preserve the image color model, but some things need to be taken care of.
switch (srcImageType)
{
case BufferedImage.TYPE_CUSTOM:
// I have seen some PNG images return TYPE_CUSTOM and creating a BufferedImage of this type fails,
// so we fallback to a more suitable value.
return BufferedImage.TYPE_INT_RGB;
case BufferedImage.TYPE_BYTE_INDEXED:
// This has some problems with colors if we use the BufferedImage ctor that accepts the color model,
// so let's just convert the bitmap to RGB color. It is enough for the sample project.
return BufferedImage.TYPE_INT_RGB;
default:
// The image format should be okay.
return srcImageType;
}
}
} | 45.467033 | 145 | 0.627915 |
31ed3562fb76f435c9d412e70fed110a9dafbe7d | 10,609 | package ch.pascal_mueller.frackstock;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainControlActivity extends AppCompatActivity implements DataExchangeInteractionListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private DataExchangeInteractionListener listener_config;
private DataExchangeInteractionListener listener_pattern;
private DataExchangeInteractionListener listener_color;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private UartService uartService = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_control);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
service_init();
}
void setDataListener(DataExchangeInteractionListener listener, int id)
{
switch (id)
{
case 1:
listener_config = listener;
break;
case 2:
listener_pattern = listener;
break;
case 3:
listener_color = listener;
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_control, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_disconnect) {
uartService.disconnect();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDataSend(byte[] data) {
uartService.writeRXCharacteristic(data);
}
/**
* A placeholder fragment containing a simple view.
*/
// public static class PlaceholderFragment extends Fragment {
// /**
// * The fragment argument representing the section number for this
// * fragment.
// */
// private static final String ARG_SECTION_NUMBER = "section_number";
//
// public PlaceholderFragment() {
// }
//
// /**
// * Returns a new instance of this fragment for the given section
// * number.
// */
// public static PlaceholderFragment newInstance(int sectionNumber) {
// PlaceholderFragment fragment = new PlaceholderFragment();
// Bundle args = new Bundle();
// args.putInt(ARG_SECTION_NUMBER, sectionNumber);
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View rootView = inflater.inflate(R.layout.fragment_main_control, container, false);
// TextView textView = (TextView) rootView.findViewById(R.id.section_label);
// textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
// return rootView;
// }
// }
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position)
{
default:
case 0:
return new ConfigurationFragment();
case 1:
return new PatternFragment();
case 2:
return new ColorFragment();
}
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
//UART service connected/disconnected
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder rawBinder) {
uartService = ((UartService.LocalBinder) rawBinder).getService();
//Log.d(TAG, "onServiceConnected mService= " + mService);
if (!uartService.initialize()) {
//Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
}
public void onServiceDisconnected(ComponentName classname) {
//// mService.disconnect(mDevice);
uartService = null;
}
};
private static Handler mHandler = new Handler() {
@Override
//Handler events that received from UART service
public void handleMessage(Message msg) {
}
};
private final BroadcastReceiver UARTStatusChangeReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
final Intent mIntent = intent;
//*********************//
if (action.equals(UartService.ACTION_GATT_CONNECTED)) {
// should not happen in this activity
}
//*********************//
if (action.equals(UartService.ACTION_GATT_DISCONNECTED)) {
runOnUiThread(new Runnable() {
public void run() {
uartService.close();
startActivity(new Intent(getApplicationContext(), ConnectActivity.class));
finish();
}
});
}
//*********************//
if (action.equals(UartService.ACTION_GATT_SERVICES_DISCOVERED)) {
uartService.enableTXNotification();
}
//*********************//
if (action.equals(UartService.ACTION_DATA_AVAILABLE)) {
final byte[] txValue = intent.getByteArrayExtra(UartService.EXTRA_DATA);
if(listener_config != null)
listener_config.onDataSend(txValue);
if(listener_pattern != null)
listener_pattern.onDataSend(txValue);
if(listener_color != null)
listener_color.onDataSend(txValue);
}
//*********************//
if (action.equals(UartService.DEVICE_DOES_NOT_SUPPORT_UART)){
//showMessage("Device doesn't support UART. Disconnecting");
uartService.disconnect();
}
}
};
private void service_init() {
Intent bindIntent = new Intent(this, UartService.class);
bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
LocalBroadcastManager.getInstance(this).registerReceiver(UARTStatusChangeReceiver, makeGattUpdateIntentFilter());
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(UartService.ACTION_GATT_CONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(UartService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(UartService.ACTION_DATA_AVAILABLE);
intentFilter.addAction(UartService.DEVICE_DOES_NOT_SUPPORT_UART);
return intentFilter;
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onDestroy() {
super.onDestroy();
//Log.d(TAG, "onDestroy()");
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(UARTStatusChangeReceiver);
} catch (Exception ignore) {
//Log.e(TAG, ignore.toString());
}
unbindService(mServiceConnection);
uartService.stopSelf();
uartService= null;
}
}
| 34.898026 | 121 | 0.629089 |
ae24c9746396605f2afbe03807ef635c24eb8fda | 104,642 | package com.alwaysallthetime.messagebeast.manager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;
import com.alwaysallthetime.adnlib.Annotations;
import com.alwaysallthetime.adnlib.AppDotNetClient;
import com.alwaysallthetime.adnlib.AppDotNetObjectCloner;
import com.alwaysallthetime.adnlib.QueryParameters;
import com.alwaysallthetime.adnlib.data.Annotation;
import com.alwaysallthetime.adnlib.data.Channel;
import com.alwaysallthetime.adnlib.data.File;
import com.alwaysallthetime.adnlib.data.Message;
import com.alwaysallthetime.adnlib.data.MessageList;
import com.alwaysallthetime.adnlib.data.Place;
import com.alwaysallthetime.adnlib.gson.AppDotNetGson;
import com.alwaysallthetime.adnlib.response.FileResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageListResponseHandler;
import com.alwaysallthetime.adnlib.response.MessageResponseHandler;
import com.alwaysallthetime.asyncgeocoder.AsyncGeocoder;
import com.alwaysallthetime.asyncgeocoder.response.AsyncGeocoderResponseHandler;
import com.alwaysallthetime.messagebeast.ADNApplication;
import com.alwaysallthetime.messagebeast.ADNSharedPreferences;
import com.alwaysallthetime.messagebeast.AnnotationUtility;
import com.alwaysallthetime.messagebeast.PrivateChannelUtility;
import com.alwaysallthetime.messagebeast.db.ADNDatabase;
import com.alwaysallthetime.messagebeast.db.AnnotationInstances;
import com.alwaysallthetime.messagebeast.db.DisplayLocationInstances;
import com.alwaysallthetime.messagebeast.db.FilteredMessageBatch;
import com.alwaysallthetime.messagebeast.db.HashtagInstances;
import com.alwaysallthetime.messagebeast.db.OrderedMessageBatch;
import com.alwaysallthetime.messagebeast.db.PendingFileAttachment;
import com.alwaysallthetime.messagebeast.db.PendingMessageDeletion;
import com.alwaysallthetime.messagebeast.filter.MessageFilter;
import com.alwaysallthetime.messagebeast.filter.MessageInstancesFilter;
import com.alwaysallthetime.messagebeast.model.CustomPlace;
import com.alwaysallthetime.messagebeast.model.DisplayLocation;
import com.alwaysallthetime.messagebeast.model.FullSyncState;
import com.alwaysallthetime.messagebeast.model.Geolocation;
import com.alwaysallthetime.messagebeast.model.MessagePlus;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
/**
* MessageManager is used to retrieve, create, and delete Messages in any number of channels.<br><br>
*
* All Messages that are obtained via the MessageManager will use a wrapper class called MessagePlus,
* which contains extra metadata associated with the Message. A MessageManagerConfiguration is required
* in order to determine which of the following features are used to add metadata to the MessagePlus:<br><br>
*
* • DisplayLocation lookup. Geolocation, Checkin, and Ohai Location annotations are consolidated into a single
* DisplayLocation object. In the case of Geolocation, an asynchronous task is fired off to perform
* reverse geolocation (in order to find a human-readable name for the location).<br>
*
* • OEmbed lookup. For all OEmbed annotations found on a Message, PhotoOEmbed and Html5OEmbed
* objects are constructed and stored for easy access on the MessagePlus. Additionally, this data
* is stored in a sqlite database so lookups can be performed (e.g. give me all messages with videos).<br>
*
* • Association of an a display date that is different than the created_at date via a MessageDateAdapter.<br><br>
*
* Some additional key features are are:<br><br>
*
* • Persistence of all Messages in a sqlite database. Messages can be loaded on subsequent launches
* by using the loadPersistedMessages methods, and several ADNDatabase methods are available for obtaining
* Messages or performing operations on them (e.g. full text search).<br>
*
* • Offline Message creation and deletion. The createUnsentMessageAndAttemptSend() methods can be used
* to create Messages that will be saved to the local sqlite database with an unsent flag set when there
* is no internet connection available. The MessageManager will return the associated MessagePlus objects
* as if they are "real" Messages and delete them after they are successfully sent (so that the "real"
* Message can be retrieved - with its server-assigned id).<br>
*
* • Perform a full sync on a specified channel, obtaining every Message in existence in that Channel.
* This is especially useful in cases where a Channel is used privately by a single user.
*/
public class MessageManager {
private static final String TAG = "MessageBeast_MessageManager";
private static final int MAX_MESSAGES_RETURNED_ON_SYNC = 100;
/**
* An intent with this action is broadcasted when unsent messages are successfully sent.
*
* The EXTRA_CHANNEL_ID and EXTRA_SENT_MESSAGE_IDS extras contain relevant info.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#EXTRA_CHANNEL_ID
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#EXTRA_SENT_MESSAGE_IDS
*/
public static final String INTENT_ACTION_UNSENT_MESSAGES_SENT = "com.alwaysallthetime.messagebeast.manager.MessageManager.intent.unsentMessagesSent";
/**
* An intent with this action is broadcasted when an unsent message fails to send upon request.
*
* The EXTRA_CHANNEL_ID, EXTRA_MESSAGE_ID, and EXTRA_SEND_ATTEMPTS extras contain relevant info.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#EXTRA_CHANNEL_ID
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#EXTRA_MESSAGE_ID
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#EXTRA_SEND_ATTEMPTS
*/
public static final String INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE = "com.alwaysallthetime.messagebeast.manager.MessageManager.intent.unsentMessageSendFailure";
public static final String EXTRA_CHANNEL_ID = "com.alwaysallthetime.messagebeast.manager.MessageManager.extras.channelId";
public static final String EXTRA_SENT_MESSAGE_IDS = "com.alwaysallthetime.messagebeast.manager.MessageManager.extras.sentMessageIds";
public static final String EXTRA_SENT_MESSAGE_REPLACEMENT_IDS = "com.alwaysallthetime.messagebeast.manager.MessageManager.extras.replacementMessageIds";
public static final String EXTRA_MESSAGE_ID = "com.alwaysallthetime.messagebeast.manager.MessageManager.extras.messageId";
public static final String EXTRA_SEND_ATTEMPTS = "com.alwaysallthetime.messagebeast.manager.MessageManager.extras.sendAttempts";
public static abstract class MessageManagerResponseHandler {
private boolean isMore;
private TreeMap<Long, MessagePlus> excludedResults;
public abstract void onSuccess(final List<MessagePlus> messages);
public abstract void onError(Exception exception);
public void setIsMore(boolean isMore) {
this.isMore = isMore;
}
public boolean isMore() {
return this.isMore;
}
public void setExcludedResults(TreeMap<Long, MessagePlus> excludedResults) {
this.excludedResults = excludedResults;
}
public TreeMap<Long, MessagePlus> getExcludedResults() {
return excludedResults;
}
}
public static abstract class MessageManagerSyncResponseHandler extends MessageManagerResponseHandler {
private int numMessagesSynced;
void setNumMessagesSynced(int numMessagesSynced) {
this.numMessagesSynced = numMessagesSynced;
}
public int getNumMessagesSynced() {
return numMessagesSynced;
}
public void onBatchSynced(List<MessagePlus> messages) {
//override this to do some processing on a batch by batch basis
}
}
public interface MessageManagerMultiChannelSyncResponseHandler {
public void onSuccess();
public void onError(Exception exception);
}
public interface MessageDeletionResponseHandler {
public void onSuccess();
public void onError(Exception exception);
}
/**
* A MessageDisplayDateAdapter can be used to return a date for which a Message should be
* associated. This is most typically used when Message.getCreatedAt() should not be used
* for sort order.
*/
public interface MessageDisplayDateAdapter {
public Date getDisplayDate(Message message);
}
private static MessageManager sInstance;
private Context mContext;
private ADNDatabase mDatabase;
private AppDotNetClient mClient;
private MessageManagerConfiguration mConfiguration;
private ActionMessageManager mAttachedActionMessageManager;
private HashMap<String, TreeMap<Long, MessagePlus>> mMessages;
private HashMap<String, TreeMap<Long, MessagePlus>> mUnsentMessages;
private HashMap<String, Set<String>> mMessagesNeedingPendingFiles;
private HashMap<String, QueryParameters> mParameters;
private HashMap<String, MinMaxPair> mMinMaxPairs;
public MessageManager(AppDotNetClient client, MessageManagerConfiguration configuration) {
mContext = ADNApplication.getContext();
mClient = client;
mConfiguration = configuration;
mDatabase = ADNDatabase.getInstance(mContext);
mMessages = new HashMap<String, TreeMap<Long, MessagePlus>>();
mUnsentMessages = new HashMap<String, TreeMap<Long, MessagePlus>>();
mMinMaxPairs = new HashMap<String, MinMaxPair>();
mParameters = new HashMap<String, QueryParameters>();
mMessagesNeedingPendingFiles = new HashMap<String, Set<String>>();
IntentFilter intentFilter = new IntentFilter(FileUploadService.INTENT_ACTION_FILE_UPLOAD_COMPLETE);
mContext.registerReceiver(fileUploadReceiver, intentFilter);
}
/**
* Purge all Message and Channel-related data from memory. This will leave the MessageManager
* in the initial state – as it was upon construction. Note that this does not delete any
* persisted data from the sqlite database.
*
* @see com.alwaysallthetime.messagebeast.db.ADNDatabase#deleteAll()
*/
public synchronized void clear() {
mMessages.clear();
mUnsentMessages.clear();
mMessagesNeedingPendingFiles.clear();
mParameters.clear();
mMinMaxPairs.clear();
}
/**
* Replace in-memory instances of the provided MessagePlus (as identified by
* channel id and display date) with the new copy.
*
* @param messagePlus the new copy of the MessagePlus to replace old versions of the same one.
*/
public synchronized void replaceInMemoryMessage(MessagePlus messagePlus) {
String channelId = messagePlus.getMessage().getChannelId();
long time = messagePlus.getDisplayDate().getTime();
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
if(channelMessages != null) {
if(channelMessages.containsKey(time)) {
channelMessages.put(time, messagePlus);
}
}
TreeMap<Long, MessagePlus> unsentChanneMessages = mUnsentMessages.get(channelId);
if(unsentChanneMessages != null) {
if(unsentChanneMessages.containsKey(time)) {
unsentChanneMessages.put(time, messagePlus);
}
}
}
private synchronized OrderedMessageBatch loadPersistedMessageBatch(String channelId, int limit, boolean performLookups) {
Date beforeDate = null;
MinMaxPair minMaxPair = getMinMaxPair(channelId);
if(minMaxPair.minDate != null) {
beforeDate = new Date(minMaxPair.minDate);
}
OrderedMessageBatch orderedMessageBatch = mDatabase.getMessages(channelId, beforeDate, limit);
TreeMap<Long, MessagePlus> messages = orderedMessageBatch.getMessages();
MinMaxPair dbMinMaxPair = orderedMessageBatch.getMinMaxPair();
minMaxPair.updateWithCombinedValues(dbMinMaxPair);
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
if(channelMessages != null) {
channelMessages.putAll(messages);
} else {
mMessages.put(channelId, messages);
}
if(performLookups) {
performLookups(messages.values(), false);
}
return orderedMessageBatch;
}
/**
* Load persisted messages that were previously stored in the sqlite database.
*
* @param channelId the id of the channel for which messages should be loaded.
* @param limit the maximum number of messages to load from the database.
* @return a TreeMap containing the newly loaded messages, mapped from message time in millis
* to MessagePlus Object. If no Messages were loaded, then an empty Map is returned.
*/
public synchronized TreeMap<Long, MessagePlus> loadPersistedMessages(String channelId, int limit) {
OrderedMessageBatch batch = loadPersistedMessageBatch(channelId, limit, true);
return batch.getMessages();
}
/**
* Load persisted messages that were previously stored in the sqlite database, using a filter
* to exclude any number of messages.
*
* @param channelId the id of the channel for which messages should be loaded.
* @param limit the maximum number of messages to load from the database.
* @param filter the MessageFilter to use to exclude messages.
*
* @return A FilteredMessageBatch containing the messages after a filter was applied, and additionally
* a Map of messages containing the excluded Messages.
*
* @see com.alwaysallthetime.messagebeast.filter.MessageFilter
* @see com.alwaysallthetime.messagebeast.db.FilteredMessageBatch
*/
public synchronized FilteredMessageBatch loadPersistedMessages(String channelId, int limit, MessageFilter filter) {
OrderedMessageBatch batch = loadPersistedMessageBatch(channelId, limit, false);
FilteredMessageBatch filteredBatch = FilteredMessageBatch.getFilteredMessageBatch(batch, filter);
TreeMap<Long, MessagePlus> excludedMessages = filteredBatch.getExcludedMessages();
//remove the filtered messages from the main channel message map.
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
removeExcludedMessages(channelMessages, excludedMessages);
//do this after we have successfully filtered out stuff,
//as to not perform lookups on things we didn't keep.
performLookups(filteredBatch.getMessages().values(), false);
return filteredBatch;
}
/**
* Load persisted Messages without keeping them in MessageManager memory.
*
* No DisplayLocation or OEmbed lookup will be performed on these Messages.
*
* @param channelId the Channel id
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, int limit) {
OrderedMessageBatch orderedMessageBatch = mDatabase.getMessages(channelId, limit);
return orderedMessageBatch.getMessages();
}
/**
* Load persisted Messages without keeping them in MessageManager memory.
*
* No DisplayLocation or OEmbed lookup will be performed on these Messages.
*
* @param channelId the Channel id
* @param beforeDate the the date before the display date of all returned messages. Can be null.
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, Date beforeDate, int limit) {
OrderedMessageBatch orderedMessageBatch = mDatabase.getMessages(channelId, beforeDate, limit);
return orderedMessageBatch.getMessages();
}
/**
* Load persisted Messages with an associated DisplayLocation without keeping them in
* MessageManager memory.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param channelId the Channel id
* @param location the DisplayLocation
* @param precision the precision to use when obtaining location instances.
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*
* @see com.alwaysallthetime.messagebeast.db.ADNDatabase#getDisplayLocationInstances(String, com.alwaysallthetime.messagebeast.model.DisplayLocation, com.alwaysallthetime.messagebeast.db.ADNDatabase.LocationPrecision)
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, DisplayLocation location, ADNDatabase.LocationPrecision precision, int limit) {
return getMessages(channelId, location, precision, null, limit);
}
/**
* Load persisted Messages with an associated DisplayLocation without keeping them in
* MessageManager memory.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param channelId the Channel id
* @param location the DisplayLocation
* @param precision the precision to use when obtaining location instances.
* @param beforeDate the the date before the display date of all returned messages. Can be null.
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*
* @see com.alwaysallthetime.messagebeast.db.ADNDatabase#getDisplayLocationInstances(String, com.alwaysallthetime.messagebeast.model.DisplayLocation, com.alwaysallthetime.messagebeast.db.ADNDatabase.LocationPrecision)
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, DisplayLocation location, ADNDatabase.LocationPrecision precision, Date beforeDate, int limit) {
DisplayLocationInstances locationInstances = mDatabase.getDisplayLocationInstances(channelId, location, precision, beforeDate, limit);
return getMessages(locationInstances.getMessageIds());
}
/**
* Load persisted Messages with a hashtag entity matching the provided hashtag, without keeping them in
* MessageManager memory.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param channelId the Channel id
* @param hashtagName the hashtag with which the lookup will be done
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, String hashtagName, int limit) {
return getMessages(channelId, hashtagName, null, limit);
}
/**
* Load persisted Messages with a hashtag entity matching the provided hashtag, without keeping them in
* MessageManager memory.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param channelId the Channel id
* @param hashtagName the hashtag with which the lookup will be done
* @param beforeDate the date before the display date of all associated messages. Can be null.
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessages(String channelId, String hashtagName, Date beforeDate, int limit) {
HashtagInstances hashtagInstances = mDatabase.getHashtagInstances(channelId, hashtagName, beforeDate, limit);
return getMessages(hashtagInstances.getMessageIds());
}
/**
* Load persisted Messages that use a specific type of Annotation, without keeping them in
* MessageManager memory.
*
* @param channelId the id of the Channel in which the returned Messages will be contained
* @param annotationType the Annotation type to look for
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessagesWithAnnotation(String channelId, String annotationType, int limit) {
return getMessagesWithAnnotation(channelId, annotationType, null, limit);
}
/**
* Load persisted Messages that use a specific type of Annotation, without keeping them in
* MessageManager memory.
*
* @param channelId the id of the Channel in which the returned Messages will be contained
* @param annotationType the Annotation type to look for
* @param beforeDate the date before the display date of all associated messages. Can be null.
* @param limit the maximum number of Messages to load from the database.
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessagesWithAnnotation(String channelId, String annotationType, Date beforeDate, int limit) {
AnnotationInstances instances = getAnnotationInstances(channelId, annotationType, beforeDate, limit);
return getMessages(instances.getMessageIds());
}
/**
* Load persisted Messages without keeping them in MessageManager memory.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param messageIds the Message ids
* @return a TreeMap mapping Message times in millis to MessagePlus objects
*/
public TreeMap<Long, MessagePlus> getMessages(Collection<String> messageIds) {
OrderedMessageBatch orderedMessageBatch = mDatabase.getMessages(messageIds);
TreeMap<Long, MessagePlus> messages = orderedMessageBatch.getMessages();
performLookups(messages.values(), false);
return messages;
}
/**
* Get a Message draft.
*
* The Message will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param messageDraftId the id of the Message draft
* @return a MessagePlus if a draft with the specified id exist, null otherwise.
*/
public MessagePlus getMessageDraft(String messageDraftId) {
MessagePlus messageDraft = mDatabase.getMessageDraft(messageDraftId);
performLookups(messageDraft, false);
return messageDraft;
}
/**
* Get draft Messages for a Channel.
*
* Messages will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param channelId the id of the the id of the Channel
* @return a List of MessagePlus objects ordered by reverse chronological creation date.
*/
public List<MessagePlus> getMessageDrafts(String channelId) {
List<MessagePlus> messageDrafts = mDatabase.getMessageDrafts(channelId);
performLookups(messageDrafts, false);
return messageDrafts;
}
/**
* Load a persisted Message without keeping it in MessageManager memory.
*
* The Message will be returned after performing DisplayLocation and OEmbed lookup, provided those
* features are enabled in the MessageManagerConfiguration.
*
* @param messageId the Message id
* @return a MessagePlus, or null if no MessagePlus with the provided id exists.
*/
public MessagePlus getMessage(String messageId) {
MessagePlus messagePlus = mDatabase.getMessage(messageId);
if(messagePlus != null) {
performLookups(messagePlus, false);
}
return messagePlus;
}
/**
* Get all HashtagInstances in a Channel.
*
* @param channelId the id of the Channel
* @return a LinkedHashMap, mapping hashtag name to a HashtagInstances object. This is
* in descending order, from most to least recent.
*/
public LinkedHashMap<String, HashtagInstances> getHashtagInstances(String channelId) {
return mDatabase.getHashtagInstances(channelId);
}
/**
* Get all HashtagInstances in a Channel, using a filter to remove unwanted results.
*
* @param channelId the id of the Channel
* @param messageFilter the filter to use to excluded unwanted results.
* @return a LinkedHashMap, mapping hashtag name to a HashtagInstances object. This is
* in descending order, from most to least recent.
*/
public LinkedHashMap<String, HashtagInstances> getHashtagInstances(String channelId, MessageInstancesFilter messageFilter) {
LinkedHashMap<String, HashtagInstances> hashtagInstances = mDatabase.getHashtagInstances(channelId);
messageFilter.filterInstances(hashtagInstances);
return hashtagInstances;
}
/**
* Get all DisplayLocationInstances in a Channel.
*
* @param channelId the id of the Channel
* @return a List of DisplayLocationInstances in descending order, from most to least recent
*/
public List<DisplayLocationInstances> getDisplayLocationInstances(String channelId) {
return mDatabase.getDisplayLocationInstances(channelId);
}
/**
* Get all DisplayLocationInstances in a Channel, using a filter to remove unwanted results.
*
* @param channelId the id of the Channel
* @param messageFilter the filter to use to excluded unwanted results.
* @return a List of DisplayLocationInstances in descending order, from most to least recent
*/
public List<DisplayLocationInstances> getDisplayLocationInstances(String channelId, MessageInstancesFilter messageFilter) {
LinkedHashMap<String, DisplayLocationInstances> displayLocationInstancesMap = mDatabase.getDisplayLocationInstancesMap(channelId);
messageFilter.filterInstances(displayLocationInstancesMap);
return new ArrayList<DisplayLocationInstances>(displayLocationInstancesMap.values());
}
/**
* Get references to Messages that use a specific type of Annotationtype.
*
* @param channelId the id of the Channel in which the returned Messages will be contained.
* @param annotationType the Annotation type to look for.
* @param limit the maximum number of Messages to load from the database.
* @return an AnnotationInstances containing message ids that correspond to Messages with
* the provided annotation type.
*/
public AnnotationInstances getAnnotationInstances(String channelId, String annotationType, int limit) {
return getAnnotationInstances(channelId, annotationType, limit);
}
/**
* Get references to Messages that use a specific type of Annotationtype.
*
* @param channelId the id of the Channel in which the returned Messages will be contained.
* @param annotationType the Annotation type to look for.
* @param beforeDate the date before the display date of all associated messages. Can be null.
* @param limit the maximum number of Messages to load from the database.
* @return an AnnotationInstances containing message ids that correspond to Messages with
* the provided annotation type.
*/
public AnnotationInstances getAnnotationInstances(String channelId, String annotationType, Date beforeDate, int limit) {
return mDatabase.getAnnotationInstances(channelId, annotationType, beforeDate, limit);
}
/**
* Search persisted Message text with a query.
*
* @param channelId the id of the Channel from which Messages will be retrieved
* @param query the search query
* @return OrderedMessageBatch
*/
public OrderedMessageBatch searchMessagesWithQuery(String channelId, String query) {
return searchMessagesWithQuery(channelId, query, null);
}
/**
* Search persisted Message text with a query, using a MessageFilter to excluded some results.
*
* @param channelId the id of the Channel from which Messages will be retrieved
* @param query the search query
* @param messageFilter the MessageFilter to use to exclude results
* @return OrderedMessageBatch
*/
public OrderedMessageBatch searchMessagesWithQuery(String channelId, String query, MessageFilter messageFilter) {
OrderedMessageBatch orderedMessageBatch = mDatabase.searchForMessages(channelId, query);
if(messageFilter != null) {
orderedMessageBatch = FilteredMessageBatch.getFilteredMessageBatch(orderedMessageBatch, messageFilter);
}
performLookups(orderedMessageBatch.getMessages().values(), false);
return orderedMessageBatch;
}
/**
* Search for persisted Messages, using a query that matches against their associated DisplayLocations.
*
* @param channelId the id of the Channel from which Messages will be retrieved
* @param query the search query
* @return OrderedMessageBatch
*/
public OrderedMessageBatch searchMessagesWithDisplayLocationQuery(String channelId, String query) {
return searchMessagesWithDisplayLocationQuery(channelId, query, null);
}
/**
* Search for persisted Messages, using a query that matches against their associated DisplayLocations.
* The provided filter will exclude unwanted results.
*
* @param channelId the id of the Channel from which Messages will be retrieved
* @param query the search query
* @param messageFilter the MessageFilter to use to exclude results.
* @return OrderedMessageBatch
*/
public OrderedMessageBatch searchMessagesWithDisplayLocationQuery(String channelId, String query, MessageFilter messageFilter) {
OrderedMessageBatch orderedMessageBatch = mDatabase.searchForMessagesByDisplayLocation(channelId, query);
if(messageFilter != null) {
orderedMessageBatch = FilteredMessageBatch.getFilteredMessageBatch(orderedMessageBatch, messageFilter);
}
performLookups(orderedMessageBatch.getMessages().values(), false);
return orderedMessageBatch;
}
private void lookupLocation(Collection<MessagePlus> messages, boolean persist) {
for(MessagePlus messagePlus : messages) {
Message message = messagePlus.getMessage();
Annotation checkin = message.getFirstAnnotationOfType(Annotations.CHECKIN);
if(checkin != null) {
DisplayLocation displayLocation = DisplayLocation.fromCheckinAnnotation(mContext, checkin);
if(displayLocation != null) {
messagePlus.setDisplayLocation(displayLocation);
if(persist) {
mDatabase.insertOrReplaceDisplayLocationInstance(messagePlus);
Place place = AnnotationUtility.getPlaceFromCheckinAnnotation(mContext, checkin);
if(place != null) {
mDatabase.insertOrReplacePlace(place);
}
}
continue;
}
}
Annotation ohaiLocation = message.getFirstAnnotationOfType(Annotations.OHAI_LOCATION);
if(ohaiLocation != null) {
messagePlus.setDisplayLocation(DisplayLocation.fromOhaiLocation(ohaiLocation));
if(persist) {
mDatabase.insertOrReplaceDisplayLocationInstance(messagePlus);
HashMap<String,Object> value = ohaiLocation.getValue();
Gson gson = AppDotNetGson.getPersistenceInstance();
String placeJson = gson.toJson(value);
Place place = gson.fromJson(placeJson, Place.class);
String id = (String) value.get("id");
if(place != null && place.getName() != null && id != null) {
CustomPlace customPlace = new CustomPlace(id, place);
mDatabase.insertOrReplacePlace(customPlace);
}
}
continue;
}
Annotation geoAnnotation = message.getFirstAnnotationOfType(Annotations.GEOLOCATION);
if(geoAnnotation != null) {
HashMap<String,Object> value = geoAnnotation.getValue();
final double latitude = (Double)value.get("latitude");
final double longitude = (Double)value.get("longitude");
Geolocation geolocationObj = mDatabase.getGeolocation(latitude, longitude);
if(geolocationObj != null) {
messagePlus.setDisplayLocation(DisplayLocation.fromGeolocation(geolocationObj));
//this might seem odd based on the fact that we just pulled the geolocation
//from the database, but the point is to save the instance of this geolocation's
//use - we might obtain a geolocation with this message's lat/long, but that
//doesn't mean that this message + geolocation combo has been saved.
//(this database lookup is merely an optimization to avoid having to fire off
// the async task in reverseGeocode().)
if(persist) {
mDatabase.insertOrReplaceDisplayLocationInstance(messagePlus);
}
continue;
} else {
reverseGeocode(messagePlus, latitude, longitude);
}
}
}
}
private void reverseGeocode(final MessagePlus messagePlus, final double latitude, final double longitude) {
if(Geocoder.isPresent()) {
AsyncGeocoder.getInstance(mContext).getFromLocation(latitude, longitude, 5, new AsyncGeocoderResponseHandler() {
@Override
public void onSuccess(final List<Address> addresses) {
Geolocation geolocation = Geolocation.getGeolocation(addresses, latitude, longitude);
if(geolocation != null) {
messagePlus.setDisplayLocation(DisplayLocation.fromGeolocation(geolocation));
mDatabase.insertOrReplaceGeolocation(geolocation);
mDatabase.insertOrReplaceDisplayLocationInstance(messagePlus);
}
if(mConfiguration.locationLookupHandler != null) {
mConfiguration.locationLookupHandler.onSuccess(messagePlus);
}
}
@Override
public void onException(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
if(mConfiguration.locationLookupHandler != null) {
mConfiguration.locationLookupHandler.onException(messagePlus, exception);
}
}
});
}
}
/**
* Get the AppDotNetClient used by this MessageManager
*
* @return AppDotNetClient
*/
public AppDotNetClient getClient() {
return mClient;
}
/**
* Get a List of all MessagePlus objects currently loaded into memory for a specific Channel
*
* @param channelId the Channel id
* @return a List of MessagePlus objects
*/
public List<MessagePlus> getMessageList(String channelId) {
Map<Long, MessagePlus> messageMap = mMessages.get(channelId);
if(messageMap == null) {
return null;
}
MessagePlus[] messages = messageMap.values().toArray(new MessagePlus[0]);
return Arrays.asList(messages);
}
/**
* Get a TreeMap that maps Message times in millis to MessagePlus objects, containing
* entries for all Messages currently loaded into memory in a specific Channel.
*
* Note that modifications to this Map can alter the functionality of the MessageManager,
* so in most cases you probably should be using getMessageList()
*
* @param channelId the Channel id
* @return the TreeMap of MessagePlus objects currently loaded into memory for the
* specified channel
*/
public TreeMap<Long, MessagePlus> getMessageMap(String channelId) {
return mMessages.get(channelId);
}
/**
* Set the QueryParameters to be used with a specific Channel
*
* @param channelId the id of the Channel
* @param parameters QueryParameters
*/
public void setParameters(String channelId, QueryParameters parameters) {
mParameters.put(channelId, parameters);
}
private synchronized MinMaxPair getMinMaxPair(String channelId) {
MinMaxPair minMaxPair = mMinMaxPairs.get(channelId);
if(minMaxPair == null) {
minMaxPair = new MinMaxPair();
mMinMaxPairs.put(channelId, minMaxPair);
}
return minMaxPair;
}
private synchronized TreeMap<Long, MessagePlus> getChannelMessages(String channelId) {
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
if(channelMessages == null) {
channelMessages = new TreeMap<Long, MessagePlus>(new ReverseChronologicalComparator());
mMessages.put(channelId, channelMessages);
}
return channelMessages;
}
private synchronized TreeMap<Long, MessagePlus> getUnsentMessages(String channelId) {
TreeMap<Long, MessagePlus> unsentMessages = mUnsentMessages.get(channelId);
if(unsentMessages == null) {
unsentMessages = mDatabase.getUnsentMessages(channelId);
mUnsentMessages.put(channelId, unsentMessages);
}
return unsentMessages;
}
private synchronized Set<String> getMessageIdsNeedingPendingFile(String pendingFileId) {
Set<String> messageIds = mMessagesNeedingPendingFiles.get(pendingFileId);
if(messageIds == null) {
messageIds = mDatabase.getMessagesDependentOnPendingFile(pendingFileId);
mMessagesNeedingPendingFiles.put(pendingFileId, messageIds);
}
return messageIds;
}
/**
* Retrieve messages in the specified channel.
*
* The since_id and before_id used in the request are based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be
* exhausting the results of loadPersistedMessages() before calling this method.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveMessages(String channelId, MessageManagerResponseHandler handler) {
return retrieveMessages(channelId, null, handler);
}
/**
* Retrieve messages in the specified channel, using a MessageFilter to exclude messages
* in the response. Excluded Messages will not be persisted and will not be returned by the
* provided response handler.
*
* The since_id and before_id used in the request are based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be
* exhausting the results of loadPersistedMessages() before calling this method.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param filter The MessageFilter to be used when retrieving messages.
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveMessages(String channelId, MessageFilter filter, MessageManagerResponseHandler handler) {
MinMaxPair minMaxPair = getMinMaxPair(channelId);
return retrieveMessages(channelId, minMaxPair.maxId, minMaxPair.minId, filter, handler);
}
/**
* Retrieve more messages in the specified channel, using a MessageFilter to exclude messages
* in the response. Excluded Messages will not be persisted and will not be returned by the
* provided response handler.
*
* The since_id used in this request is based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be calling
* loadPersistedMessages() at least once so that the max message Id is known.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param messageFilter The MessageFilter to be used when retrieving messages.
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveNewestMessages(String channelId, MessageFilter messageFilter, MessageManagerResponseHandler handler) {
return retrieveMessages(channelId, getMinMaxPair(channelId).maxId, null, messageFilter, handler);
}
/**
* Retrieve the newest messages in the specified channel.
*
* The since_id used in this request is based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be calling
* loadPersistedMessages() at least once so that the max message Id is known.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveNewestMessages(String channelId, MessageManagerResponseHandler handler) {
return retrieveNewestMessages(channelId, null, handler);
}
/**
* Retrieve the more (older) messages in the specified channel, using a MessageFilter to exclude messages
* in the response. Excluded Messages will not be persisted and will not be returned by the
* provided response handler.
*
* The before_id used in this request is based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be
* exhausting the results of loadPersistedMessages() before calling this method.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param filter The MessageFilter to be used when retrieving messages.
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveMoreMessages(String channelId, MessageFilter filter, MessageManagerResponseHandler handler) {
return retrieveMessages(channelId, null, getMinMaxPair(channelId).minId, filter, handler);
}
/**
* Retrieve the more (older) messages in the specified channel.
*
* The before_id used in this request is based off the ids of the messages
* currently loaded into memory for this channel. For this reason, you should probably be exhausting
* the results of loadPersistedMessages() before calling this method.
*
* If false is returned, there are unsent messages or pending deletions that must be sent before retrieving.
*
* @param channelId The id of the channel for which more messages should be obtained
* @param handler The handler that will deliver the result of this request
* @return return false if unsent messages exist and we are unable to retrieve more, true otherwise.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#loadPersistedMessages(String, int)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
*/
public synchronized boolean retrieveMoreMessages(String channelId, MessageManagerResponseHandler handler) {
return retrieveMoreMessages(channelId, null, handler);
}
/**
* Create a new Message in the Channel with the specified id.
*
* A runtime exception will be thrown if you have any unsent messages that need to be sent. If
* this is the case, you should probably be calling createUnsentMessageAndAttemptSend() anyway/instead.
*
* @param channelId the id of the Channel in which the Message should be created.
* @param message The Message to be created.
* @param handler The handler that will deliver the result of this request
*/
public synchronized void createMessage(final String channelId, final Message message, final MessageManagerResponseHandler handler) {
if(getUnsentMessages(channelId).size() > 0) {
throw new RuntimeException("This method should not be called when you have unsent messages.");
}
mClient.createMessage(channelId, message, new MessageResponseHandler() {
@Override
public void onSuccess(Message responseData) {
//we finish this off by retrieving the newest messages in case we were missing any
//that came before the one we just created.
retrieveNewestMessages(channelId, handler);
}
@Override
public void onError(Exception error) {
super.onError(error);
handler.onError(error);
}
});
}
/**
* Create a new unsent Message in the channel with the specified id and optionally attempt to send it.
*
* If the Message cannot be sent (e.g. no internet connection), it will still be stored in the
* sqlite database as if the Message exists in the Channel, but with an unsent flag set on it.
* Any number of unsent messages can exist, but no more messages can be retrieved until all
* unsent messages have been successfully sent (or deleted).
*
* Upon completion of the send request, a broadcast will be sent with either the action
* INTENT_ACTION_UNSENT_MESSAGES_SENT or INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE.
*
* @param channelId the id of the Channel in which the Message should be created.
* @param message The Message to be created.
* @param attemptToSendImmediately true if the MessageManager should attempt to send the Message
* immediately, false if the client application will send it
* at a later time.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#INTENT_ACTION_UNSENT_MESSAGES_SENT
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE
*/
public synchronized MessagePlus createUnsentMessage(final String channelId, Message message, boolean attemptToSendImmediately) {
return createUnsentMessage(channelId, message, new ArrayList<PendingFileAttachment>(0), attemptToSendImmediately);
}
/**
* Create a new unsent Message that requires pending files to be uploaded prior to creation.
*
* If the Message cannot be sent (e.g. no internet connection), it will still be stored in the
* sqlite database as if the Message exists in the Channel, but with an unsent flag set on it.
* Any number of unsent messages can exist, but no more messages can be retrieved until all
* unsent messages have been successfully sent (or deleted).
*
* Upon completion of the send request, a broadcast will be sent with either the action
* INTENT_ACTION_UNSENT_MESSAGES_SENT or INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE.
*
* @param channelId the id of the Channel in which the Message should be created.
* @param message The Message to be created.
* @param pendingFileAttachments The pending files that need to be sent before this Message can
* be sent to the server.
* @param attemptToSendImmediately true if the MessageManager should attempt to send the Message
* immediately, false if the client application will send it
* at a later time.
*
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendUnsentMessages(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendPendingDeletions(String, com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDeletionResponseHandler)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#sendAllUnsent(String)
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#INTENT_ACTION_UNSENT_MESSAGES_SENT
* @see com.alwaysallthetime.messagebeast.manager.MessageManager#INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE
*/
public synchronized MessagePlus createUnsentMessage(final String channelId, Message message, List<PendingFileAttachment> pendingFileAttachments, boolean attemptToSendImmediately) {
//An unsent message id is always set to the max id + 1.
//
//This will work because we will never allow message retrieval to happen
//until unsent messages are sent to the server and they get their "real"
//message id. After they reach the server, we will delete them from existence
//on the client and retrieve them from the server.
//
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
if(channelMessages.size() == 0) {
//we do this so that the current max date for this channel is known.
loadPersistedMessages(channelId, 1);
}
String newMessageIdString = UUID.randomUUID().toString();
MessagePlus.UnsentMessagePlusBuilder unsentBuilder = MessagePlus.UnsentMessagePlusBuilder.newBuilder(channelId, newMessageIdString, message);
for(PendingFileAttachment attachment : pendingFileAttachments) {
unsentBuilder.addPendingFileAttachment(attachment);
}
final MessagePlus messagePlus = unsentBuilder.build();
if(mConfiguration.isLocationLookupEnabled) {
ArrayList<MessagePlus> mp = new ArrayList<MessagePlus>(1);
mp.add(messagePlus);
lookupLocation(mp, true);
}
insertIntoDatabase(messagePlus);
TreeMap<Long, MessagePlus> channelUnsentMessages = getUnsentMessages(channelId);
channelUnsentMessages.put(messagePlus.getDisplayDate().getTime(), messagePlus);
TreeMap<Long, MessagePlus> newChannelMessages = new TreeMap<Long, MessagePlus>(new ReverseChronologicalComparator());
newChannelMessages.put(messagePlus.getDisplayDate().getTime(), messagePlus);
newChannelMessages.putAll(channelMessages);
mMessages.put(channelId, newChannelMessages);
//update the MinMaxPair
//we can assume the new id is the max (that's how we generated it)
//but we have to check to see if the time is min or max
MinMaxPair minMaxPair = getMinMaxPair(channelId);
minMaxPair.expandDateIfMinOrMax(messagePlus.getDisplayDate().getTime());
Log.d(TAG, "Created and stored unsent message with id " + newMessageIdString + " for channel " + channelId + " and time " + messagePlus.getDisplayDate().getTime());
if(attemptToSendImmediately) {
sendUnsentMessages(channelId);
}
return messagePlus;
}
/**
* Create a draft MessagePlus and persist it to the the database.
*
* Although drafts are considered "unsent," they will not be sent by sendAllUnsent().
*
* Additionally, draft MessagePlus objects will not have annotations or hashtags extracted.
*
* @param channelId the id of the Channel in which the Message should be created.
* @param message The Message to be created.
* @return the draft MessagePlus that was created and persisted.
*/
public synchronized MessagePlus createMessageDraft(final String channelId, Message message) {
return createMessageDraft(channelId, message, new ArrayList<PendingFileAttachment>(0));
}
/**
* Create a draft MessagePlus that requires pending files to be uploaded prior to creation.
*
* Although drafts are considered "unsent," they will not be sent by sendAllUnsent().
*
* Additionally, draft MessagePlus objects will not have annotations or hashtags extracted.
*
* @param channelId the id of the Channel in which the Message should be created.
* @param message The Message to be created.
* @return the draft MessagePlus that was created and persisted.
*/
public synchronized MessagePlus createMessageDraft(String channelId, Message message, List<PendingFileAttachment> pendingFileAttachments) {
String newMessageIdString = UUID.randomUUID().toString();
MessagePlus.UnsentMessagePlusBuilder unsentBuilder = MessagePlus.UnsentMessagePlusBuilder.newBuilder(channelId, newMessageIdString, message);
for(PendingFileAttachment attachment : pendingFileAttachments) {
unsentBuilder.addPendingFileAttachment(attachment);
}
final MessagePlus messagePlus = unsentBuilder.build();
mDatabase.insertOrReplaceMessageDraft(messagePlus);
return messagePlus;
}
/**
* Delete a Message. If the specified Message is unsent, it will simply be deleted from the local
* sqlite database and no server request is required.
*
* @param messagePlus The MessagePlus associated with the Message to be deleted
*/
public synchronized void deleteMessage(final MessagePlus messagePlus) {
deleteMessage(messagePlus, null);
}
/**
* Delete a Message. If the specified Message is unsent, it will simply be deleted from the local
* sqlite database and no server request is required.
*
* @param messagePlus The MessagePlus associated with the Message to be deleted
* @param handler The handler that will act as a callback upon deletion.
*/
public synchronized void deleteMessage(final MessagePlus messagePlus, final MessageDeletionResponseHandler handler) {
deleteMessage(messagePlus, false, handler);
}
/**
* Delete a Message. If the specified Message is unsent, it will simply be deleted from the local
* sqlite database and no server request is required.
*
* @param messagePlus The MessagePlus associated with the Message to be deleted
* @param deleteAssociatedFiles true if all files from OEmbed and attachment annotations should be deleted from
* the server, false otherwise. This will never affect local files.
* @param handler The handler that will act as a callback upon deletion.
*/
public synchronized void deleteMessage(final MessagePlus messagePlus, boolean deleteAssociatedFiles, final MessageDeletionResponseHandler handler) {
if(messagePlus.isUnsent()) {
Message message = messagePlus.getMessage();
String channelId = message.getChannelId();
mDatabase.deleteMessage(messagePlus);
getUnsentMessages(channelId).remove(messagePlus.getDisplayDate().getTime());
deleteMessageFromChannelMapAndUpdateMinMaxPair(messagePlus);
if(handler != null) {
handler.onSuccess();
}
} else {
final Runnable runnable = new Runnable() {
@Override
public void run() {
mDatabase.insertOrReplacePendingMessageDeletion(messagePlus);
mDatabase.deleteMessage(messagePlus);
deleteMessageFromChannelMapAndUpdateMinMaxPair(messagePlus);
mClient.deleteMessage(messagePlus.getMessage(), new MessageResponseHandler() {
//note: if the message was previously deleted, then we get a 200 and
//onSuccess() is called. this differs from file deletion behavior -
//the same scenario with a file deletion would result in a 403.
@Override
public void onSuccess(Message responseData) {
mDatabase.deletePendingMessageDeletion(responseData.getId());
if(handler != null) {
handler.onSuccess();
}
}
@Override
public void onError(Exception error) {
super.onError(error);
if(handler != null) {
handler.onError(error);
}
}
});
}
};
if(deleteAssociatedFiles) {
List<Annotation> oEmbeds = messagePlus.getMessage().getAnnotationsOfType(Annotations.OEMBED);
deleteOEmbed(0, oEmbeds, new Runnable() {
@Override
public void run() {
List<Annotation> attachments = messagePlus.getMessage().getAnnotationsOfType(Annotations.ATTACHMENTS);
deleteAttachmentsLists(0, attachments, runnable);
}
});
} else {
runnable.run();
}
}
}
/**
* Delete a Message draft.
*
* @param messagePlus the draft to delete.
*/
public void deleteMessageDraft(MessagePlus messagePlus) {
mDatabase.deleteMessageDraft(messagePlus);
}
private synchronized void deleteOEmbed(final int index, final List<Annotation> oEmbedAnnotations, final Runnable completionRunnable) {
if(index >= oEmbedAnnotations.size()) {
completionRunnable.run();
} else {
Annotation oEmbed = oEmbedAnnotations.get(index);
final String fileId = (String) oEmbed.getValue().get("file_id");
if(fileId != null) {
mClient.deleteFile(fileId, new FileResponseHandler() {
@Override
public void onSuccess(File responseData) {
deleteOEmbed(index + 1, oEmbedAnnotations, completionRunnable);
}
@Override
public void onError(Exception error) {
super.onError(error);
//statusCode == null probably means no internet
//statusCode 403 means it's already deleted
Integer statusCode = getStatusCode();
if(statusCode == null || statusCode != 403) {
mDatabase.insertOrReplacePendingFileDeletion(fileId);
}
deleteOEmbed(index + 1, oEmbedAnnotations, completionRunnable);
}
});
} else {
deleteOEmbed(index + 1, oEmbedAnnotations, completionRunnable);
}
}
}
private synchronized void deleteAttachmentsLists(final int index, final List<Annotation> attachmentsAnnotations, final Runnable completionRunnable) {
if(index >= attachmentsAnnotations.size()) {
completionRunnable.run();
} else {
Annotation attachment = attachmentsAnnotations.get(index);
deleteFileInAttachmentsAnnotation(0, (List<Map<String, Object>>) attachment.getValueForKey(Annotations.FILE_LIST), new Runnable() {
@Override
public void run() {
deleteAttachmentsLists(index+1, attachmentsAnnotations, completionRunnable);
}
});
}
}
private synchronized void deleteFileInAttachmentsAnnotation(final int index, final List<Map<String, Object>> fileList, final Runnable completionRunnable) {
if(index >= fileList.size()) {
completionRunnable.run();
} else {
Map<String, Object> file = fileList.get(index);
final String fileId = (String) file.get("file_id");
mClient.deleteFile(fileId, new FileResponseHandler() {
@Override
public void onSuccess(File responseData) {
deleteFileInAttachmentsAnnotation(index + 1, fileList, completionRunnable);
}
@Override
public void onError(Exception error) {
super.onError(error);
//statusCode == null probably means no internet
//statusCode 403 means it's already deleted
Integer statusCode = getStatusCode();
if(statusCode == null || statusCode != 403) {
mDatabase.insertOrReplacePendingFileDeletion(fileId);
}
deleteFileInAttachmentsAnnotation(index + 1, fileList, completionRunnable);
}
});
}
}
private synchronized void deleteMessageFromChannelMapAndUpdateMinMaxPair(MessagePlus messagePlus) {
Long removedTime = messagePlus.getDisplayDate().getTime();
String channelId = messagePlus.getMessage().getChannelId();
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
if(channelMessages.containsKey(removedTime)) {
//
//modify the MinMaxPair if the removed message was at the min or max date/id.
//we know the channel messages are ordered by date, but the ids are not necessarily ordered.
//
MinMaxPair minMaxPair = getMinMaxPair(channelId);
String deletedMessageId = messagePlus.getMessage().getId();
boolean adjustMax = deletedMessageId.equals(minMaxPair.maxId);
boolean adjustMin = deletedMessageId.equals(minMaxPair.minId);
Integer maxIdAsInteger = minMaxPair.getMaxIdAsInteger();
Integer minIdAsInteger = minMaxPair.getMinIdAsInteger();
Integer newMaxId = null;
Integer newMinId = null;
//we have to iterate for these reasons:
//1. ids are not in order in map, need to find new min/max
//2. need to get to the second to last date (if the deleted message was the last)
Iterator<Long> timeIterator = channelMessages.keySet().iterator();
Long secondToLastDate = null;
Long lastDate = null;
while(timeIterator.hasNext()) {
Long nextTime = timeIterator.next();
//so this is the second date, and the first date was the one that was removed
//the new max date is the second key.
if(lastDate != null && secondToLastDate == null && lastDate.equals(removedTime) ) {
minMaxPair.maxDate = nextTime;
}
MessagePlus nextMessagePlus = channelMessages.get(nextTime);
if(!nextMessagePlus.isUnsent()) {
Integer nextId = Integer.parseInt(nextMessagePlus.getMessage().getId());
if(adjustMax && maxIdAsInteger > nextId && (newMaxId == null || nextId > newMaxId)) {
newMaxId = nextId;
}
if(adjustMin && minIdAsInteger < nextId && (newMinId == null || nextId < newMinId)) {
newMinId = nextId;
}
}
secondToLastDate = lastDate;
lastDate = nextTime;
}
//the last date was the removed one, so the new min date is the second to last date.
if(removedTime.equals(lastDate)) {
minMaxPair.minDate = secondToLastDate;
}
if(newMaxId != null) {
minMaxPair.maxId = String.valueOf(newMaxId);
}
if(newMinId != null) {
minMaxPair.minId = String.valueOf(newMinId);
}
//handle the edge case where there is only one item in the map, about to get removed
if(channelMessages.size() == 1) {
minMaxPair.maxId = null;
minMaxPair.minId = null;
minMaxPair.maxDate = null;
minMaxPair.minDate = null;
}
channelMessages.remove(removedTime);
}
}
/**
* Obtain fresh copy of the specified Message.
*
* This is most useful in cases where fields have expired (e.g. file urls).
*
* @param message the Message to refresh.
* @param handler The handler that will act as a callback upon refresh completion.
*/
public synchronized void refreshMessage(final Message message, final MessageManagerResponseHandler handler) {
final String channelId = message.getChannelId();
mClient.retrieveMessage(channelId, message.getId(), mParameters.get(channelId), new MessageResponseHandler() {
@Override
public void onSuccess(Message responseData) {
MessagePlus mPlus = new MessagePlus(responseData);
adjustDate(mPlus);
insertIntoDatabase(mPlus);
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
if(channelMessages != null) { //could be null of channel messages weren't loaded first, etc.
channelMessages.put(mPlus.getDisplayDate().getTime(), mPlus);
}
ArrayList<MessagePlus> messagePlusList = new ArrayList<MessagePlus>(1);
messagePlusList.add(mPlus);
performLookups(messagePlusList, true);
handler.onSuccess(messagePlusList);
}
@Override
public void onError(Exception error) {
super.onError(error);
handler.onError(error);
}
});
}
public synchronized void refreshMessages(Collection<String> messageIds, final String channelId, final MessageManagerResponseHandler handler) {
mClient.retrieveMessagesById(messageIds, mParameters.get(channelId), new MessageListResponseHandler() {
@Override
public void onSuccess(MessageList responseData) {
TreeMap<Long, MessagePlus> messagePlusMap = new TreeMap<Long, MessagePlus>(new ReverseChronologicalComparator());
TreeMap<Long, MessagePlus> channelMessages = mMessages.get(channelId);
for(Message message : responseData) {
MessagePlus mPlus = new MessagePlus(message);
Date date = adjustDate(mPlus);
insertIntoDatabase(mPlus);
if(channelMessages != null && channelMessages.containsKey(mPlus.getDisplayDate().getTime())) { //could be null of channel messages weren't loaded first, etc.
channelMessages.put(mPlus.getDisplayDate().getTime(), mPlus);
}
messagePlusMap.put(mPlus.getDisplayDate().getTime(), mPlus);
}
ArrayList<MessagePlus> messagePlusses = new ArrayList<MessagePlus>(messagePlusMap.values());
performLookups(messagePlusses, true);
handler.onSuccess(messagePlusses);
}
@Override
public void onError(Exception error) {
super.onError(error);
handler.onError(error);
}
});
}
/**
* Get the FullSyncState for the Channel with the specified id.
*
* @param channelId the channel id
* @return a FullSyncState corresponding to the sync state of the Channel
* with the specified id
*/
public FullSyncState getFullSyncState(String channelId) {
return ADNSharedPreferences.getFullSyncState(channelId);
}
/**
* Set the FullSyncState for the Channel with the specified id.
*
* @param channelId the channel id
* @param state the FullSyncState to associate with the Channel.
*/
public void setFullSyncState(String channelId, FullSyncState state) {
ADNSharedPreferences.setFullSyncState(channelId, state);
}
/**
* Get a FullSyncState representing the sync state of multiple channels.
* In some cases, we might need several channels to be synced, and one
* or more of them may be in a NOT_STARTED or STARTED state. Since we typically
* would not need to disclose granular details about the sync state of
* many channels to a user, this method will return STARTED if *any* channel
* in the provided array is in the STARTED state. Otherwise, NOT_STARTED will
* be returned if any of the channels is not COMPLETE.
*
* @param channels
* @return A FullSyncState representing the sync state of the provided group of Channels.
*/
public synchronized FullSyncState getFullSyncState(Channel[] channels) {
FullSyncState state = FullSyncState.COMPLETE;
for(Channel channel : channels) {
if(getFullSyncState(channel.getId()) == FullSyncState.STARTED) {
return FullSyncState.STARTED;
} else if(getFullSyncState(channel.getId()) == FullSyncState.NOT_STARTED) {
state = FullSyncState.NOT_STARTED;
}
}
return state;
}
/**
* Sync and persist all Messages for every provided Channel.
*
* Each Channel is synced - one at a time. If an Action Channel is encountered, the
* ActionMessageManager is used to sync the Messages in that Channel. Unlike the
* other retrieveAndPersistAllMessages method that accepts a single Channel id, this
* method examines the FullSyncState for a Channel and skips it if it is marked COMPLETE.
*
* @param channels
* @param responseHandler
*/
public synchronized void retrieveAndPersistAllMessages(Channel[] channels, MessageManagerMultiChannelSyncResponseHandler responseHandler) {
int i = 0;
while(i < channels.length && getFullSyncState(channels[i].getId()) == FullSyncState.COMPLETE) {
i++;
}
if(i == channels.length) {
responseHandler.onSuccess();
} else {
retrieveAndPersistAllMessages(channels, i, responseHandler);
}
}
private synchronized void retrieveAndPersistAllMessages(final Channel[] channels, final int currentChannelIndex, final MessageManagerMultiChannelSyncResponseHandler responseHandler) {
MessageManagerSyncResponseHandler currentChannelSyncHandler = new MessageManagerSyncResponseHandler() {
@Override
public void onSuccess(List<MessagePlus> responseData) {
int i = currentChannelIndex + 1;
while(i < channels.length && getFullSyncState(channels[i].getId()) == FullSyncState.COMPLETE) {
i++;
}
if(i == channels.length) {
responseHandler.onSuccess();
} else {
retrieveAndPersistAllMessages(channels, i, responseHandler);
}
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
responseHandler.onError(exception);
}
};
Channel nextChannel = channels[currentChannelIndex];
String type = nextChannel.getType();
if(PrivateChannelUtility.CHANNEL_TYPE_ACTION.equals(type)) {
if(mAttachedActionMessageManager != null) {
mAttachedActionMessageManager.retrieveAndPersistAllActionMessages(nextChannel.getId(), currentChannelSyncHandler);
} else {
throw new IllegalStateException("ActionMessageManager must be attached to persist action channel messages.");
}
} else {
retrieveAndPersistAllMessages(channels[currentChannelIndex].getId(), currentChannelSyncHandler);
}
}
/**
* Sync and persist all Messages in a Channel.
*
* This is intended to be used as a one-time sync, e.g. after a user signs in. Typically, you
* should call getFullSyncState() to check whether this channel has already been synced before
* calling this method.
*
* Because this could potentially result in a very large amount of Messages being obtained,
* the provided MessageManagerResponseHandler will only be passed the first 100 Messages that are
* obtained, while the others will be persisted to the sqlite database, but not kept in memory.
* However, these can easily be loaded into memory afterwards by calling loadPersistedMessages().
*
* @param channelId The id of the Channel from which to obtain Messages.
* @param responseHandler MessageManagerResponseHandler
*
* @see MessageManager#loadPersistedMessages(String, int)
*/
public synchronized void retrieveAndPersistAllMessages(String channelId, MessageManagerSyncResponseHandler responseHandler) {
ADNSharedPreferences.setFullSyncState(channelId, FullSyncState.STARTED);
final ArrayList<MessagePlus> messages = new ArrayList<MessagePlus>(MAX_MESSAGES_RETURNED_ON_SYNC);
String sinceId = null;
String beforeId = null;
retrieveAllMessages(messages, sinceId, beforeId, channelId, responseHandler);
}
private synchronized void retrieveAllMessages(final ArrayList<MessagePlus> messages, String sinceId, String beforeId, final String channelId, final MessageManagerSyncResponseHandler responseHandler) {
QueryParameters params = (QueryParameters) mParameters.get(channelId).clone();
params.put("since_id", sinceId);
params.put("before_id", beforeId);
params.put("count", String.valueOf(MAX_MESSAGES_RETURNED_ON_SYNC));
boolean keepInMemory = messages.size() == 0;
retrieveMessages(params, null, channelId, keepInMemory, new MessageManagerResponseHandler() {
@Override
public void onSuccess(List<MessagePlus> responseData) {
if(messages.size() == 0) {
messages.addAll(responseData);
}
responseHandler.setNumMessagesSynced(responseHandler.getNumMessagesSynced() + responseData.size());
responseHandler.onBatchSynced(responseData);
if(isMore()) {
//never rely on MinMaxPair for min id here because
//when keepInMemory = false, the MinMaxPair will not change
//(and this would keep requesting the same batch over and over).
MessagePlus minMessage = responseData.get(responseData.size() - 1);
retrieveAllMessages(messages, null, minMessage.getMessage().getId(), channelId, responseHandler);
} else {
ADNSharedPreferences.setFullSyncState(channelId, FullSyncState.COMPLETE);
Log.d(TAG, "Num messages synced: " + responseHandler.getNumMessagesSynced());
responseHandler.onSuccess(messages);
}
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
responseHandler.onError(exception);
}
});
}
private synchronized boolean retrieveMessages(final String channelId, final String sinceId, final String beforeId, final MessageFilter messageFilter, final MessageManagerResponseHandler handler) {
QueryParameters params = (QueryParameters) mParameters.get(channelId).clone();
params.put("since_id", sinceId);
params.put("before_id", beforeId);
return retrieveMessages(params, messageFilter, channelId, false, handler);
}
private synchronized void sendUnsentMessages(final TreeMap<Long, MessagePlus> unsentMessages, final ArrayList<String> sentMessageIds, final ArrayList<String> replacementMessageIds) {
final MessagePlus messagePlus = unsentMessages.get(unsentMessages.keySet().iterator().next());
if(messagePlus.hasPendingFileAttachments()) {
String pendingFileId = messagePlus.getPendingFileAttachments().keySet().iterator().next();
Set<String> messagesNeedingPendingFile = getMessageIdsNeedingPendingFile(pendingFileId);
messagesNeedingPendingFile.add(messagePlus.getMessage().getId());
FileManager.getInstance(mClient).startPendingFileUpload(pendingFileId, messagePlus.getMessage().getChannelId());
return;
}
Message theMessage = messagePlus.getMessage();
final Message message = (Message) AppDotNetObjectCloner.getClone(theMessage);
final String channelId = message.getChannelId();
//we had them set for display locally, but we should
//let the server generate the "real" entities.
message.setEntities(null);
mClient.createMessage(channelId, message, mParameters.get(channelId), new MessageResponseHandler() {
@Override
public void onSuccess(Message newMessage) {
String newMessageId = newMessage.getId();
Log.d(TAG, "Channel " + channelId + "; Successfully sent unsent message with id " + message.getId() + "; replaced with message " + newMessageId);
long sentMessageTime = messagePlus.getDisplayDate().getTime();
//
//TODO: is using this "removed" in the if block below the right
//thing to be doing? how does that mean it's replacing an existing
//message in memory? add comment with explanation!
//
MessagePlus removed = unsentMessages.remove(sentMessageTime);
sentMessageIds.add(message.getId());
replacementMessageIds.add(newMessageId);
mDatabase.deleteMessage(messagePlus);
deleteMessageFromChannelMapAndUpdateMinMaxPair(messagePlus);
MinMaxPair minMaxPair = getMinMaxPair(channelId);
MessagePlus newMessagePlus = new MessagePlus(newMessage);
Date date = adjustDate(newMessagePlus);
performLookups(newMessagePlus, true);
insertIntoDatabase(newMessagePlus);
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
//just like with retrieveMessages(), only keep this message in memory if
//it is replacing an existing message in memory, or if the date is greater
//than the current min date in memory.
long time = date.getTime();
if(removed != null || minMaxPair.minDate == null || time >= minMaxPair.minDate) {
channelMessages.put(time, newMessagePlus);
minMaxPair.expandDateIfMinOrMax(time);
minMaxPair.expandIdIfMinOrMax(newMessageId);
}
if(unsentMessages.size() > 0) {
sendUnsentMessages(unsentMessages, sentMessageIds, replacementMessageIds);
} else {
if(mAttachedActionMessageManager != null) {
mAttachedActionMessageManager.onUnsentMessagesSentPrivate(newMessage.getChannelId(), sentMessageIds, replacementMessageIds);
} else {
sendUnsentMessagesSentBroadcast(newMessage.getChannelId(), sentMessageIds, replacementMessageIds);
}
}
}
@Override
public void onError(Exception exception) {
super.onError(exception);
int sendAttempts = messagePlus.incrementSendAttempts();
mDatabase.insertOrReplaceMessage(messagePlus);
Intent i = new Intent(INTENT_ACTION_UNSENT_MESSAGE_SEND_FAILURE);
i.putExtra(EXTRA_CHANNEL_ID, message.getChannelId());
i.putExtra(EXTRA_MESSAGE_ID, message.getId());
i.putExtra(EXTRA_SEND_ATTEMPTS, sendAttempts);
mContext.sendBroadcast(i);
}
});
}
void sendUnsentMessagesSentBroadcast(String channelId, ArrayList<String> sentMessageIds, ArrayList<String> replacementMessageIds) {
Intent i = new Intent(INTENT_ACTION_UNSENT_MESSAGES_SENT);
i.putExtra(EXTRA_CHANNEL_ID, channelId);
i.putStringArrayListExtra(EXTRA_SENT_MESSAGE_IDS, sentMessageIds);
i.putStringArrayListExtra(EXTRA_SENT_MESSAGE_REPLACEMENT_IDS, replacementMessageIds);
mContext.sendBroadcast(i);
}
/**
* Return true if the Channel with the specified id has unsent Messages.
*
* @param channelId the Channel id
* @return true if the Channel has unsent Messages, false otherwise
*/
public synchronized boolean hasUnsentMessages(String channelId) {
return getUnsentMessages(channelId).size() > 0;
}
/**
* Send all pending deletions and unsent Messages in a Channel.
* Calling this with an Action Channel will result in an IllegalStateException (you
* should never have to manually send Action Channel messages).
*
* The pending deletions will be sent first.
*
* @param channel the Channel
*/
public void sendAllUnsent(Channel channel) {
if(AnnotationUtility.getActionChannelType(channel) == null) {
sendAllUnsent(channel.getId());
} else {
throw new IllegalStateException("You cannot call MessageManager.sendAllUnsent() with an Action Channel.");
}
}
/**
* Send all pending deletions and unsent Messages in a Channel.
*
* The pending deletions will be sent first.
*
* @param channelId the Channel id
*/
synchronized void sendAllUnsent(final String channelId) {
FileManager.getInstance(mClient).sendPendingFileDeletions();
sendPendingDeletions(channelId, new MessageDeletionResponseHandler() {
@Override
public void onSuccess() {
sendUnsentMessages(channelId);
}
@Override
public void onError(Exception exception) {
Log.e(TAG, exception.getMessage(), exception);
//try this anyway.
sendUnsentMessages(channelId);
}
});
}
/**
* Send all unsent Messages in a Channel.
*
* @param channelId the the Channel id
* @return true if unsent Messages are being sent, false if none exist
*/
synchronized boolean sendUnsentMessages(final String channelId) {
TreeMap<Long, MessagePlus> unsentMessages = getUnsentMessages(channelId);
if(unsentMessages.size() > 0) {
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
if(channelMessages.size() == 0) {
//we do this so that the max id for this channel is known.
loadPersistedMessages(channelId, unsentMessages.size() + 1);
}
ArrayList<String> sentMessageIds = new ArrayList<String>(unsentMessages.size());
ArrayList<String> replacementMessageIds = new ArrayList<String>(unsentMessages.size());
sendUnsentMessages(unsentMessages, sentMessageIds, replacementMessageIds);
return true;
}
return false;
}
/**
* Send all pending Message deletions in a Channel.
*
* @param channelId the Channel id
* @param responseHandler MessageDeletionResponseHandler
*/
public synchronized void sendPendingDeletions(final String channelId, MessageDeletionResponseHandler responseHandler) {
HashMap<String, PendingMessageDeletion> pendingMessageDeletions = mDatabase.getPendingMessageDeletions(channelId);
if(pendingMessageDeletions.size() > 0) {
ArrayList<PendingMessageDeletion> deletions = new ArrayList<PendingMessageDeletion>(pendingMessageDeletions.values());
sendPendingDeletion(0, deletions, responseHandler);
} else if(responseHandler != null) {
responseHandler.onSuccess();
}
}
private synchronized void sendPendingDeletion(final int index, final List<PendingMessageDeletion> pendingMessageDeletions, final MessageDeletionResponseHandler responseHandler) {
if(index >= pendingMessageDeletions.size()) {
if(responseHandler != null) {
responseHandler.onSuccess();
}
} else {
final PendingMessageDeletion deletion = pendingMessageDeletions.get(index);
mClient.deleteMessage(deletion.getChannelId(), deletion.getMessageId(), new MessageResponseHandler() {
@Override
public void onSuccess(Message responseData) {
mDatabase.deletePendingMessageDeletion(deletion.getMessageId());
sendPendingDeletion(index + 1, pendingMessageDeletions, responseHandler);
}
@Override
public void onError(Exception error) {
Log.e(TAG, "failed to send pending file deletion for message " + deletion.getMessageId() + "; " + error.getMessage(), error);
if(responseHandler != null) {
responseHandler.onError(error);
}
}
});
}
}
private synchronized boolean retrieveMessages(final QueryParameters queryParameters,
final MessageFilter filter,
final String channelId,
final boolean forceKeepInMemory,
final MessageManagerResponseHandler handler) {
TreeMap<Long, MessagePlus> unsentMessages = getUnsentMessages(channelId);
HashMap<String, PendingMessageDeletion> pendingMessageDeletions = mDatabase.getPendingMessageDeletions(channelId);
if(unsentMessages.size() > 0 || pendingMessageDeletions.size() > 0) {
return false;
}
mClient.retrieveMessagesInChannel(channelId, queryParameters, new MessageListResponseHandler() {
@Override
public void onSuccess(final MessageList responseData) {
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
TreeMap<Long, MessagePlus> newestMessagesMap = new TreeMap<Long, MessagePlus>(new ReverseChronologicalComparator());
TreeMap<Long, MessagePlus> newFullChannelMessagesMap = new TreeMap<Long, MessagePlus>(new ReverseChronologicalComparator());
newFullChannelMessagesMap.putAll(channelMessages);
MinMaxPair minMaxPair = getMinMaxPair(channelId);
for(Message m : responseData) {
MessagePlus messagePlus = new MessagePlus(m);
Date date = adjustDate(messagePlus);
long time = date.getTime();
newestMessagesMap.put(time, messagePlus);
//only keep messages in memory if they are newer than the ones
//we currently have in memory, or no messages are in memory, indicating
//that there are no persisted messages.
//(unless forceKeepMemory == true)
if(forceKeepInMemory || minMaxPair.minDate == null || time >= minMaxPair.minDate) {
newFullChannelMessagesMap.put(time, messagePlus);
}
}
if(filter != null) {
TreeMap<Long, MessagePlus> excludedResults = filter.getExcludedResults(newestMessagesMap);
removeExcludedMessages(newFullChannelMessagesMap, excludedResults);
removeExcludedMessages(newestMessagesMap, excludedResults);
if(handler != null) {
handler.setExcludedResults(excludedResults);
}
}
Long minDate = null, maxDate = null;
//this needs to happen after filtering.
//damn. not as efficient as doing it in the loop above.
for(MessagePlus messagePlus : newestMessagesMap.values()) {
insertIntoDatabase(messagePlus);
Long time = messagePlus.getDisplayDate().getTime();
//only consider this a candidate for a min/max if
//we kept it in the newFullChannelMessagesMap - a couple steps above.
if(newFullChannelMessagesMap.containsKey(time)) {
if(minDate == null || time < minDate) {
minDate = time;
}
if(maxDate == null || time > maxDate) {
maxDate = time;
}
}
}
//the important stuff.
mMessages.put(channelId, newFullChannelMessagesMap);
minMaxPair.updateWithCombinedValues(new MinMaxPair(getMinId(), getMaxId(), minDate, maxDate));
ArrayList<MessagePlus> newestMessages = new ArrayList<MessagePlus>(responseData.size());
newestMessages.addAll(newestMessagesMap.values());
performLookups(newestMessages, true);
if(handler != null) {
handler.setIsMore(isMore());
handler.onSuccess(newestMessages);
}
}
@Override
public void onError(Exception error) {
Log.e(TAG, error.getMessage(), error);
if(handler != null) {
handler.onError(error);
}
}
});
return true;
}
private Date adjustDate(MessagePlus messagePlus) {
Date adjustedDate = getAdjustedDate(messagePlus.getMessage());
messagePlus.setDisplayDate(adjustedDate);
return adjustedDate;
}
private void insertIntoDatabase(MessagePlus messagePlus) {
mDatabase.insertOrReplaceMessage(messagePlus);
if(mConfiguration.isHashtagExtractionEnabled) {
mDatabase.insertOrReplaceHashtagInstances(messagePlus);
}
if(mConfiguration.annotationsToExtract != null) {
for(String annotationType : mConfiguration.annotationsToExtract) {
mDatabase.insertOrReplaceAnnotationInstances(annotationType, messagePlus);
}
}
}
private Date getAdjustedDate(Message message) {
return mConfiguration.dateAdapter == null ? message.getCreatedAt() : mConfiguration.dateAdapter.getDisplayDate(message);
}
private void performLookups(MessagePlus message, boolean persist) {
ArrayList<MessagePlus> messagePlusses = new ArrayList<MessagePlus>(1);
messagePlusses.add(message);
performLookups(messagePlusses, persist);
}
private void performLookups(Collection<MessagePlus> messages, boolean persist) {
if(mConfiguration.isLocationLookupEnabled) {
lookupLocation(messages, persist);
}
}
private void removeExcludedMessages(TreeMap<Long, MessagePlus> fromMap, TreeMap<Long, MessagePlus> removedEntries) {
Iterator<Long> filteredTimeIterator = removedEntries.keySet().iterator();
while(filteredTimeIterator.hasNext()) {
fromMap.remove(filteredTimeIterator.next());
}
}
void attachActionMessageManager(ActionMessageManager actionMessageManager) {
mAttachedActionMessageManager = actionMessageManager;
}
private synchronized void onFileUploadComplete(Intent intent) {
String pendingFileId = intent.getStringExtra(FileUploadService.EXTRA_PENDING_FILE_ID);
String associatedChannelId = intent.getStringExtra(FileUploadService.EXTRA_ASSOCIATED_CHANNEL_ID);
if(pendingFileId != null) {
boolean success = intent.getBooleanExtra(FileUploadService.EXTRA_SUCCESS, false);
if(success) {
Log.d(TAG, "Successfully uploaded pending file with id " + pendingFileId);
Set<String> messagesIdsNeedingFile = getMessageIdsNeedingPendingFile(pendingFileId);
if(messagesIdsNeedingFile != null) {
TreeMap<Long, MessagePlus> messagesNeedingFile = mDatabase.getMessages(messagesIdsNeedingFile).getMessages();
//always add the associated channel Id so that we can finish the
//sending of the unsent message in the channel that triggered the upload.
HashSet<String> channelIdsWithMessagesToSend = new HashSet<String>();
channelIdsWithMessagesToSend.add(associatedChannelId);
String fileJson = intent.getStringExtra(FileUploadService.EXTRA_FILE);
File file = AppDotNetGson.getPersistenceInstance().fromJson(fileJson, File.class);
for(MessagePlus messagePlus : messagesNeedingFile.values()) {
Message message = messagePlus.getMessage();
messagePlus.replacePendingFileAttachmentWithAnnotation(pendingFileId, file);
//TODO: this is kind of crappy, but needs to be done
//modify the in-memory message plusses to use this new copy
//in the future, we might want to change the way unsent messages
//are held on to in memory.
String channelId = message.getChannelId();
long time = messagePlus.getDisplayDate().getTime();
TreeMap<Long, MessagePlus> channelMessages = getChannelMessages(channelId);
if(channelMessages.containsKey(time)) {
channelMessages.put(time, messagePlus);
}
TreeMap<Long, MessagePlus> unsentMessages = getUnsentMessages(channelId);
if(unsentMessages.containsKey(time)) {
unsentMessages.put(time, messagePlus);
}
mDatabase.insertOrReplaceMessage(messagePlus);
mDatabase.deletePendingFileAttachment(pendingFileId, message.getId());
if(messagePlus.getPendingFileAttachments().size() == 0) {
channelIdsWithMessagesToSend.add(channelId);
}
}
mMessagesNeedingPendingFiles.remove(pendingFileId);
for(String channelId : channelIdsWithMessagesToSend) {
sendUnsentMessages(channelId);
Log.d(TAG, "Now retrying send for unsent messages in channel " + channelId);
}
}
}
}
}
private final BroadcastReceiver fileUploadReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(FileUploadService.INTENT_ACTION_FILE_UPLOAD_COMPLETE.equals(intent.getAction())) {
onFileUploadComplete(intent);
}
}
};
public static class MessageManagerConfiguration {
public static interface MessageLocationLookupHandler {
public void onSuccess(MessagePlus messagePlus);
public void onException(MessagePlus messagePlus, Exception exception);
}
boolean isLocationLookupEnabled;
boolean isHashtagExtractionEnabled;
MessageDisplayDateAdapter dateAdapter;
MessageLocationLookupHandler locationLookupHandler;
Set<String> annotationsToExtract;
/**
* Set a MessageDisplayDateAdapter.
*
* @param adapter
* @see com.alwaysallthetime.messagebeast.manager.MessageManager.MessageDisplayDateAdapter
*/
public void setMessageDisplayDateAdapter(MessageDisplayDateAdapter adapter) {
this.dateAdapter = adapter;
}
/**
* Enable location lookup on Messages. If enabled, annotations will be examined in order
* to construct a DisplayLocation. A DisplayLocation will be set on the associated MessagePlus
* Object, based off one of these three annotations, if they exist:
*
* net.app.core.checkin
* net.app.ohai.location
* net.app.core.geolocation
*
* In the case of net.app.core.geolocation, an asynchronous task will be fired off to
* perform reverse geolocation on the latitude/longitude coordinates. For this reason, you
* should set a MessageLocationLookupHandler on this configuration if you want to perform
* a task such as update UI after a location is obtained.
*
* If none of these annotations are found, then a null DisplayLocation is set on the
* associated MessagePlus.
*
* @param isEnabled true if location lookup should be performed on all Messages
*
* @see com.alwaysallthetime.messagebeast.model.MessagePlus#getDisplayLocation()
* @see com.alwaysallthetime.messagebeast.model.MessagePlus#hasDisplayLocation()
*/
public void setLocationLookupEnabled(boolean isEnabled) {
this.isLocationLookupEnabled = isEnabled;
}
/**
* Enable hashtag extraction. This tells the MessageManager to store references to hashtags
* in the database so that you can easily find all messages with a specific hashtag at a
* later time.
*
* @param isEnabled true if hashtag extraction should be enabled, false otherwise.
*/
public void setHashtagExtractionEnabled(boolean isEnabled) {
this.isHashtagExtractionEnabled = isEnabled;
}
/**
* Specify a handler to be notified when location lookup has completed for a MessagePlus.
* This is particularly useful when a geolocation annotation requires an asynchronous
* reverse geocoding task.
*
* @param handler
*/
public void setLocationLookupHandler(MessageLocationLookupHandler handler) {
this.locationLookupHandler = handler;
}
/**
* Tell the MessageManager to examine the Annotations on all Messages to see if
* Annotations with the specified type exist. If so, a reference to the Message will be
* persisted to the sqlite database for lookup at a later time. For example, if you
* want to be able to find all Messages with OEmbeds at a later time, then
* you might call this method with the annotation type net.app.core.oembed.
*
* @param annotationType The Annotation type of interest.
*/
public void addAnnotationExtraction(String annotationType) {
if(annotationsToExtract == null) {
annotationsToExtract = new HashSet<String>();
}
annotationsToExtract.add(annotationType);
}
}
}
| 49.1277 | 221 | 0.673372 |
9f56a1ea15ad33b652e55f00b1628a580e4bd257 | 2,831 | package com.ca.agency.car.seller.domain;
import java.io.Serializable;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
public class Listing implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "dealer", referencedColumnName = "id")
private Dealer dealer;
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
private LocalDate postingDate;
private Double price;
@Enumerated(EnumType.STRING)
private ListingState state;
private String brand;
private String model;
private String shortDescription;
private String longDescription;
public Listing() {
super();
}
public Listing(Dealer dealer, Double price, ListingState state, String brand, String model, String shortDescription, String longDescription) {
this.dealer = dealer;
this.price = price;
this.state = state;
this.brand = brand;
this.model = model;
this.shortDescription = shortDescription;
this.longDescription = longDescription;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public LocalDate getPostingDate() {
return postingDate;
}
public void setPostingDate(LocalDate postingDate) {
this.postingDate = postingDate;
}
public ListingState getState() {
return state;
}
public void setState(ListingState state) {
this.state = state;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Dealer getDealer() {
return dealer;
}
public void setDealer(Dealer dealer) {
this.dealer = dealer;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getLongDescription() {
return longDescription;
}
public void setLongDescription(String longDescription) {
this.longDescription = longDescription;
}
}
| 22.648 | 146 | 0.666196 |
7b77478e4b8d94bbcc2cf0dad6d52efbc43ddc6f | 1,269 | package io.github.herobrine2nether.netherLauncher.backend.files;
import io.github.herobrine2nether.netherLauncher.backend.Util.Logging;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
public class FileOps {
public static void NewInstall() {
try {
FileUtils.forceMkdir(Assets.Dir);
FileUtils.forceMkdir(Assets.Versions);
Assets.RAM.createNewFile();
Assets.Account.createNewFile();
} catch (IOException e) {
Logging.Log(e.getMessage(), 3);
e.printStackTrace();
}
SetDefaultSettings();
}
public static void RenewInstall() {
try {
FileUtils.copyURLToFile(Assets.VanillaUrl(), Assets.Vanilla);
} catch (IOException e) {
Logging.Log(e.getMessage(), 3);
e.printStackTrace();
}
SetRenewingSettings();
}
public static void SetDefaultSettings() {
//do one time stuff
}
public static void SetRenewingSettings() {
//do repeated stuff on startup
}
public static void WriteSettings() {
// Write settings to file
}
public static void ReadSettings() {
// Read settings from .cfg
}
}
| 25.38 | 73 | 0.613081 |
1891640e019a7112ca8d01d182cbb07f8d7ea574 | 1,116 | package binarysearch;
import java.util.LinkedList;
import java.util.Queue;
/*
* Problem: https://binarysearch.com/problems/Binary-Tree-to-Linked-List
* Submission: https://binarysearch.com/problems/Binary-Tree-to-Linked-List/submissions/6916754
*/
public class P0231 {
class Solution {
public LLNode solve(Tree root) {
if (root == null)
return null;
var head = new LLNode();
var queue = new LinkedList<Tree>();
traverse(root, queue);
var current = head;
while (!queue.isEmpty()) {
var el = queue.poll();
var l = new LLNode();
l.val = el.val;
current.next = l;
current = current.next;
}
return head.next;
}
private void traverse(Tree node, Queue<Tree> ll) {
if (node == null)
return;
traverse(node.left, ll);
ll.add(node);
traverse(node.right, ll);
}
public class LLNode {
int val;
LLNode next;
}
public class Tree {
int val;
Tree left;
Tree right;
}
}
} | 20.290909 | 96 | 0.547491 |
eb45e476752bceaeebe730187925379907f28121 | 2,921 | package com.moon.util;
import org.junit.jupiter.api.Test;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
/**
* @author benshaoye
*/
class DateUtilTestTest {
@Test
void testNow() {
}
@Test
void testNowDate() {
}
@Test
void testNowSqlDate() {
}
@Test
void testNowSqlTime() {
}
@Test
void testNowCalendar() {
}
@Test
void testClearTime() {
Date date = DateUtil.clearTime(DateUtil.nowDate());
}
@Test
void testClearMilliseconds() {
}
@Test
void testNextYear() {
}
@Test
void testNextMonth() {
}
@Test
void testNextDay() {
}
@Test
void testNextHour() {
}
@Test
void testNextMinute() {
}
@Test
void testNextSecond() {
}
@Test
void testNextMillisecond() {
}
@Test
void testPrevYear() {
}
@Test
void testPrevMonth() {
}
@Test
void testPrevDay() {
}
@Test
void testPrevHour() {
}
@Test
void testPrevMinute() {
}
@Test
void testPrevSecond() {
}
@Test
void testPrevMillisecond() {
}
@Test
void testPlusYears() {
}
@Test
void testPlusMonths() {
}
@Test
void testPlusDays() {
}
@Test
void testPlusHours() {
}
@Test
void testPlusMinutes() {
}
@Test
void testPlusSeconds() {
}
@Test
void testPlusMilliSeconds() {
}
@Test
void testMinusYears() {
}
@Test
void testMinusMonths() {
}
@Test
void testMinusDays() {
}
@Test
void testMinusHours() {
}
@Test
void testMinusMinutes() {
}
@Test
void testMinusSeconds() {
}
@Test
void testMinusMilliSeconds() {
}
@Test
void testSetYear() {
}
@Test
void testSetMonth() {
}
@Test
void testSetDayOfMonth() {
}
@Test
void testSetHour() {
}
@Test
void testSetMinute() {
}
@Test
void testSetSecond() {
}
@Test
void testSetMillisecond() {
}
@Test
void testSet() {
}
@Test
void testGetYear() {
}
@Test
void testGetMonth() {
}
@Test
void testGetDayOfMonth() {
}
@Test
void testGetHour() {
}
@Test
void testGetMinute() {
}
@Test
void testGetSecond() {
}
@Test
void testGetMillisecond() {
}
@Test
void testGet() {
}
@Test
void testCopy() {
}
@Test
void testFormat() {
}
@Test
void testParseToCalendar() {
}
@Test
void testParse() {
}
@Test
void testToSqlTime() {
}
@Test
void testToTimestamp() {
}
@Test
void testToSqlDate() {
}
@Test
void testToDate() {
}
@Test
void testToCalendar() {
}
} | 11.5 | 59 | 0.503595 |
7ea356762ee690db310b50e5add43fdbd31ba689 | 1,189 | /*
* Copyright (C) 2008 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.generics;
public class FooBar<K,V,L> extends Foo<V> implements Bar<K> {
public class C
{
}
public class CI extends C implements Iface
{
}
public FooBar(K k) {
super(null);
throw new RuntimeException("!");
}
public K bar(K arg) {
return null;
}
public FooBar<K,? extends Foo,L> a(K arg) {
return null;
}
public FooBar<V,K,L> b(Bar<? extends K> arg) {
return null;
}
public <L extends C & Iface> void f(L arg) {
}
public V v;
}
| 22.865385 | 75 | 0.640875 |
51329750fdf62de3c86764844f1389299c8e28c3 | 2,571 | package com.example.administrator.myjournal.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.myjournal.R;
import com.example.administrator.myjournal.db.JournalDB;
import com.example.administrator.myjournal.model.Hint;
import com.example.administrator.myjournal.util.MyApplication;
/**
* Created by Administrator on 2016/6/17.
*/
public class ChangeDefinitionActivity extends BaseActivity {
private TextView tagName;
private TextView oldDefinition;
private EditText newDefinition;
private Button certainButton;
private String definition;
private JournalDB journalDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_definition);
newDefinition = (EditText) findViewById(R.id.change_definition);
oldDefinition = (TextView) findViewById(R.id.old_definition);
tagName = (TextView) findViewById(R.id.tag_name);
certainButton = (Button) findViewById(R.id.certain_button);
String tag = getIntent().getStringExtra("tagName");
definition = getIntent().getStringExtra("tagDefinition");
journalDB = JournalDB.getInstance(MyApplication.getContext());
oldDefinition.setText(definition);
tagName.setText(tag);
certainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (newDefinition.getText().length() == 0) {
Toast.makeText(ChangeDefinitionActivity.this, "请检查输入", Toast.LENGTH_SHORT).show();
} else if (definition.equals(newDefinition.getText().toString())){
Toast.makeText(ChangeDefinitionActivity.this, "未修改定义", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ChangeDefinitionActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
Hint hint = new Hint(tagName.getText().toString(), newDefinition.getText().toString());
journalDB.changeDefinition(hint);
Intent backIntent = new Intent();
backIntent.putExtra("content", newDefinition.getText().toString());
setResult(RESULT_OK, backIntent);
finish();
}
}
});
}
}
| 37.26087 | 107 | 0.669389 |
e323c4fea5230bf30f50c474b9e8648d68c765e8 | 148 | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.parser.template;
public interface StringEscaper {
String escape(String str);
} | 16.444444 | 42 | 0.736486 |
26073f92af3460b694888b86f5ae223ba99538d2 | 2,921 | package com.wuest.prefab;
import com.wuest.prefab.proxy.messages.TagMessage;
import com.wuest.prefab.structures.messages.StructureTagMessage;
import io.netty.util.internal.StringUtil;
import net.minecraft.core.Direction;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.TextComponent;
import org.apache.commons.lang3.text.WordUtils;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
public class Utils {
public static String[] WrapString(String value) {
return Utils.WrapString(value, 50);
}
public static String[] WrapString(String value, int width) {
String result = WordUtils.wrap(value, width);
String[] results = result.split("\n");
String[] returnValue = new String[results.length];
for (int i = 0; i < results.length; i++) {
returnValue[i] = results[i].trim();
}
return returnValue;
}
public static ArrayList<TextComponent> WrapStringToLiterals(String value) {
return Utils.WrapStringToLiterals(value, 50);
}
/**
* This is a wrapper method to make sure that when minecraft changes the name of the StringTextComponent again it's a single place update.
*
* @param value The text to create the object from.
* @return A StringTextComponent object.
*/
public static TextComponent createTextComponent(String value) {
return new TextComponent(value);
}
public static ArrayList<TextComponent> WrapStringToLiterals(String value, int width) {
String[] values = Utils.WrapString(value, width);
ArrayList<TextComponent> returnValue = new ArrayList<>();
for (String stringValue : values) {
returnValue.add(Utils.createTextComponent(stringValue));
}
return returnValue;
}
public static TagMessage createMessage(CompoundTag tag) {
return new TagMessage(tag);
}
public static <T extends TagMessage> T createGenericMessage(CompoundTag tag, Class<T> tClass) {
try {
return tClass.getConstructor(CompoundTag.class).newInstance(tag);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
public static StructureTagMessage createStructureMessage(CompoundTag tag, StructureTagMessage.EnumStructureConfiguration structureConfiguration) {
return new StructureTagMessage(tag, structureConfiguration);
}
public static Direction getDirectionByName(String name) {
if (!StringUtil.isNullOrEmpty(name)) {
for (Direction direction : Direction.values()) {
if (direction.getSerializedName().equalsIgnoreCase(name)) {
return direction;
}
}
}
return Direction.NORTH;
}
}
| 33.574713 | 150 | 0.680931 |
03922c49d65fc7323966ccc2fc603f85f93d330f | 203 | package dev.cheerfun.pixivic.biz.web.admin.dto;
import lombok.Data;
/**
* @author OysterQAQ
* @version 1.0
* @date 2020/4/24 3:26 下午
* @description CommentDTO
*/
@Data
public class CommentDTO {
}
| 14.5 | 47 | 0.694581 |
543916629acec62f084ed8f26f5150c7f4d31b37 | 4,991 | package com.bitdubai.fermat_ccp_plugin.layer.request.crypto_payment.developer.bitdubai.version_1.structure;
import com.bitdubai.fermat_api.layer.all_definition.enums.Actors;
import com.bitdubai.fermat_api.layer.all_definition.enums.BlockchainNetworkType;
import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress;
import com.bitdubai.fermat_ccp_api.layer.request.crypto_payment.enums.CryptoPaymentState;
import com.bitdubai.fermat_ccp_api.layer.request.crypto_payment.enums.CryptoPaymentType;
import com.bitdubai.fermat_ccp_api.layer.request.crypto_payment.interfaces.CryptoPayment;
import java.util.UUID;
/**
* The class <code>com.bitdubai.fermat_ccp_plugin.layer.request.crypto_payment.developer.bitdubai.version_1.structure.CryptoPaymentRequestRecord</code>
* is the representation of a Crypto Payment Request Record in database.
* <p/>
* Created by Leon Acosta - ([email protected]) on 01/10/2015.
*/
public class CryptoPaymentRequestRecord implements CryptoPayment {
private final UUID requestId ;
private final String walletPublicKey ;
private final String identityPublicKey;
private final Actors identityType ;
private final String actorPublicKey ;
private final Actors actorType ;
private final String description ;
private final CryptoAddress cryptoAddress ;
private final long amount ;
private final long startTimeStamp ;
private final long endTimeStamp ;
private final CryptoPaymentType type ;
private final CryptoPaymentState state ;
private final BlockchainNetworkType networkType ;
public CryptoPaymentRequestRecord(final UUID requestId ,
final String walletPublicKey ,
final String identityPublicKey,
final Actors identityType ,
final String actorPublicKey ,
final Actors actorType ,
final String description ,
final CryptoAddress cryptoAddress ,
final long amount ,
final long startTimeStamp ,
final long endTimeStamp ,
final CryptoPaymentType type ,
final CryptoPaymentState state ,
final BlockchainNetworkType networkType ) {
this.requestId = requestId ;
this.walletPublicKey = walletPublicKey ;
this.identityPublicKey = identityPublicKey;
this.identityType = identityType ;
this.actorPublicKey = actorPublicKey ;
this.actorType = actorType ;
this.description = description ;
this.cryptoAddress = cryptoAddress ;
this.amount = amount ;
this.startTimeStamp = startTimeStamp ;
this.endTimeStamp = endTimeStamp ;
this.type = type ;
this.state = state ;
this.networkType = networkType ;
}
@Override
public UUID getRequestId() {
return requestId;
}
@Override
public String getWalletPublicKey() {
return walletPublicKey;
}
@Override
public String getIdentityPublicKey() {
return identityPublicKey;
}
@Override
public String getActorPublicKey() {
return actorPublicKey;
}
@Override
public String getDescription() {
return description;
}
@Override
public CryptoAddress getCryptoAddress() {
return cryptoAddress;
}
@Override
public long getAmount() {
return amount;
}
@Override
public long getStartTimeStamp() {
return startTimeStamp;
}
@Override
public long getEndTimeStamp() {
return endTimeStamp;
}
@Override
public CryptoPaymentType getType() {
return type;
}
@Override
public CryptoPaymentState getState() {
return state;
}
@Override
public Actors getIdentityType() {
return identityType;
}
@Override
public Actors getActorType() {
return actorType;
}
@Override
public BlockchainNetworkType getNetworkType() {
return networkType;
}
}
| 36.698529 | 151 | 0.553997 |
4bed0e39bcfc4f2089b864c142ad1a19d38da183 | 2,643 | /*
* 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.beam.sdk.io.kinesis;
import java.util.NoSuchElementException;
import java.util.Objects;
/**
* Similar to Guava {@code Optional}, but throws {@link NoSuchElementException} for missing element.
*/
abstract class CustomOptional<T> {
@SuppressWarnings("unchecked")
public static <T> CustomOptional<T> absent() {
return (Absent<T>) Absent.INSTANCE;
}
public static <T> CustomOptional<T> of(T v) {
return new Present<>(v);
}
public abstract boolean isPresent();
public abstract T get();
private static class Present<T> extends CustomOptional<T> {
private final T value;
private Present(T value) {
this.value = value;
}
@Override
public boolean isPresent() {
return true;
}
@Override
public T get() {
return value;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Present)) {
return false;
}
Present<?> present = (Present<?>) o;
return Objects.equals(value, present.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
private static class Absent<T> extends CustomOptional<T> {
private static final Absent<Object> INSTANCE = new Absent<>();
private Absent() {
}
@Override
public boolean isPresent() {
return false;
}
@Override
public T get() {
throw new NoSuchElementException();
}
@Override
public boolean equals(Object o) {
return o instanceof Absent;
}
@Override
public int hashCode() {
return 0;
}
}
}
| 26.43 | 100 | 0.608778 |
1e07b5fccb118bb3e80f9571688aff08816e689e | 3,985 | package befaster.solutions.CHK;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class CheckoutSolutionTest {
private final CheckoutSolution checkoutSolution = new CheckoutSolution();
@Test
public void shouldReturnMinusOneForInvalidInput() {
assertThat(checkoutSolution.checkout(null), is(-1));
}
@Test
public void shouldReturnZeroForEmptyInput() {
// - {"method":"checkout","params":[""],"id":"CHL_R1_002"}, expected: 0, got: -1
assertThat(checkoutSolution.checkout(""), is(0));
assertThat(checkoutSolution.checkout("a"), is(-1));
assertThat(checkoutSolution.checkout("-"), is(-1));
// id = CHL_R1_009, req = checkout("ABCa"), resp = 4
// id = CHL_R1_010, req = checkout("AxA"), resp = 3
assertThat(checkoutSolution.checkout("ABCa"), is(-1));
assertThat(checkoutSolution.checkout("AxA"), is(-1));
}
@Test
public void shouldReturnItemCost__IfTableContainsItemAndNoSpecialOfferApplicable() {
// - {"method":"checkout","params":["A"],"id":"CHL_R1_003"}, expected: 50, got: 1
// - {"method":"checkout","params":["B"],"id":"CHL_R1_004"}, expected: 30, got: 1
// id = CHL_R1_013, req = checkout("AA"), resp = 2
assertThat(checkoutSolution.checkout("A"), is(50));
assertThat(checkoutSolution.checkout("AA"), is(100));
assertThat(checkoutSolution.checkout("B"), is(30));
assertThat(checkoutSolution.checkout("C"), is(20));
assertThat(checkoutSolution.checkout("D"), is(15));
assertThat(checkoutSolution.checkout("E"), is(40));
}
@Test
public void shouldSumItemsCosts() {
// id = CHL_R1_011, req = checkout("ABCD"), resp = 4
assertThat(checkoutSolution.checkout("ABCD"), is(115));
}
@Test
public void shouldReturnItemCostWithSpecialOffer__IfApplicable() {
// id = CHL_R1_014, req = checkout("AAA"), resp = 3
// id = CHL_R1_019, req = checkout("BB"), resp = 2
// id = CHL_R1_017, req = checkout("AAAAAA"), resp = 6
// id = CHL_R1_021, req = checkout("BBBB"), resp = 4
assertThat(checkoutSolution.checkout("AAA"), is(130));
assertThat(checkoutSolution.checkout("AAAAAA"), is(250));
assertThat(checkoutSolution.checkout("BB"), is(45));
assertThat(checkoutSolution.checkout("BBBB"), is(90));
}
@Test
public void shouldSumSpecialOfferAndUsualCost__IfApplicable() {
assertThat(checkoutSolution.checkout("AAAA"), is(180));
assertThat(checkoutSolution.checkout("AAAAA"), is(200));
assertThat(checkoutSolution.checkout("BBB"), is(75));
assertThat(checkoutSolution.checkout("AAABB"), is(175));
}
@Test
public void shouldNotDependOnItemsOrder() {
//{"method":"checkout","params":["ABCDABCD"],"id":"CHL_R1_022"}, expected: 215, got: 230
//{"method":"checkout","params":["BABDDCAC"],"id":"CHL_R1_023"}, expected: 215, got: 230
//{"method":"checkout","params":["ABCDCBAABCABBAAA"],"id":"CHL_R1_001"}, expected: 505, got: 540// assertThat(checkoutSolution.checkout("ABCDABCD"), is(180));
assertThat(checkoutSolution.checkout("ABCDABCD"), is(215));
assertThat(checkoutSolution.checkout("BABDDCAC"), is(215));
assertThat(checkoutSolution.checkout("ABCDCBAABCABBAAA"), is(495));
}
@Test
public void shouldHandleSpecialOffersWithExtraItems() {
//todo (assumption): free B affect minus to total
assertThat(checkoutSolution.checkout("EE"), is(80));
assertThat(checkoutSolution.checkout("EEEEBB"), is(160));
assertThat(checkoutSolution.checkout("BEBEEE"), is(160));
assertThat(checkoutSolution.checkout("FF"), is(20));
assertThat(checkoutSolution.checkout("FFF"), is(20));
assertThat(checkoutSolution.checkout("FFFFFF"), is(40));
assertThat(checkoutSolution.checkout("VVVVV"), is(220));
}
@Test
public void shouldCombineOffersStartingFromTheBest() {
assertThat(checkoutSolution.checkout("AAAAAA"), is(250));
assertThat(checkoutSolution.checkout("AAAAAAAA"), is(330));
}
}
| 41.947368 | 165 | 0.685571 |
d78baab7d435caf78441aa5c7f5bf18e35bde27d | 354 | /*******************************************************************************
* © 2012 Global Retail Information Ltd.
******************************************************************************/
package com.epa.plugins.exception;
/**
* @author programador6
* @version $Revision: 1.0 $
*/
public class DeviceIOException extends Exception {
}
| 27.230769 | 80 | 0.389831 |
d7e411a9ae0d9340cfecf1fa8240a545c6948c37 | 331 | package cn.xjjdog.bcmall.module.product.persistence.dao;
import cn.xjjdog.bcmall.module.product.persistence.BrandEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Copyright (c) 2021. All Rights Reserved.
*
* @author xjjdog
*/
public interface BrandDao extends JpaRepository<BrandEntity, String> {
}
| 25.461538 | 70 | 0.785498 |
45800128ed52a8cc60634db417256806ca0580d7 | 2,359 | package ru.illine.weather.geomagnetic.config;
import ru.illine.weather.geomagnetic.config.property.RestProperties;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import org.zalando.logbook.Logbook;
import org.zalando.logbook.httpclient.LogbookHttpRequestInterceptor;
import org.zalando.logbook.httpclient.LogbookHttpResponseInterceptor;
@Configuration
class RestTemplateConfig {
private final RestProperties properties;
@Autowired
RestTemplateConfig(RestProperties properties) {
this.properties = properties;
}
@Bean
RestTemplate swpcNoaaRestTemplate(HttpComponentsClientHttpRequestFactory commonHttpRequestFactory) {
return new RestTemplate(commonHttpRequestFactory);
}
@Bean
HttpComponentsClientHttpRequestFactory commonHttpRequestFactory(Logbook logbook,
PoolingHttpClientConnectionManager commonConnection) {
var httpRequestFactory =
new HttpComponentsClientHttpRequestFactory(
HttpClients
.custom()
.setConnectionManager(commonConnection)
.addInterceptorFirst(new LogbookHttpRequestInterceptor(logbook))
.addInterceptorFirst(new LogbookHttpResponseInterceptor())
.build()
);
httpRequestFactory.setReadTimeout(properties.getReadTimeout());
httpRequestFactory.setConnectTimeout(properties.getConnectionTimeout());
return httpRequestFactory;
}
@Bean
PoolingHttpClientConnectionManager commonConnection() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(properties.getMaxThread());
connectionManager.setDefaultMaxPerRoute(properties.getMaxRoute());
return connectionManager;
}
} | 43.685185 | 122 | 0.718525 |
7a36ee714c44631bda50600f3153be042f3ab8c0 | 1,066 | package service.food.app.Service;
import service.food.app.persistence.jpa.dto.RestaurantDto;
import service.food.app.persistence.jpa.entity.RestaurantEntity;
import service.food.app.persistence.jpa.repository.RestaurantRespository;
import service.food.app.persistence.jpa.service.RestaurantPersistanceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
@Slf4j
public class RestaurantService {
private final RestaurantPersistanceService restaurantPersistanceService;
private final RestaurantRespository restaurantRespository;
public RestaurantEntity save(RestaurantEntity restaurant){
return restaurantPersistanceService.save(restaurant);
}
public List<RestaurantDto> getAllRestaurant(){
return restaurantPersistanceService.getAllRestaurants();
}
public RestaurantDto getRestaurantByName(String name){
return restaurantPersistanceService.getRestaurantByName(name);
}
}
| 31.352941 | 77 | 0.816135 |
dd25b7e3df005ca1c33ad54801169a01f8e6079c | 944 | package com.github.pixelstuermer.patterns.composite.model;
import java.util.Iterator;
import com.github.pixelstuermer.patterns.composite.composite.SpeisekartenComponent;
import com.github.pixelstuermer.patterns.composite.iterator.NullIterator;
public class Speise extends SpeisekartenComponent {
private String name;
private double price;
public Speise( String name, double preis ) {
this.name = name;
this.price = preis;
}
@Override
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
@Override
public double getPrice() {
return price;
}
public void setPrice( double preis ) {
this.price = preis;
}
@Override
public void ausgeben() {
System.out.println( "Name: " + name + " / Preis: " + price );
}
@Override
public Iterator<?> createIterator() {
return new NullIterator();
}
}
| 20.085106 | 83 | 0.664195 |
8689e399458b3ef8ebfad6451ed2c9570147c398 | 1,601 | /*
* Copyright 2022 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ctrip.framework.apollo.core.signature;
import com.google.common.io.BaseEncoding;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* @author nisiyong
*/
public class HmacSha1Utils {
private static final String ALGORITHM_NAME = "HmacSHA1";
private static final String ENCODING = "UTF-8";
public static String signString(String stringToSign, String accessKeySecret) {
try {
Mac mac = Mac.getInstance(ALGORITHM_NAME);
mac.init(new SecretKeySpec(
accessKeySecret.getBytes(ENCODING),
ALGORITHM_NAME
));
byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING));
return BaseEncoding.base64().encode(signData);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) {
throw new IllegalArgumentException(e.toString());
}
}
}
| 33.354167 | 95 | 0.74391 |
05174224d31211f433b25e73780d6e3a510b945b | 166 | package com.rabbit.lancealance.service;
import com.rabbit.lancealance.model.lance.Partida;
public interface IPartidaService extends IBaseService<Partida, Long> {
}
| 23.714286 | 70 | 0.825301 |
14a48088d23380d96691b2a57f8fe3892c7ec4bf | 6,071 | /*
* 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.solr.update;
import static org.hamcrest.CoreMatchers.is;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.lucene.util.TestUtil;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.CollectionAdminRequest.Create;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestInPlaceUpdateWithRouteField extends SolrCloudTestCase {
private static final int NUMBER_OF_DOCS = 100;
private static final String COLLECTION = "collection1";
private static final String[] shards = new String[]{"shard1","shard2","shard3"};
@BeforeClass
public static void setupCluster() throws Exception {
final Path configDir = Paths.get(TEST_HOME(), "collection1", "conf");
String configName = "solrCloudCollectionConfig";
int nodeCount = TestUtil.nextInt(random(), 1, 3);
configureCluster(nodeCount)
.addConfig(configName, configDir)
.configure();
Map<String, String> collectionProperties = new HashMap<>();
collectionProperties.put("config", "solrconfig-tlog.xml" );
collectionProperties.put("schema", "schema-inplace-updates.xml");
int replicas = 2;
// router field can be defined either for ImplicitDocRouter or CompositeIdRouter
boolean implicit = random().nextBoolean();
String routerName = implicit ? "implicit":"compositeId";
Create createCmd = CollectionAdminRequest.createCollection(COLLECTION, configName, shards.length, replicas)
.setMaxShardsPerNode(shards.length * replicas)
.setProperties(collectionProperties)
.setRouterName(routerName)
.setRouterField("shardName");
if (implicit) {
createCmd.setShards(Arrays.stream(shards).collect(Collectors.joining(",")));
}
createCmd.process(cluster.getSolrClient());
}
@Test
public void testUpdatingDocValuesWithRouteField() throws Exception {
new UpdateRequest()
.deleteByQuery("*:*").commit(cluster.getSolrClient(), COLLECTION);
new UpdateRequest().add(createDocs(NUMBER_OF_DOCS)).commit(cluster.getSolrClient(), COLLECTION);
int id = TestUtil.nextInt(random(), 1, NUMBER_OF_DOCS - 1);
SolrDocument solrDocument = queryDoc(id);
Long initialVersion = (Long) solrDocument.get("_version_");
Integer luceneDocId = (Integer) solrDocument.get("[docid]");
String shardName = (String) solrDocument.get("shardName");
Assert.assertThat(solrDocument.get("inplace_updatable_int"), is(id));
int newDocValue = TestUtil.nextInt(random(), 1, 2 * NUMBER_OF_DOCS - 1);
SolrInputDocument sdoc = sdoc("id", ""+id,
// use route field in update command
"shardName", shardName,
"inplace_updatable_int", map("set", newDocValue));
UpdateRequest updateRequest = new UpdateRequest()
.add(sdoc);
updateRequest.commit(cluster.getSolrClient(), COLLECTION);
solrDocument = queryDoc(id);
Long newVersion = (Long) solrDocument.get("_version_");
Assert.assertTrue("Version of updated document must be greater than original one",
newVersion > initialVersion);
Assert.assertThat( "Doc value must be updated", solrDocument.get("inplace_updatable_int"), is(newDocValue));
Assert.assertThat("Lucene doc id should not be changed for In-Place Updates.", solrDocument.get("[docid]"), is(luceneDocId));
try {
sdoc.remove("shardName");
new UpdateRequest()
.add(sdoc).process(cluster.getSolrClient(), COLLECTION);
fail("expect an exception w/o route field");
}catch(SolrException ex) {
assertThat("expecting 400 in "+ex.getMessage(), ex.code(), is(400));
}
}
private Collection<SolrInputDocument> createDocs(int number) {
List<SolrInputDocument> result = new ArrayList<>();
for (int i = 0; i < number; i++) {
String randomShard = shards[random().nextInt(shards.length)];
result.add(sdoc("id", String.valueOf(i),
"shardName", randomShard,
"inplace_updatable_int", i));
}
return result;
}
private SolrDocument queryDoc(int id) throws SolrServerException, IOException {
SolrQuery query = new SolrQuery(
"q", "id:" + id,
"fl", "_version_,inplace_updatable_int,[docid],shardName",
"targetCollection", COLLECTION);
QueryResponse response = cluster.getSolrClient().query(COLLECTION, query);
SolrDocumentList result = (SolrDocumentList) response.getResponse().get("response");
Assert.assertThat(result.getNumFound(), is(1L));
return result.get(0);
}
}
| 40.744966 | 129 | 0.726404 |
98b4f09939ba14d0b676669c77033ad855463fc5 | 4,039 | /**
* (C) Copyright 2011-2015 FastConnect SAS
* (http://www.fastconnect.fr/) and others.
*
* 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 fr.fastconnect.factory.tibco.bw.maven.doc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.xml.bind.JAXBException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.maven.model.FileSet;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo;
import fr.fastconnect.factory.tibco.bw.maven.source.AbstractProjectsListMojo;
import fr.fastconnect.factory.tibco.bw.maven.source.ProcessModel;
/**
* <p>
* This goal generates an XML documentation file from TIBCO BusinessWorks source
* files.
* </p>
*
* @author Mathieu Debove
*
*/
public abstract class AbstractDocMojo extends AbstractBWMojo {
/**
* Path to the output folder.
*
* Default is "target/doc"
*/
@Parameter( property = "project.doc.directory",
required=true,
defaultValue = "target/doc" )
protected File docDirectory;
/**
* The list of files to process for documentation.
*/
private List<File> files;
public abstract void processFile(File f) throws MojoExecutionException;
/**
* @throws JAXBException
*
*/
protected String getDescription(File f) throws JAXBException {
ProcessModel pm = new ProcessModel(f);
String description = pm.getProcess().getDescription();
return description;
}
@Override
public void execute() throws MojoExecutionException {
super.execute();
if (!docDirectory.exists()) {
docDirectory.mkdirs();
}
getLog().info("Generating project documentation in '" + docDirectory + '"');
try {
files = initFiles(); // look for ".process" files in "target/src" folder
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
for (File f : this.getFiles()) {
processFile(f);
}
}
public List<File> getFiles() {
return files;
}
protected File getDirectoryToProcess() {
return buildSrcDirectory;
}
protected List<File> initFiles() throws IOException {
getLog().debug("Looking for files to process...");
FileSet restriction = new FileSet();
File directory = getDirectoryToProcess();
if (directory == null) {
directory = new File(".");
}
restriction.setDirectory(directory.getAbsolutePath());
restriction.addInclude("**/*.process");
return AbstractProjectsListMojo.toFileList(restriction);
}
public void applyXSL(File in, File out, InputStream inputStream) throws MojoExecutionException {
try {
TransformerFactory factory = TransformerFactory.newInstance();
Templates template = factory.newTemplates(new StreamSource(inputStream));
Transformer xformer = template.newTransformer();
Source source = new StreamSource(new FileInputStream(in));
Result result = new StreamResult(new FileOutputStream(out));
xformer.transform(source, result);
} catch (Exception e) {
throw new MojoExecutionException(e.getMessage(), e);
}
}
}
| 28.048611 | 100 | 0.71998 |
c2705dc7a2ac12bec946fa0e7f9baafe87c50775 | 1,782 | package parsing;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author exponential-e
* 백준 1388번: 바닥 장식
*
* @see https://www.acmicpc.net/problem/1388/
*
*/
public class Boj1388 {
private static boolean[][] used;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
char[][] floor = new char[N][M];
used = new boolean[N][M];
for(int i = 0; i < N; i++){
String line = br.readLine();
for(int j = 0; j < M; j++){
floor[i][j] = line.charAt(j);
}
}
System.out.println(counting(N, M, floor));
}
private static int counting(int n, int m, char[][] f){
int count = 0;
for (int i = 0; i < f.length; i++){
for(int j = 0; j < f[i].length; j++){
if(used[i][j]) continue;
used[i][j] = true;
if(f[i][j] == '-') spread(m, f, i, j + 1, true, f[i][j]); // col
else spread(n, f, i + 1, j, false, f[i][j]); // row
count++;
}
}
return count;
}
private static void spread(int len, char[][] f, int i, int j, boolean flag, char src){
int target = flag ? j: i;
while(target < len){
char snk = flag ? f[i][target]: f[target][j];
if(snk != src) break;
if(flag) used[i][target++] = true;
else used[target++][j] = true;
}
}
}
| 26.205882 | 90 | 0.494388 |
4b2eb0d3d59e706814ae56b6c912e206a17d3a9d | 1,891 | /**
* Copyright (C) 2013-2016 The Rythm Engine project
* for LICENSE and other details see:
* https://github.com/rythmengine/rythmengine
*/
package org.rythmengine.cache;
/*-
* #%L
* Rythm Template Engine
* %%
* Copyright (C) 2017 - 2021 OSGL (Open Source General Library)
* %%
* 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.rythmengine.extension.ICacheService;
import java.io.Serializable;
/**
* A do-nothing implementation of {@link org.rythmengine.extension.ICacheService}
*/
public class NoCacheService implements ICacheService {
public static final NoCacheService INSTANCE = new NoCacheService();
private NoCacheService() {
}
@Override
public void put(String key, Serializable value, int ttl) {
}
@Override
public void put(String key, Serializable value) {
}
@Override
public Serializable remove(String key) {
return null;
}
@Override
public void evict(String key) {
return;
}
@Override
public Serializable get(String key) {
return null;
}
@Override
public boolean contains(String key) {
return false;
}
@Override
public void clear() {
}
@Override
public void setDefaultTTL(int ttl) {
}
@Override
public void shutdown() {
}
@Override
public void startup() {
}
}
| 21.988372 | 81 | 0.669487 |
16f37a3d4a6010e2f2db7a25eb669b176e96f0ae | 852 | package com.compomics.icelogo.core.enumeration;
/**
* Created by IntelliJ IDEA.
* User: kenny
* Date: Jun 18, 2009
* Time: 4:04:16 PM
* <p/>
* This class
*/
public enum LogoProperties {
FASTAFILE_1("FASTAFILE_1"),
FASTAFILE_2("FASTAFILE_2"),
FASTAFILE_3("FASTAFILE_3"),
PVALUE("PVALUE"),
HEATMAP_MAGNITUDE("HEATMAP_ORDERS_OF_MAGNITUDE"),
STARTPOSITION("STARTPOSITION"),
ITERATIONSIZE("ITERATIONSIZE"),
STATIC_SPECIES1("STATIC_SPECIES1"),
STATIC_SPECIES2("STATIC_SPECIES2"),
STATIC_SPECIES3("STATIC_SPECIES3"),
STATIC_SPECIES4("STATIC_SPECIES4"),
STATIC_SPECIES5("STATIC_SPECIES5"),
STATIC_SPECIES6("STATIC_SPECIES6");
private String iName;
LogoProperties(final String aName) {
iName = aName;
}
@Override
public String toString() {
return iName;
}
}
| 23.027027 | 53 | 0.680751 |
d6bdb2b2d743e47e55712227c28d98ebdbdc692c | 512 | package com.tassioauad.gamecheck.dagger;
import android.app.Application;
import android.content.Context;
import dagger.Module;
import dagger.Provides;
@Module(library = true)
public class AppModule {
private static Application app;
public AppModule(Application app) {
this.app = app;
}
public AppModule() {
}
@Provides
public Application provideApplication() {
return app;
}
@Provides
public Context provideContext() {
return app;
}
}
| 16 | 45 | 0.666016 |
a55c54526c4ce5a89b6c2979f490ff95373d95b8 | 462 | public class PessoaJuridica extends Pessoa{
private String CNPJ;
public PessoaJuridica(String nome, String CNPJ){
super(nome);
this.CNPJ = CNPJ;
}
// Getters
public String getCNPJ(){
return this.CNPJ;
}
// Setters
public void setCNPJ(String CNPJ){
this.CNPJ = CNPJ;
}
@Override
public String toString(){
return super.toString() + " CNPJ: " + this.getCNPJ() + ".\n";
}
}
| 19.25 | 69 | 0.573593 |
f7ebfc6bd413e3492dd7934c8cec2134a8ced6b0 | 3,877 | /*
* #%L
* Learnr
* %%
* Copyright (C) 2014 Ondrej Skopek
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package cz.matfyz.oskopek.learnr.ui;
import cz.matfyz.oskopek.learnr.data.LimitWatcher;
import cz.matfyz.oskopek.learnr.tools.Localizable;
import javax.swing.*;
import java.awt.*;
/**
* Simple panel for displaying limit counter and last answer status.
*/
public class StatusPanel extends JPanel implements Localizable {
final QuestionAnswerPanel parentPanel;
private final JLabel sessionCount;
private final JLabel dailyCount;
private final JLabel sessionText;
private final JLabel dailyText;
private final JLabel lastAnswerText;
private final JLabel lastAnswerCorectness;
private boolean lastAnswerWasGood;
public StatusPanel(QuestionAnswerPanel parentPanel) {
this.parentPanel = parentPanel;
setLayout(new FlowLayout());
sessionText = new JLabel(localizedText("session") + ":");
dailyText = new JLabel(localizedText("daily") + ":");
sessionCount = new JLabel("0");
dailyCount = new JLabel("0");
lastAnswerText = new JLabel(localizedText("last-answer") + ":");
lastAnswerCorectness = new JLabel("-");
add(sessionText);
add(sessionCount);
add(dailyText);
add(dailyCount);
add(lastAnswerText);
add(lastAnswerCorectness);
}
public void updateLimitCounters(LimitWatcher limitWatcher) {
sessionCount.setText(limitWatcher.getSessionCounter() + "");
dailyCount.setText(limitWatcher.getDailyCounter() + "");
if (limitWatcher.isValidSession()) {
sessionCount.setForeground(Color.BLACK);
} else {
sessionCount.setForeground(Color.RED);
}
if (limitWatcher.isValidDaily()) {
dailyCount.setForeground(Color.BLACK);
} else {
dailyCount.setForeground(Color.RED);
}
}
public void updateLastAnswerCorectness(boolean lastAnswerWasGood) {
this.lastAnswerWasGood = lastAnswerWasGood;
if (lastAnswerWasGood) {
lastAnswerCorectness.setText(localizedText("good"));
lastAnswerCorectness.setForeground(Color.GREEN);
} else {
lastAnswerCorectness.setText(localizedText("bad"));
lastAnswerCorectness.setForeground(Color.RED);
}
}
@Override
public String localizedText(String id) {
return parentPanel.localizedText(id);
}
@Override
public void localizationChanged() {
sessionText.setText(localizedText("session") + ":");
dailyText.setText(localizedText("daily") + ":");
lastAnswerText.setText(localizedText("last-answer") + ":");
updateLastAnswerCorectness(lastAnswerWasGood); // translates the good/bad string
}
}
| 36.92381 | 88 | 0.689709 |
62560909444d1f63198adb03e35315cbdd5eaf01 | 1,302 | package org.red5.server;
import org.red5.server.api.scope.IScope;
import org.red5.server.api.stream.IStreamFilenameGenerator;
public class FilenameGenerator implements IStreamFilenameGenerator {
/** Path that will store recorded videos */
public String recordPath = "recordedStreams/";
/** Path that contains VOD files */
public String playbackPath = "videoStreams/";
/** Set if the path is absolute or relative */
public boolean resolvesAbsolutePath;
public String generateFilename(IScope scope, String name, GenerationType type) {
// Generate the file name without the extension
return generateFilename(scope, name, null, type);
}
public String generateFilename(IScope scope, String name, String extension, GenerationType type) {
String filename;
if (type == GenerationType.RECORD) {
filename = recordPath + name;
} else {
filename = playbackPath + name;
}
if (extension != null) {
// add the extension
filename += extension;
}
return filename;
}
public boolean resolvesToAbsolutePath() {
return resolvesAbsolutePath;
}
public void setRecordPath(String path) {
recordPath = path;
}
public void setPlaybackPath(String path) {
playbackPath = path;
}
public void setAbsolutePath(boolean absolute) {
resolvesAbsolutePath = absolute;
}
}
| 25.038462 | 99 | 0.740399 |
1f9b494e5a7ef841b51f90077670a54e1aeadb1e | 414 | package com.leetcode.algorithm.easy.implementqueueusingstacks;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
public class MyQueueTest {
@Test
public void testCase1() {
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
assertEquals(1, queue.peek());
assertEquals(1, queue.pop());
assertEquals(false, queue.empty());
}
}
| 21.789474 | 62 | 0.707729 |
6101089f68d40bd99d6a4829cd381dab9f21559f | 475 | package tp5;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculatriceAvecMemoireTest {
@Test
public void testSaveAndReload() {
CalculatriceAvecMemoire calc = new CalculatriceAvecMemoire();
calc.setValeurCourante(5);
assertEquals(5.0, calc.getValeurCourante(), 0.0);
calc.save();
calc.setValeurCourante(10);
assertEquals(10.0, calc.getValeurCourante(), 0.0);
calc.load();
assertEquals(5.0, calc.getValeurCourante(), 0.0);
}
}
| 21.590909 | 63 | 0.734737 |
7f3c61e44a8ada35752d5936332aa5f62ad56df7 | 710 | package it.redhat.demo.ogm;
import static org.assertj.core.api.Assertions.assertThat;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import io.thorntail.test.ThorntailTestRunner;
/**
* Integration test using Hibernate OGM application within Thorntail framework.
*
* This test requires a remote Infinispan server
* Port and host are defined in hotrodclient.properties
*/
@RunWith(ThorntailTestRunner.class)
public class OgmAppIT {
@Inject
private EmployeeRepo repo;
@Test
public void testJpa() {
assertThat( repo ).isNotNull();
repo.add( 1, "Fabio" );
Employee employee = repo.load( 1 );
assertThat( employee.getName() ).isEqualTo( "Fabio" );
}
}
| 20.882353 | 79 | 0.746479 |
8f48d09d42f2f3cadb03189b9484b8353d47ac7a | 520 | package com.nukkitx.network;
import com.nukkitx.network.util.DisconnectReason;
import java.net.InetSocketAddress;
public interface SessionConnection<T> {
InetSocketAddress getAddress();
default InetSocketAddress getRealAddress() {
return getAddress();
}
void close();
void close(DisconnectReason reason);
void disconnect();
void disconnect(DisconnectReason reason);
void send(T packet);
void sendImmediate(T packet);
boolean isClosed();
long getPing();
}
| 16.774194 | 49 | 0.703846 |
0c8a890c2f9717b535fc7abea15cc2a71a153546 | 1,919 | package com.tumblr.b1moz.caderninho003.adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RatingBar;
import android.widget.TextView;
import com.tumblr.b1moz.caderninho003.R;
import com.tumblr.b1moz.caderninho003.domain.Review;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MyReviewListRecyclerviewAdapter extends RecyclerView.Adapter<MyReviewListRecyclerviewAdapter.ViewHolder> {
private List<Review> mList;
public MyReviewListRecyclerviewAdapter(List<Review> mList) {
this.mList = mList;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_review, viewGroup,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
viewHolder.clientName.setText(mList.get(i).getCostumer().getName());
viewHolder.ratingBar.setRating(mList.get(i).getReview());
viewHolder.reviewComment.setText(mList.get(i).getComment());
viewHolder.reviewDate.setText(mList.get(i).getDate());
}
@Override
public int getItemCount() {
return mList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.item_review_client_name) TextView clientName;
@BindView(R.id.item_review_ratingbar) RatingBar ratingBar;
@BindView(R.id.item_review_date) TextView reviewDate;
@BindView(R.id.item_review_comment) TextView reviewComment;
public ViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
| 30.951613 | 119 | 0.730589 |
70901bc71e5fdeb7250b3bd2f4c3782707145589 | 5,258 | /*
* Copyright (c) 2014, Kustaa Nyholm / SpareTimeLabs
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the Kustaa Nyholm or SpareTimeLabs nor the names of its
* contributors may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*/
package purejavahidapi;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import purejavahidapi.shared.Backend;
import purejavahidapi.shared.Frontend;
import com.sun.jna.Platform;
/** PureJavaHidApi class is the entry point to access USB HID devices.
* <p>
* Static methods in PureJavaHidApi allow enumeration and opening of HID devices.
* <p>
* {@link #enumerateDevices(int, int)} method returns a iist of HidDeviceInfo
* objects from which a device path can be obtained. The path can be passed to
* the {@link #openDevice(String)} method to obtain a {@link HidDevice} object which
* can then be used to communicate with the device.
* <p>
* See javadoc for above mentioned classes and methods for details.
*
*/
public class PureJavaHidApi {
private static Object m_Mutex = new Object();
final private static Backend m_Backend;
private static LinkedList<HidDevice> m_OpenDevices = new LinkedList();
/**
*
* @return PureJavaHidApi library version string
*/
public String getVersion() {
return "0.0.1";
}
/**
* Returns a list of available USB HID devices.
* <p>
* Passing a 0 for the vendorId or productId mathes everything and thus works
* as a wild card for mathcing. Passing 0 for both will return a list
* of all USB HID devices.
*
* @return List of HidDeviceInfo objects representing the matching devices.
*/
public static List<HidDeviceInfo> enumerateDevices() {
synchronized (m_Mutex) {
if (m_Backend==null)
throw new IllegalStateException("Unsupported platform");
return m_Backend.enumerateDevices();
}
}
/**
* Given a device path opens a USB device for communication.
*
* @param path A path obtained from a HidDeviceInfo object.
* @return An instance of HidDevice that can be used to communicate with the HID device.
* @throws IOException if the device cannot be opened
* @see HidDeviceInfo#getPath()
*/
public static HidDevice openDevice(String path) throws IOException {
synchronized (m_Mutex) {
if (m_Backend==null)
throw new IllegalStateException("Unsupported platform");
HidDevice device = m_Backend.openDevice(path, new Frontend() {
@Override
public void closeDevice(HidDevice device) {
m_OpenDevices.remove(device);
}
});
if (device!=null)
m_OpenDevices.add(device);
return device;
}
}
/**
* Given a device path opens a USB device for communication.
*
* @param path A path obtained from a HidDeviceInfo object.
* @param scanInterValMs The interval in units of ms in which the device state will be read. (Only implemented for Windows!)
* @return An instance of HidDevice that can be used to communicate with the HID device.
* @throws IOException if the device cannot be opened
* @see HidDeviceInfo#getPath()
*/
public static HidDevice openDeviceNonBlocking(String path, long scanInterValMs) throws IOException {
synchronized (m_Mutex) {
if (m_Backend==null)
throw new IllegalStateException("Unsupported platform");
HidDevice device = m_Backend.openDevice(path, new Frontend() {
@Override
public void closeDevice(HidDevice device) {
m_OpenDevices.remove(device);
}
}, scanInterValMs);
if (device!=null)
m_OpenDevices.add(device);
return device;
}
}
static {
if (Platform.isMac()) {
m_Backend = new purejavahidapi.macosx.MacOsXBackend();
} else if (Platform.isWindows()) {
m_Backend = new purejavahidapi.windows.WindowsBackend();
} else if (Platform.isLinux()) {
m_Backend = new purejavahidapi.linux.LinuxBackend();
} else
m_Backend = null;
if (m_Backend!=null)
m_Backend.init();
}
}
| 36.013699 | 125 | 0.735831 |
c52ee33af186797758ea2006b734a5dddc99c94b | 188 | package br.ufsc.bridge.res.domain;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum Sort {
ASC(""),
DESC("-");
private String code;
}
| 12.533333 | 34 | 0.734043 |
b23e6846602886c96985e8eb2b4d8342ee919495 | 436 | package com.mehdi.shortcutdemo.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import com.mehdi.shortcutdemo.R;
public class FavoriteActivity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite_activity);
}
}
| 27.25 | 63 | 0.78211 |
0693ae4f912f7397d0cb515e72afec7f0ce06bc1 | 541 | package org.nutz.validate.impl;
import org.nutz.validate.NutValidateException;
import org.nutz.validate.NutValidator;
public class StrValueValidator implements NutValidator {
private String str;
public StrValueValidator(Object any){
this.str = any.toString();
}
@Override
public Object check(Object val) throws NutValidateException {
if(null==val) {
return val;
}
return str.equals(val);
}
@Override
public int order() {
return 1000;
}
}
| 19.321429 | 65 | 0.63586 |
d5a67f1d169ac71d6457ff288a0c34422a7d7ed2 | 234 | // this is my favorite file
package io.github.opencubicchunks.cubicchunks.chunk;
public interface VerticalViewDistanceListener {
void setIncomingVerticalViewDistance(int verticalDistance);
int getVerticalViewDistance();
}
| 21.272727 | 63 | 0.807692 |
e8b0f49e4d9ecde6ba9d7f54f607ab6317c0d119 | 28,137 | package com.google.android.rappor;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import com.google.common.io.BaseEncoding;
import com.google.common.primitives.Bytes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* Unit tests for {@link HmacDrbg}.
*
* Test vectors come from NIST's SHA-256 HMAC_DRBG no reseed known input test vectors at
* http://csrc.nist.gov/groups/STM/cavp/random-number-generation.html#drbgvs
*/
@RunWith(JUnit4.class)
public final class HmacDrbgTest {
private byte[] hexToBytes(String s) {
return BaseEncoding.base16().decode(s.toUpperCase());
}
// ==== Test vectors for HMAC_DRBG with no personalization. ====
@Test
public void testHmacDrbgNistCase0() {
byte[] entropy =
hexToBytes("ca851911349384bffe89de1cbdc46e6831e44d34a4fb935ee285dd14b71a7488");
byte[] nonce = hexToBytes("659ba96c601dc69fc902940805ec0ca8");
byte[] expected = hexToBytes(
"e528e9abf2dece54d47c7e75e5fe302149f817ea9fb4bee6f4199697d04d5b89"
+ "d54fbb978a15b5c443c9ec21036d2460b6f73ebad0dc2aba6e624abf07745bc1"
+ "07694bb7547bb0995f70de25d6b29e2d3011bb19d27676c07162c8b5ccde0668"
+ "961df86803482cb37ed6d5c0bb8d50cf1f50d476aa0458bdaba806f48be9dcb8");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase1() {
byte[] entropy =
hexToBytes("79737479ba4e7642a221fcfd1b820b134e9e3540a35bb48ffae29c20f5418ea3");
byte[] nonce = hexToBytes("3593259c092bef4129bc2c6c9e19f343");
byte[] expected = hexToBytes(
"cf5ad5984f9e43917aa9087380dac46e410ddc8a7731859c84e9d0f31bd43655"
+ "b924159413e2293b17610f211e09f770f172b8fb693a35b85d3b9e5e63b1dc25"
+ "2ac0e115002e9bedfb4b5b6fd43f33b8e0eafb2d072e1a6fee1f159df9b51e6c"
+ "8da737e60d5032dd30544ec51558c6f080bdbdab1de8a939e961e06b5f1aca37");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase2() {
byte[] entropy =
hexToBytes("b340907445b97a8b589264de4a17c0bea11bb53ad72f9f33297f05d2879d898d");
byte[] nonce = hexToBytes("65cb27735d83c0708f72684ea58f7ee5");
byte[] expected = hexToBytes(
"75183aaaf3574bc68003352ad655d0e9ce9dd17552723b47fab0e84ef903694a"
+ "32987eeddbdc48efd24195dbdac8a46ba2d972f5808f23a869e71343140361f5"
+ "8b243e62722088fe10a98e43372d252b144e00c89c215a76a121734bdc485486"
+ "f65c0b16b8963524a3a70e6f38f169c12f6cbdd169dd48fe4421a235847a23ff");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase3() {
byte[] entropy =
hexToBytes("8e159f60060a7d6a7e6fe7c9f769c30b98acb1240b25e7ee33f1da834c0858e7");
byte[] nonce = hexToBytes("c39d35052201bdcce4e127a04f04d644");
byte[] expected = hexToBytes(
"62910a77213967ea93d6457e255af51fc79d49629af2fccd81840cdfbb491099"
+ "1f50a477cbd29edd8a47c4fec9d141f50dfde7c4d8fcab473eff3cc2ee9e7cc9"
+ "0871f180777a97841597b0dd7e779eff9784b9cc33689fd7d48c0dcd341515ac"
+ "8fecf5c55a6327aea8d58f97220b7462373e84e3b7417a57e80ce946d6120db5");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase4() {
byte[] entropy =
hexToBytes("74755f196305f7fb6689b2fe6835dc1d81484fc481a6b8087f649a1952f4df6a");
byte[] nonce = hexToBytes("c36387a544a5f2b78007651a7b74b749");
byte[] expected = hexToBytes(
"b2896f3af4375dab67e8062d82c1a005ef4ed119d13a9f18371b1b8737744186"
+ "84805fd659bfd69964f83a5cfe08667ddad672cafd16befffa9faed49865214f"
+ "703951b443e6dca22edb636f3308380144b9333de4bcb0735710e4d926678634"
+ "2fc53babe7bdbe3c01a3addb7f23c63ce2834729fabbd419b47beceb4a460236");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase5() {
byte[] entropy =
hexToBytes("4b222718f56a3260b3c2625a4cf80950b7d6c1250f170bd5c28b118abdf23b2f");
byte[] nonce = hexToBytes("7aed52d0016fcaef0b6492bc40bbe0e9");
byte[] expected = hexToBytes(
"a6da029b3665cd39fd50a54c553f99fed3626f4902ffe322dc51f0670dfe8742"
+ "ed48415cf04bbad5ed3b23b18b7892d170a7dcf3ef8052d5717cb0c1a8b3010d"
+ "9a9ea5de70ae5356249c0e098946030c46d9d3d209864539444374d8fbcae068"
+ "e1d6548fa59e6562e6b2d1acbda8da0318c23752ebc9be0c1c1c5b3cf66dd967");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase6() {
byte[] entropy =
hexToBytes("b512633f27fb182a076917e39888ba3ff35d23c3742eb8f3c635a044163768e0");
byte[] nonce = hexToBytes("e2c39b84629a3de5c301db5643af1c21");
byte[] expected = hexToBytes(
"fb931d0d0194a97b48d5d4c231fdad5c61aedf1c3a55ac24983ecbf38487b1c9"
+ "3396c6b86ff3920cfa8c77e0146de835ea5809676e702dee6a78100da9aa43d8"
+ "ec0bf5720befa71f82193205ac2ea403e8d7e0e6270b366dc4200be26afd9f63"
+ "b7e79286a35c688c57cbff55ac747d4c28bb80a2b2097b3b62ea439950d75dff");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase7() {
byte[] entropy =
hexToBytes("aae3ffc8605a975befefcea0a7a286642bc3b95fb37bd0eb0585a4cabf8b3d1e");
byte[] nonce = hexToBytes("9504c3c0c4310c1c0746a036c91d9034");
byte[] expected = hexToBytes(
"2819bd3b0d216dad59ddd6c354c4518153a2b04374b07c49e64a8e4d055575df"
+ "bc9a8fcde68bd257ff1ba5c6000564b46d6dd7ecd9c5d684fd757df62d852115"
+ "75d3562d7814008ab5c8bc00e7b5a649eae2318665b55d762de36eba00c2906c"
+ "0e0ec8706edb493e51ca5eb4b9f015dc932f262f52a86b11c41e9a6d5b3bd431");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase8() {
byte[] entropy =
hexToBytes("b9475210b79b87180e746df704b3cbc7bf8424750e416a7fbb5ce3ef25a82cc6");
byte[] nonce = hexToBytes("24baf03599c10df6ef44065d715a93f7");
byte[] expected = hexToBytes(
"ae12d784f796183c50db5a1a283aa35ed9a2b685dacea97c596ff8c294906d1b"
+ "1305ba1f80254eb062b874a8dfffa3378c809ab2869aa51a4e6a489692284a25"
+ "038908a347342175c38401193b8afc498077e10522bec5c70882b7f760ea5946"
+ "870bd9fc72961eedbe8bff4fd58c7cc1589bb4f369ed0d3bf26c5bbc62e0b2b2");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase9() {
byte[] entropy =
hexToBytes("27838eb44ceccb4e36210703ebf38f659bc39dd3277cd76b7a9bcd6bc964b628");
byte[] nonce = hexToBytes("39cfe0210db2e7b0eb52a387476e7ea1");
byte[] expected = hexToBytes(
"e5e72a53605d2aaa67832f97536445ab774dd9bff7f13a0d11fd27bf6593bfb5"
+ "2309f2d4f09d147192199ea584503181de87002f4ee085c7dc18bf32ce531564"
+ "7a3708e6f404d6588c92b2dda599c131aa350d18c747b33dc8eda15cf40e9526"
+ "3d1231e1b4b68f8d829f86054d49cfdb1b8d96ab0465110569c8583a424a099a");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase10() {
byte[] entropy =
hexToBytes("d7129e4f47008ad60c9b5d081ff4ca8eb821a6e4deb91608bf4e2647835373a5");
byte[] nonce = hexToBytes("a72882773f78c2fc4878295840a53012");
byte[] expected = hexToBytes(
"0cbf48585c5de9183b7ff76557f8fc9ebcfdfde07e588a8641156f61b7952725"
+ "bbee954f87e9b937513b16bba0f2e523d095114658e00f0f3772175acfcb3240"
+ "a01de631c19c5a834c94cc58d04a6837f0d2782fa53d2f9f65178ee9c8372224"
+ "94c799e64c60406069bd319549b889fa00a0032dd7ba5b1cc9edbf58de82bfcd");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase11() {
byte[] entropy =
hexToBytes("67fe5e300c513371976c80de4b20d4473889c9f1214bce718bc32d1da3ab7532");
byte[] nonce = hexToBytes("e256d88497738a33923aa003a8d7845c");
byte[] expected = hexToBytes(
"b44660d64ef7bcebc7a1ab71f8407a02285c7592d755ae6766059e894f694373"
+ "ed9c776c0cfc8594413eefb400ed427e158d687e28da3ecc205e0f7370fb0896"
+ "76bbb0fa591ec8d916c3d5f18a3eb4a417120705f3e2198154cd60648dbfcfc9"
+ "01242e15711cacd501b2c2826abe870ba32da785ed6f1fdc68f203d1ab43a64f");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase12() {
byte[] entropy =
hexToBytes("de8142541255c46d66efc6173b0fe3ffaf5936c897a3ce2e9d5835616aafa2cb");
byte[] nonce = hexToBytes("d01f9002c407127bc3297a561d89b81d");
byte[] expected = hexToBytes(
"64d1020929d74716446d8a4e17205d0756b5264867811aa24d0d0da8644db25d"
+ "5cde474143c57d12482f6bf0f31d10af9d1da4eb6d701bdd605a8db74fb4e77f"
+ "79aaa9e450afda50b18d19fae68f03db1d7b5f1738d2fdce9ad3ee9461b58ee2"
+ "42daf7a1d72c45c9213eca34e14810a9fca5208d5c56d8066bab1586f1513de7");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase13() {
byte[] entropy =
hexToBytes("4a8e0bd90bdb12f7748ad5f147b115d7385bb1b06aee7d8b76136a25d779bcb7");
byte[] nonce = hexToBytes("7f3cce4af8c8ce3c45bdf23c6b181a00");
byte[] expected = hexToBytes(
"320c7ca4bbeb7af977bc054f604b5086a3f237aa5501658112f3e7a33d2231f5"
+ "536d2c85c1dad9d9b0bf7f619c81be4854661626839c8c10ae7fdc0c0b571be3"
+ "4b58d66da553676167b00e7d8e49f416aacb2926c6eb2c66ec98bffae20864cf"
+ "92496db15e3b09e530b7b9648be8d3916b3c20a3a779bec7d66da63396849aaf");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistCase14() {
byte[] entropy =
hexToBytes("451ed024bc4b95f1025b14ec3616f5e42e80824541dc795a2f07500f92adc665");
byte[] nonce = hexToBytes("2f28e6ee8de5879db1eccd58c994e5f0");
byte[] expected = hexToBytes(
"3fb637085ab75f4e95655faae95885166a5fbb423bb03dbf0543be063bcd4879"
+ "9c4f05d4e522634d9275fe02e1edd920e26d9accd43709cb0d8f6e50aa54a5f3"
+ "bdd618be23cf73ef736ed0ef7524b0d14d5bef8c8aec1cf1ed3e1c38a808b35e"
+ "61a44078127c7cb3a8fd7addfa50fcf3ff3bc6d6bc355d5436fe9b71eb44f7fd");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
// ==== Test vectors for HMAC_DRBG with personalization. ====
@Test
public void testHmacDrbgNistWithPersonalizationCase0() {
byte[] entropy =
hexToBytes("5cacc68165a2e2ee20812f35ec73a79dbf30fd475476ac0c44fc6174cdac2b55");
byte[] nonce = hexToBytes("6f885496c1e63af620becd9e71ecb824");
byte[] personalizationString =
hexToBytes("e72dd8590d4ed5295515c35ed6199e9d211b8f069b3058caa6670b96ef1208d0");
byte[] expected = hexToBytes(
"f1012cf543f94533df27fedfbf58e5b79a3dc517a9c402bdbfc9a0c0f721f9d5"
+ "3faf4aafdc4b8f7a1b580fcaa52338d4bd95f58966a243cdcd3f446ed4bc546d"
+ "9f607b190dd69954450d16cd0e2d6437067d8b44d19a6af7a7cfa8794e5fbd72"
+ "8e8fb2f2e8db5dd4ff1aa275f35886098e80ff844886060da8b1e7137846b23b");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase1() {
byte[] entropy =
hexToBytes("8df013b4d103523073917ddf6a869793059e9943fc8654549e7ab22f7c29f122");
byte[] nonce = hexToBytes("da2625af2ddd4abcce3cf4fa4659d84e");
byte[] personalizationString =
hexToBytes("b571e66d7c338bc07b76ad3757bb2f9452bf7e07437ae8581ce7bc7c3ac651a9");
byte[] expected = hexToBytes(
"b91cba4cc84fa25df8610b81b641402768a2097234932e37d590b1154cbd23f9"
+ "7452e310e291c45146147f0da2d81761fe90fba64f94419c0f662b28c1ed94da"
+ "487bb7e73eec798fbcf981b791d1be4f177a8907aa3c401643a5b62b87b89d66"
+ "b3a60e40d4a8e4e9d82af6d2700e6f535cdb51f75c321729103741030ccc3a56");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase2() {
byte[] entropy =
hexToBytes("565b2b77937ba46536b0f693b3d5e4a8a24563f9ef1f676e8b5b2ef17823832f");
byte[] nonce = hexToBytes("4ef3064ec29f5b7f9686d75a23d170e3");
byte[] personalizationString =
hexToBytes("3b722433226c9dba745087270ab3af2c909425ba6d39f5ce46f07256068319d9");
byte[] expected = hexToBytes(
"d144ee7f8363d128872f82c15663fe658413cd42651098e0a7c51a970de75287"
+ "ec943f9061e902280a5a9e183a7817a44222d198fbfab184881431b4adf35d3d"
+ "1019da5a90b3696b2349c8fba15a56d0f9d010a88e3f9eeedb67a69bcaa71281"
+ "b41afa11af576b765e66858f0eb2e4ec4081609ec81da81df0a0eb06787340ea");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase3() {
byte[] entropy =
hexToBytes("fc3832a91b1dcdcaa944f2d93cbceb85c267c491b7b59d017cde4add79a836b6");
byte[] nonce = hexToBytes("d5e76ce9eabafed06e33a913e395c5e0");
byte[] personalizationString =
hexToBytes("ffc5f6eefd51da64a0f67b5f0cf60d7ab43fc7836bca650022a0cee57a43c148");
byte[] expected = hexToBytes(
"0e713c6cc9a4dbd4249201d12b7bf5c69c3e18eb504bf3252db2f43675e17d99"
+ "b6a908400cea304011c2e54166dae1f20260008efe4e06a87e0ce525ca482bca"
+ "223a902a14adcf2374a739a5dfeaf14cadd72efa4d55d15154c974d9521535bc"
+ "b70658c5b6c944020afb04a87b223b4b8e5d89821704a9985bb010405ba8f3d4");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase4() {
byte[] entropy =
hexToBytes("8009eb2cb49fdf16403bcdfd4a9f952191062acb9cc111eca019f957fb9f4451");
byte[] nonce = hexToBytes("355598866952394b1eddd85d59f81c9d");
byte[] personalizationString =
hexToBytes("09ff1d4b97d83b223d002e05f754be480d13ba968e5aac306d71cc9fc49cc2dd");
byte[] expected = hexToBytes(
"9550903c2f02cf77c8f9c9a37041d0040ee1e3ef65ba1a1fbbcf44fb7a2172bd"
+ "6b3aaabe850281c3a1778277bacd09614dfefececac64338ae24a1bf150cbf9d"
+ "9541173a82ecba08aa19b75abb779eb10efa4257d5252e8afcac414bc3bb5d30"
+ "06b6f36fb9daea4c8c359ef6cdbeff27c1068571dd3c89dc87eda9190086888d");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase5() {
byte[] entropy =
hexToBytes("a6e4c9a8bd6da23b9c2b10a7748fd08c4f782fadbac7ea501c17efdc6f6087bd");
byte[] nonce = hexToBytes("acdc47edf1d3b21d0aec7631abb6d7d5");
byte[] personalizationString =
hexToBytes("c16ee0908a5886dccf332fbc61de9ec7b7972d2c4c83c477409ce8a15c623294");
byte[] expected = hexToBytes(
"a52f93ccb363e2bdf0903622c3caedb7cffd04b726052b8d455744c71b76dee1"
+ "b71db9880dc3c21850489cb29e412d7d80849cfa9151a151dcbf32a32b4a54ca"
+ "c01d3200200ed66a3a5e5c131a49655ffbf1a8824ff7f265690dffb4054df46a"
+ "707b9213924c631c5bce379944c856c4f7846e281ac89c64fad3a49909dfb92b");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase6() {
byte[] entropy =
hexToBytes("59d6307460a9bdd392dfc0904973991d585696010a71e52d590a5039b4849fa4");
byte[] nonce = hexToBytes("34a0aafb95917cbf8c38fc5548373c05");
byte[] personalizationString =
hexToBytes("0407b7c57bc11361747c3d67526c36e228028a5d0b145d66ab9a2fe4b07507a0");
byte[] expected = hexToBytes(
"299aba0661315211b09d2861855d0b4b125ab24649461341af6abd903ed6f025"
+ "223b3299f2126fcad44c675166d800619cf49540946b12138989417904324b0d"
+ "dad121327211a297f11259c9c34ce4c70c322a653675f78d385e4e2443f8058d"
+ "141195e17e0bd1b9d44bf3e48c376e6eb44ef020b11cf03eb141c46ecb43cf3d");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase7() {
byte[] entropy =
hexToBytes("9ae3506aadbc8358696ba1ba17e876e1157b7048235921503d36d9211b430342");
byte[] nonce = hexToBytes("9abf7d66afee5d2b811cba358bbc527d");
byte[] personalizationString =
hexToBytes("0d645f6238e9ceb038e4af9772426ca110c5be052f8673b8b5a65c4e53d2f519");
byte[] expected = hexToBytes(
"5f032c7fec6320fe423b6f38085cbad59d826085afe915247b3d546c4c6b1745"
+ "54dd4877c0d671de9554b505393a44e71f209b70f991ac8aa6e08f983fff2a4c"
+ "817b0cd26c12b2c929378506489a75b2025b358cb5d0400821e7e252ac6376cd"
+ "94a40c911a7ed8b6087e3de5fa39fa6b314c3ba1c593b864ce4ff281a97c325b");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase8() {
byte[] entropy =
hexToBytes("96ae3b8775b36da2a29b889ad878941f43c7d51295d47440cd0e3c4999193109");
byte[] nonce = hexToBytes("1fe022a6fc0237b055d4d6a7036b18d5");
byte[] personalizationString =
hexToBytes("1e40e97362d0a823d3964c26b81ab53825c56446c5261689011886f19b08e5c2");
byte[] expected = hexToBytes(
"e707cd14b06ce1e6dbcceaedbf08d88891b03f44ad6a797bd12fdeb557d0151d"
+ "f9346a028dec004844ca46adec3051dafb345895fa9f4604d8a13c8ff66ae093"
+ "fa63c4d9c0816d55a0066d31e8404c841e87b6b2c7b5ae9d7afb6840c2f7b441"
+ "bf2d3d8bd3f40349c1c014347c1979213c76103e0bece26ad7720601eff42275");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase9() {
byte[] entropy =
hexToBytes("33f5120396336e51ee3b0b619b5f873db05ca57cda86aeae2964f51480d14992");
byte[] nonce = hexToBytes("6f1f6e9807ba5393edcf3cb4e4bb6113");
byte[] personalizationString =
hexToBytes("3709605af44d90196867c927512aa8ba31837063337b4879408d91a05c8efa9f");
byte[] expected = hexToBytes(
"8b8291126ded9acef12516025c99ccce225d844308b584b872c903c7bc646759"
+ "9a1cead003dc4c70f6d519f5b51ce0da57f53da90dbe8f666a1a1dde297727fe"
+ "e2d44cebd1301fc1ca75956a3fcae0d374e0df6009b668fd21638d2b733e6902"
+ "d22d5bfb4af1b455975e08eef0ebe4dc87705801e7776583c8de11672729f723");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase10() {
byte[] entropy =
hexToBytes("ad300b799005f290fee7f930eebce158b98fb6cb449987fe433f955456b35300");
byte[] nonce = hexToBytes("06aa2514e4bd114edf7ac105cfef2772");
byte[] personalizationString =
hexToBytes("87ada711465e4169da2a74c931afb9b5a5b190d07b7af342aa99570401c3ee8a");
byte[] expected = hexToBytes(
"80d7c606ff49415a3a92ba1f2943235c01339c8f9cd0b0511fbfdf3ef23c42ff"
+ "ff008524193faaa4b7f2f2eb0cfa221d9df89bd373fe4e158ec06fad3ecf1eb4"
+ "8b8239b0bb826ee69d773883a3e8edac66254610ff70b6609836860e39ea1f3b"
+ "fa04596fee1f2baca6cebb244774c6c3eb4af1f02899eba8f4188f91776de16f");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase11() {
byte[] entropy =
hexToBytes("130b044e2c15ab89375e54b72e7baae6d4cad734b013a090f4df057e634f6ff0");
byte[] nonce = hexToBytes("65fd6ac602cd44107d705dbc066e52b6");
byte[] personalizationString =
hexToBytes("f374aba16f34d54aae5e494505b67d3818ef1c08ea24967a76876d4361379aec");
byte[] expected = hexToBytes(
"5d179534fb0dba3526993ed8e27ec9f915183d967336bb24352c67f4ab5d7935"
+ "d3168e57008da851515efbaecb69904b6d899d3bfa6e9805659aef2942c49038"
+ "75b8fcbc0d1d24d1c075f0ff667c1fc240d8b410dff582fa71fa30878955ce2e"
+ "d786ef32ef852706e62439b69921f26e84e0f54f62b938f04905f05fcd7c2204");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase12() {
byte[] entropy =
hexToBytes("716430e999964b35459c17921fe5f60e09bd9ab234cb8f4ba4932bec4a60a1d5");
byte[] nonce = hexToBytes("9533b711e061b07d505da707cafbca03");
byte[] personalizationString =
hexToBytes("372ae616d1a1fc45c5aecad0939c49b9e01c93bfb40c835eebd837af747f079d");
byte[] expected = hexToBytes(
"a80d6a1b2d0ce01fe0d26e70fb73da20d45841cf01bfbd50b90d2751a46114c0"
+ "e758cb787d281a0a9cf62f5c8ce2ee7ca74fefff330efe74926acca6d6f0646e"
+ "4e3c1a1e52fce1d57b88beda4a5815896f25f38a652cc240deb582921c8b1d03"
+ "a1da966dd04c2e7eee274df2cd1837096b9f7a0d89a82434076bc30173229a60");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase13() {
byte[] entropy =
hexToBytes("7679f154296e6d580854826539003a82d1c54e2e062c619d00da6c6ac820789b");
byte[] nonce = hexToBytes("55d12941b0896462e7d888e5322a99a3");
byte[] personalizationString =
hexToBytes("ba4d1ed696f58ef64596c76cee87cc1ca83069a79e7982b9a06f9d62f4209faf");
byte[] expected = hexToBytes(
"10dc7cd2bb68c2c28f76d1b04ae2aa287071e04c3b688e1986b05cc1209f691d"
+ "aa55868ebb05b633c75a40a32b49663185fe5bb8f906008347ef51590530948b"
+ "87613920014802e5864e0758f012e1eae31f0c4c031ef823aecfb2f8a73aaa94"
+ "6fc507037f9050b277bdeaa023123f9d22da1606e82cb7e56de34bf009eccb46");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgNistWithPersonalizationCase14() {
byte[] entropy =
hexToBytes("8ca4a964e1ff68753db86753d09222e09b888b500be46f2a3830afa9172a1d6d");
byte[] nonce = hexToBytes("a59394e0af764e2f21cf751f623ffa6c");
byte[] personalizationString =
hexToBytes("eb8164b3bf6c1750a8de8528af16cffdf400856d82260acd5958894a98afeed5");
byte[] expected = hexToBytes(
"fc5701b508f0264f4fdb88414768e1afb0a5b445400dcfdeddd0eba67b4fea8c"
+ "056d79a69fd050759fb3d626b29adb8438326fd583f1ba0475ce7707bd294ab0"
+ "1743d077605866425b1cbd0f6c7bba972b30fbe9fce0a719b044fcc139435489"
+ "5a9f8304a2b5101909808ddfdf66df6237142b6566588e4e1e8949b90c27fc1f");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), personalizationString);
byte[] out1 = new byte[1024 / 8];
drbg.nextBytes(out1);
byte[] out2 = new byte[1024 / 8];
drbg.nextBytes(out2);
assertArrayEquals(expected, out2);
}
@Test
public void testHmacDrbgGenerateEntropyInput() {
byte[] got = HmacDrbg.generateEntropyInput();
assertEquals(got.length, HmacDrbg.ENTROPY_INPUT_SIZE_BYTES);
}
@Test
public void testHmacDrbgZeroLengthOutput() {
byte[] entropy =
hexToBytes("8ca4a964e1ff68753db86753d09222e09b888b500be46f2a3830afa9172a1d6d");
byte[] nonce = hexToBytes("a59394e0af764e2f21cf751f623ffa6c");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out = drbg.nextBytes(0);
assertArrayEquals(new byte[0], out);
}
@Test
public void testHmacDrbgCanGenerateMaxBytesOutput() {
byte[] entropy =
hexToBytes("8ca4a964e1ff68753db86753d09222e09b888b500be46f2a3830afa9172a1d6d");
byte[] nonce = hexToBytes("a59394e0af764e2f21cf751f623ffa6c");
HmacDrbg drbg = new HmacDrbg(Bytes.concat(entropy, nonce), null);
byte[] out = drbg.nextBytes(HmacDrbg.MAX_BYTES_TOTAL);
assertEquals(HmacDrbg.MAX_BYTES_TOTAL, out.length);
}
}
| 43.022936 | 88 | 0.76195 |
78f5d206f2100d51af222e49541e42cc0d44f00d | 403 | package com.github.eostermueller.perfgoat;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
public class ITBlock {
@Test
public void test() throws IOException {
String killFileName = System.getProperty("com.github.eostermueller.snail4j.kill.file");
BlockOnSentinelFile blocker = new BlockOnSentinelFile(killFileName);
blocker.block();
}
}
| 18.318182 | 89 | 0.746898 |
eeec6f99cfb9e6e95fe938ee02b24075c0ca4739 | 3,207 | /**
* 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.journalkeeper.rpc.remoting.transport.support;
import io.journalkeeper.rpc.remoting.concurrent.EventBus;
import io.journalkeeper.rpc.remoting.concurrent.EventListener;
import io.journalkeeper.rpc.remoting.event.TransportEvent;
import io.journalkeeper.rpc.remoting.transport.ChannelTransport;
import io.journalkeeper.rpc.remoting.transport.Transport;
import io.journalkeeper.rpc.remoting.transport.TransportClient;
import io.journalkeeper.rpc.remoting.transport.TransportClientSupport;
import io.journalkeeper.rpc.remoting.transport.config.TransportConfig;
import io.journalkeeper.rpc.remoting.transport.exception.TransportException;
import java.net.SocketAddress;
/**
* FailoverTransportClient
* author: gaohaoxiang
*
* date: 2018/10/30
*/
public class FailoverTransportClient implements TransportClient {
private TransportClient delegate;
private TransportConfig config;
private EventBus<TransportEvent> transportEventBus;
public FailoverTransportClient(TransportClient delegate, TransportConfig config, EventBus<TransportEvent> transportEventBus) {
this.delegate = delegate;
this.config = config;
this.transportEventBus = transportEventBus;
}
@Override
public Transport createTransport(String address) throws TransportException {
return this.createTransport(address, -1);
}
@Override
public Transport createTransport(String address, long connectionTimeout) throws TransportException {
return this.createTransport(TransportClientSupport.createInetSocketAddress(address), connectionTimeout);
}
@Override
public Transport createTransport(SocketAddress address) throws TransportException {
return this.createTransport(address, -1);
}
@Override
public Transport createTransport(SocketAddress address, long connectionTimeout) throws TransportException {
ChannelTransport transport = (ChannelTransport) delegate.createTransport(address, connectionTimeout);
return new FailoverChannelTransport(transport, address, connectionTimeout, delegate, config, transportEventBus);
}
@Override
public void addListener(EventListener<TransportEvent> listener) {
delegate.addListener(listener);
}
@Override
public void removeListener(EventListener<TransportEvent> listener) {
delegate.removeListener(listener);
}
@Override
public void start() throws Exception {
delegate.start();
}
@Override
public void stop() {
delegate.stop();
}
@Override
public boolean isStarted() {
return delegate.isStarted();
}
} | 35.241758 | 130 | 0.758029 |
8e941f258add95b50a344a23f1d60aaaa4c80126 | 10,638 | /*
* 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.netbeans.core.output2;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.Position;
import javax.swing.text.View;
import org.netbeans.core.output2.ui.AbstractOutputPane;
import org.netbeans.junit.NbTestCase;
import org.netbeans.junit.RandomlyFails;
import org.openide.util.Exceptions;
import org.openide.windows.IOContainer;
import org.openide.windows.OutputEvent;
import org.openide.windows.OutputListener;
/**
*
* @author Tim Boudreau
*/
@RandomlyFails // "Cannot write XdndAware property" from XDnDDropTargetProtocol.registerDropTarget in setUp
public class WrappedTextViewTest extends NbTestCase {
public WrappedTextViewTest(String testName) {
super(testName);
}
IOContainer iowin;
private NbIO io;
JFrame jf = null;
static int testNum;
@Override
protected void setUp() throws Exception {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
iowin = IOContainer.getDefault();
JComponent wnd = LifecycleTest.getIOWindow();
jf = new JFrame();
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(wnd, BorderLayout.CENTER);
jf.setBounds(20, 20, 700, 300);
jf.setVisible(true);
io = (NbIO) new NbIOProvider().getIO("Test" + testNum++, false);
}
});
sleep();
io.select();
io.getOut().println ("Test line 1");
sleep();
sleep();
sleep();
for (int i=0; i < 100; i++) {
if (i == 42) {
io.getOut().println ("This is a hyperlink to click which may or may not trigger the problem", new L());
}
if (i % 2 == 0) {
io.getOut().println ("Hello there. What a short line");
io.getOut().println("Splead 2 - 148: Wow, we will write a long line of text here. Very long in fact - who knows just how long it might end up being? Well, we'll have to see. Why it's extraordinarily long! It might even wrap several times! How do you like them apples, eh? Maybe we should just go on and on and on, and never stop. That would be cool, huh?\n");
} else {
//io.getErr().println ("aaa: This is a not so long line");
}
}
io.getOut().close();
sleep();
SwingUtilities.invokeAndWait (new Runnable() {
public void run() {
((OutputTab) iowin.getSelected()).getOutputPane().setWrapped(true);
}
});
}
private final void sleep() {
try {
Thread.sleep(200);
SwingUtilities.invokeAndWait (new Runnable() {
public void run() {
System.currentTimeMillis();
}
});
Thread.sleep(200);
} catch (Exception e) {
fail (e.getMessage());
}
}
/**
* tests if caret position is computed correctly (see issue #122492)
*/
public void testViewToModel() {
final Integer pos1 = new Integer(-2);
final Integer pos2 = new Integer(-1);
class R implements Runnable {
int charPos;
int expCharPos;
public void run() {
AbstractOutputPane pane = ((OutputTab) iowin.getSelected()).getOutputPane();
Graphics g = pane.getGraphics();
FontMetrics fm = g.getFontMetrics(pane.getTextView().getFont());
int charWidth = fm.charWidth('m');
int charHeight = fm.getHeight();
int fontDescent = fm.getDescent();
float x = charWidth * 50;
float y = charHeight * 1 + fontDescent;
charPos = pane.getTextView().getUI().getRootView(null).viewToModel(x, y, new Rectangle(), new Position.Bias[]{});
expCharPos = 43;
}
}
R r = new R();
try {
SwingUtilities.invokeAndWait(r);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (InvocationTargetException ex) {
Exceptions.printStackTrace(ex);
}
assertTrue("viewToModel returned wrong value (it would result in bad caret position)!", r.charPos == r.expCharPos);
}
public void testModelToView() throws Exception {
System.out.println("testModelToView");
if (true) {
//THIS TEST TAKES ABOUT 10 MINUTES TO RUN! LEAVE IT COMMENTED OUT
//FOR PRODUCTION AND USE IT JUST FOR DEBUGGING
return;
}
class R implements Runnable {
boolean errorsFound;
java.awt.image.BufferedImage img;
ArrayList<String> errors;
public void run() {
AbstractOutputPane pane = ((OutputTab) iowin.getSelected()).getOutputPane();
JTextComponent text = pane.getTextView();
View view = text.getUI().getRootView(text);
Rectangle r = new Rectangle(1, 1, 1, 1);
Rectangle alloc = new Rectangle();
java.awt.image.ColorModel model = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration().getColorModel(java.awt.Transparency.TRANSLUCENT);
img = new java.awt.image.BufferedImage(model,
model.createCompatibleWritableRaster(text.getWidth() + 10, text.getHeight() + 10), model.isAlphaPremultiplied(), null);
text.paint(img.getGraphics());
errorsFound = false;
errors = new ArrayList<String>();
System.out.println("...scanning " + (text.getWidth() * text.getHeight() + " pixels to make sure viewToModel() matches modeltoView(). Expect it to take about 10 minutes."));
for (int y = 0; y < text.getHeight(); y++) {
r.y = y;
for (int x = 0; x < text.getWidth(); x++) {
r.x = x;
alloc.setBounds(0, 0, text.getWidth(), text.getHeight());
int vtm = view.viewToModel(x, y, alloc, new Position.Bias[1]);
Rectangle mtv = null;
try {
mtv = (Rectangle) view.modelToView(vtm, Position.Bias.Forward, vtm, Position.Bias.Forward, new Rectangle(0, 0, text.getWidth(), text.getHeight()));
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
int xvtm = view.viewToModel(mtv.x, mtv.y, alloc, new Position.Bias[1]);
if (vtm != xvtm) {
errorsFound = true;
try {
errors.add("ViewToModel(" + x + "," + y + ") returns character position " + vtm + "; modelToView on " + vtm + " returns " + mtv + "; that Rectangle's corner, passed back to viewToModel maps to a different character position: " + xvtm + "\n");
img.setRGB(x, y, vtm > xvtm ? Color.RED.getRGB() : Color.BLUE.getRGB());
img.setRGB(x - 1, y - 1, vtm > xvtm ? Color.RED.getRGB() : Color.BLUE.getRGB());
img.setRGB(x + 1, y - 1, vtm > xvtm ? Color.RED.getRGB() : Color.BLUE.getRGB());
img.setRGB(x + 1, y + 1, vtm > xvtm ? Color.RED.getRGB() : Color.BLUE.getRGB());
img.setRGB(x - 1, y + 1, vtm > xvtm ? Color.RED.getRGB() : Color.BLUE.getRGB());
} catch (ArrayIndexOutOfBoundsException aioobe) {
System.err.println("OUT OF BOUNDS: " + x + "," + y + " image width " + img.getWidth() + " img height " + img.getHeight());
}
System.err.println(x + "," + y + "=" + vtm + " -> [" + mtv.x + "," + mtv.y + "," + mtv.width + "," + mtv.height + "]->" + xvtm);
}
r.y = y; //just in case
r.width = 1;
r.height = 1;
}
}
}
}
R r = new R();
SwingUtilities.invokeAndWait(r);
if (r.errorsFound) {
String dir = System.getProperty ("java.io.tmpdir");
if (!dir.endsWith(File.separator)) {
dir += File.separator;
}
String fname = dir + "outputWindowDiffs.png";
ImageIO.write (r.img, "png", new File (fname));
fail ("In a wrapped view, some points as mapped by viewToModel do " +
"not map back to the same coordinates in viewToModel. \nA bitmap " +
"of the problem coordinates is saved in " + fname + " Problem" +
"spots are marked in red and blue.\n" + r.errors);
}
}
public class L implements OutputListener {
public void outputLineSelected(OutputEvent ev) {
}
public void outputLineAction(OutputEvent ev) {
}
public void outputLineCleared(OutputEvent ev) {
}
}
}
| 41.717647 | 382 | 0.554428 |
fbcf23fc0f3de9dce773e9376a589fb47d09ea25 | 862 | package cc.mrbird.febs;
import cc.mrbird.febs.common.entity.BaseEntity;
import cc.mrbird.febs.system.entity.DictDetail;
import cc.mrbird.febs.system.mapper.DictDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ClassUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.util.CastUtils;
@Slf4j
@SpringBootTest(classes = FebsApplication.class)
public class FebsApplicationTest {
@Autowired
private DictDetailMapper dictDetailMapper;
@BeforeEach
public void before() {
}
@Test
public void runTestCase() {
BaseEntity entity = new DictDetail();
dictDetailMapper.insert(CastUtils.cast(entity));
}
}
| 26.121212 | 62 | 0.772622 |
2c7d0f04b283c5c500eb24e73aa3048cd2f53f2e | 557 | package org.checkerframework.common.reflection.qual;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation for methods of the form:
* <br>
* <code>{@link MethodVal}(classname=c, methodname=m, params=p) Method
* method(Class<c> this, String m, Object... params)</code>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface GetMethod {}
| 29.315789 | 70 | 0.771993 |
5801d7dde575177709626e25125723ab59e57831 | 969 | package swarm.client.view;
import swarm.shared.utils.U_Math;
public class Tweener
{
private double m_tweenTime;
private double m_startValue;
private double m_endValue;
private double m_elapsedTime;
public Tweener(double tweenTime)
{
m_tweenTime = tweenTime;
m_elapsedTime = m_tweenTime;
m_startValue = m_endValue = 0;
}
public boolean isTweening()
{
return m_elapsedTime < m_tweenTime;
}
public void start(double startValue, double endValue)
{
m_startValue = startValue;
m_endValue = endValue;
m_elapsedTime = 0;
}
public void stop()
{
m_elapsedTime = m_tweenTime;
}
public double update(double timeStep)
{
m_elapsedTime += timeStep;
m_elapsedTime = U_Math.clamp(m_elapsedTime, 0, m_tweenTime);
double timeRatio = 1 - m_elapsedTime / m_tweenTime;
double tweenRatio = 1 - Math.pow(timeRatio, 6);
double tweenValue = m_startValue + (m_endValue - m_startValue) * tweenRatio;
return tweenValue;
}
}
| 19 | 78 | 0.72549 |
c90b05a63255c057d02bfd4c53a19c1815b08a11 | 5,418 | package hs.strategy;
import hs.Timer;
import hs.heuristic.HeuristicFunction;
import hs.representation.Board;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
public class IDAlphaBetaSearchH_RandomMoves implements SearchStrategy {
private int plyThreshold;
private long timeThreshold;
private HeuristicFunction h;
private boolean exit;
private ArrayList<int[]> decisionList;
private int[] decision;
private double decisionValue;
private int visited = 0;
private Timer timer;
private Random r;
private int maxDepth = 0;
public int maxd = 0;
private HashMap<Integer, int[]> pv = new HashMap<Integer, int[]>(20);
public IDAlphaBetaSearchH_RandomMoves(int movesThreshold,
long timeThreshold, HeuristicFunction h) {
if (movesThreshold <= 0) {
throw new IllegalArgumentException("Moves must be positive! "
+ movesThreshold);
}
if (timeThreshold <= 0) {
throw new IllegalArgumentException("Time must be positive! "
+ timeThreshold);
}
if (h == null) {
throw new NullPointerException();
}
this.plyThreshold = movesThreshold;
this.timeThreshold = timeThreshold;
this.timer = new Timer(this.timeThreshold);
this.h = h;
this.decisionList = new ArrayList<int[]>(100);
this.r = new Random();
}
@Override
public int[] nextMove(Board b) {
timer.start();
return alphaBetaDecision(b);
}
public long getTimeThreshold() {
return this.timeThreshold;
}
private int[] alphaBetaDecision(Board b) {
double alpha = Double.NEGATIVE_INFINITY;
double beta = Double.POSITIVE_INFINITY;
decisionList.clear();
decisionValue = Double.NEGATIVE_INFINITY;
pv.clear();
int depth = 0;
int depthLimit = 0;
int lastDepth = 0;
exit = false;
maxDepth = 0;
do {
visited = 0;
alpha = Double.NEGATIVE_INFINITY;
beta = Double.POSITIVE_INFINITY;
depthLimit++;
// int[] newDecision = null;
double newDecisionValue = Double.NEGATIVE_INFINITY;
boolean flag = false;
Iterator<int[]> legalMovesIt = b.legalMovesIterator();
while (legalMovesIt.hasNext()) {
if (decisionList != null && timer.isExpired()) {
exit = true;
break;
}
int[] move = null;
if (pv.get(depth) != null && !flag
&& b.isMoveLegal(pv.get(depth))) {
flag = true;
move = pv.get(depth);
} else {
move = legalMovesIt.next();
}
b.move(move[0], move[1], move[2], move[3]);
double value = minValue(b, alpha, beta, depth + 1, depthLimit);
if (value > newDecisionValue) {
newDecisionValue = value;
decisionList.clear();
decisionList.add(move);
pv.put(depth, move);
} else {
if (value == newDecisionValue) {
decisionList.add(move);
}
}
if (newDecisionValue >= beta) {
b.unmove();
return move;
}
alpha = (newDecisionValue > alpha) ? newDecisionValue : alpha;
b.unmove();
}
if (!exit) {
int i = r.nextInt(decisionList.size());
decision = decisionList.get(i);
decisionValue = newDecisionValue;
}
if (lastDepth == maxDepth) {
timer.stop();
return decision;
} else {
lastDepth = maxDepth;
}
maxd = maxDepth > maxd ? maxDepth : maxd;
} while (!exit);
return decision;
}
private double maxValue(Board b, double alpha, double beta, int depth,
int depthLimit) {
visited++;
if (depth > maxDepth) {
maxDepth = depth;
}
if (cutoff(b, depth, depthLimit)) {
return h.evaluate(b, depth);
}
double v = Double.NEGATIVE_INFINITY;
boolean flag = false;
Iterator<int[]> legalMovesIt = b.legalMovesIterator();
while (legalMovesIt.hasNext() && !exit) {
int[] move = null;
if (pv.get(depth) != null && !flag && b.isMoveLegal(pv.get(depth))) {
flag = true;
move = pv.get(depth);
} else {
move = legalMovesIt.next();
}
b.move(move[0], move[1], move[2], move[3]);
double minValue = minValue(b, alpha, beta, depth + 1, depthLimit);
if (minValue > v) {
v = minValue;
pv.put(depth, move);
}
if (v >= beta) {
b.unmove();
return v;
}
alpha = (v > alpha) ? v : alpha;
b.unmove();
}
return v;
}
private double minValue(Board b, double alpha, double beta, int depth,
int depthLimit) {
visited++;
if (depth > maxDepth) {
maxDepth = depth;
}
if (cutoff(b, depth, depthLimit)) {
return h.evaluate(b, depth);
}
boolean flag = false;
double v = Double.POSITIVE_INFINITY;
Iterator<int[]> legalMovesIt = b.legalMovesIterator();
while (legalMovesIt.hasNext() && !exit) {
int[] move = null;
if (pv.get(depth) != null && !flag && b.isMoveLegal(pv.get(depth))) {
flag = true;
move = pv.get(depth);
} else {
move = legalMovesIt.next();
}
b.move(move[0], move[1], move[2], move[3]);
double maxValue = maxValue(b, alpha, beta, depth + 1, depthLimit);
if (maxValue < v) {
v = maxValue;
pv.put(depth, move);
}
if (v <= alpha) {
b.unmove();
return v;
}
beta = (v < beta) ? v : beta;
b.unmove();
}
return v;
}
private boolean cutoff(Board b, int depth, int depthLimit) {
if (timer.isExpired()) {
exit = true;
return true;
}
return depth >= depthLimit || depth == plyThreshold
|| b.isGameFinished();
}
@Override
public int[] getLastMove() {
// attention, aliasing!
return decision;
}
@Override
public double getLastValue() {
return decisionValue;
}
} | 23.353448 | 72 | 0.637135 |
b005f716f40d46fc142ee21aff4421d9aa8879b7 | 12,727 | /*
* Licensed to Crate under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. Crate 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.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial
* agreement.
*/
package io.crate.expression.tablefunctions;
import io.crate.data.Bucket;
import io.crate.data.Input;
import io.crate.data.Row;
import io.crate.data.RowN;
import io.crate.metadata.FunctionIdent;
import io.crate.metadata.FunctionInfo;
import io.crate.metadata.FunctionName;
import io.crate.metadata.TransactionContext;
import io.crate.metadata.functions.Signature;
import io.crate.metadata.pgcatalog.PgCatalogSchemaInfo;
import io.crate.metadata.tablefunctions.TableFunctionImplementation;
import io.crate.types.DataType;
import io.crate.types.DataTypes;
import io.crate.types.RowType;
import org.joda.time.Period;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.BinaryOperator;
/**
* <pre>
* {@code
* generate_series :: a -> a -> table a
* generate_series(start, stop)
*
* generate_series :: a -> a -> a -> table a
* generate_series(start, stop, step)
*
* where: a = Integer or Long
* }
* </pre>
*/
public final class GenerateSeries<T extends Number> extends TableFunctionImplementation<T> {
public static final FunctionName NAME = new FunctionName(PgCatalogSchemaInfo.NAME, "generate_series");
public static void register(TableFunctionModule module) {
// without step
module.register(
Signature.table(
NAME,
DataTypes.LONG.getTypeSignature(),
DataTypes.LONG.getTypeSignature(),
new RowType(List.of(DataTypes.LONG)).getTypeSignature()),
(signature, argTypes) -> new GenerateSeries<>(
signature,
argTypes,
1L,
(x, y) -> x - y,
Long::sum,
(x, y) -> x / y,
Long::compare)
);
module.register(
Signature.table(
NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
new RowType(List.of(DataTypes.INTEGER)).getTypeSignature()),
(signature, argTypes) -> new GenerateSeries<>(
signature,
argTypes,
1,
(x, y) -> x - y,
Integer::sum,
(x, y) -> x / y,
Integer::compare)
);
// with step
module.register(
Signature.table(
NAME,
DataTypes.LONG.getTypeSignature(),
DataTypes.LONG.getTypeSignature(),
DataTypes.LONG.getTypeSignature(),
new RowType(List.of(DataTypes.LONG)).getTypeSignature()),
(signature, argTypes) -> new GenerateSeries<>(
signature,
argTypes,
1L,
(x, y) -> x - y,
Long::sum,
(x, y) -> x / y,
Long::compare)
);
module.register(
Signature.table(
NAME,
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
DataTypes.INTEGER.getTypeSignature(),
new RowType(List.of(DataTypes.INTEGER)).getTypeSignature()),
(signature, argTypes) -> new GenerateSeries<>(
signature,
argTypes,
1,
(x, y) -> x - y,
Integer::sum,
(x, y) -> x / y,
Integer::compare)
);
// generate_series(ts, ts, interval)
for (var supportedType : List.of(DataTypes.TIMESTAMP, DataTypes.TIMESTAMPZ)) {
module.register(
Signature.table(
NAME,
supportedType.getTypeSignature(),
supportedType.getTypeSignature(),
DataTypes.INTERVAL.getTypeSignature(),
new RowType(List.of(supportedType)).getTypeSignature()),
GenerateSeriesIntervals::new
);
module.register(
Signature.table(
NAME,
supportedType.getTypeSignature(),
supportedType.getTypeSignature(),
new RowType(List.of(supportedType)).getTypeSignature()),
(signature, argTypes) -> {
throw new IllegalArgumentException(
"generate_series(start, stop) has type `" + argTypes.get(0).getName() +
"` for start, but requires long/int values for start and stop, " +
"or if used with timestamps, it requires a third argument for the step (interval)");
}
);
}
}
private final FunctionInfo info;
private final Signature signature;
private final T defaultStep;
private final BinaryOperator<T> minus;
private final BinaryOperator<T> plus;
private final BinaryOperator<T> divide;
private final Comparator<T> comparator;
private final RowType returnType;
private GenerateSeries(Signature signature,
List<DataType> dataTypes,
T defaultStep,
BinaryOperator<T> minus,
BinaryOperator<T> plus,
BinaryOperator<T> divide,
Comparator<T> comparator) {
this.signature = signature;
this.defaultStep = defaultStep;
this.minus = minus;
this.plus = plus;
this.divide = divide;
this.comparator = comparator;
this.returnType = new RowType(List.of((DataType<?>) dataTypes.get(0)));
this.info = new FunctionInfo(
new FunctionIdent(NAME, dataTypes),
dataTypes.get(0),
FunctionInfo.Type.TABLE);
}
@Override
public Bucket evaluate(TransactionContext txnCtx, Input<T>... args) {
T startInclusive = args[0].value();
T stopInclusive = args[1].value();
T step = args.length == 3 ? args[2].value() : defaultStep;
if (startInclusive == null || stopInclusive == null || step == null) {
return Bucket.EMPTY;
}
T diff = minus.apply(plus.apply(stopInclusive, step), startInclusive);
final int numRows = Math.max(0, divide.apply(diff, step).intValue());
final boolean reverseCompare = comparator.compare(startInclusive, stopInclusive) > 0 && numRows > 0;
final Object[] cells = new Object[1];
cells[0] = startInclusive;
final RowN rowN = new RowN(cells);
return new Bucket() {
@Override
public int size() {
return numRows;
}
@Override
@Nonnull
public Iterator<Row> iterator() {
return new Iterator<>() {
boolean doStep = false;
T val = startInclusive;
@Override
public boolean hasNext() {
if (doStep) {
val = plus.apply(val, step);
doStep = false;
}
int compare = comparator.compare(val, stopInclusive);
if (reverseCompare) {
return compare >= 0;
} else {
return compare <= 0;
}
}
@Override
public Row next() {
if (!hasNext()) {
throw new NoSuchElementException("Iterator has no more elements");
}
doStep = true;
cells[0] = val;
return rowN;
}
};
}
};
}
@Override
public FunctionInfo info() {
return info;
}
@Nullable
@Override
public Signature signature() {
return signature;
}
@Override
public RowType returnType() {
return returnType;
}
@Override
public boolean hasLazyResultSet() {
return true;
}
private static class GenerateSeriesIntervals extends TableFunctionImplementation<Object> {
private final FunctionInfo info;
private final RowType returnType;
private final Signature signature;
public GenerateSeriesIntervals(Signature signature, List<DataType> types) {
this.signature = signature;
info = new FunctionInfo(new FunctionIdent(NAME, types), types.get(0), FunctionInfo.Type.TABLE);
returnType = new RowType(List.of((DataType<?>) types.get(0)));
}
@Override
public FunctionInfo info() {
return info;
}
@Nullable
@Override
public Signature signature() {
return signature;
}
@Override
public Iterable<Row> evaluate(TransactionContext txnCtx, Input<Object>... args) {
Long startInclusive = (Long) args[0].value();
Long stopInclusive = (Long) args[1].value();
Period step = (Period) args[2].value();
if (startInclusive == null || stopInclusive == null || step == null) {
return Bucket.EMPTY;
}
ZonedDateTime start = Instant.ofEpochMilli(startInclusive).atZone(ZoneOffset.UTC);
ZonedDateTime stop = Instant.ofEpochMilli(stopInclusive).atZone(ZoneOffset.UTC);
boolean reverse = start.compareTo(stop) > 0;
if (reverse && add(start, step).compareTo(start) >= 0) {
return Bucket.EMPTY;
}
return () -> new Iterator<>() {
final Object[] cells = new Object[1];
final RowN rowN = new RowN(cells);
ZonedDateTime value = start;
boolean doStep = false;
@Override
public boolean hasNext() {
if (doStep) {
value = add(value, step);
doStep = false;
}
int compare = value.compareTo(stop);
return reverse
? compare >= 0
: compare <= 0;
}
@Override
public Row next() {
if (!hasNext()) {
throw new NoSuchElementException("No more element in generate_series");
}
doStep = true;
cells[0] = (value.toEpochSecond() * 1000);
return rowN;
}
};
}
private static ZonedDateTime add(ZonedDateTime dateTime, Period step) {
return dateTime
.plusYears(step.getYears())
.plusMonths(step.getMonths())
.plusWeeks(step.getWeeks())
.plusDays(step.getDays())
.plusHours(step.getHours())
.plusMinutes(step.getMinutes())
.plusSeconds(step.getSeconds())
.plusNanos(step.getMillis() * 1000_0000L);
}
@Override
public RowType returnType() {
return returnType;
}
@Override
public boolean hasLazyResultSet() {
return true;
}
}
}
| 35.352778 | 108 | 0.53579 |
874fd9be065a11a8a4630758c49f8ae1f07cf4a0 | 2,020 | package lv.lumii.obis.schema.services.extractor;
import lombok.extern.slf4j.Slf4j;
import lv.lumii.obis.schema.model.*;
import lv.lumii.obis.schema.services.common.dto.QueryResult;
import lv.lumii.obis.schema.services.extractor.dto.*;
import org.springframework.stereotype.Service;
import javax.annotation.Nonnull;
import java.util.*;
import static lv.lumii.obis.schema.services.extractor.SchemaExtractorQueries.*;
/**
* Service to get data by executing just a few but complex queries.
* For example - ask all possible intersection classes, all possible data type or object properties.
*/
@Slf4j
@Service
public class SchemaExtractorFewQueries extends SchemaExtractor {
@Override
protected void findIntersectionClassesAndUpdateClassNeighbors(@Nonnull List<SchemaClass> classes, @Nonnull Map<String, SchemaExtractorClassNodeInfo> graphOfClasses, @Nonnull SchemaExtractorRequestDto request) {
List<QueryResult> queryResults = sparqlEndpointProcessor.read(request, FIND_INTERSECTION_CLASSES);
updateGraphOfClassesWithNeighbors(queryResults, graphOfClasses, request);
queryResults.clear();
}
@Override
protected Map<String, SchemaExtractorPropertyNodeInfo> findAllDataTypeProperties(@Nonnull List<SchemaClass> classes, @Nonnull SchemaExtractorRequestDto request) {
List<QueryResult> queryResults = sparqlEndpointProcessor.read(request, FIND_ALL_DATATYPE_PROPERTIES);
Map<String, SchemaExtractorPropertyNodeInfo> properties = new HashMap<>();
processAllDataTypeProperties(queryResults, properties, request);
return properties;
}
@Override
protected Map<String, SchemaExtractorPropertyNodeInfo> findAllObjectTypeProperties(@Nonnull List<SchemaClass> classes, @Nonnull SchemaExtractorRequestDto request) {
List<QueryResult> queryResults = sparqlEndpointProcessor.read(request, FIND_OBJECT_PROPERTIES_WITH_DOMAIN_RANGE);
Map<String, SchemaExtractorPropertyNodeInfo> properties = new HashMap<>();
processAllObjectTypeProperties(queryResults, properties, request);
return properties;
}
}
| 43.913043 | 211 | 0.824752 |
9ae02f177db703f099a05c91f282df6fb777ea49 | 3,515 | package edu.colorado.csdms.heat;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* JUnit tests for the grid information methods of the {@link BmiHeat} class.
*/
public class TestGridInfo {
private String varName;
private int gridId;
private int[] shape;
private double[] spacing;
private double[] origin;
private int size;
private String type;
private Double delta; // maximum difference to be considered equal
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
varName = "plate_surface__temperature";
gridId = 0;
shape = new int[] {10, 20};
spacing = new double[] {1.0, 1.0};
origin = new double[] {0.0, 0.0};
size = 200;
type = "uniform_rectilinear_grid";
delta = 0.1;
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
/**
* Test method for {@link BmiHeat#getVarGrid(java.lang.String)}.
*/
@Test
public final void testGetVarGrid() {
BmiHeat component = new BmiHeat();
component.initialize();
assertEquals(gridId, component.getVarGrid(varName));
}
/**
* Test method for {@link BmiHeat#getGridShape(int)}.
*/
@Test
public final void testGetGridShape() {
BmiHeat component = new BmiHeat();
component.initialize();
assertArrayEquals(shape, component.getGridShape(gridId));
}
/**
* Test method for {@link BmiHeat#getGridX(int)}.
*/
@Test
public final void testGetGridX() {
return; // Not implemented for Heat
}
/**
* Test method for {@link BmiHeat#getGridY(int)}.
*/
@Test
public final void testGetGridY() {
return; // Not implemented for Heat
}
/**
* Test method for {@link BmiHeat#getGridZ(int)}.
*/
@Test
public final void testGetGridZ() {
return; // Not implemented for Heat
}
/**
* Test method for {@link BmiHeat#getGridRank(int)}.
*/
@Test
public final void testGetGridRank() {
BmiHeat component = new BmiHeat();
component.initialize();
assertEquals(shape.length, component.getGridRank(gridId));
}
/**
* Test method for {@link BmiHeat#getGridSize(int)}.
*/
@Test
public final void testGetGridSize() {
BmiHeat component = new BmiHeat();
component.initialize();
assertEquals(size, component.getGridSize(gridId));
}
/**
* Test method for {@link BmiHeat#getGridType(int)}.
*/
@Test
public final void testGetGridType() {
BmiHeat component = new BmiHeat();
component.initialize();
assertEquals(type, component.getGridType(gridId));
}
/**
* Test method for {@link BmiHeat#getGridSpacing(int)}.
*/
@Test
public final void testGetGridSpacing() {
BmiHeat component = new BmiHeat();
component.initialize();
assertArrayEquals(spacing, component.getGridSpacing(gridId), delta);
}
/**
* Test method for {@link BmiHeat#getGridOrigin(int)}.
*/
@Test
public final void testGetGridOrigin() {
BmiHeat component = new BmiHeat();
component.initialize();
assertArrayEquals(origin, component.getGridOrigin(gridId), delta);
}
/**
* Test method for {@link BmiHeat#getGridConnectivity(int)}.
*/
@Test
public final void testGetGridConnectivity() {
return; // Not implemented for Heat
}
/**
* Test method for {@link BmiHeat#getGridOffset(int)}.
*/
@Test
public final void testGetGridOffset() {
return; // Not implemented for Heat
}
}
| 22.532051 | 77 | 0.654339 |
3a1a7019c248f92f24b09eee384fbeb32ebf8b42 | 2,902 | /*
* Copyright 2017 Ribose Inc. <https://www.ribose.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ribose.jenkins.plugin.awscodecommittrigger.it.mock;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.services.sqs.AmazonSQS;
import com.ribose.jenkins.plugin.awscodecommittrigger.Context;
import com.ribose.jenkins.plugin.awscodecommittrigger.interfaces.SQSFactory;
import com.ribose.jenkins.plugin.awscodecommittrigger.interfaces.SQSQueue;
import com.ribose.jenkins.plugin.awscodecommittrigger.interfaces.SQSQueueMonitor;
import com.ribose.jenkins.plugin.awscodecommittrigger.net.RequestFactory;
import com.ribose.jenkins.plugin.awscodecommittrigger.net.SQSChannel;
import com.ribose.jenkins.plugin.awscodecommittrigger.net.SQSChannelImpl;
import com.ribose.jenkins.plugin.awscodecommittrigger.threading.SQSQueueMonitorImpl;
import javax.inject.Inject;
import java.net.Proxy;
import java.util.concurrent.ExecutorService;
public class MockSQSFactory implements SQSFactory {
@Inject
private RequestFactory factory;
public MockSQSFactory() {
Context.injector().injectMembers(this);
}
@Override
public AmazonSQS createSQSAsync(SQSQueue queue) {
return MockAwsSqs.get().getSqsClient();
}
@Override
public AmazonSQS createSQSAsync(String accessKey, String secretKey) {
return MockAwsSqs.get().getSqsClient();
}
@Override
public AmazonSQS createSQSAsync(String accessKey, String secretKey, String region) {
return MockAwsSqs.get().getSqsClient();
}
@Override
public SQSQueueMonitor createMonitor(ExecutorService executor, SQSQueue queue) {
final AmazonSQS sqs = this.createSQSAsync(queue);
final SQSChannel channel = new SQSChannelImpl(sqs, queue, this.factory);
return new SQSQueueMonitorImpl(executor, queue, channel);
}
@Override
public SQSQueueMonitor createMonitor(SQSQueueMonitor monitor, SQSQueue queue) {
final SQSChannel channel = this.createChannel(queue);
return monitor.clone(queue, channel);
}
@Override
public ClientConfiguration getClientConfiguration(Proxy proxy) {
return null;
}
private SQSChannel createChannel(final SQSQueue queue) {
final AmazonSQS sqs = this.createSQSAsync(queue);
return new SQSChannelImpl(sqs, queue, this.factory);
}
}
| 35.390244 | 88 | 0.75603 |
c074726bef66ae4258f01e994e47282c38696573 | 3,035 | package ru.job4j.board;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Класс StartTest.
* @author Konstantin Kolganov ([email protected])
* @since 07.10.2017
* @version 2.0
*/
public class StartTest {
/**
* Тест метод.
* Если в текущей ячейке стоит слон, то метод move вернет значение true.
*/
@Test
public void whenInCurrentCellIsElephantThenMethodMoveReturnTrue() {
// Создаем объект класса Board
Board board = new Board();
// Создаем шахматную доску
board.createBoard();
// Создаем массив фигур и расставим их по клеткам шахматной доски
board.createFigure();
// Координаты текущей ячейки source
// и целевой dist
String source = "c-1";
String dist = "g-5";
// Уберем пешку "d-2" на пути слона
board.translate("d-2").setFigure(null);
// Результат
boolean result = false;
try {
result = board.move(board.translate(source), board.translate(dist));
} catch (ImpossibleMoveException ime) {
System.out.println("Moving is impossible. Select another cell.");
} catch (FigureNotFoundException fnfe) {
System.out.println("Figure not found!");
} catch (OccupiedWayException owe) {
System.out.println("On the way there is a figure!");
}
// Сравниваем результат с ожидаемым значением
assertThat(result, is(true));
}
/**
* Тест метод.
* Если слон пройдет из поля c-1 в поле g-5, то получим массив из четырех ячеек.
*/
@Test
public void whenElephantGotoThreeCellDiagonThenReturnDistance() {
// Создаем объект класса Board
Board board = new Board();
// Создаем шахматную доску
board.createBoard();
// Создаем массив фигур и расставим их по клеткам
board.createFigure();
// Координаты текущей ячейки source
// и целевой dist
String source = "c-1";
String dist = "g-5";
// Сохраним Слона!
Figure figure = board.translate(source).getFigure();
Cell[] cell = null;
try {
cell = figure.way(board.translate(dist));
} catch (ImpossibleMoveException ime) {
System.out.println("Moving is impossible. Select another cell.");
}
// Сравниваем результат с ожидаемым значением
assertThat(cell.length, is(4));
}
/**
* Тест метод.
* Если выполняются все условия перемещения, то слон из поля "c-1" окажется в "d-5".
*/
@Test
public void whenElephantGotoFourCellDiagonThenDistCellGetElephant() {
// Создаем объект класса Board
Board board = new Board();
// Создаем шахматную доску
board.createBoard();
// Создаем массив фигур и расставим их по клеткам
board.createFigure();
// Координаты текущей ячейки source
// и целевой dist
String source = "c-1";
String dist = "g-5";
// Уберем пешку "d-2" на пути слона
board.translate("d-2").setFigure(null);
// Сохраним Слона!
Figure figure = board.translate(source).getFigure();
// Новый объект класса Start
Start start = new Start(board);
// Двигаем фигуру из source в dist
start.init(source, dist);
// Сравниваем результат с ожидаемым значением
assertThat(board.translate(dist).getFigure(), is(figure));
}
} | 30.049505 | 83 | 0.708402 |
cbd920b65323d05e6243f29de4921e726d9ae79d | 879 | package org.gillius.jagnet.netty;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
public class KryoEncoder extends MessageToByteEncoder<Object> {
private final Kryo kryo;
private final boolean includeLengthField;
private final Output output;
public KryoEncoder(Kryo kryo, boolean includeLengthField) {
this.kryo = kryo;
this.includeLengthField = includeLengthField;
output = new Output(1024, 65535);
}
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
output.clear();
kryo.writeClassAndObject(output, msg);
int len = output.position();
if (includeLengthField)
out.writeShort(len);
out.writeBytes(output.getBuffer(), 0, len);
}
}
| 29.3 | 93 | 0.782708 |
689e9414b3920266e025b3523d542ee6512394a6 | 11,537 | package ui.custom.fx;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.beans.WeakInvalidationListener;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.text.Text;
import javafx.util.StringConverter;
import java.lang.ref.WeakReference;
/**
* A {@link javafx.scene.control.cell.TextFieldTreeCell} that takes a {@link javafx.beans.binding.StringBinding}
* the value of which will be concatenated to the end of actual value of the tree item for display
*/
public class ValueAddedTextFieldTreeCell<T> extends TreeCell<T> {
static int TREE_VIEW_HBOX_GRAPHIC_PADDING = 3;
private ObservableValue<String> toConcat;
private Paint concatFill;
private OverrunStyle concatOverrun;
private TextField textField;
private HBox hbox;
// --- converter
private ObjectProperty<StringConverter<T>> converter = new SimpleObjectProperty<>(this, "converter");
private WeakReference<TreeItem<T>> treeItemRef;
private InvalidationListener treeItemGraphicListener = observable -> {
updateDisplay(getItem(), isEmpty());
};
private InvalidationListener treeItemListener = new InvalidationListener() {
@Override public void invalidated(Observable observable) {
TreeItem<T> oldTreeItem = treeItemRef == null ? null : treeItemRef.get();
if (oldTreeItem != null) {
oldTreeItem.graphicProperty().removeListener(weakTreeItemGraphicListener);
}
TreeItem<T> newTreeItem = getTreeItem();
if (newTreeItem != null) {
newTreeItem.graphicProperty().addListener(weakTreeItemGraphicListener);
treeItemRef = new WeakReference<>(newTreeItem);
}
}
};
private WeakInvalidationListener weakTreeItemGraphicListener =
new WeakInvalidationListener(treeItemGraphicListener);
private WeakInvalidationListener weakTreeItemListener =
new WeakInvalidationListener(treeItemListener);
/**
* The {@link StringConverter} property.
*/
public final ObjectProperty<StringConverter<T>> converterProperty() {
return converter;
}
/**
* Sets the {@link StringConverter} to be used in this cell.
*/
public final void setConverter(StringConverter<T> value) {
converterProperty().set(value);
}
/**
* Returns the {@link StringConverter} used in this cell.
*/
public final StringConverter<T> getConverter() {
return converterProperty().get();
}
/**
* Creates a ValueAddedTextFieldTreeCell that provides a {@link TextField} when put
* into editing mode that allows editing of the cell content. This method
* will work on any TreeView instance, regardless of its generic type.
* However, to enable this, a {@link StringConverter} must be provided that
* will convert the given String (from what the user typed in) into an
* instance of type T. This item will then be passed along to the
* {@link TreeView#onEditCommitProperty()} callback.
*
* @param converter A {@link StringConverter converter} that can convert
* the given String (from what the user typed in) into an instance of
* type T.
*/
public ValueAddedTextFieldTreeCell(StringConverter<T> converter) {
setConverter(converter);
this.concatFill = this.getTextFill();
this.concatOverrun = this.getTextOverrun();
treeItemProperty().addListener(weakTreeItemListener);
if (getTreeItem() != null) {
getTreeItem().graphicProperty().addListener(weakTreeItemGraphicListener);
}
}
public void setBinding(ObservableValue<String> toConcat) {
if (toConcat == null) {
this.textProperty().unbind();
this.toConcat = toConcat;
} else {
this.toConcat = toConcat;
}
}
public void setConcatFill(Paint concatFill) {
this.concatFill = concatFill;
}
public void setConcatOverrun(OverrunStyle style) {
this.concatOverrun = style;
}
void updateDisplay(T item, boolean empty) {
textProperty().unbind();
setText(null);
if (item == null || empty) {
hbox = null;
setGraphic(null);
} else {
// update the graphic if one is set in the TreeItem
TreeItem<T> treeItem = getTreeItem();
Label concatText = new Label("");
concatText.setTextFill(this.concatFill);
concatText.setTextOverrun(this.concatOverrun);
if (toConcat != null) {
concatText.textProperty().bind(toConcat);
}
if (hbox == null) {
hbox = new HBox(3);
}
if (treeItem != null && treeItem.getGraphic() != null) {
if (item instanceof Node) {
// the item is a Node, and the graphic exists, so
// we must insert both into an HBox and present that
// to the user (see RT-15910)
hbox.getChildren().setAll(treeItem.getGraphic(), (Node)item, concatText);
setGraphic(hbox);
} else {
Text itemText = new Text(item.toString());
hbox.getChildren().setAll(treeItem.getGraphic(), itemText, concatText);
setGraphic(hbox);
}
} else {
if (item instanceof Node) {
hbox.getChildren().setAll((Node)item, concatText);
setGraphic(hbox);
} else {
Text itemText = new Text(item.toString());
hbox.getChildren().setAll(itemText, concatText);
setGraphic(hbox);
}
}
}
}
/** {@inheritDoc} */
@Override public void startEdit() {
if (! isEditable() || ! getTreeView().isEditable()) {
return;
}
super.startEdit();
if (isEditing()) {
StringConverter<T> converter = getConverter();
if (textField == null) {
textField = createTextField(this, converter);
}
if (hbox == null) {
hbox = new HBox(TREE_VIEW_HBOX_GRAPHIC_PADDING);
}
startEdit(this, converter, hbox, getTreeItemGraphic(), textField);
}
}
/** {@inheritDoc} */
@Override public void cancelEdit() {
super.cancelEdit();
cancelEdit(this, getConverter(), getTreeItemGraphic());
this.updateDisplay(this.getItem(), this.isEmpty());
}
/** {@inheritDoc} */
@Override public void updateItem(T item, boolean empty) {
this.textProperty().unbind();
updateItem(this, getConverter(), hbox, getTreeItemGraphic(), textField);
updateDisplay(item, empty);
super.updateItem(item, empty);
}
/***************************************************************************
* *
* Private Implementation *
* *
**************************************************************************/
private Node getTreeItemGraphic() {
TreeItem<T> treeItem = getTreeItem();
return treeItem == null ? null : treeItem.getGraphic();
}
// Pulled from Cell Utils
/***************************************************************************
* *
* TextField convenience *
* *
**************************************************************************/
static <T> void updateItem(final Cell<T> cell,
final StringConverter<T> converter,
final HBox hbox,
final Node graphic,
final TextField textField) {
if (cell.isEmpty()) {
cell.setText(null);
cell.setGraphic(null);
} else {
if (cell.isEditing()) {
if (textField != null) {
textField.setText(getItemText(cell, converter));
}
cell.setText(null);
if (graphic != null) {
hbox.getChildren().setAll(graphic, textField);
cell.setGraphic(hbox);
} else {
cell.setGraphic(textField);
}
} else {
cell.setText(getItemText(cell, converter));
cell.setGraphic(graphic);
}
}
}
static <T> void startEdit(final Cell<T> cell,
final StringConverter<T> converter,
final HBox hbox,
final Node graphic,
final TextField textField) {
if (textField != null) {
textField.setText(getItemText(cell, converter));
}
cell.textProperty().unbind();
cell.setText(null);
if (graphic != null) {
hbox.getChildren().setAll(graphic, textField);
cell.setGraphic(hbox);
} else {
cell.setGraphic(textField);
}
textField.selectAll();
// requesting focus so that key input can immediately go into the
// TextField (see RT-28132)
textField.requestFocus();
}
static <T> void cancelEdit(Cell<T> cell, final StringConverter<T> converter, Node graphic) {
cell.setText(getItemText(cell, converter));
cell.setGraphic(graphic);
}
static <T> TextField createTextField(final Cell<T> cell, final StringConverter<T> converter) {
final TextField textField = new TextField(getItemText(cell, converter));
// Use onAction here rather than onKeyReleased (with check for Enter),
// as otherwise we encounter RT-34685
textField.setOnAction(event -> {
if (converter == null) {
throw new IllegalStateException(
"Attempting to convert text input into Object, but provided "
+ "StringConverter is null. Be sure to set a StringConverter "
+ "in your cell factory.");
}
cell.commitEdit(converter.fromString(textField.getText()));
event.consume();
});
textField.setOnKeyReleased(t -> {
if (t.getCode() == KeyCode.ESCAPE) {
cell.cancelEdit();
t.consume();
}
});
return textField;
}
private static <T> String getItemText(Cell<T> cell, StringConverter<T> converter) {
return converter == null ?
cell.getItem() == null ? "" : cell.getItem().toString() :
converter.toString(cell.getItem());
}
}
| 35.94081 | 112 | 0.542515 |
5f562edd34ee1b01fe8e7f94055ff3f53a85f074 | 653 | package im.wangbo.java.leetcode.tree;
/**
* See https://leetcode-cn.com/explore/interview/card/top-interview-questions-medium/32/trees-and-graphs/87/
*
* 根据一棵树的前序遍历与中序遍历构造二叉树。
*
* 注意:
* 你可以假设树中没有重复的元素。
*
* 例如,给出
*
* 前序遍历 preorder = [3,9,20,15,7]
* 中序遍历 inorder = [9,3,15,20,7]
* 返回如下的二叉树:
*
* 3
* / \
* 9 20
* / \
* 15 7
*
* @author Elvis Wang
*/
class BuildTreeFromPreorderAndInorderSolution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length != inorder.length) return null;
if (preorder.length == 0) return null;
// TODO
return null;
}
}
| 19.205882 | 108 | 0.600306 |
c46df6d25d012a75017e9a65c7677bba464c8f29 | 1,039 | package com.didiglobal.logi.log.common.enums;
/**
* @author jinbinbin
* @version $Id: StorageEnum.java, v 0.1 2018年03月22日 23:31 jinbinbin Exp $
*/
public enum StorageEnum {
//
KAFKA(0, "kafka"),
//
DATA_CENTER(1, "data_center"),
//
MQ(2, "ddmq"),
//
HDFS(3, "HDFS"),
//
ES(4, "ES"),
//
HBASE(5, "hbase"),
//
KAFKA_MOCK(6, "kafka mock"),
//
CEPH(7, "ceph"),
//
;
private int code;
private String desc;
StorageEnum(int code, String desc){
this.code = code;
this.desc = desc;
}
public int getCode() {
return code;
}
public String getDesc() {
return desc;
}
}
| 24.162791 | 74 | 0.347449 |
bcbab632b769a000defb63186063371c1eaf92e6 | 1,066 | package poussecafe.attribute;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* @param <U> Stored type
* @param <T> Attribute type
*/
public class AdaptingReadWriteOptionalAttributeBuilder<U, T> {
AdaptingReadWriteOptionalAttributeBuilder(Supplier<T> getter, Function<T, U> adapter) {
this.getter = getter;
this.adapter = adapter;
}
private Supplier<T> getter;
private Function<T, U> adapter;
public ReadWriteOptionalAttributeBuilder<T> write(Consumer<U> setter) {
Objects.requireNonNull(setter);
CompositeAttribute<T, T> compositeAttribute = new CompositeAttribute<>();
compositeAttribute.getter = getter;
compositeAttribute.setter = value -> {
if(value != null) {
setter.accept(adapter.apply(value));
} else {
setter.accept(null);
}
};
return new ReadWriteOptionalAttributeBuilder<>(compositeAttribute);
}
}
| 28.052632 | 91 | 0.660413 |
64602728d7d865c6814e8acfcda0cd0aec813983 | 94 | package org.jvnet.jaxb2_commons.xml.bind.model;
public interface MTransientPropertyInfo {
}
| 15.666667 | 47 | 0.819149 |
7693c8afe1eaeb95aa00ec1c9810e9beab0a4f54 | 6,916 | /*
* 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.facebook.presto.spi.function;
import com.facebook.presto.spi.api.Experimental;
import com.facebook.presto.spi.type.TypeSignature;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import static com.facebook.presto.spi.function.FunctionKind.SCALAR;
import static com.facebook.presto.spi.function.SqlFunctionVisibility.PUBLIC;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
@Experimental
public class SqlInvokedFunction
implements SqlFunction
{
private final List<SqlParameter> parameters;
private final String description;
private final RoutineCharacteristics routineCharacteristics;
private final String body;
private final Signature signature;
private final SqlFunctionId functionId;
private final Optional<SqlFunctionHandle> functionHandle;
public SqlInvokedFunction(
QualifiedFunctionName functionName,
List<SqlParameter> parameters,
TypeSignature returnType,
String description,
RoutineCharacteristics routineCharacteristics,
String body,
Optional<Long> version)
{
this.parameters = requireNonNull(parameters, "parameters is null");
this.description = requireNonNull(description, "description is null");
this.routineCharacteristics = requireNonNull(routineCharacteristics, "routineCharacteristics is null");
this.body = requireNonNull(body, "body is null");
List<TypeSignature> argumentTypes = parameters.stream()
.map(SqlParameter::getType)
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
this.signature = new Signature(functionName, SCALAR, returnType, argumentTypes);
this.functionId = new SqlFunctionId(functionName, argumentTypes);
this.functionHandle = version.map(v -> new SqlFunctionHandle(this.functionId, v));
}
public SqlInvokedFunction withVersion(long version)
{
if (getVersion().isPresent()) {
throw new IllegalArgumentException(format("function %s is already with version %s", signature.getName(), getVersion().get()));
}
return new SqlInvokedFunction(
signature.getName(),
parameters,
signature.getReturnType(),
description,
routineCharacteristics,
body,
Optional.of(version));
}
@Override
public Signature getSignature()
{
return signature;
}
@Override
public SqlFunctionVisibility getVisibility()
{
return PUBLIC;
}
@Override
public boolean isDeterministic()
{
return routineCharacteristics.isDeterministic();
}
@Override
public boolean isCalledOnNullInput()
{
return routineCharacteristics.isCalledOnNullInput();
}
@Override
public String getDescription()
{
return description;
}
public List<SqlParameter> getParameters()
{
return parameters;
}
public RoutineCharacteristics getRoutineCharacteristics()
{
return routineCharacteristics;
}
public String getBody()
{
return body;
}
public SqlFunctionId getFunctionId()
{
return functionId;
}
public Optional<SqlFunctionHandle> getFunctionHandle()
{
return functionHandle;
}
public Optional<Long> getVersion()
{
return functionHandle.map(SqlFunctionHandle::getVersion);
}
public FunctionImplementationType getFunctionImplementationType()
{
return FunctionImplementationType.SQL;
}
public SqlFunctionHandle getRequiredFunctionHandle()
{
Optional<? extends SqlFunctionHandle> functionHandle = getFunctionHandle();
if (!functionHandle.isPresent()) {
throw new IllegalStateException("missing functionHandle");
}
return functionHandle.get();
}
public long getRequiredVersion()
{
Optional<Long> version = getVersion();
if (!version.isPresent()) {
throw new IllegalStateException("missing version");
}
return version.get();
}
public boolean hasSameDefinitionAs(SqlInvokedFunction function)
{
if (function == null) {
throw new IllegalArgumentException("function is null");
}
return Objects.equals(parameters, function.parameters)
&& Objects.equals(description, function.description)
&& Objects.equals(routineCharacteristics, function.routineCharacteristics)
&& Objects.equals(body, function.body)
&& Objects.equals(signature, function.signature);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
SqlInvokedFunction o = (SqlInvokedFunction) obj;
return Objects.equals(parameters, o.parameters)
&& Objects.equals(description, o.description)
&& Objects.equals(routineCharacteristics, o.routineCharacteristics)
&& Objects.equals(body, o.body)
&& Objects.equals(signature, o.signature)
&& Objects.equals(functionId, o.functionId)
&& Objects.equals(functionHandle, o.functionHandle);
}
@Override
public int hashCode()
{
return Objects.hash(parameters, description, routineCharacteristics, body, signature, functionId, functionHandle);
}
@Override
public String toString()
{
return format(
"%s(%s):%s%s {%s} %s",
signature.getName(),
parameters.stream()
.map(Object::toString)
.collect(joining(",")),
signature.getReturnType(),
getVersion().map(version -> ":" + version).orElse(""),
body,
routineCharacteristics);
}
}
| 31.870968 | 138 | 0.64893 |
d8572e98a4f9c3841955e6ea5bd9e1db0b012605 | 5,599 | /*
* This file is part of BDF
* BDF,Bstek Development Framework
* Copyright 2002-2013, BSTEK
* Dual licensed under the Bstek Commercial or GPL Version 2 licenses.
* http://www.bstek.com/
*/
package com.bstek.bdf.plugins.databasetool.wizard.pages.dialog;
import java.io.File;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.bstek.bdf.plugins.databasetool.dialect.DbDriverMetaData;
public class DbDriverLocationDialog extends Dialog {
private String dialogTitle = "设置数据库驱动";
private DbDriverMetaData dbDriverMetaData;
private Text dbNameText;
private Text driverClassNameText;
private Text driverLocationText;
private Button buttonBrowerDriverFile;
private Button buttonOk;
private Button buttonCancel;
private String driverLocation;
public DbDriverLocationDialog(Shell parentShell, DbDriverMetaData dbDriverMetaData) {
super(parentShell);
this.dbDriverMetaData = dbDriverMetaData;
}
public DbDriverLocationDialog(String dialogTitle, Shell parentShell, DbDriverMetaData dbDriverMetaData) {
super(parentShell);
this.dbDriverMetaData = dbDriverMetaData;
this.dialogTitle = dialogTitle;
}
private void createControl(Composite container) {
GridLayout layout = new GridLayout();
container.setLayout(layout);
layout.numColumns = 3;
layout.verticalSpacing = 10;
layout.marginTop = 10;
layout.marginWidth = 10;
GridData gd = null;
Label dbNameLabel = new Label(container, SWT.LEFT);
dbNameLabel.setText("数据库名称:");
gd = new GridData();
gd.horizontalSpan = 1;
dbNameLabel.setLayoutData(gd);
dbNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
dbNameText.setEnabled(false);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
dbNameText.setLayoutData(gd);
Label driverClassNameLabel = new Label(container, SWT.LEFT);
driverClassNameLabel.setText("Jdbc驱动类:");
gd = new GridData();
gd.horizontalSpan = 1;
driverClassNameLabel.setLayoutData(gd);
driverClassNameText = new Text(container, SWT.BORDER | SWT.SINGLE);
driverClassNameText.setEnabled(false);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 2;
driverClassNameText.setLayoutData(gd);
Label driverLocationLabel = new Label(container, SWT.LEFT);
driverLocationLabel.setText("Jdbc驱动位置:");
gd = new GridData();
gd.horizontalSpan = 1;
driverLocationLabel.setLayoutData(gd);
driverLocationText = new Text(container, SWT.BORDER | SWT.SINGLE);
driverLocationText.setEditable(false);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan = 1;
driverLocationText.setLayoutData(gd);
buttonBrowerDriverFile = new Button(container, SWT.PUSH);
buttonBrowerDriverFile.setText("浏览...");
gd = new GridData();
gd.horizontalSpan = 1;
gd.widthHint = 80;
buttonBrowerDriverFile.setLayoutData(gd);
buttonBrowerDriverFile.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(getShell(), SWT.MULTI);
dialog.setFilterExtensions(new String[] { "*.jar" });
if (dialog.open() != null) {
String[] fileNames = dialog.getFileNames();
StringBuffer sb = new StringBuffer();
if (fileNames.length > 0) {
int i = 1;
for (String fileName : fileNames) {
File file = new File(dialog.getFilterPath(), fileName);
sb.append(file.getAbsolutePath());
if (i != fileNames.length) {
sb.append(";");
}
i++;
}
}
driverLocationText.setText(sb.toString());
setDriverLocation(sb.toString());
}
}
});
initTextControlData();
}
private void initTextControlData() {
if (dbDriverMetaData != null) {
dbNameText.setText(dbDriverMetaData.getDbType());
driverClassNameText.setText(dbDriverMetaData.getDriverClassName());
driverLocationText.setText(dbDriverMetaData.getDriverLocation() == null ? "" : dbDriverMetaData.getDriverLocation());
}
}
protected Point getInitialSize() {
return new Point(500, 200);
}
protected Control createDialogArea(Composite parent) {
Composite container = (Composite) super.createDialogArea(parent);
createControl(container);
return container;
}
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(getDialogTitle());
}
@Override
protected void cancelPressed() {
super.cancelPressed();
}
@Override
protected void okPressed() {
super.okPressed();
}
@Override
protected void initializeBounds() {
super.initializeBounds();
buttonOk = getButton(IDialogConstants.OK_ID);
buttonOk.setText("确定");
buttonCancel = getButton(IDialogConstants.CANCEL_ID);
buttonCancel.setText("取消");
}
public String getDriverLocation() {
if(driverLocation==null){
return "";
}
return driverLocation;
}
public void setDriverLocation(String driverLocation) {
this.driverLocation = driverLocation;
}
public String getDialogTitle() {
return dialogTitle;
}
public void setDialogTitle(String dialogTitle) {
this.dialogTitle = dialogTitle;
}
} | 28.712821 | 120 | 0.746026 |
dff28a44de8b6ad25879c9c0cef61dfa939f571c | 46,106 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v7.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.*;
import android.widget.FrameLayout;
// Referenced classes of package android.support.v7.widget:
// ActionBarBackgroundDrawableV21, ActionBarBackgroundDrawable, ScrollingTabContainerView
public class ActionBarContainer extends FrameLayout
{
public ActionBarContainer(Context context)
{
this(context, ((AttributeSet) (null)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aconst_null
// 3 3:invokespecial #27 <Method void ActionBarContainer(Context, AttributeSet)>
// 4 6:return
}
public ActionBarContainer(Context context, AttributeSet attributeset)
{
super(context, attributeset);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:invokespecial #29 <Method void FrameLayout(Context, AttributeSet)>
Object obj;
if(android.os.Build.VERSION.SDK_INT >= 21)
//* 4 6:getstatic #34 <Field int android.os.Build$VERSION.SDK_INT>
//* 5 9:bipush 21
//* 6 11:icmplt 27
obj = ((Object) (new ActionBarBackgroundDrawableV21(this)));
// 7 14:new #36 <Class ActionBarBackgroundDrawableV21>
// 8 17:dup
// 9 18:aload_0
// 10 19:invokespecial #39 <Method void ActionBarBackgroundDrawableV21(ActionBarContainer)>
// 11 22:astore 4
else
//* 12 24:goto 37
obj = ((Object) (new ActionBarBackgroundDrawable(this)));
// 13 27:new #41 <Class ActionBarBackgroundDrawable>
// 14 30:dup
// 15 31:aload_0
// 16 32:invokespecial #42 <Method void ActionBarBackgroundDrawable(ActionBarContainer)>
// 17 35:astore 4
ViewCompat.setBackground(((View) (this)), ((Drawable) (obj)));
// 18 37:aload_0
// 19 38:aload 4
// 20 40:invokestatic #48 <Method void ViewCompat.setBackground(View, Drawable)>
context = ((Context) (context.obtainStyledAttributes(attributeset, android.support.v7.appcompat.R.styleable.ActionBar)));
// 21 43:aload_1
// 22 44:aload_2
// 23 45:getstatic #54 <Field int[] android.support.v7.appcompat.R$styleable.ActionBar>
// 24 48:invokevirtual #60 <Method TypedArray Context.obtainStyledAttributes(AttributeSet, int[])>
// 25 51:astore_1
mBackground = ((TypedArray) (context)).getDrawable(android.support.v7.appcompat.R.styleable.ActionBar_background);
// 26 52:aload_0
// 27 53:aload_1
// 28 54:getstatic #63 <Field int android.support.v7.appcompat.R$styleable.ActionBar_background>
// 29 57:invokevirtual #69 <Method Drawable TypedArray.getDrawable(int)>
// 30 60:putfield #71 <Field Drawable mBackground>
mStackedBackground = ((TypedArray) (context)).getDrawable(android.support.v7.appcompat.R.styleable.ActionBar_backgroundStacked);
// 31 63:aload_0
// 32 64:aload_1
// 33 65:getstatic #74 <Field int android.support.v7.appcompat.R$styleable.ActionBar_backgroundStacked>
// 34 68:invokevirtual #69 <Method Drawable TypedArray.getDrawable(int)>
// 35 71:putfield #76 <Field Drawable mStackedBackground>
mHeight = ((TypedArray) (context)).getDimensionPixelSize(android.support.v7.appcompat.R.styleable.ActionBar_height, -1);
// 36 74:aload_0
// 37 75:aload_1
// 38 76:getstatic #79 <Field int android.support.v7.appcompat.R$styleable.ActionBar_height>
// 39 79:iconst_m1
// 40 80:invokevirtual #83 <Method int TypedArray.getDimensionPixelSize(int, int)>
// 41 83:putfield #85 <Field int mHeight>
if(getId() == android.support.v7.appcompat.R.id.split_action_bar)
//* 42 86:aload_0
//* 43 87:invokevirtual #89 <Method int getId()>
//* 44 90:getstatic #94 <Field int android.support.v7.appcompat.R$id.split_action_bar>
//* 45 93:icmpne 112
{
mIsSplit = true;
// 46 96:aload_0
// 47 97:iconst_1
// 48 98:putfield #96 <Field boolean mIsSplit>
mSplitBackground = ((TypedArray) (context)).getDrawable(android.support.v7.appcompat.R.styleable.ActionBar_backgroundSplit);
// 49 101:aload_0
// 50 102:aload_1
// 51 103:getstatic #99 <Field int android.support.v7.appcompat.R$styleable.ActionBar_backgroundSplit>
// 52 106:invokevirtual #69 <Method Drawable TypedArray.getDrawable(int)>
// 53 109:putfield #101 <Field Drawable mSplitBackground>
}
((TypedArray) (context)).recycle();
// 54 112:aload_1
// 55 113:invokevirtual #105 <Method void TypedArray.recycle()>
boolean flag;
if(mIsSplit)
//* 56 116:aload_0
//* 57 117:getfield #96 <Field boolean mIsSplit>
//* 58 120:ifeq 140
{
if(mSplitBackground == null)
//* 59 123:aload_0
//* 60 124:getfield #101 <Field Drawable mSplitBackground>
//* 61 127:ifnonnull 135
flag = true;
// 62 130:iconst_1
// 63 131:istore_3
else
//* 64 132:goto 161
flag = false;
// 65 135:iconst_0
// 66 136:istore_3
} else
//* 67 137:goto 161
if(mBackground == null && mStackedBackground == null)
//* 68 140:aload_0
//* 69 141:getfield #71 <Field Drawable mBackground>
//* 70 144:ifnonnull 159
//* 71 147:aload_0
//* 72 148:getfield #76 <Field Drawable mStackedBackground>
//* 73 151:ifnonnull 159
flag = true;
// 74 154:iconst_1
// 75 155:istore_3
else
//* 76 156:goto 161
flag = false;
// 77 159:iconst_0
// 78 160:istore_3
setWillNotDraw(flag);
// 79 161:aload_0
// 80 162:iload_3
// 81 163:invokevirtual #109 <Method void setWillNotDraw(boolean)>
// 82 166:return
}
private int getMeasuredHeightWithMargins(View view)
{
android.widget.FrameLayout.LayoutParams layoutparams = (android.widget.FrameLayout.LayoutParams)view.getLayoutParams();
// 0 0:aload_1
// 1 1:invokevirtual #117 <Method android.view.ViewGroup$LayoutParams View.getLayoutParams()>
// 2 4:checkcast #119 <Class android.widget.FrameLayout$LayoutParams>
// 3 7:astore_2
return view.getMeasuredHeight() + layoutparams.topMargin + layoutparams.bottomMargin;
// 4 8:aload_1
// 5 9:invokevirtual #122 <Method int View.getMeasuredHeight()>
// 6 12:aload_2
// 7 13:getfield #125 <Field int android.widget.FrameLayout$LayoutParams.topMargin>
// 8 16:iadd
// 9 17:aload_2
// 10 18:getfield #128 <Field int android.widget.FrameLayout$LayoutParams.bottomMargin>
// 11 21:iadd
// 12 22:ireturn
}
private boolean isCollapsed(View view)
{
return view == null || view.getVisibility() == 8 || view.getMeasuredHeight() == 0;
// 0 0:aload_1
// 1 1:ifnull 20
// 2 4:aload_1
// 3 5:invokevirtual #133 <Method int View.getVisibility()>
// 4 8:bipush 8
// 5 10:icmpeq 20
// 6 13:aload_1
// 7 14:invokevirtual #122 <Method int View.getMeasuredHeight()>
// 8 17:ifne 22
// 9 20:iconst_1
// 10 21:ireturn
// 11 22:iconst_0
// 12 23:ireturn
}
protected void drawableStateChanged()
{
super.drawableStateChanged();
// 0 0:aload_0
// 1 1:invokespecial #136 <Method void FrameLayout.drawableStateChanged()>
if(mBackground != null && mBackground.isStateful())
//* 2 4:aload_0
//* 3 5:getfield #71 <Field Drawable mBackground>
//* 4 8:ifnull 33
//* 5 11:aload_0
//* 6 12:getfield #71 <Field Drawable mBackground>
//* 7 15:invokevirtual #142 <Method boolean Drawable.isStateful()>
//* 8 18:ifeq 33
mBackground.setState(getDrawableState());
// 9 21:aload_0
// 10 22:getfield #71 <Field Drawable mBackground>
// 11 25:aload_0
// 12 26:invokevirtual #146 <Method int[] getDrawableState()>
// 13 29:invokevirtual #150 <Method boolean Drawable.setState(int[])>
// 14 32:pop
if(mStackedBackground != null && mStackedBackground.isStateful())
//* 15 33:aload_0
//* 16 34:getfield #76 <Field Drawable mStackedBackground>
//* 17 37:ifnull 62
//* 18 40:aload_0
//* 19 41:getfield #76 <Field Drawable mStackedBackground>
//* 20 44:invokevirtual #142 <Method boolean Drawable.isStateful()>
//* 21 47:ifeq 62
mStackedBackground.setState(getDrawableState());
// 22 50:aload_0
// 23 51:getfield #76 <Field Drawable mStackedBackground>
// 24 54:aload_0
// 25 55:invokevirtual #146 <Method int[] getDrawableState()>
// 26 58:invokevirtual #150 <Method boolean Drawable.setState(int[])>
// 27 61:pop
if(mSplitBackground != null && mSplitBackground.isStateful())
//* 28 62:aload_0
//* 29 63:getfield #101 <Field Drawable mSplitBackground>
//* 30 66:ifnull 91
//* 31 69:aload_0
//* 32 70:getfield #101 <Field Drawable mSplitBackground>
//* 33 73:invokevirtual #142 <Method boolean Drawable.isStateful()>
//* 34 76:ifeq 91
mSplitBackground.setState(getDrawableState());
// 35 79:aload_0
// 36 80:getfield #101 <Field Drawable mSplitBackground>
// 37 83:aload_0
// 38 84:invokevirtual #146 <Method int[] getDrawableState()>
// 39 87:invokevirtual #150 <Method boolean Drawable.setState(int[])>
// 40 90:pop
// 41 91:return
}
public View getTabContainer()
{
return mTabContainer;
// 0 0:aload_0
// 1 1:getfield #154 <Field View mTabContainer>
// 2 4:areturn
}
public void jumpDrawablesToCurrentState()
{
if(android.os.Build.VERSION.SDK_INT >= 11)
//* 0 0:getstatic #34 <Field int android.os.Build$VERSION.SDK_INT>
//* 1 3:bipush 11
//* 2 5:icmplt 54
{
super.jumpDrawablesToCurrentState();
// 3 8:aload_0
// 4 9:invokespecial #157 <Method void FrameLayout.jumpDrawablesToCurrentState()>
if(mBackground != null)
//* 5 12:aload_0
//* 6 13:getfield #71 <Field Drawable mBackground>
//* 7 16:ifnull 26
mBackground.jumpToCurrentState();
// 8 19:aload_0
// 9 20:getfield #71 <Field Drawable mBackground>
// 10 23:invokevirtual #160 <Method void Drawable.jumpToCurrentState()>
if(mStackedBackground != null)
//* 11 26:aload_0
//* 12 27:getfield #76 <Field Drawable mStackedBackground>
//* 13 30:ifnull 40
mStackedBackground.jumpToCurrentState();
// 14 33:aload_0
// 15 34:getfield #76 <Field Drawable mStackedBackground>
// 16 37:invokevirtual #160 <Method void Drawable.jumpToCurrentState()>
if(mSplitBackground != null)
//* 17 40:aload_0
//* 18 41:getfield #101 <Field Drawable mSplitBackground>
//* 19 44:ifnull 54
mSplitBackground.jumpToCurrentState();
// 20 47:aload_0
// 21 48:getfield #101 <Field Drawable mSplitBackground>
// 22 51:invokevirtual #160 <Method void Drawable.jumpToCurrentState()>
}
// 23 54:return
}
public void onFinishInflate()
{
super.onFinishInflate();
// 0 0:aload_0
// 1 1:invokespecial #163 <Method void FrameLayout.onFinishInflate()>
mActionBarView = findViewById(android.support.v7.appcompat.R.id.action_bar);
// 2 4:aload_0
// 3 5:aload_0
// 4 6:getstatic #166 <Field int android.support.v7.appcompat.R$id.action_bar>
// 5 9:invokevirtual #170 <Method View findViewById(int)>
// 6 12:putfield #172 <Field View mActionBarView>
mContextView = findViewById(android.support.v7.appcompat.R.id.action_context_bar);
// 7 15:aload_0
// 8 16:aload_0
// 9 17:getstatic #175 <Field int android.support.v7.appcompat.R$id.action_context_bar>
// 10 20:invokevirtual #170 <Method View findViewById(int)>
// 11 23:putfield #177 <Field View mContextView>
// 12 26:return
}
public boolean onInterceptTouchEvent(MotionEvent motionevent)
{
return mIsTransitioning || super.onInterceptTouchEvent(motionevent);
// 0 0:aload_0
// 1 1:getfield #181 <Field boolean mIsTransitioning>
// 2 4:ifne 15
// 3 7:aload_0
// 4 8:aload_1
// 5 9:invokespecial #183 <Method boolean FrameLayout.onInterceptTouchEvent(MotionEvent)>
// 6 12:ifeq 17
// 7 15:iconst_1
// 8 16:ireturn
// 9 17:iconst_0
// 10 18:ireturn
}
public void onLayout(boolean flag, int i, int j, int k, int l)
{
super.onLayout(flag, i, j, k, l);
// 0 0:aload_0
// 1 1:iload_1
// 2 2:iload_2
// 3 3:iload_3
// 4 4:iload 4
// 5 6:iload 5
// 6 8:invokespecial #187 <Method void FrameLayout.onLayout(boolean, int, int, int, int)>
View view = mTabContainer;
// 7 11:aload_0
// 8 12:getfield #154 <Field View mTabContainer>
// 9 15:astore 6
if(view != null && view.getVisibility() != 8)
//* 10 17:aload 6
//* 11 19:ifnull 37
//* 12 22:aload 6
//* 13 24:invokevirtual #133 <Method int View.getVisibility()>
//* 14 27:bipush 8
//* 15 29:icmpeq 37
flag = true;
// 16 32:iconst_1
// 17 33:istore_1
else
//* 18 34:goto 39
flag = false;
// 19 37:iconst_0
// 20 38:istore_1
if(view != null && view.getVisibility() != 8)
//* 21 39:aload 6
//* 22 41:ifnull 97
//* 23 44:aload 6
//* 24 46:invokevirtual #133 <Method int View.getVisibility()>
//* 25 49:bipush 8
//* 26 51:icmpeq 97
{
j = getMeasuredHeight();
// 27 54:aload_0
// 28 55:invokevirtual #188 <Method int getMeasuredHeight()>
// 29 58:istore_3
android.widget.FrameLayout.LayoutParams layoutparams = (android.widget.FrameLayout.LayoutParams)view.getLayoutParams();
// 30 59:aload 6
// 31 61:invokevirtual #117 <Method android.view.ViewGroup$LayoutParams View.getLayoutParams()>
// 32 64:checkcast #119 <Class android.widget.FrameLayout$LayoutParams>
// 33 67:astore 7
view.layout(i, j - view.getMeasuredHeight() - layoutparams.bottomMargin, k, j - layoutparams.bottomMargin);
// 34 69:aload 6
// 35 71:iload_2
// 36 72:iload_3
// 37 73:aload 6
// 38 75:invokevirtual #122 <Method int View.getMeasuredHeight()>
// 39 78:isub
// 40 79:aload 7
// 41 81:getfield #128 <Field int android.widget.FrameLayout$LayoutParams.bottomMargin>
// 42 84:isub
// 43 85:iload 4
// 44 87:iload_3
// 45 88:aload 7
// 46 90:getfield #128 <Field int android.widget.FrameLayout$LayoutParams.bottomMargin>
// 47 93:isub
// 48 94:invokevirtual #192 <Method void View.layout(int, int, int, int)>
}
i = 0;
// 49 97:iconst_0
// 50 98:istore_2
j = 0;
// 51 99:iconst_0
// 52 100:istore_3
if(mIsSplit)
//* 53 101:aload_0
//* 54 102:getfield #96 <Field boolean mIsSplit>
//* 55 105:ifeq 137
{
if(mSplitBackground != null)
//* 56 108:aload_0
//* 57 109:getfield #101 <Field Drawable mSplitBackground>
//* 58 112:ifnull 309
{
mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
// 59 115:aload_0
// 60 116:getfield #101 <Field Drawable mSplitBackground>
// 61 119:iconst_0
// 62 120:iconst_0
// 63 121:aload_0
// 64 122:invokevirtual #195 <Method int getMeasuredWidth()>
// 65 125:aload_0
// 66 126:invokevirtual #188 <Method int getMeasuredHeight()>
// 67 129:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
i = 1;
// 68 132:iconst_1
// 69 133:istore_2
}
} else
//* 70 134:goto 309
{
if(mBackground != null)
//* 71 137:aload_0
//* 72 138:getfield #71 <Field Drawable mBackground>
//* 73 141:ifnull 260
{
if(mActionBarView.getVisibility() == 0)
//* 74 144:aload_0
//* 75 145:getfield #172 <Field View mActionBarView>
//* 76 148:invokevirtual #133 <Method int View.getVisibility()>
//* 77 151:ifne 192
mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(), mActionBarView.getRight(), mActionBarView.getBottom());
// 78 154:aload_0
// 79 155:getfield #71 <Field Drawable mBackground>
// 80 158:aload_0
// 81 159:getfield #172 <Field View mActionBarView>
// 82 162:invokevirtual #201 <Method int View.getLeft()>
// 83 165:aload_0
// 84 166:getfield #172 <Field View mActionBarView>
// 85 169:invokevirtual #204 <Method int View.getTop()>
// 86 172:aload_0
// 87 173:getfield #172 <Field View mActionBarView>
// 88 176:invokevirtual #207 <Method int View.getRight()>
// 89 179:aload_0
// 90 180:getfield #172 <Field View mActionBarView>
// 91 183:invokevirtual #210 <Method int View.getBottom()>
// 92 186:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
else
//* 93 189:goto 258
if(mContextView != null && mContextView.getVisibility() == 0)
//* 94 192:aload_0
//* 95 193:getfield #177 <Field View mContextView>
//* 96 196:ifnull 247
//* 97 199:aload_0
//* 98 200:getfield #177 <Field View mContextView>
//* 99 203:invokevirtual #133 <Method int View.getVisibility()>
//* 100 206:ifne 247
mBackground.setBounds(mContextView.getLeft(), mContextView.getTop(), mContextView.getRight(), mContextView.getBottom());
// 101 209:aload_0
// 102 210:getfield #71 <Field Drawable mBackground>
// 103 213:aload_0
// 104 214:getfield #177 <Field View mContextView>
// 105 217:invokevirtual #201 <Method int View.getLeft()>
// 106 220:aload_0
// 107 221:getfield #177 <Field View mContextView>
// 108 224:invokevirtual #204 <Method int View.getTop()>
// 109 227:aload_0
// 110 228:getfield #177 <Field View mContextView>
// 111 231:invokevirtual #207 <Method int View.getRight()>
// 112 234:aload_0
// 113 235:getfield #177 <Field View mContextView>
// 114 238:invokevirtual #210 <Method int View.getBottom()>
// 115 241:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
else
//* 116 244:goto 258
mBackground.setBounds(0, 0, 0, 0);
// 117 247:aload_0
// 118 248:getfield #71 <Field Drawable mBackground>
// 119 251:iconst_0
// 120 252:iconst_0
// 121 253:iconst_0
// 122 254:iconst_0
// 123 255:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
j = 1;
// 124 258:iconst_1
// 125 259:istore_3
}
mIsStacked = flag;
// 126 260:aload_0
// 127 261:iload_1
// 128 262:putfield #212 <Field boolean mIsStacked>
i = j;
// 129 265:iload_3
// 130 266:istore_2
if(flag)
//* 131 267:iload_1
//* 132 268:ifeq 309
{
i = j;
// 133 271:iload_3
// 134 272:istore_2
if(mStackedBackground != null)
//* 135 273:aload_0
//* 136 274:getfield #76 <Field Drawable mStackedBackground>
//* 137 277:ifnull 309
{
mStackedBackground.setBounds(view.getLeft(), view.getTop(), view.getRight(), view.getBottom());
// 138 280:aload_0
// 139 281:getfield #76 <Field Drawable mStackedBackground>
// 140 284:aload 6
// 141 286:invokevirtual #201 <Method int View.getLeft()>
// 142 289:aload 6
// 143 291:invokevirtual #204 <Method int View.getTop()>
// 144 294:aload 6
// 145 296:invokevirtual #207 <Method int View.getRight()>
// 146 299:aload 6
// 147 301:invokevirtual #210 <Method int View.getBottom()>
// 148 304:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
i = 1;
// 149 307:iconst_1
// 150 308:istore_2
}
}
}
if(i != 0)
//* 151 309:iload_2
//* 152 310:ifeq 317
invalidate();
// 153 313:aload_0
// 154 314:invokevirtual #215 <Method void invalidate()>
// 155 317:return
}
public void onMeasure(int i, int j)
{
int k = j;
// 0 0:iload_2
// 1 1:istore_3
if(mActionBarView == null)
//* 2 2:aload_0
//* 3 3:getfield #172 <Field View mActionBarView>
//* 4 6:ifnonnull 46
{
k = j;
// 5 9:iload_2
// 6 10:istore_3
if(android.view.View.MeasureSpec.getMode(j) == 0x80000000)
//* 7 11:iload_2
//* 8 12:invokestatic #223 <Method int android.view.View$MeasureSpec.getMode(int)>
//* 9 15:ldc1 #224 <Int 0x80000000>
//* 10 17:icmpne 46
{
k = j;
// 11 20:iload_2
// 12 21:istore_3
if(mHeight >= 0)
//* 13 22:aload_0
//* 14 23:getfield #85 <Field int mHeight>
//* 15 26:iflt 46
k = android.view.View.MeasureSpec.makeMeasureSpec(Math.min(mHeight, android.view.View.MeasureSpec.getSize(j)), 0x80000000);
// 16 29:aload_0
// 17 30:getfield #85 <Field int mHeight>
// 18 33:iload_2
// 19 34:invokestatic #227 <Method int android.view.View$MeasureSpec.getSize(int)>
// 20 37:invokestatic #232 <Method int Math.min(int, int)>
// 21 40:ldc1 #224 <Int 0x80000000>
// 22 42:invokestatic #235 <Method int android.view.View$MeasureSpec.makeMeasureSpec(int, int)>
// 23 45:istore_3
}
}
super.onMeasure(i, k);
// 24 46:aload_0
// 25 47:iload_1
// 26 48:iload_3
// 27 49:invokespecial #237 <Method void FrameLayout.onMeasure(int, int)>
if(mActionBarView == null)
//* 28 52:aload_0
//* 29 53:getfield #172 <Field View mActionBarView>
//* 30 56:ifnonnull 60
return;
// 31 59:return
j = android.view.View.MeasureSpec.getMode(k);
// 32 60:iload_3
// 33 61:invokestatic #223 <Method int android.view.View$MeasureSpec.getMode(int)>
// 34 64:istore_2
if(mTabContainer != null && mTabContainer.getVisibility() != 8 && j != 0x40000000)
//* 35 65:aload_0
//* 36 66:getfield #154 <Field View mTabContainer>
//* 37 69:ifnull 177
//* 38 72:aload_0
//* 39 73:getfield #154 <Field View mTabContainer>
//* 40 76:invokevirtual #133 <Method int View.getVisibility()>
//* 41 79:bipush 8
//* 42 81:icmpeq 177
//* 43 84:iload_2
//* 44 85:ldc1 #238 <Int 0x40000000>
//* 45 87:icmpeq 177
{
if(!isCollapsed(mActionBarView))
//* 46 90:aload_0
//* 47 91:aload_0
//* 48 92:getfield #172 <Field View mActionBarView>
//* 49 95:invokespecial #240 <Method boolean isCollapsed(View)>
//* 50 98:ifne 113
i = getMeasuredHeightWithMargins(mActionBarView);
// 51 101:aload_0
// 52 102:aload_0
// 53 103:getfield #172 <Field View mActionBarView>
// 54 106:invokespecial #242 <Method int getMeasuredHeightWithMargins(View)>
// 55 109:istore_1
else
//* 56 110:goto 138
if(!isCollapsed(mContextView))
//* 57 113:aload_0
//* 58 114:aload_0
//* 59 115:getfield #177 <Field View mContextView>
//* 60 118:invokespecial #240 <Method boolean isCollapsed(View)>
//* 61 121:ifne 136
i = getMeasuredHeightWithMargins(mContextView);
// 62 124:aload_0
// 63 125:aload_0
// 64 126:getfield #177 <Field View mContextView>
// 65 129:invokespecial #242 <Method int getMeasuredHeightWithMargins(View)>
// 66 132:istore_1
else
//* 67 133:goto 138
i = 0;
// 68 136:iconst_0
// 69 137:istore_1
if(j == 0x80000000)
//* 70 138:iload_2
//* 71 139:ldc1 #224 <Int 0x80000000>
//* 72 141:icmpne 152
j = android.view.View.MeasureSpec.getSize(k);
// 73 144:iload_3
// 74 145:invokestatic #227 <Method int android.view.View$MeasureSpec.getSize(int)>
// 75 148:istore_2
else
//* 76 149:goto 155
j = 0x7fffffff;
// 77 152:ldc1 #243 <Int 0x7fffffff>
// 78 154:istore_2
setMeasuredDimension(getMeasuredWidth(), Math.min(getMeasuredHeightWithMargins(mTabContainer) + i, j));
// 79 155:aload_0
// 80 156:aload_0
// 81 157:invokevirtual #195 <Method int getMeasuredWidth()>
// 82 160:aload_0
// 83 161:aload_0
// 84 162:getfield #154 <Field View mTabContainer>
// 85 165:invokespecial #242 <Method int getMeasuredHeightWithMargins(View)>
// 86 168:iload_1
// 87 169:iadd
// 88 170:iload_2
// 89 171:invokestatic #232 <Method int Math.min(int, int)>
// 90 174:invokevirtual #246 <Method void setMeasuredDimension(int, int)>
}
// 91 177:return
}
public boolean onTouchEvent(MotionEvent motionevent)
{
super.onTouchEvent(motionevent);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:invokespecial #249 <Method boolean FrameLayout.onTouchEvent(MotionEvent)>
// 3 5:pop
return true;
// 4 6:iconst_1
// 5 7:ireturn
}
public void setPrimaryBackground(Drawable drawable)
{
if(mBackground != null)
//* 0 0:aload_0
//* 1 1:getfield #71 <Field Drawable mBackground>
//* 2 4:ifnull 23
{
mBackground.setCallback(((android.graphics.drawable.Drawable.Callback) (null)));
// 3 7:aload_0
// 4 8:getfield #71 <Field Drawable mBackground>
// 5 11:aconst_null
// 6 12:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
unscheduleDrawable(mBackground);
// 7 15:aload_0
// 8 16:aload_0
// 9 17:getfield #71 <Field Drawable mBackground>
// 10 20:invokevirtual #258 <Method void unscheduleDrawable(Drawable)>
}
mBackground = drawable;
// 11 23:aload_0
// 12 24:aload_1
// 13 25:putfield #71 <Field Drawable mBackground>
if(drawable != null)
//* 14 28:aload_1
//* 15 29:ifnull 79
{
drawable.setCallback(((android.graphics.drawable.Drawable.Callback) (this)));
// 16 32:aload_1
// 17 33:aload_0
// 18 34:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
if(mActionBarView != null)
//* 19 37:aload_0
//* 20 38:getfield #172 <Field View mActionBarView>
//* 21 41:ifnull 79
mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(), mActionBarView.getRight(), mActionBarView.getBottom());
// 22 44:aload_0
// 23 45:getfield #71 <Field Drawable mBackground>
// 24 48:aload_0
// 25 49:getfield #172 <Field View mActionBarView>
// 26 52:invokevirtual #201 <Method int View.getLeft()>
// 27 55:aload_0
// 28 56:getfield #172 <Field View mActionBarView>
// 29 59:invokevirtual #204 <Method int View.getTop()>
// 30 62:aload_0
// 31 63:getfield #172 <Field View mActionBarView>
// 32 66:invokevirtual #207 <Method int View.getRight()>
// 33 69:aload_0
// 34 70:getfield #172 <Field View mActionBarView>
// 35 73:invokevirtual #210 <Method int View.getBottom()>
// 36 76:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
}
boolean flag;
if(mIsSplit)
//* 37 79:aload_0
//* 38 80:getfield #96 <Field boolean mIsSplit>
//* 39 83:ifeq 103
{
if(mSplitBackground == null)
//* 40 86:aload_0
//* 41 87:getfield #101 <Field Drawable mSplitBackground>
//* 42 90:ifnonnull 98
flag = true;
// 43 93:iconst_1
// 44 94:istore_2
else
//* 45 95:goto 124
flag = false;
// 46 98:iconst_0
// 47 99:istore_2
} else
//* 48 100:goto 124
if(mBackground == null && mStackedBackground == null)
//* 49 103:aload_0
//* 50 104:getfield #71 <Field Drawable mBackground>
//* 51 107:ifnonnull 122
//* 52 110:aload_0
//* 53 111:getfield #76 <Field Drawable mStackedBackground>
//* 54 114:ifnonnull 122
flag = true;
// 55 117:iconst_1
// 56 118:istore_2
else
//* 57 119:goto 124
flag = false;
// 58 122:iconst_0
// 59 123:istore_2
setWillNotDraw(flag);
// 60 124:aload_0
// 61 125:iload_2
// 62 126:invokevirtual #109 <Method void setWillNotDraw(boolean)>
invalidate();
// 63 129:aload_0
// 64 130:invokevirtual #215 <Method void invalidate()>
// 65 133:return
}
public void setSplitBackground(Drawable drawable)
{
if(mSplitBackground != null)
//* 0 0:aload_0
//* 1 1:getfield #101 <Field Drawable mSplitBackground>
//* 2 4:ifnull 23
{
mSplitBackground.setCallback(((android.graphics.drawable.Drawable.Callback) (null)));
// 3 7:aload_0
// 4 8:getfield #101 <Field Drawable mSplitBackground>
// 5 11:aconst_null
// 6 12:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
unscheduleDrawable(mSplitBackground);
// 7 15:aload_0
// 8 16:aload_0
// 9 17:getfield #101 <Field Drawable mSplitBackground>
// 10 20:invokevirtual #258 <Method void unscheduleDrawable(Drawable)>
}
mSplitBackground = drawable;
// 11 23:aload_0
// 12 24:aload_1
// 13 25:putfield #101 <Field Drawable mSplitBackground>
if(drawable != null)
//* 14 28:aload_1
//* 15 29:ifnull 68
{
drawable.setCallback(((android.graphics.drawable.Drawable.Callback) (this)));
// 16 32:aload_1
// 17 33:aload_0
// 18 34:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
if(mIsSplit && mSplitBackground != null)
//* 19 37:aload_0
//* 20 38:getfield #96 <Field boolean mIsSplit>
//* 21 41:ifeq 68
//* 22 44:aload_0
//* 23 45:getfield #101 <Field Drawable mSplitBackground>
//* 24 48:ifnull 68
mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
// 25 51:aload_0
// 26 52:getfield #101 <Field Drawable mSplitBackground>
// 27 55:iconst_0
// 28 56:iconst_0
// 29 57:aload_0
// 30 58:invokevirtual #195 <Method int getMeasuredWidth()>
// 31 61:aload_0
// 32 62:invokevirtual #188 <Method int getMeasuredHeight()>
// 33 65:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
}
boolean flag;
if(mIsSplit)
//* 34 68:aload_0
//* 35 69:getfield #96 <Field boolean mIsSplit>
//* 36 72:ifeq 92
{
if(mSplitBackground == null)
//* 37 75:aload_0
//* 38 76:getfield #101 <Field Drawable mSplitBackground>
//* 39 79:ifnonnull 87
flag = true;
// 40 82:iconst_1
// 41 83:istore_2
else
//* 42 84:goto 113
flag = false;
// 43 87:iconst_0
// 44 88:istore_2
} else
//* 45 89:goto 113
if(mBackground == null && mStackedBackground == null)
//* 46 92:aload_0
//* 47 93:getfield #71 <Field Drawable mBackground>
//* 48 96:ifnonnull 111
//* 49 99:aload_0
//* 50 100:getfield #76 <Field Drawable mStackedBackground>
//* 51 103:ifnonnull 111
flag = true;
// 52 106:iconst_1
// 53 107:istore_2
else
//* 54 108:goto 113
flag = false;
// 55 111:iconst_0
// 56 112:istore_2
setWillNotDraw(flag);
// 57 113:aload_0
// 58 114:iload_2
// 59 115:invokevirtual #109 <Method void setWillNotDraw(boolean)>
invalidate();
// 60 118:aload_0
// 61 119:invokevirtual #215 <Method void invalidate()>
// 62 122:return
}
public void setStackedBackground(Drawable drawable)
{
if(mStackedBackground != null)
//* 0 0:aload_0
//* 1 1:getfield #76 <Field Drawable mStackedBackground>
//* 2 4:ifnull 23
{
mStackedBackground.setCallback(((android.graphics.drawable.Drawable.Callback) (null)));
// 3 7:aload_0
// 4 8:getfield #76 <Field Drawable mStackedBackground>
// 5 11:aconst_null
// 6 12:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
unscheduleDrawable(mStackedBackground);
// 7 15:aload_0
// 8 16:aload_0
// 9 17:getfield #76 <Field Drawable mStackedBackground>
// 10 20:invokevirtual #258 <Method void unscheduleDrawable(Drawable)>
}
mStackedBackground = drawable;
// 11 23:aload_0
// 12 24:aload_1
// 13 25:putfield #76 <Field Drawable mStackedBackground>
if(drawable != null)
//* 14 28:aload_1
//* 15 29:ifnull 86
{
drawable.setCallback(((android.graphics.drawable.Drawable.Callback) (this)));
// 16 32:aload_1
// 17 33:aload_0
// 18 34:invokevirtual #255 <Method void Drawable.setCallback(android.graphics.drawable.Drawable$Callback)>
if(mIsStacked && mStackedBackground != null)
//* 19 37:aload_0
//* 20 38:getfield #212 <Field boolean mIsStacked>
//* 21 41:ifeq 86
//* 22 44:aload_0
//* 23 45:getfield #76 <Field Drawable mStackedBackground>
//* 24 48:ifnull 86
mStackedBackground.setBounds(mTabContainer.getLeft(), mTabContainer.getTop(), mTabContainer.getRight(), mTabContainer.getBottom());
// 25 51:aload_0
// 26 52:getfield #76 <Field Drawable mStackedBackground>
// 27 55:aload_0
// 28 56:getfield #154 <Field View mTabContainer>
// 29 59:invokevirtual #201 <Method int View.getLeft()>
// 30 62:aload_0
// 31 63:getfield #154 <Field View mTabContainer>
// 32 66:invokevirtual #204 <Method int View.getTop()>
// 33 69:aload_0
// 34 70:getfield #154 <Field View mTabContainer>
// 35 73:invokevirtual #207 <Method int View.getRight()>
// 36 76:aload_0
// 37 77:getfield #154 <Field View mTabContainer>
// 38 80:invokevirtual #210 <Method int View.getBottom()>
// 39 83:invokevirtual #198 <Method void Drawable.setBounds(int, int, int, int)>
}
boolean flag;
if(mIsSplit)
//* 40 86:aload_0
//* 41 87:getfield #96 <Field boolean mIsSplit>
//* 42 90:ifeq 110
{
if(mSplitBackground == null)
//* 43 93:aload_0
//* 44 94:getfield #101 <Field Drawable mSplitBackground>
//* 45 97:ifnonnull 105
flag = true;
// 46 100:iconst_1
// 47 101:istore_2
else
//* 48 102:goto 131
flag = false;
// 49 105:iconst_0
// 50 106:istore_2
} else
//* 51 107:goto 131
if(mBackground == null && mStackedBackground == null)
//* 52 110:aload_0
//* 53 111:getfield #71 <Field Drawable mBackground>
//* 54 114:ifnonnull 129
//* 55 117:aload_0
//* 56 118:getfield #76 <Field Drawable mStackedBackground>
//* 57 121:ifnonnull 129
flag = true;
// 58 124:iconst_1
// 59 125:istore_2
else
//* 60 126:goto 131
flag = false;
// 61 129:iconst_0
// 62 130:istore_2
setWillNotDraw(flag);
// 63 131:aload_0
// 64 132:iload_2
// 65 133:invokevirtual #109 <Method void setWillNotDraw(boolean)>
invalidate();
// 66 136:aload_0
// 67 137:invokevirtual #215 <Method void invalidate()>
// 68 140:return
}
public void setTabContainer(ScrollingTabContainerView scrollingtabcontainerview)
{
if(mTabContainer != null)
//* 0 0:aload_0
//* 1 1:getfield #154 <Field View mTabContainer>
//* 2 4:ifnull 15
removeView(mTabContainer);
// 3 7:aload_0
// 4 8:aload_0
// 5 9:getfield #154 <Field View mTabContainer>
// 6 12:invokevirtual #266 <Method void removeView(View)>
mTabContainer = ((View) (scrollingtabcontainerview));
// 7 15:aload_0
// 8 16:aload_1
// 9 17:putfield #154 <Field View mTabContainer>
if(scrollingtabcontainerview != null)
//* 10 20:aload_1
//* 11 21:ifnull 50
{
addView(((View) (scrollingtabcontainerview)));
// 12 24:aload_0
// 13 25:aload_1
// 14 26:invokevirtual #269 <Method void addView(View)>
android.view.ViewGroup.LayoutParams layoutparams = scrollingtabcontainerview.getLayoutParams();
// 15 29:aload_1
// 16 30:invokevirtual #272 <Method android.view.ViewGroup$LayoutParams ScrollingTabContainerView.getLayoutParams()>
// 17 33:astore_2
layoutparams.width = -1;
// 18 34:aload_2
// 19 35:iconst_m1
// 20 36:putfield #277 <Field int android.view.ViewGroup$LayoutParams.width>
layoutparams.height = -2;
// 21 39:aload_2
// 22 40:bipush -2
// 23 42:putfield #280 <Field int android.view.ViewGroup$LayoutParams.height>
scrollingtabcontainerview.setAllowCollapse(false);
// 24 45:aload_1
// 25 46:iconst_0
// 26 47:invokevirtual #283 <Method void ScrollingTabContainerView.setAllowCollapse(boolean)>
}
// 27 50:return
}
public void setTransitioning(boolean flag)
{
mIsTransitioning = flag;
// 0 0:aload_0
// 1 1:iload_1
// 2 2:putfield #181 <Field boolean mIsTransitioning>
int i;
if(flag)
//* 3 5:iload_1
//* 4 6:ifeq 16
i = 0x60000;
// 5 9:ldc2 #285 <Int 0x60000>
// 6 12:istore_2
else
//* 7 13:goto 20
i = 0x40000;
// 8 16:ldc2 #286 <Int 0x40000>
// 9 19:istore_2
setDescendantFocusability(i);
// 10 20:aload_0
// 11 21:iload_2
// 12 22:invokevirtual #290 <Method void setDescendantFocusability(int)>
// 13 25:return
}
public void setVisibility(int i)
{
super.setVisibility(i);
// 0 0:aload_0
// 1 1:iload_1
// 2 2:invokespecial #293 <Method void FrameLayout.setVisibility(int)>
boolean flag;
if(i == 0)
//* 3 5:iload_1
//* 4 6:ifne 14
flag = true;
// 5 9:iconst_1
// 6 10:istore_2
else
//* 7 11:goto 16
flag = false;
// 8 14:iconst_0
// 9 15:istore_2
if(mBackground != null)
//* 10 16:aload_0
//* 11 17:getfield #71 <Field Drawable mBackground>
//* 12 20:ifnull 33
mBackground.setVisible(flag, false);
// 13 23:aload_0
// 14 24:getfield #71 <Field Drawable mBackground>
// 15 27:iload_2
// 16 28:iconst_0
// 17 29:invokevirtual #297 <Method boolean Drawable.setVisible(boolean, boolean)>
// 18 32:pop
if(mStackedBackground != null)
//* 19 33:aload_0
//* 20 34:getfield #76 <Field Drawable mStackedBackground>
//* 21 37:ifnull 50
mStackedBackground.setVisible(flag, false);
// 22 40:aload_0
// 23 41:getfield #76 <Field Drawable mStackedBackground>
// 24 44:iload_2
// 25 45:iconst_0
// 26 46:invokevirtual #297 <Method boolean Drawable.setVisible(boolean, boolean)>
// 27 49:pop
if(mSplitBackground != null)
//* 28 50:aload_0
//* 29 51:getfield #101 <Field Drawable mSplitBackground>
//* 30 54:ifnull 67
mSplitBackground.setVisible(flag, false);
// 31 57:aload_0
// 32 58:getfield #101 <Field Drawable mSplitBackground>
// 33 61:iload_2
// 34 62:iconst_0
// 35 63:invokevirtual #297 <Method boolean Drawable.setVisible(boolean, boolean)>
// 36 66:pop
// 37 67:return
}
public ActionMode startActionModeForChild(View view, android.view.ActionMode.Callback callback)
{
return null;
// 0 0:aconst_null
// 1 1:areturn
}
public ActionMode startActionModeForChild(View view, android.view.ActionMode.Callback callback, int i)
{
if(i != 0)
//* 0 0:iload_3
//* 1 1:ifeq 12
return super.startActionModeForChild(view, callback, i);
// 2 4:aload_0
// 3 5:aload_1
// 4 6:aload_2
// 5 7:iload_3
// 6 8:invokespecial #302 <Method ActionMode FrameLayout.startActionModeForChild(View, android.view.ActionMode$Callback, int)>
// 7 11:areturn
else
return null;
// 8 12:aconst_null
// 9 13:areturn
}
protected boolean verifyDrawable(Drawable drawable)
{
return drawable == mBackground && !mIsSplit || drawable == mStackedBackground && mIsStacked || drawable == mSplitBackground && mIsSplit || super.verifyDrawable(drawable);
// 0 0:aload_1
// 1 1:aload_0
// 2 2:getfield #71 <Field Drawable mBackground>
// 3 5:if_acmpne 15
// 4 8:aload_0
// 5 9:getfield #96 <Field boolean mIsSplit>
// 6 12:ifeq 53
// 7 15:aload_1
// 8 16:aload_0
// 9 17:getfield #76 <Field Drawable mStackedBackground>
// 10 20:if_acmpne 30
// 11 23:aload_0
// 12 24:getfield #212 <Field boolean mIsStacked>
// 13 27:ifne 53
// 14 30:aload_1
// 15 31:aload_0
// 16 32:getfield #101 <Field Drawable mSplitBackground>
// 17 35:if_acmpne 45
// 18 38:aload_0
// 19 39:getfield #96 <Field boolean mIsSplit>
// 20 42:ifne 53
// 21 45:aload_0
// 22 46:aload_1
// 23 47:invokespecial #306 <Method boolean FrameLayout.verifyDrawable(Drawable)>
// 24 50:ifeq 55
// 25 53:iconst_1
// 26 54:ireturn
// 27 55:iconst_0
// 28 56:ireturn
}
private View mActionBarView;
Drawable mBackground;
private View mContextView;
private int mHeight;
boolean mIsSplit;
boolean mIsStacked;
private boolean mIsTransitioning;
Drawable mSplitBackground;
Drawable mStackedBackground;
private View mTabContainer;
}
| 40.232112 | 172 | 0.56433 |
3697bbc22d1aaceeb28aac574127ee6a0fa5ec9f | 2,094 | /*
* 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.aries.async.impl;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.async.Async;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
public class AsyncServiceFactory implements ServiceFactory<Async> {
private final ExecutorService executor;
private final ScheduledExecutorService ses;
private final ServiceTracker<LogService, LogService> logServiceTracker;
public AsyncServiceFactory(ExecutorService executor, ScheduledExecutorService ses,
ServiceTracker<LogService, LogService> logServiceTracker) {
//IC see: https://issues.apache.org/jira/browse/ARIES-1318
this.logServiceTracker = logServiceTracker;
this.executor = executor;
this.ses = ses;
}
public Async getService(Bundle bundle,
ServiceRegistration<Async> registration) {
return new AsyncService(bundle, executor, ses, logServiceTracker);
}
public void ungetService(Bundle bundle,
//IC see: https://issues.apache.org/jira/browse/ARIES-1603
ServiceRegistration<Async> registration, Async service) {
((AsyncService) service).clear();
}
}
| 34.9 | 84 | 0.782235 |
141af6668ad3710cff1d70061fe495b9fe569780 | 3,029 | package com.aromero.theamcrmservice.security;
import com.aromero.theamcrmservice.api.user.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
public class CustomUserDetails implements UserDetails {
private Long id;
private String name;
private String lastName;
private Boolean isAdmin;
@JsonIgnore
private String email;
@JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public CustomUserDetails(Long id, String name, String lastName, Boolean isAdmin, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.name = name;
this.lastName = lastName;
this.isAdmin = isAdmin;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static CustomUserDetails create(User user) {
List<GrantedAuthority> authorities = new ArrayList<>();
if (user.isAdmin()) {
authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
return new CustomUserDetails(
user.getId(),
user.getName(),
user.getLastName(),
user.isAdmin(),
user.getEmail(),
user.getHashedPassword(),
authorities
);
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getLastName() {
return lastName;
}
public Boolean getAdmin() {
return isAdmin;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return email;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
//TODO: change to use the active field of the user
return true;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
CustomUserDetails otherCustomUserDetails = (CustomUserDetails) o;
return Objects.equals(id, otherCustomUserDetails.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| 23.850394 | 115 | 0.62859 |
81f22eff55523661071980994b9ca7bcae8ea796 | 156,213 | package functionalj.list;
import static functionalj.TestHelper.assertAsString;
import static functionalj.functions.TimeFuncs.Sleep;
import static functionalj.lens.Access.theDouble;
import static functionalj.lens.Access.theInteger;
import static functionalj.lens.Access.theLong;
import static functionalj.ref.Run.With;
import static functionalj.stream.ZipWithOption.AllowUnpaired;
import static java.util.stream.Collector.Characteristics.CONCURRENT;
import static java.util.stream.Collector.Characteristics.UNORDERED;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.IntUnaryOperator;
import java.util.function.ObjIntConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
import java.util.stream.Collector.Characteristics;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import org.junit.Test;
import functionalj.function.FuncUnit1;
import functionalj.function.FuncUnit2;
import functionalj.function.aggregator.IntAggregation;
import functionalj.function.aggregator.IntAggregationToInt;
import functionalj.functions.TimeFuncs;
import functionalj.lens.LensTest.Car;
import functionalj.list.FuncList.Mode;
import functionalj.list.doublelist.DoubleFuncList;
import functionalj.list.intlist.ImmutableIntFuncList;
import functionalj.list.intlist.IntFuncList;
import functionalj.list.intlist.IntFuncListBuilder;
import functionalj.list.intlist.IntFuncListDerived;
import functionalj.map.FuncMap;
import functionalj.promise.DeferAction;
import functionalj.stream.IncompletedSegment;
import functionalj.stream.intstream.IntStreamPlus;
import functionalj.stream.intstream.collect.IntCollectorPlus;
import functionalj.stream.intstream.collect.IntCollectorToIntPlus;
import lombok.val;
public class IntFuncListTest {
static final int MinusOne = -1;
static final int Zero = 0;
static final int One = 1;
static final int Two = 2;
static final int Three = 3;
static final int Four = 4;
static final int Five = 5;
static final int Six = 6;
static final int Seven = 7;
static final int Eight = 8;
static final int Nine = 9;
static final int Ten = 10;
static final int Eleven = 11;
static final int Twelve = 12;
static final int Thirteen = 13;
static final int Seventeen = 17;
static final int Nineteen = 19;
static final int TwentyThree = 23;
private <T> void run(FuncList<T> list, FuncUnit1<FuncList<T>> action) {
action.accept(list);
action.accept(list);
}
private void run(IntFuncList list, FuncUnit1<IntFuncList> action) {
action.accept(list);
action.accept(list);
}
private void run(DoubleFuncList list, FuncUnit1<DoubleFuncList> action) {
action.accept(list);
action.accept(list);
}
private void run(IntFuncList list1, IntFuncList list2, FuncUnit2<IntFuncList, IntFuncList> action) {
action.accept(list1, list2);
action.accept(list1, list2);
}
@Test
public void testEmpty() {
run(IntFuncList.empty(), list -> {
assertAsString("[]", list);
});
}
@Test
public void testEmptyFuncList() {
run(IntFuncList.emptyList(), list -> {
assertAsString("[]", list);
});
}
@Test
public void testEmpty_intFuncList() {
run(IntFuncList.emptyIntList(), list -> {
assertAsString("[]", list);
});
}
@Test
public void testOf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testAllOf() {
run(IntFuncList.AllOf(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testInts() {
run(IntFuncList.ints(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testIntList() {
run(IntFuncList.intList(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testListOf() {
run(IntFuncList.ListOf(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
run(IntFuncList.listOf(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
//-- From --
@Test
public void testFrom_array() {
run(IntFuncList.from(new int[] {1, 2, 3}), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testFrom_collection() {
Collection<Integer> collection = Arrays.asList(One, Two, Three, null);
run(IntFuncList.from(collection, -1), list -> {
assertAsString("[1, 2, 3, -1]", list);
});
Set<Integer> set = new LinkedHashSet<>(collection);
run(IntFuncList.from(set, -2), list -> {
assertAsString("[1, 2, 3, -2]", list);
});
FuncList<Integer> lazyList = FuncList.of(One, Two, Three, null);
run(IntFuncList.from(lazyList, -3), list -> {
assertAsString("[1, 2, 3, -3]", list);
assertTrue (list.isLazy());
});
FuncList<Integer> eagerList = FuncList.of(One, Two, Three, null).toEager();
run(IntFuncList.from(eagerList, -4), list -> {
assertAsString("[1, 2, 3, -4]", list);
assertTrue (list.isEager());
});
}
@Test
public void testFrom_funcList() {
run(IntFuncList.from(Mode.lazy, IntFuncList.of(One, Two, Three)), list -> {
assertAsString("[1, 2, 3]", list);
assertTrue (list.isLazy());
});
run(IntFuncList.from(Mode.eager, IntFuncList.of(One, Two, Three)), list -> {
assertAsString("[1, 2, 3]", list);
assertTrue (list.isEager());
});
run(IntFuncList.from(Mode.cache, IntFuncList.of(One, Two, Three)), list -> {
assertAsString("[1, 2, 3]", list);
assertTrue (list.isCache());
});
}
@Test
public void testFrom_stream() {
run(IntFuncList.from(IntStreamPlus.infiniteInt().limit(3)), list -> {
assertAsString("[0, 1, 2]", list.limit(3));
});
}
@Test
public void testFrom_streamSupplier() {
run(IntFuncList.from(() -> IntStreamPlus.infiniteInt()), list -> {
assertAsString("[0, 1, 2, 3, 4]", list.limit(5));
assertAsString("[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]", list.limit(10));
});
}
@Test
public void testZeroes() {
run(IntFuncList.zeroes().limit(5), list -> {
assertAsString("[0, 0, 0, 0, 0]", list);
assertAsString("[0, 5, 0, 0, 0]", list.with(1, 5));
});
run(IntFuncList.zeroes(5), list -> {
assertAsString("[0, 0, 0, 0, 0]", list);
assertAsString("[0, 5, 0, 0, 0]", list.with(1, 5));
});
}
@Test
public void testOnes() {
run(IntFuncList.ones().limit(5), list -> {
assertAsString("[1, 1, 1, 1, 1]", list);
assertAsString("[1, 5, 1, 1, 1]", list.with(1, 5));
});
run(IntFuncList.ones(5), list -> {
assertAsString("[1, 1, 1, 1, 1]", list);
assertAsString("[1, 5, 1, 1, 1]", list.with(1, 5));
});
}
@Test
public void testRepeat() {
run(IntFuncList.repeat(0, 42), list -> {
assertAsString("[0, 42, 0, 42, 0]", list.limit(5));
assertAsString("[0, 42, 0, 42, 0, 42, 0]", list.limit(7));
});
run(IntFuncList.repeat(IntFuncList.cycle(0, 1, 2, 42).limit(5)), list -> {
assertAsString("[0, 1, 2, 42, 0, 0, 1]", list.limit(7));
assertAsString("[0, 1, 2, 42, 0, 0, 1, 2, 42, 0]", list.limit(10));
});
}
@Test
public void testCycle() {
run(IntFuncList.cycle(0, 1, 42), list -> {
assertAsString("[0, 1, 42, 0, 1]", list.limit(5));
assertAsString("[0, 1, 42, 0, 1, 42, 0]", list.limit(7));
});
run(IntFuncList.cycle(IntFuncList.cycle(0, 1, 2, 42).limit(5)), list -> {
assertAsString("[0, 1, 2, 42, 0, 0, 1]", list.limit(7));
assertAsString("[0, 1, 2, 42, 0, 0, 1, 2, 42, 0]", list.limit(10));
});
}
@Test
public void testLoop() {
run(IntFuncList.loop(), list -> assertAsString("[0, 1, 2, 3, 4]", list.limit(5)));
run(IntFuncList.loop(5), list -> assertAsString("[0, 1, 2, 3, 4]", list));
}
@Test
public void testLoopBy() {
run(IntFuncList.loopBy(3), list -> assertAsString("[0, 3, 6, 9, 12]", list.limit(5)));
run(IntFuncList.loopBy(3, 5), list -> assertAsString("[0, 3, 6, 9, 12]", list));
}
@Test
public void testInfinite() {
run(IntFuncList.infinite(), list -> assertAsString("[0, 1, 2, 3, 4]", list.limit(5)));
run(IntFuncList.infiniteInt(), list -> assertAsString("[0, 1, 2, 3, 4]", list.limit(5)));
}
@Test
public void testNaturalNumbers() {
run(IntFuncList.naturalNumbers(), list -> assertAsString("[1, 2, 3, 4, 5]", list.limit(5)));
run(IntFuncList.naturalNumbers(5), list -> assertAsString("[1, 2, 3, 4, 5]", list));
}
@Test
public void testWholeNumbers() {
run(IntFuncList.wholeNumbers(), list -> assertAsString("[0, 1, 2, 3, 4]", list.limit(5)));
run(IntFuncList.wholeNumbers(5), list -> assertAsString("[0, 1, 2, 3, 4]", list));
}
@Test
public void testRange() {
run(IntFuncList.range( 3, 7), list -> assertAsString("[3, 4, 5, 6]", list.limit(5)));
run(IntFuncList.range(-3, 3), list -> assertAsString("[-3, -2, -1, 0, 1, 2]", list.limit(10)));
}
@Test
public void testEquals() {
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertTrue (Objects.equals(list1, list2));
assertEquals(list1, list2);
});
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three, Four),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertFalse (Objects.equals(list1, list2));
assertNotEquals(list1, list2);
});
// Make it a derived list
run(IntFuncList.of(One, Two, Three).map(value -> value),
IntFuncList.of(One, Two, Three).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertEquals(list1, list2);
});
run(IntFuncList.of(One, Two, Three) .map(value -> value),
IntFuncList.of(One, Two, Three, Four).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertNotEquals(list1, list2);
});
}
@Test
public void testHashCode() {
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertEquals(list1.hashCode(), list2.hashCode());
});
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three, Four),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertNotEquals(list1.hashCode(), list2.hashCode());
});
// Make it a derived list
run(IntFuncList.of(One, Two, Three).map(value -> value),
IntFuncList.of(One, Two, Three).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertEquals(list1.hashCode(), list2.hashCode());
});
run(IntFuncList.of(One, Two, Three).map(value -> value),
IntFuncList.of(One, Two, Three, Four).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertNotEquals(list1.hashCode(), list2.hashCode());
});
}
@Test
public void testToString() {
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertEquals(list1.toString(), list2.toString());
});
run(IntFuncList.of(One, Two, Three),
IntFuncList.of(One, Two, Three, Four),
(list1, list2) -> {
assertTrue (list1 instanceof ImmutableIntFuncList);
assertTrue (list2 instanceof ImmutableIntFuncList);
assertNotEquals(list1.toString(), list2.toString());
});
// Make it a derived list
run(IntFuncList.of(One, Two, Three).map(value -> value),
IntFuncList.of(One, Two, Three).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertEquals(list1.toString(), list2.toString());
});
run(IntFuncList.of(One, Two, Three).map(value -> value),
IntFuncList.of(One, Two, Three, Four).map(value -> value),
(list1, list2) -> {
assertTrue (list1 instanceof IntFuncListDerived);
assertTrue (list2 instanceof IntFuncListDerived);
assertNotEquals(list1.toString(), list2.toString());
});
}
// -- Concat + Combine --
@Test
public void testConcat() {
run(IntFuncList.concat(IntFuncList.of(One, Two), IntFuncList.of(Three, Four)),
list -> {
assertAsString("[1, 2, 3, 4]", list);
}
);
}
@Test
public void testCombine() {
run(IntFuncList.combine(IntFuncList.of(One, Two), IntFuncList.of(Three, Four)),
list -> {
assertAsString("[1, 2, 3, 4]", list);
}
);
}
//-- Generate --
@Test
public void testGenerate() {
run(IntFuncList.generateWith(() -> {
val counter = new AtomicInteger();
IntSupplier supplier = ()-> counter.getAndIncrement();
return supplier;
}),
list -> {
assertAsString("[0, 1, 2, 3, 4]", list.limit(5));
}
);
run(IntFuncList.generateWith(() -> {
val counter = new AtomicInteger();
IntSupplier supplier = ()->{
int count = counter.getAndIncrement();
if (count < 5)
return count;
return FuncList.noMoreElement();
};
return supplier;
}),
list -> {
assertAsString("[0, 1, 2, 3, 4]", list);
}
);
}
//-- Iterate --
@Test
public void testIterate() {
run(IntFuncList.iterate(1, (i) -> 2*(i + 1)), list -> assertAsString("[1, 4, 10, 22, 46, 94, 190, 382, 766, 1534]", list.limit(10)));
run(IntFuncList.iterate(1, 2, (a, b) -> a + b), list -> assertAsString("[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]", list.limit(10)));
}
//-- Compound --
@Test
public void testCompound() {
run(IntFuncList.compound(1, (i) -> 2*(i + 1)), list -> assertAsString("[1, 4, 10, 22, 46, 94, 190, 382, 766, 1534]", list.limit(10)));
run(IntFuncList.compound(1, 2, (a, b) -> a + b), list -> assertAsString("[1, 2, 3, 5, 8, 13, 21, 34, 55, 89]", list.limit(10)));
}
//-- zipOf --
@Test
public void testZipOf_toTuple() {
run(IntFuncList.of(1000, 2000, 3000, 4000, 5000),
IntFuncList.of(1, 2, 3, 4),
(list1, list2) -> {
assertAsString(
"[(1000,1), (2000,2), (3000,3), (4000,4)]",
IntFuncList.zipOf(list1, list2));
});
}
@Test
public void testZipOf_toTuple_default() {
run(IntFuncList.of(1000, 2000, 3000, 4000, 5000),
IntFuncList.of(1, 2, 3, 4),
(list1, list2) -> {
assertAsString(
"[(1000,1), (2000,2), (3000,3), (4000,4), (5000,-1)]",
IntFuncList.zipOf(list1, -1000, list2, -1));
});
run(IntFuncList.of(1000, 2000, 3000, 4000),
IntFuncList.of(1, 2, 3, 4, 5),
(list1, list2) -> {
assertAsString(
"[(1000,1), (2000,2), (3000,3), (4000,4), (-1000,5)]",
IntFuncList.zipOf(list1, -1000, list2, -1));
});
}
@Test
public void testZipOf_merge() {
run(IntFuncList.of(1000, 2000, 3000, 4000, 5000),
IntFuncList.of(1, 2, 3, 4),
(list1, list2) -> {
assertAsString(
"[1001, 2002, 3003, 4004]",
FuncList.zipOf(
list1, list2,
(a, b) -> a + + b));
});
}
@Test
public void testZipOf_merge_default() {
run(IntFuncList.of(1000, 2000, 3000, 4000, 5000),
IntFuncList.of(1, 2, 3, 4),
(list1, list2) -> {
assertAsString(
"[1000, 4000, 9000, 16000, -5000]",
IntFuncList.zipOf(list1, -1000, list2, -1, (a, b) -> a*b));
});
run(IntFuncList.of(1000, 2000, 3000, 4000),
IntFuncList.of(1, 2, 3, 4, 5),
(list1, list2) -> {
assertAsString(
"[1000, 4000, 9000, 16000, -5000]",
IntFuncList.zipOf(list1, -1000, list2, -1, (a, b) -> a*b));
});
}
@Test
public void testNew() {
IntFuncListBuilder funcList1 = IntFuncList.newListBuilder();
IntFuncListBuilder funcList2 = IntFuncList.newBuilder();
IntFuncListBuilder funcList3 = IntFuncList.newIntListBuilder();
run(funcList1.add(One).add(Two).add(Three).build(), list -> {
assertAsString("[1, 2, 3]", list);
});
run(funcList2.add(One).add(Two).add(Three).build(), list -> {
assertAsString("[1, 2, 3]", list);
});
run(funcList3.add(One).add(Two).add(Three).build(), list -> {
assertAsString("[1, 2, 3]", list);
});
}
//-- Derive --
@Test
public void testDeriveFrom() {
run(IntFuncList.deriveFrom(FuncList.of(One, Two, Three), s -> s.mapToInt(v -> -v)), list -> {
assertAsString("[-1, -2, -3]", list);
});
run(IntFuncList.deriveFrom(IntFuncList.of(1, 2, 3), s -> s.map(v -> -v)), list -> {
assertAsString("[-1, -2, -3]", list);
});
run(IntFuncList.deriveFrom(DoubleFuncList.of(1.0, 2.0, 3.0), s -> s.mapToInt(v -> (int)Math.round(-v))), list -> {
assertAsString("[-1, -2, -3]", list);
});
}
@Test
public void testDeriveTo() {
run(IntFuncList.deriveToObj(IntFuncList.of(One, Two, Three), s -> s.mapToObj(v -> "-" + v + "-")), list -> {
assertTrue (list instanceof FuncList);
assertAsString("[-1-, -2-, -3-]", list);
});
run(IntFuncList.deriveToInt(IntFuncList.of(One, Two, Three), s -> s.map(v -> v + 5)), list -> {
assertAsString("[6, 7, 8]", list);
});
run(IntFuncList.deriveToDouble(IntFuncList.of(One, Two, Three), s -> s.mapToDouble(v -> 3.0*v)), list -> {
assertAsString("[3.0, 6.0, 9.0]", list);
});
}
//-- Predicate --
@Test
public void testTest_predicate() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue (list.test(One));
assertTrue (list.test(Two));
assertTrue (list.test(Three));
assertFalse(list.test(Four));
assertFalse(list.test(Five));
assertFalse(list.test(Six));
});
}
//-- Eager+Lazy --
@Test
public void testIsEagerIsLazy() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue(list.toLazy().isLazy());
assertTrue(list.toEager().isEager());
assertTrue(list.toLazy().freeze().isLazy());
val logs = new ArrayList<String>();
IntFuncList lazyList
= list
.peek(value -> logs.add("" + value));
lazyList.forEach(value -> {}); // ForEach but do nothing
assertEquals("[1, 2, 3]", logs.toString());
// Lazy list will have to be re-evaluated again so the logs double.
lazyList.forEach(value -> {});
assertEquals("[1, 2, 3, 1, 2, 3]", logs.toString());
logs.clear();
assertEquals("[]", logs.toString());
// Freeze but still lazy
IntFuncList frozenList
= list
.freeze()
.peek(value -> logs.add("" + value));
frozenList.forEach(value -> {}); // ForEach but do nothing
assertEquals("[1, 2, 3]", logs.toString());
// Freeze list but still lazy so it will have to be re-evaluated again so the logs double
frozenList.forEach(value -> {});
assertEquals("[1, 2, 3, 1, 2, 3]", logs.toString());
// Eager list
logs.clear();
IntFuncList eagerList
= list
.toEager()
.peek(value -> logs.add("" + value));
eagerList.forEach(value -> {}); // ForEach but do nothing
assertEquals("[1, 2, 3]", logs.toString());
// Eager list does not re-evaluate so the log stay the same.
eagerList.forEach(value -> {});
assertEquals("[1, 2, 3]", logs.toString());
});
}
@Test
public void testEagerLazy() {
{
val logs = new ArrayList<String>();
// We want to confirm that the list is lazy
val list = IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten).peek(value -> logs.add("" + value)).toFuncList();
// The function has not been materialized so nothing goes through peek.
assertAsString("[]", logs);
// Get part of them so those peek will goes through the peek
assertAsString("[1, 2, 3, 4, 5]", list.limit(5));
assertAsString("[1, 2, 3, 4, 5]", logs);
}
{
val logs = new ArrayList<String>();
// We want to confirm that the list is eager
val list = IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten).peek(value -> logs.add("" + value)).toFuncList().toEager();
// The function has been materialized so all element goes through peek.
assertAsString("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", logs);
// Even we only get part of it,
assertAsString("[1, 2, 3, 4, 5]", list.limit(5));
assertAsString("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", logs);
}
}
@Test
public void testEagerLazy_more() {
{
val logs1 = new ArrayList<String>();
val logs2 = new ArrayList<String>();
val orgData = IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten).toFuncList();
// We want to confirm that the list is lazy
val list = orgData
.toLazy ()
.peek (v -> logs1.add("" + v))
.exclude(theInteger.thatLessThanOrEqualsTo(3))
.peek (v -> logs2.add("" + v))
;
// The list has not been materialized so nothing goes through peek.
assertAsString("[]", logs1);
assertAsString("[]", logs2);
// Get part of them so those peek will goes through the peek
assertAsString("[4, 5, 6, 7, 8]", list.limit(5));
// Now that the list has been materialize all the element has been through the logs
// The first log has all the number until there are 5 elements that are bigger than 3.
assertAsString("[1, 2, 3, 4, 5, 6, 7, 8]", logs1);
// 1 2 3 4 5
// The second log captures all the number until 5 of them that are bigger than 3.
assertAsString("[4, 5, 6, 7, 8]", logs2);
}
{
val logs1 = new ArrayList<String>();
val logs2 = new ArrayList<String>();
val orgData = IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten).toFuncList();
// We want to confirm that the list is lazy
val list = orgData
.toEager()
.peek (v -> logs1.add("" + v))
.exclude(theInteger.thatLessThanOrEqualsTo(3))
.peek (v -> logs2.add("" + v))
;
// Since the list is eager, all the value pass through all peek all the time
assertAsString("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", logs1);
assertAsString("[4, 5, 6, 7, 8, 9, 10]", logs2);
// Get part of them so those peek will goes through the peek
assertAsString("[4, 5, 6, 7, 8]", list.limit(5));
// No more passing through the log stay still
assertAsString("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", logs1);
assertAsString("[4, 5, 6, 7, 8, 9, 10]", logs2);
}
}
//-- List --
@Test
public void testToFuncList() {
run(IntFuncList.of(One, Two, Three), list -> {
val funcList = list.toFuncList();
assertAsString("[1, 2, 3]", funcList.toString());
assertTrue(funcList instanceof IntFuncList);
});
}
@Test
public void testToJavaList() {
run(IntFuncList.of(One, Two, Three), list -> {
val funcList = list.toJavaList();
assertAsString("[1, 2, 3]", funcList);
assertFalse(funcList instanceof FuncList);
});
}
@Test
public void testToImmutableList() {
run(IntFuncList.of(One, Two, Three), list -> {
val funcList = list.toImmutableList();
assertAsString("[1, 2, 3]", funcList);
assertTrue(funcList instanceof ImmutableIntFuncList);
assertAsString("[1, 2, 3]", funcList.map(value -> value).toImmutableList());
assertTrue(funcList instanceof ImmutableIntFuncList);
});
}
@Test
public void testIterable() {
run(IntFuncList.of(One, Two, Three), list -> {
val iterator = list.iterable().iterator();
assertTrue(iterator.hasNext());
assertTrue(One == iterator.nextInt());
assertTrue(iterator.hasNext());
assertTrue(Two == iterator.nextInt());
assertTrue(iterator.hasNext());
assertTrue(Three == iterator.nextInt());
assertFalse(iterator.hasNext());
});
}
@Test
public void testIterator() {
run(IntFuncList.of(One, Two, Three), list -> {
val iterator = list.iterator();
assertTrue(iterator.hasNext());
assertTrue(One == iterator.nextInt());
assertTrue(iterator.hasNext());
assertTrue(Two == iterator.nextInt());
assertTrue(iterator.hasNext());
assertTrue(Three == iterator.nextInt());
assertFalse(iterator.hasNext());
});
}
@Test
public void testSpliterator() {
run(IntFuncList.of(One, Two, Three), list -> {
Spliterator.OfInt spliterator = list.spliterator();
IntStream stream = StreamSupport.intStream(spliterator, false);
IntStreamPlus streamPlus = IntStreamPlus.from(stream);
assertAsString("[1, 2, 3]", streamPlus.toListString());
});
}
@Test
public void testContainsAllOf() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertTrue (list.containsAllOf(One, Five));
assertFalse(list.containsAllOf(One, Six));
});
}
@Test
public void testContainsAnyOf() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertTrue (list.containsSomeOf(One, Six));
assertFalse(list.containsSomeOf(Six, Seven));
});
}
@Test
public void testContainsNoneOf() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertTrue (list.containsNoneOf(Six, Seven));
assertFalse(list.containsNoneOf(One, Six));
});
}
@Test
public void testJavaList_for() {
run(IntFuncList.of(One, Two, Three), list -> {
val logs = new ArrayList<String>();
for(val value : list.boxed()) {
logs.add("" + value);
}
assertAsString("[1, 2, 3]", logs);
});
}
@Test
public void testJavaList_size_isEmpty() {
run(IntFuncList.of(One, Two, Three), list -> {
assertEquals(3, list.size());
assertFalse (list.isEmpty());
});
run(IntFuncList.empty(), list -> {
assertEquals(0, list.size());
assertTrue (list.isEmpty());
});
}
@Test
public void testJavaList_contains() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue (list.contains(Two));
assertFalse(list.contains(Five));
});
}
@Test
public void testJavaList_containsAllOf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue (list.containsAllOf(Two, Three));
assertTrue (list.containsAllOf(FuncList. listOf(Two, Three)));
assertTrue (list.containsAllOf(IntFuncList.listOf(Two, Three)));
assertFalse(list.containsAllOf(Two, Five));
assertFalse(list.containsAllOf(FuncList. listOf(Two, Five)));
assertFalse(list.containsAllOf(IntFuncList.listOf(Two, Five)));
});
}
@Test
public void testJavaList_containsSomeOf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue (list.containsSomeOf(Two, Five));
assertTrue (list.containsSomeOf(FuncList. listOf(Two, Five)));
assertTrue (list.containsSomeOf(IntFuncList.listOf(Two, Five)));
assertFalse(list.containsSomeOf(Five, Seven));
assertFalse(list.containsSomeOf(FuncList. listOf(Five, Seven)));
assertFalse(list.containsSomeOf(IntFuncList.listOf(Five, Seven)));
});
}
@Test
public void testJavaList_containsNoneOf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue (list.containsNoneOf(Five, Six));
assertTrue (list.containsNoneOf(FuncList. listOf(Five, Six)));
assertTrue (list.containsNoneOf(IntFuncList.listOf(Five, Six)));
assertFalse(list.containsNoneOf(Two, Five));
assertFalse(list.containsNoneOf(FuncList .listOf(Two, Five)));
assertFalse(list.containsNoneOf(IntFuncList.listOf(Two, Five)));
});
}
@Test
public void testForEach() {
run(IntFuncList.of(One, Two, Three), list -> {
val logs = new ArrayList<String>();
list.forEach(s -> logs.add("" + s));
assertAsString("[1, 2, 3]", logs);
});
}
@Test
public void testForEachOrdered() {
run(IntFuncList.of(One, Two, Three), list -> {
val logs = new ArrayList<String>();
list.forEachOrdered(s -> logs.add("" + s));
assertAsString("[1, 2, 3]", logs);
});
}
@Test
public void testReduce() {
run(IntFuncList.of(1, 2, 3), list -> {
assertEquals(6, list.reduce(0, (a, b) -> a + b));
assertEquals(6, list.reduce((a, b) -> a + b).getAsInt());
});
}
static class Sum extends IntAggregationToInt {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorToIntPlus<int[]> collectorPlus = new IntCollectorToIntPlus<int[]>() {
@Override public Supplier<int[]> supplier() { return ()->new int[] { 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, s)->{ a[0] += s; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { a1[0] + a1[1] }; }
@Override public ToIntFunction<int[]> finisherToInt() { return a -> a[0]; }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorToIntPlus<?> intCollectorToIntPlus() {
return collectorPlus;
}
}
@Test
public void testCollect() {
run(IntFuncList.of(One, Two, Three), list -> {
val sum = new Sum();
assertAsString("6", list.collect(sum.intCollectorToIntPlus()));
Supplier<StringBuffer> supplier = () -> new StringBuffer();
ObjIntConsumer<StringBuffer> accumulator = (buffer, i) -> buffer.append(i);
BiConsumer<StringBuffer, StringBuffer> combiner = (b1, b2) -> b1.append(b2.toString());
assertAsString("123", list.collect(supplier, accumulator, combiner));
});
}
@Test
public void testSize() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("4", list.size());
});
}
@Test
public void testCount() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("4", list.count());
});
}
@Test
public void testSum() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("6", list.sum());
});
}
@Test
public void testProduct() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[6]", list.product());
});
}
@Test
public void testMinMax() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("OptionalInt[1]", list.min());
assertAsString("OptionalInt[4]", list.max());
});
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("Optional[(1,4)]", list.minMax());
});
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("Optional[(4,1)]", list.minMax((a,b) -> b - a));
});
}
@Test
public void testMinByMaxBy() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("OptionalInt[1]", list.minBy(a -> a));
assertAsString("OptionalInt[4]", list.maxBy(a -> a));
assertAsString("OptionalInt[4]", list.minBy(a -> -a));
assertAsString("OptionalInt[1]", list.maxBy(a -> -a));
});
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("OptionalInt[1]", list.minBy(a -> a, (a,b)->a-b));
assertAsString("OptionalInt[4]", list.maxBy(a -> a, (a,b)->a-b));
assertAsString("OptionalInt[4]", list.minBy(a -> -a, (a,b)->a-b));
assertAsString("OptionalInt[1]", list.maxBy(a -> -a, (a,b)->a-b));
});
}
@Test
public void testMinMaxBy() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("Optional[(1,4)]", list.minMaxBy(a -> a));
});
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("Optional[(4,1)]", list.minMaxBy(a -> a, (a,b)->b-a));
});
}
@Test
public void testMinOfMaxOf() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("OptionalInt[1]", list.minOf(a -> a));
assertAsString("OptionalInt[4]", list.maxOf(a -> a));
assertAsString("OptionalInt[4]", list.minOf(a -> -a));
assertAsString("OptionalInt[1]", list.maxOf(a -> -a));
});
}
@Test
public void testMinIndex() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("OptionalInt[0]", list.minIndex());
});
}
@Test
public void testMaxIndex() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("OptionalInt[5]", list.maxIndex());
});
}
@Test
public void testMinIndexBy() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("OptionalInt[0]", list.minIndexBy(value -> value));
});
}
@Test
public void testMinIndexOf() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
IntPredicate condition = value -> value > 2;
IntUnaryOperator operator = value -> value;
assertAsString("OptionalInt[2]", list.minIndexOf(condition, operator));
});
}
@Test
public void testMaxIndexBy() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("OptionalInt[5]", list.maxIndexBy(value -> value));
});
}
@Test
public void testMaxIndexOf() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
IntPredicate condition = value -> value > 2;
IntUnaryOperator operator = value -> value;
assertAsString("OptionalInt[5]", list.maxIndexOf(condition, operator));
});
}
@Test
public void testAnyMatch() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue(list.anyMatch(value -> value == One));
});
}
@Test
public void testAllMatch() {
run(IntFuncList.of(One, Two, Three), list -> {
assertFalse(list.allMatch(value -> value == One));
});
}
@Test
public void testNoneMatch() {
run(IntFuncList.of(One, Two, Three), list -> {
assertTrue(list.noneMatch(value -> value == Five));
});
}
@Test
public void testFindFirst() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[1]", list.findFirst());
});
}
@Test
public void testFindAny() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[1]", list.findAny());
});
}
@Test
public void testFindLast() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[3]", list.findLast());
});
}
@Test
public void testFirstResult() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[1]", list.first());
});
}
@Test
public void testLastResult() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("OptionalInt[3]", list.last());
});
}
@Test
public void testJavaList_get() {
run(IntFuncList.of(One, Two, Three), list -> {
assertEquals(One, list.get(0));
assertEquals(Two, list.get(1));
assertEquals(Three, list.get(2));
});
}
@Test
public void testJavaList_indexOf() {
run(IntFuncList.of(One, Two, Three, Two, Three), list -> {
assertEquals( 1, list.indexOf(Two));
assertEquals(-1, list.indexOf(Five));
});
}
@Test
public void testJavaList_lastIndexOf() {
run(IntFuncList.of(One, Two, Three, Two, Three), list -> {
assertEquals( 3, list.lastIndexOf(Two));
assertEquals(-1, list.lastIndexOf(Five));
});
}
@Test
public void testJavaList_subList() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[2, 3]", list.subList(1, 3));
assertAsString("[2, 3, 4, 5]", list.subList(1, 10));
});
}
//-- IntFuncListWithGroupingBy --
@Test
public void testGroupingBy() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"{1:[1, 2], 2:[3, 4], 3:[5]}",
list
.groupingBy(theInteger.dividedBy(2).asInteger())
.sortedByKey(theInteger));
});
}
@Test
public void testGroupingBy_aggregate() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"{1:[1.0, 2.0], 2:[3.0, 4.0], 3:[5.0]}",
list
.groupingBy(theInteger.dividedBy(2).asInteger(), l -> l.mapToDouble())
.sortedByKey(theInteger));
});
}
//
// @Test
// public void testGroupingBy_collect() {
// run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
// IntAggregationToInt sum = new Sum();
// assertAsString(
//// "{1:[1, 2], 2:[3, 4], 3:[5]}", << Before sum
// "{1:3, 2:7, 3:5}",
// list
// .groupingBy(theInteger.dividedBy(2).asInteger(), sum)
// .sortedByKey(theInteger));
// });
// }
//
// @Test
// public void testGroupingBy_process() {
// run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
// val sumHalf = new SumHalf();
// assertAsString(
//// "{1:[1, 2], 2:[3, 4], 3:[5]}", << Before half
//// "{1:[0, 1], 2:[1, 2], 3:[2]}", << Half
// "{1:1, 2:3, 3:2}",
// list
// .groupingBy(theInteger.dividedBy(2).asInteger(), sumHalf)
// .sortedByKey(theInteger));
// });
// }
//-- Functional list
@Test
public void testMapToString() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[1, 2, 3, 4, 5]",
list
.mapToString()
);
});
}
@Test
public void testMap() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[2, 4, 6, 8, 10]",
list
.map(theInteger.time(2))
);
});
}
@Test
public void testMapToInt() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[10, 20, 30]",
list
.map(theInteger.time(10))
);
});
}
@Test
public void testMapToDouble() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString(
"[1.0, 1.4142135623730951, 1.7320508075688772]",
list.mapToDouble(theInteger.squareRoot()));
});
}
@Test
public void testMapToObj() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[-1-, -2-, -3-, -4-, -5-]",
list
.mapToObj(i -> "-" + i + "-")
);
});
}
//-- FlatMap --
@Test
public void testFlatMap() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString(
"[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]",
list.flatMap(i -> IntFuncList.cycle(i).limit(i)));
});
}
@Test
public void testFlatMapToInt() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString(
"[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]",
list.flatMapToInt(i -> IntFuncList.cycle(i).limit(i)));
});
}
@Test
public void testFlatMapToDouble() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString(
"[1.0, 2.0, 2.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0]",
list
.flatMapToDouble(i -> DoubleFuncList.cycle(i).limit(i)));
});
}
//-- Filter --
@Test
public void testFilter() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString(
"[3]",
list.filter(theInteger.time(2).thatGreaterThan(4)));
});
}
@Test
public void testFilter_mapper() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString(
"[3]",
list.filter(theInteger.time(2), theInteger.thatGreaterThan(4)));
});
}
@Test
public void testPeek() {
run(IntFuncList.of(One, Two, Three), list -> {
val logs = new ArrayList<String>();
assertAsString("[1, 2, 3]", list.peek(i -> logs.add("" + i)));
assertAsString("[1, 2, 3]", logs);
});
}
@Test
public void testLimit() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[1, 2, 3]", list.limit(3));
});
}
@Test
public void testSkip() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[3, 4, 5]", list.skip(2));
});
}
@Test
public void testDistinct() {
run(IntFuncList.of(One, Two, Two, Three), list -> {
assertAsString("[1, 2, 3]", list.distinct());
});
}
@Test
public void testSorted() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[2, 4, 6, 8, 10]", list.map(theInteger.time(2)).sorted());
assertAsString("[10, 8, 6, 4, 2]", list.map(theInteger.time(2)).sorted((a, b) -> (b - a)));
});
}
@Test
public void testBoxed() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testToArray() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", Arrays.toString(list.toArray()));
});
}
@Test
public void testNullableOptionalResult() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("Nullable.of([1, 2, 3])", list.__nullable());
assertAsString("Optional[[1, 2, 3]]", list.__optional());
assertAsString("Result:{ Value: [1, 2, 3] }", list.__result());
});
}
@Test
public void testIndexOf() {
run(IntFuncList.of(One, Two, Three, Four, Five, Three), list -> {
assertAsString("2", list.indexOf(Three));
});
}
@Test
public void testLastIndexOf() {
run(IntFuncList.of(Three, One, Two, Three, Four, Five), list -> {
assertAsString("3", list.lastIndexOf(Three));
});
}
@Test
public void testIndexesOf() {
run(IntFuncList.of(One, Two, Three, Four, Two), list -> {
assertAsString("[0, 2]", list.indexesOf(value -> value == One || value == Three));
assertAsString("[1, 4]", list.indexesOf(Two));
});
}
@Test
public void testToBuilder() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3, 4, 5]", list.toBuilder().add(Four).add(Five).build());
});
}
@Test
public void testFirst() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[1]", list.first());
assertAsString("[1, 2, 3]", list.first(3));
});
}
@Test
public void testLast() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[5]", list.last());
assertAsString("[3, 4, 5]", list.last(3));
});
}
@Test
public void testAt() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.at(2));
assertAsString("OptionalInt.empty", list.at(10));
});
}
@Test
public void testTail() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[2, 3, 4, 5]", list.tail());
});
}
@Test
public void testAppend() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[1, 2, 3, 4]", list.append(Four));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testAppendAll() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[1, 2, 3, 4, 5]", list.appendAll(Four, Five));
assertAsString("[1, 2, 3, 4, 5]", list.appendAll(IntFuncList.listOf(Four, Five)));
assertAsString("[1, 2, 3, 4, 5]", list.appendAll(IntFuncList.of(Four, Five)));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testPrepend() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[0, 1, 2, 3]", list.prepend(Zero));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testPrependAll() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[-1, 0, 1, 2, 3]", list.prependAll(MinusOne, Zero));
assertAsString("[-1, 0, 1, 2, 3]", list.prependAll(IntFuncList.listOf(MinusOne, Zero)));
assertAsString("[-1, 0, 1, 2, 3]", list.prependAll(IntFuncList.of(MinusOne, Zero)));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testWith() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[1, 0, 3]", list.with(1, Zero));
assertAsString("[1, 102, 3]", list.with(1, value -> value + 100));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testInsertAt() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[1, 0, 2, 3]", list.insertAt(1, Zero));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testInsertAllAt() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
assertAsString("[1, 2, 0, 0, 3]", list.insertAt(2, Zero, Zero));
assertAsString("[1, 2, 0, 0, 3]", list.insertAllAt(2, IntFuncList.listOf(Zero, Zero)));
assertAsString("[1, 2, 0, 0, 3]", list.insertAllAt(2, IntFuncList.of(Zero, Zero)));
assertAsString("[1, 2, 3]", list);
});
}
@Test
public void testExclude() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[1, 2, 3, 4, 5]", list);
assertAsString("[1, 3, 4, 5]", list.exclude(Two));
assertAsString("[1, 3, 4, 5]", list.exclude(theInteger.eq(Two)));
assertAsString("[1, 3, 4, 5]", list.excludeAt(1));
assertAsString("[1, 5]", list.excludeFrom(1, 3));
assertAsString("[1, 4, 5]", list.excludeBetween(1, 3));
assertAsString("[1, 2, 3, 4, 5]", list);
});
}
@Test
public void testReverse() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[1, 2, 3, 4, 5]", list);
assertAsString("[5, 4, 3, 2, 1]", list.reverse());
assertAsString("[1, 2, 3, 4, 5]", list);
});
}
@Test
public void testShuffle() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten), list -> {
assertAsString ("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", list);
assertNotEquals("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", list.shuffle().toString());
assertAsString ("[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", list);
});
}
@Test
public void testQuery() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("[1, 2, 3, 4, 5, 6]", list);
assertAsString("[(2,3), (5,6)]", list.query(theInteger.thatIsDivisibleBy(3)));
assertAsString("[1, 2, 3, 4, 5, 6]", list);
});
}
//-- AsIntFuncListWithConversion --
@Test
public void testToByteArray() {
run(IntFuncList.of('A', 'B', 'C', 'D'), list -> {
assertAsString("[65, 66, 67, 68]", Arrays.toString(list.toByteArray(c -> (byte)(int)c)));
});
}
@Test
public void testToIntArray() {
run(IntFuncList.of('A', 'B', 'C', 'D'), list -> {
assertAsString("[65, 66, 67, 68]", Arrays.toString(list.toIntArray(c -> (int)c)));
});
}
@Test
public void testToDoubleArray() {
run(IntFuncList.of('A', 'B', 'C', 'D'), list -> {
assertAsString("[65.0, 66.0, 67.0, 68.0]", Arrays.toString(list.toDoubleArray(c -> (double)(int)c)));
});
}
@Test
public void testToArrayList() {
run(IntFuncList.of(One, Two, Three), list -> {
val newList = list.toArrayList();
assertAsString("[1, 2, 3]", newList);
assertTrue(newList instanceof ArrayList);
});
}
@Test
public void testToList() {
run(IntFuncList.of(One, Two, Three), list -> {
val newList = list.toJavaList();
assertAsString("[1, 2, 3]", newList);
assertTrue(newList instanceof List);
});
}
@Test
public void testToMutableList() {
run(IntFuncList.of(One, Two, Three), list -> {
val newList = list.toMutableList();
assertAsString("[1, 2, 3]", newList);
// This is because we use ArrayList as mutable list ... not it should not always be.
assertTrue(newList instanceof ArrayList);
});
}
//-- join --
@Test
public void testJoin() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("123", list.join());
});
}
@Test
public void testJoin_withDelimiter() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("1, 2, 3", list.join(", "));
});
}
@Test
public void testToListString() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list);
});
}
//-- toMap --
@Test
public void testToMap() {
run(IntFuncList.of(One, Three, Five), list -> {
assertAsString("{1:1, 3:3, 5:5}", list.toMap(theInteger));
});
}
@Test
public void testToMap_withValue() {
run(IntFuncList.of(One, Three, Five), list -> {
assertAsString("{1:1, 3:9, 5:25}", list.toMap(theInteger, theInteger.square()));
});
}
@Test
public void testToMap_withMappedMergedValue() {
run(IntFuncList.of(One, Two, Three, Five), list -> {
// 0:2, 1:1+3+5
assertAsString("{0:2, 1:9}", list.toMap(theInteger.remainderBy(2), theInteger, (a, b) -> a + b));
});
}
@Test
public void testToMap_withMergedValue() {
run(IntFuncList.of(One, Two, Three, Five), list -> {
// 0:2, 1:1*3*5
assertAsString("{0:2, 1:15}", list.toMap(theInteger.remainderBy(2), (a, b) -> a * b));
});
}
@Test
public void testToSet() {
run(IntFuncList.of(One, Two, Three), list -> {
val set = list.toSet();
assertAsString("[1, 2, 3]", set);
assertTrue(set instanceof Set);
});
}
@Test
public void testForEachWithIndex() {
run(IntFuncList.of(One, Two, Three), list -> {
val logs = new ArrayList<String>();
list.forEachWithIndex((i, s) -> logs.add(i + ":" + s));
assertAsString("[0:1, 1:2, 2:3]", logs);
});
}
@Test
public void testPopulateArray() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
val array = new int[5];
list.populateArray(array);
assertAsString("[1, 2, 3, 4, 5]", Arrays.toString(array));
});
}
@Test
public void testPopulateArray_withOffset() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
val array = new int[3];
list.populateArray(array, 2);
assertAsString("[0, 0, 1]", Arrays.toString(array));
});
}
@Test
public void testPopulateArray_withOffsetLength() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
val array = new int[5];
list.populateArray(array, 1, 3);
assertAsString("[0, 1, 2, 3, 0]", Arrays.toString(array));
});
}
//-- AsIntFuncListWithMatch --
@Test
public void testFindFirst_withPredicate() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.findFirst(theInteger.square().thatGreaterThan(theInteger.time(2))));
});
}
@Test
public void testFindAny_withPredicate() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.findFirst(theInteger.square().thatGreaterThan(theInteger.time(2))));
});
}
@Test
public void testFindFirst_withMapper_withPredicate() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.findFirst(theInteger.square(), theInteger.thatGreaterThan(5)));
});
}
@Test
public void testFindAny_withMapper_withPredicate() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.findAny(theInteger.square(), theInteger.thatGreaterThan(5)));
});
}
//-- AsFuncListWithStatistic --
@Test
public void testMinBy() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.minBy(theInteger.minus(3).square()));
});
}
@Test
public void testMaxBy() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.maxBy(theInteger.minus(3).square().negate()));
});
}
@Test
public void testMinBy_withMapper() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("OptionalInt[6]", list.minBy(theInteger.minus(3).square(), (a, b)->b-a));
});
}
@Test
public void testMaxBy_withMapper() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("OptionalInt[3]", list.maxBy(theInteger.minus(3).square(), (a, b)->b-a));
});
}
@Test
public void testMinMaxBy_withMapper() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
assertAsString("Optional[(3,6)]", list.minMaxBy(theInteger.minus(3).square()));
});
}
@Test
public void testMinMaxBy_withMapper_withComparator() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString("Optional[(1,3)]", list.minMaxBy(theInteger.minus(3).square(), (a, b) -> b-a));
});
}
//-- IntFuncListWithCalculate --
static class SumHalf extends IntAggregation<Integer> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Integer> collectorPlus = new IntCollectorPlus<int[], Integer>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] += i; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { a1[0] + a2[0] }; }
@Override public Function<int[], Integer> finisher() { return (a) -> a[0] / 2; }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Integer> intCollectorPlus() {
return collectorPlus;
}
}
static class Average extends IntAggregation<Double> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Double> collectorPlus = new IntCollectorPlus<int[], Double>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0, 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] += i; a[1] += 1; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { a1[0] + a2[0], a1[1] + a2[1] }; }
@Override public Function<int[], Double> finisher() { return (a) -> (a[1] == 0) ? null : (1.0*a[0]/a[1]); }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Double> intCollectorPlus() {
return collectorPlus;
}
}
static class MinInt extends IntAggregation<Integer> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Integer> collectorPlus = new IntCollectorPlus<int[], Integer>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0, 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] = Math.min(i, a[0]); a[1] = 1; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { Math.min(a1[0], a2[0]), a1[1] + a2[1] }; }
@Override public Function<int[], Integer> finisher() { return (a) -> (a[1] == 0) ? null : (a[0]); }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Integer> intCollectorPlus() {
return collectorPlus;
}
}
static class MaxInt extends IntAggregation<Integer> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Integer> collectorPlus = new IntCollectorPlus<int[], Integer>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0, 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] = Math.max(i, a[0]); a[1] = 1; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { Math.max(a1[0], a2[0]), a1[1] + a2[1] }; }
@Override public Function<int[], Integer> finisher() { return (a) -> (a[1] == 0) ? null : (a[0]); }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Integer> intCollectorPlus() {
return collectorPlus;
}
}
static class SumInt extends IntAggregation<Integer> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Integer> collectorPlus = new IntCollectorPlus<int[], Integer>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] += i; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { a1[0] + a2[0] }; }
@Override public Function<int[], Integer> finisher() { return (a) -> a[0]; }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Integer> intCollectorPlus() {
return collectorPlus;
}
}
static class AvgInt extends IntAggregation<Integer> {
private Set<Characteristics> characteristics = EnumSet.of(CONCURRENT, UNORDERED);
private IntCollectorPlus<int[], Integer> collectorPlus = new IntCollectorPlus<int[], Integer>() {
@Override public Supplier<int[]> supplier() { return () -> new int[] { 0, 0 }; }
@Override public ObjIntConsumer<int[]> intAccumulator() { return (a, i) -> { a[0] += i; a[1] += 1; }; }
@Override public BinaryOperator<int[]> combiner() { return (a1, a2) -> new int[] { a1[0] + a2[0], a1[1] + a2[1] }; }
@Override public Function<int[], Integer> finisher() { return (a) -> (a[1] == 0) ? null : (a[0]/a[1]); }
@Override public Set<Characteristics> characteristics() { return characteristics; }
};
@Override
public IntCollectorPlus<?, Integer> intCollectorPlus() {
return collectorPlus;
}
}
@Test
public void testCalculate() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
assertAsString("10", list.calculate(sumHalf).intValue());
});
}
@Test
public void testCalculate2() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
assertAsString(
"(10,5.0)",
list.calculate(sumHalf, average));
});
}
@Test
public void testCalculate2_combine() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val minInt = new MinInt();
val maxInt = new MaxInt();
val range = list.calculate(minInt, maxInt).mapTo((max, min) -> max + min);
assertAsString("11", range);
});
}
@Test
public void testCalculate3() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
assertAsString(
"(10,5.0,0)",
list.calculate(sumHalf, average, minInt));
});
}
@Test
public void testCalculate3_combine() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val value = list
.calculate(sumHalf, average, minInt)
.mapTo((sumH, avg, min) -> "sumH: " + sumH + ", avg: " + avg + ", min: " + min);
assertAsString(
"sumH: 10, avg: 5.0, min: 0",
value);
});
}
@Test
public void testCalculate4() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
assertAsString(
"(10,5.0,0,11)",
list.calculate(sumHalf, average, minInt, maxInt));
});
}
@Test
public void testCalculate4_combine() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
val value = list
.calculate(sumHalf, average, minInt, maxInt)
.mapTo((sumH, avg, min, max) -> "sumH: " + sumH + ", avg: " + avg + ", min: " + min + ", max: " + max);
assertAsString(
"sumH: 10, "
+ "avg: 5.0, "
+ "min: 0, "
+ "max: 11",
value);
});
}
@Test
public void testCalculate5() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
val sumInt = new SumInt();
assertAsString(
"(10,5.0,0,11,20)",
list.calculate(sumHalf, average, minInt, maxInt, sumInt));
});
}
@Test
public void testCalculate5_combine() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
val sumInt = new SumInt();
val value = list
.calculate(sumHalf, average, minInt, maxInt, sumInt)
.mapTo((sumH, avg, min, max, sumI) -> {
return "sumH: " + sumH + ", avg: " + avg + ", min: " + min + ", max: " + max + ", max: " + max + ", sumI: " + sumI;
});
assertAsString(
"sumH: 10, avg: 5.0, min: 0, max: 11, max: 11, sumI: 20",
value);
});
}
@Test
public void testCalculate6() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
val sumInt = new SumInt();
val avgInt = new AvgInt();
assertAsString(
"(10,5.0,0,11,20,5)",
list.calculate(sumHalf, average, minInt, maxInt, sumInt, avgInt));
});
}
@Test
public void testCalculate6_combine() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sumHalf = new SumHalf();
val average = new Average();
val minInt = new MinInt();
val maxInt = new MaxInt();
val sumInt = new SumInt();
val avgInt = new AvgInt();
val value = list
.calculate(sumHalf, average, minInt, maxInt, sumInt, avgInt)
.mapTo((sumH, avg, min, max, sumI, avgI) -> {
return "sumH: " + sumH + ", avg: " + avg + ", min: " + min + ", max: " + max + ", max: " + max + ", sumI: " + sumI + ", avgI: " + avgI;
});
assertAsString(
"sumH: 10, "
+ "avg: 5.0, "
+ "min: 0, "
+ "max: 11, "
+ "max: 11, "
+ "sumI: 20, "
+ "avgI: 5",
value);
});
}
@Test
public void testCalculate_of() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val sum = new Sum();
// 2*2 + 3*2 + 4*2 + 11*2
// 4 + 6 + 8 + 22
assertAsString("40", list.calculate(sum.ofInt(theInteger.time(2))));
});
}
//-- FuncListWithCombine --
@Test
public void testAppendWith() {
run(IntFuncList.of(One, Two), IntFuncList.of(Three, Four), (list1, list2) -> {
assertAsString(
"[1, 2, 3, 4]",
list1.appendWith(list2)
);
});
}
@Test
public void testParependWith() {
run(IntFuncList.of(One, Two), IntFuncList.of(Three, Four), (list1, list2) -> {
assertAsString(
"[1, 2, 3, 4]",
list2.prependWith(list1)
);
});
}
@Test
public void testMerge() {
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(list1, streamabl2) -> {
assertAsString(
"100, 0, 200, 1, 300, 2, 3, 4, 5, 6",
list1
.mergeWith(streamabl2)
.limit (10)
.join (", "));
});
}
@Test
public void testZipWith() {
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
"(100,0), (200,1), (300,2)",
listA.zipWith(listB).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7 8 9
"(100,0), (200,1), (300,2), (-1,3), (-1,4), (-1,5), (-1,6), (-1,7), (-1,8), (-1,9)",
listA.zipWith(listB, -1).join(", "));
});
run(IntFuncList.of(100, 200, 300, 400, 500),
IntFuncList.infinite().limit(3),
(listA, listB) -> {
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7 8 9
"(100,0), (200,1), (300,2), (400,-1), (500,-1)",
listA.zipWith(-100, listB, -1).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300
// 0 1 2
"100, 201, 302",
listA.zipWith(listB, (iA, iB) -> iA + iB).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7 8 9
"100, 201, 302, 2, 3, 4, 5, 6, 7, 8",
listA.zipWith(listB, -1, (iA, iB) -> iA + iB).join(", "));
});
run(IntFuncList.of(100, 200, 300, 400, 500),
IntFuncList.infinite().limit(3),
(listA, listB) -> {
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7 8 9
"10000, 20001, 30002, 39999, 49999",
listA.zipWith(-100, listB, -1, (a, b) -> a*100 + b).join(", "));
});
}
@Test
public void testZipWith_object() {
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
"(100,0), (200,1), (300,2)",
listA.zipWith(listB.boxed()).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
"(100,0), (200,1), (300,2), (-1,3), (-1,4), (-1,5), (-1,6), (-1,7), (-1,8), (-1,9)",
listA.zipWith(-1, listB.boxed()).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
"100->0, 200->1, 300->2",
listA.zipWith(listB.boxed(), (a, b) -> a + "->" + b).join(", "));
});
run(IntFuncList.of(100, 200, 300, 400, 500),
IntFuncList.infinite().limit(3),
(listA, listB) -> {
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7 8 9
"10000, 20001, 30002, 39999, 49999",
listA.zipWith(-100, listB, -1, (a, b) -> a*100 + b).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300
// 0 1 2
"100<->0, 200<->1, 300<->2",
listA.zipToObjWith(listB, (iA, iB) -> iA + "<->" + iB).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300
// 0 1 2
"100<->0, 200<->1, 300<->2, -100<->3, -100<->4, -100<->5, -100<->6, -100<->7, -100<->8, -100<->9",
listA.zipToObjWith(-100, listB, -1, (iA, iB) -> iA + "<->" + iB).join(", "));
});
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
assertAsString(
// 100 200 300
// 0 1 2
"100<->0, 200<->1, 300<->2, -100<->3, -100<->4, -100<->5, -100<->6, -100<->7, -100<->8, -100<->9",
listA.zipToObjWith(-100, listB.boxed(), (iA, iB) -> iA + "<->" + iB).join(", "));
});
}
@Test
public void testChoose() {
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
val bool = new AtomicBoolean(true);
assertAsString("100, 1, 300, 3, 4", listA.choose(listB, (a, b) -> {
// This logic which to choose from one then another
boolean curValue = bool.get();
return bool.getAndSet(!curValue);
}).limit(5).join(", "));
});
}
@Test
public void testChoose_AllowUnpaired() {
run(IntFuncList.of(100, 200, 300),
IntFuncList.infinite().limit(10),
(listA, listB) -> {
val bool = new AtomicBoolean(true);
assertAsString(
// 100 200 300 -1 -1 -1 -1 -1
// 0 1 2 3 4 5 6 7
"100, 1, 300, 3, 4, 5, 6",
listA.choose(listB, AllowUnpaired, (a, b) -> {
// This logic which to choose from one then another
boolean curValue = bool.get();
return bool.getAndSet(!curValue);
}).limit(7).join(", "));
});
}
//-- IntStreamPlusWithFilter --
@Test
public void testFilter_withMappter() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 5]",
list.filter(
theInteger.square(),
theInteger.thatIsOdd()));
});
}
@Test
public void testFilterAsInt() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 5]",
list.filterAsInt(
theInteger.square(),
theInteger.thatIsOdd()));
});
}
@Test
public void testFilterAsLong() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 5]",
list.filterAsLong(
theInteger.square().asLong(),
theLong.thatIsOdd()));
});
}
@Test
public void testFilterAsDouble() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 5]",
list.filterAsDouble(
theInteger.square().asDouble() ,
theDouble.asInteger().thatIsOdd()));
});
}
@Test
public void testFilterAsObject() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 5]",
list.filterAsObject(
i -> "" + i,
s -> (Integer.parseInt(s) % 2) == 1));
});
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
IntFunction<String> mapper = i -> "" + i;
Predicate<String> checker = s -> (Integer.parseInt(s) % 2) == 1;
assertAsString(
"[1, 3, 5]",
list.filterAsObject(mapper, checker));
});
}
@Test
public void testFilterWithIndex() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString("[4]", list.filterWithIndex((index, value) -> (index > 2) && (value < 5)));
});
}
@Test
public void testFilterNonNull() {
val cars = new Car[] {
new Car("Blue"),
new Car("Green"),
null,
new Car(null),
new Car("Red")
};
run(IntFuncList.wholeNumbers(cars.length), list -> {
assertAsString(
"[0, 1, 3, 4]",
list.filterNonNull(i -> cars[i]));
});
}
@Test
public void testExcludeNull() {
val cars = new Car[] {
new Car("Blue"),
new Car("Green"),
null,
new Car(null),
new Car("Red")
};
run(IntFuncList.wholeNumbers(cars.length), list -> {
assertAsString(
"[0, 1, 3, 4]",
list.excludeNull(i -> cars[i]));
});
}
@Test
public void testFilterIn_array() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[2, 5]",
list.filterIn(Two, Five));
});
}
@Test
public void testExcludeIn_array() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 4]",
list.excludeIn(Two, Five));
});
}
@Test
public void testFilterIn_funcList() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[2, 5]",
list.filterIn(IntFuncList.of(Two, Five)));
});
}
@Test
public void testExcludeIn_funcList() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 4]",
list.excludeIn(IntFuncList.of(Two, Five)));
});
}
@Test
public void testFilterIn_collection() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[2, 5]",
list.filterIn(Arrays.asList(Two, Five)));
});
}
@Test
public void testExcludeIn_collection() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1, 3, 4]",
list.excludeIn(Arrays.asList(Two, Five)));
});
}
//-- FuncListWithFlatMap --
@Test
public void testFlatMapOnly() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString(
"[1, 2, 3, 3, 3]",
list.flatMapOnly(
theInteger.thatIsOdd(),
i -> IntFuncList.cycle(i).limit(i)));
});
}
@Test
public void testFlatMapIf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString(
"[1, -2, -2, 3, 3, 3]",
list.flatMapIf(
theInteger.thatIsOdd(),
i -> IntFuncList.cycle(i).limit(i),
i -> IntFuncList.cycle(-i).limit(i)));
});
}
//-- FuncListWithLimit --
@Test
public void testSkipLimitLong() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[2]", list.skip((Long)1L).limit((Long)1L));
});
}
@Test
public void testSkipLimitLongNull() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list.skip(null).limit(null));
});
}
@Test
public void testSkipLimitLongMinus() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 3]", list.skip(Long.valueOf(-1)).limit(Long.valueOf(-1)));
});
}
@Test
public void testSkipWhile() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
assertAsString("[3, 4, 5, 4, 3, 2, 1]", list.skipWhile(i -> i < 3));
assertAsString("[1, 2, 3, 4, 5, 4, 3, 2, 1]", list.skipWhile(i -> i > 3));
assertAsString("[5, 4, 3, 2, 1]", list.skipWhile((p, e) -> p == e + 1));
assertAsString("[1, 2, 3, 4, 5, 4, 3, 2, 1]", list.skipWhile((p, e) -> p == e - 1));
});
}
@Test
public void testSkipUntil() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
assertAsString("[4, 5, 4, 3, 2, 1]", list.skipUntil(i -> i > 3));
assertAsString("[1, 2, 3, 4, 5, 4, 3, 2, 1]", list.skipUntil(i -> i < 3));
assertAsString("[1, 2, 3, 4, 5, 4, 3, 2, 1]", list.skipUntil((p, e) -> p == e + 1));
assertAsString("[5, 4, 3, 2, 1]", list.skipUntil((p, e) -> p == e - 1));
});
}
@Test
public void testTakeWhile() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
val logs = new ArrayList<Integer>();
assertAsString("[1, 2, 3]", list.peek(logs::add).takeWhile(i -> i < 4));
assertAsString("[1, 2, 3, 4]", logs);
// ^--- Because it needs 4 to do the check in `takeWhile`
logs.clear();
assertAsString("[]", list.peek(logs::add).takeWhile(i -> i > 4));
assertAsString("[1]", logs);
// ^--- Because it needs 1 to do the check in `takeWhile`
});
}
@Test
public void testTakeWhile_previous() {
run(IntFuncList.of(1, 2, 3, 4, 6, 4, 3, 2, 1), list -> {
assertAsString("[1, 2, 3, 4]", list.takeWhile((a, b) -> b == a + 1));
});
}
@Test
public void testTakeUtil() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
val logs = new ArrayList<Integer>();
assertAsString("[1, 2, 3, 4]", list.peek(logs::add).takeUntil(i -> i > 4));
assertAsString("[1, 2, 3, 4, 5]", logs);
// ^--- Because it needs 5 to do the check in `takeUntil`
logs.clear();
assertAsString("[]", list.peek(logs::add).takeUntil(i -> i < 4));
assertAsString("[1]", logs);
// ^--- Because it needs 1 to do the check in `takeUntil`
});
}
@Test
public void testTakeUntil_previous() {
run(IntFuncList.of(1, 2, 3, 4, 6, 4, 3, 2, 1), list -> {
assertAsString("[1, 2, 3, 4]", list.takeUntil((a, b) -> b > a + 1));
});
}
@Test
public void testDropAfter() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
assertAsString("[1, 2, 3, 4]", list.dropAfter(i -> i == 4));
// ^--- Include 4
});
}
@Test
public void testDropAfter_previous() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
assertAsString("[1, 2, 3, 4, 5, 4]", list.dropAfter((a, b) -> b < a));
// ^--- Include 4
});
}
@Test
public void testSkipTake() {
run(IntFuncList.of(1, 2, 3, 4, 5, 4, 3, 2, 1), list -> {
val logs = new ArrayList<Integer>();
assertAsString("[3, 4, 5, 4, 3]", list.peek(logs::add).skipWhile(i -> i < 3).takeUntil(i -> i < 3));
assertAsString("[1, 2, 3, 4, 5, 4, 3, 2]", logs);
// ^--^-----------------^--- Because it needs these number to do the check in `skipWhile` and `takeWhile`
});
}
//-- FuncListWithMap --
@Test
public void testMapOnly() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 2, 9]",
list
.mapOnly(
theInteger.thatIsOdd(),
theInteger.square())
);
});
}
@Test
public void testMapIf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 1, 9]",
list
.mapIf(
theInteger.thatIsOdd(),
theInteger.square(),
theInteger.squareRoot().round().asInteger()
));
});
}
@Test
public void testMapToObjIf() {
run(IntFuncList.of(One, Two, Three), list -> {
assertAsString("[1, 1, 9]",
list
.mapToObjIf(
theInteger.thatIsOdd(),
theInteger.square().asString(),
theInteger.squareRoot().round().asInteger().asString()
));
});
}
//== Map First ==
@Test
public void testMapFirst_2() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve), list -> {
assertAsString(
"[1, 2, Three, 4, 5, 6, 7, 8, 9, 10, 11, 12]",
list
.mapFirst(
i -> i == 3 ? "Three" : null,
i -> "" + i
)
);
});
}
@Test
public void testMapFirst_3() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve), list -> {
assertAsString("[1, 2, Three, 4, 5, 6, Seven, 8, 9, 10, 11, 12]",
list
.mapFirst(
i -> i == 3 ? "Three" : null,
i -> i == 7 ? "Seven" : null,
i -> "" + i
)
);
});
}
@Test
public void testMapFirst_4() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve), list -> {
assertAsString("[1, 2, Three, 4, 5, 6, Seven, 8, 9, 10, Eleven, 12]",
list
.mapFirst(
i -> i == 3 ? "Three" : null,
i -> i == 7 ? "Seven" : null,
i -> i == 11 ? "Eleven" : null,
i -> "" + i
)
);
});
}
@Test
public void testMapFirst_5() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve), list -> {
assertAsString("[One, 2, Three, 4, 5, 6, Seven, 8, 9, 10, Eleven, 12]",
list
.mapFirst(
i -> i == 3 ? "Three" : null,
i -> i == 7 ? "Seven" : null,
i -> i == 11 ? "Eleven" : null,
i -> i == 1 ? "One" : null,
i -> "" + i
)
);
});
}
@Test
public void testMapFirst_6() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Eleven, Twelve), list -> {
assertAsString("[One, 2, Three, 4, Five, 6, Seven, 8, 9, 10, Eleven, 12]",
list
.mapFirst(
i -> i == 3 ? "Three" : null,
i -> i == 7 ? "Seven" : null,
i -> i == 11 ? "Eleven" : null,
i -> i == 1 ? "One" : null,
i -> i == 5 ? "Five" : null,
i -> "" + i
)
);
});
}
//== MapThen ==
@Test
public void testMapThen_2() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1-2, 2-3, 3-4, 4-5, 5-6]",
list
.mapThen(
theInteger,
theInteger.plus(1),
(a, b) -> a + "-" + b)
);
});
}
@Test
public void testMapThen_3() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1-2-3, 2-3-6, 3-4-9, 4-5-12, 5-6-15]",
list
.mapThen(
theInteger,
theInteger.plus(1),
theInteger.time(3),
(a, b, c) -> a + "-" + b + "-" + c)
);
});
}
@Test
public void testMapThen_4() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1-2-3-1, 2-3-6-4, 3-4-9-9, 4-5-12-16, 5-6-15-25]",
list
.mapThen(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square(),
(a, b, c, d) -> a + "-" + b + "-" + c + "-" + d)
);
});
}
@Test
public void testMapThen_5() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1-2-3-1-1, 2-3-6-4-2, 3-4-9-9-6, 4-5-12-16-24, 5-6-15-25-120]",
list
.mapThen(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square(),
theInteger.factorial(),
(a, b, c, d, e) -> a + "-" + b + "-" + c + "-" + d + "-" + e)
);
});
}
@Test
public void testMapThen_6() {
run(IntFuncList.of(One, Two, Three, Four, Five), list -> {
assertAsString(
"[1-2-3-1-1--1, 2-3-6-4-2--2, 3-4-9-9-6--3, 4-5-12-16-24--4, 5-6-15-25-120--5]",
list
.mapThen(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square(),
theInteger.factorial(),
theInteger.negate(),
(a, b, c, d, e, f) -> a + "-" + b + "-" + c + "-" + d + "-" + e + "-" + f)
);
});
}
//-- FuncListWithMapGroup --
// @Test
// public void testMapGroup_specific() {
// run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight), list -> {
// assertAsString(
// "[One:Two, Two:Three, Three:Four, Four:Five, Five:Six, Six:Seven, Seven:Eight]",
// list.mapGroup((a,b) -> a+":"+b));
// assertAsString(
// "[One:Two:Three, Two:Three:Four, Three:Four:Five, Four:Five:Six, Five:Six:Seven, Six:Seven:Eight]",
// list.mapGroup((a,b,c) -> a+":"+b+":"+c));
// assertAsString(
// "[One:Two:Three:Four, Two:Three:Four:Five, Three:Four:Five:Six, Four:Five:Six:Seven, Five:Six:Seven:Eight]",
// list.mapGroup((a,b,c,d) -> a+":"+b+":"+c+":"+d));
// assertAsString(
// "[One:Two:Three:Four:Five, Two:Three:Four:Five:Six, Three:Four:Five:Six:Seven, Four:Five:Six:Seven:Eight]",
// list.mapGroup((a,b,c,d,e) -> a+":"+b+":"+c+":"+d+":"+e));
// assertAsString(
// "[One:Two:Three:Four:Five:Six, Two:Three:Four:Five:Six:Seven, Three:Four:Five:Six:Seven:Eight]",
// list.mapGroup((a,b,c,d,e,f) -> a+":"+b+":"+c+":"+d+":"+e+":"+f));
// });
// }
//
@Test
public void testMapGroup_count() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six), list -> {
ToIntFunction<IntStreamPlus> joiner = intStream -> Integer.parseInt(intStream.mapToString().join());
assertAsString(
"[12, 23, 34, 45, 56]",
list.mapGroup(2, joiner));
assertAsString(
"[123, 234, 345, 456]",
list.mapGroup(3, joiner));
assertAsString(
"[1234, 2345, 3456]",
list.mapGroup(4, joiner));
assertAsString(
"[12345, 23456]",
list.mapGroup(5, joiner));
assertAsString(
"[123456]",
list.mapGroup(6, joiner));
});
}
@Test
public void testMapGroup() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight), list -> {
assertAsString(
"[12, 23, 34, 45, 56, 67, 78]",
list.mapTwo((a, b) -> a*10 + b));
});
}
@Test
public void testMapGroupToInt() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight), list -> {
assertAsString(
"[12, 23, 34, 45, 56, 67, 78]",
list.mapTwoToInt((a, b) -> a*10 + b));
assertAsString(
"[12, 23, 34, 45, 56, 67, 78]",
list.mapGroupToInt(2, ints -> Integer.parseInt(ints.mapToString().join())));
});
}
@Test
public void testMapGroupToDouble() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight), list -> {
assertAsString(
"[12.0, 23.0, 34.0, 45.0, 56.0, 67.0, 78.0]",
list.mapTwoToDouble((a, b) -> a*10 + b));
assertAsString(
"[12.0, 23.0, 34.0, 45.0, 56.0, 67.0, 78.0]",
list.mapGroupToDouble(2, ints -> Integer.parseInt(ints.mapToString().join())));
});
}
@Test
public void testMapGroupToObj() {
run(IntFuncList.of(One, Two, Three, Four, Five, Six, Seven, Eight), list -> {
assertAsString(
"[(1,2), (2,3), (3,4), (4,5), (5,6), (6,7), (7,8)]",
list.mapTwoToObj());
assertAsString(
"[1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8]",
list.mapTwoToObj((a,b) -> a + "-" + b));
assertAsString(
"[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8]]",
list.mapGroupToObj(3).map(IntStreamPlus::toListString));
assertAsString(
"[123, 234, 345, 456, 567, 678]",
list.mapGroupToObj(3, ints -> Integer.parseInt(ints.mapToString().join())));
});
}
//-- FuncListWithMapToMap --
@Test
public void testMapToMap_1() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1}, "
+ "{<1>:3}, "
+ "{<1>:5}, "
+ "{<1>:7}, "
+ "{<1>:11}, "
+ "{<1>:13}, "
+ "{<1>:17}"
+ "]",
list
.mapToMap(
"<1>", theInteger)
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_2() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1}, "
+ "{<1>:3, <2>:-3}, "
+ "{<1>:5, <2>:-5}, "
+ "{<1>:7, <2>:-7}, "
+ "{<1>:11, <2>:-11}, "
+ "{<1>:13, <2>:-13}, "
+ "{<1>:17, <2>:-17}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate())
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_3() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2}, "
+ "{<1>:3, <2>:-3, <3>:4}, "
+ "{<1>:5, <2>:-5, <3>:6}, "
+ "{<1>:7, <2>:-7, <3>:8}, "
+ "{<1>:11, <2>:-11, <3>:12}, "
+ "{<1>:13, <2>:-13, <3>:14}, "
+ "{<1>:17, <2>:-17, <3>:18}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1))
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_4() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2, <4>:-1}, "
+ "{<1>:3, <2>:-3, <3>:4, <4>:1}, "
+ "{<1>:5, <2>:-5, <3>:6, <4>:3}, "
+ "{<1>:7, <2>:-7, <3>:8, <4>:5}, "
+ "{<1>:11, <2>:-11, <3>:12, <4>:9}, "
+ "{<1>:13, <2>:-13, <3>:14, <4>:11}, "
+ "{<1>:17, <2>:-17, <3>:18, <4>:15}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2))
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_5() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3}, "
+ "{<1>:3, <2>:-3, <3>:4, <4>:1, <5>:9}, "
+ "{<1>:5, <2>:-5, <3>:6, <4>:3, <5>:15}, "
+ "{<1>:7, <2>:-7, <3>:8, <4>:5, <5>:21}, "
+ "{<1>:11, <2>:-11, <3>:12, <4>:9, <5>:33}, "
+ "{<1>:13, <2>:-13, <3>:14, <4>:11, <5>:39}, "
+ "{<1>:17, <2>:-17, <3>:18, <4>:15, <5>:51}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3))
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_6() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3, <6>:1}, "
+ "{<1>:3, <2>:-3, <3>:4, <4>:1, <5>:9, <6>:81}, "
+ "{<1>:5, <2>:-5, <3>:6, <4>:3, <5>:15, <6>:625}, "
+ "{<1>:7, <2>:-7, <3>:8, <4>:5, <5>:21, <6>:2401}, "
+ "{<1>:11, <2>:-11, <3>:12, <4>:9, <5>:33, <6>:14641}, "
+ "{<1>:13, <2>:-13, <3>:14, <4>:11, <5>:39, <6>:28561}, "
+ "{<1>:17, <2>:-17, <3>:18, <4>:15, <5>:51, <6>:83521}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3),
"<6>", theInteger.pow(4).asInteger())
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_7() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3, <6>:1, <7>:1}, "
+ "{<1>:3, <2>:-3, <3>:4, <4>:1, <5>:9, <6>:81, <7>:9}, "
+ "{<1>:5, <2>:-5, <3>:6, <4>:3, <5>:15, <6>:625, <7>:25}, "
+ "{<1>:7, <2>:-7, <3>:8, <4>:5, <5>:21, <6>:2401, <7>:49}, "
+ "{<1>:11, <2>:-11, <3>:12, <4>:9, <5>:33, <6>:14641, <7>:121}, "
+ "{<1>:13, <2>:-13, <3>:14, <4>:11, <5>:39, <6>:28561, <7>:169}, "
+ "{<1>:17, <2>:-17, <3>:18, <4>:15, <5>:51, <6>:83521, <7>:289}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3),
"<6>", theInteger.pow(4).asInteger(),
"<7>", theInteger.square())
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_8() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"{<1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3, <6>:1, <7>:1, <8>:1},\n"
+ "{<1>:3, <2>:-3, <3>:4, <4>:1, <5>:9, <6>:81, <7>:9, <8>:2},\n"
+ "{<1>:5, <2>:-5, <3>:6, <4>:3, <5>:15, <6>:625, <7>:25, <8>:2},\n"
+ "{<1>:7, <2>:-7, <3>:8, <4>:5, <5>:21, <6>:2401, <7>:49, <8>:3},\n"
+ "{<1>:11, <2>:-11, <3>:12, <4>:9, <5>:33, <6>:14641, <7>:121, <8>:3},\n"
+ "{<1>:13, <2>:-13, <3>:14, <4>:11, <5>:39, <6>:28561, <7>:169, <8>:4},\n"
+ "{<1>:17, <2>:-17, <3>:18, <4>:15, <5>:51, <6>:83521, <7>:289, <8>:4}",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3),
"<6>", theInteger.pow(4).asInteger(),
"<7>", theInteger.square(),
"<8>", theInteger.squareRoot().asInteger())
.map(map -> map.sorted())
.join(",\n")
);
});
}
@Test
public void testMapToMap_9() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen), list -> {
assertAsString(
"["
+ "{<1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3, <6>:1, <7>:1, <8>:1, <9>:1}, "
+ "{<1>:3, <2>:-3, <3>:4, <4>:1, <5>:9, <6>:81, <7>:9, <8>:2, <9>:6}, "
+ "{<1>:5, <2>:-5, <3>:6, <4>:3, <5>:15, <6>:625, <7>:25, <8>:2, <9>:120}, "
+ "{<1>:7, <2>:-7, <3>:8, <4>:5, <5>:21, <6>:2401, <7>:49, <8>:3, <9>:5040}, "
+ "{<1>:11, <2>:-11, <3>:12, <4>:9, <5>:33, <6>:14641, <7>:121, <8>:3, <9>:39916800}, "
+ "{<1>:13, <2>:-13, <3>:14, <4>:11, <5>:39, <6>:28561, <7>:169, <8>:4, <9>:1932053504}, "
+ "{<1>:17, <2>:-17, <3>:18, <4>:15, <5>:51, <6>:83521, <7>:289, <8>:4, <9>:-288522240}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3),
"<6>", theInteger.pow(4).asInteger(),
"<7>", theInteger.square(),
"<8>", theInteger.squareRoot().asInteger(),
"<9>", theInteger.factorial())
.map(map -> map.sorted())
);
});
}
@Test
public void testMapToMap_10() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven, Thirteen, Seventeen, Nineteen, TwentyThree), list -> {
assertAsString(
"["
+ "{<10>:1, <1>:1, <2>:-1, <3>:2, <4>:-1, <5>:3, <6>:1, <7>:1, <8>:1, <9>:1}, "
+ "{<10>:2, <1>:3, <2>:-3, <3>:4, <4>:1, <5>:9, <6>:81, <7>:9, <8>:2, <9>:6}, "
+ "{<10>:3, <1>:5, <2>:-5, <3>:6, <4>:3, <5>:15, <6>:625, <7>:25, <8>:2, <9>:120}, "
+ "{<10>:4, <1>:7, <2>:-7, <3>:8, <4>:5, <5>:21, <6>:2401, <7>:49, <8>:3, <9>:5040}, "
+ "{<10>:6, <1>:11, <2>:-11, <3>:12, <4>:9, <5>:33, <6>:14641, <7>:121, <8>:3, <9>:39916800}, "
+ "{<10>:7, <1>:13, <2>:-13, <3>:14, <4>:11, <5>:39, <6>:28561, <7>:169, <8>:4, <9>:1932053504}, "
+ "{<10>:9, <1>:17, <2>:-17, <3>:18, <4>:15, <5>:51, <6>:83521, <7>:289, <8>:4, <9>:-288522240}, "
+ "{<10>:10, <1>:19, <2>:-19, <3>:20, <4>:17, <5>:57, <6>:130321, <7>:361, <8>:4, <9>:109641728}, "
+ "{<10>:12, <1>:23, <2>:-23, <3>:24, <4>:21, <5>:69, <6>:279841, <7>:529, <8>:5, <9>:862453760}"
+ "]",
list
.mapToMap(
"<1>", theInteger,
"<2>", theInteger.negate(),
"<3>", theInteger.plus(1),
"<4>", theInteger.minus(2),
"<5>", theInteger.time(3),
"<6>", theInteger.pow(4).asInteger(),
"<7>", theInteger.square(),
"<8>", theInteger.squareRoot().asInteger(),
"<9>", theInteger.factorial(),
"<10>", theInteger.dividedBy(2).asInteger())
.map(map -> map.sorted())
);
});
}
//-- FuncListWithMapToTuple --
@Test
public void testMapToTuple_2() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"["
+ "(1,2), "
+ "(3,4), "
+ "(5,6), "
+ "(7,8), "
+ "(11,12)"
+ "]",
list
.mapToTuple(
theInteger,
theInteger.plus(1))
);
});
}
@Test
public void testMapToTuple_3() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"["
+ "(1,2,3), "
+ "(3,4,9), "
+ "(5,6,15), "
+ "(7,8,21), "
+ "(11,12,33)"
+ "]",
list
.mapToTuple(
theInteger,
theInteger.plus(1),
theInteger.time(3))
);
});
}
@Test
public void testMapToTuple_4() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"["
+ "(1,2,3,1), "
+ "(3,4,9,9), "
+ "(5,6,15,25), "
+ "(7,8,21,49), "
+ "(11,12,33,121)"
+ "]",
list
.mapToTuple(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square())
);
});
}
@Test
public void testMapToTuple_5() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"["
+ "(1,2,3,1,1), "
+ "(3,4,9,9,6), "
+ "(5,6,15,25,120), "
+ "(7,8,21,49,5040), "
+ "(11,12,33,121,39916800)"
+ "]",
list
.mapToTuple(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square(),
theInteger.factorial())
);
});
}
@Test
public void testMapToTuple_6() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"["
+ "(1,2,3,1,1,-1), "
+ "(3,4,9,9,6,-3), "
+ "(5,6,15,25,120,-5), "
+ "(7,8,21,49,5040,-7), "
+ "(11,12,33,121,39916800,-11)"
+ "]",
list
.mapToTuple(
theInteger,
theInteger.plus(1),
theInteger.time(3),
theInteger.square(),
theInteger.factorial(),
theInteger.negate())
);
});
}
//-- StreamPlusWithMapWithIndex --
@Test
public void testMapWithIndex() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"[(0,1), (1,3), (2,5), (3,7), (4,11)]",
list
.mapWithIndex()
);
});
}
@Test
public void testMapWithIndex_combine() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"[1, 13, 25, 37, 411]",
list
.mapWithIndex((i, each) -> Integer.parseInt( i + "" + each))
);
});
}
@Test
public void testMapToObjWithIndex_combine() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"[0: 1, 1: 3, 2: 5, 3: 7, 4: 11]",
list
.mapToObjWithIndex((i, each) -> i + ": " + each)
);
assertAsString(
"[0: 2, 1: 6, 2: 10, 3: 14, 4: 22]",
list
.mapWithIndex(i -> i*2, (i, each) -> i + ": " + each)
);
assertAsString(
"[0: 2, 1: 6, 2: 10, 3: 14, 4: 22]",
list
.mapWithIndex(i -> i*2, (i, each) -> i + ": " + each)
);
assertAsString(
"[0: 2, 1: 6, 2: 10, 3: 14, 4: 22]",
list
.mapToObjWithIndex(i -> "" + i*2, (i, each) -> i + ": " + each)
);
});
}
//-- FuncListWithModify --
@Test
public void testAccumulate() {
run(IntFuncList.of(1, 2, 3, 4, 5), list -> {
assertAsString(
"[1, 3, 6, 10, 15]",
list.accumulate((prev, current) -> prev + current));
assertAsString(
"[1, 12, 123, 1234, 12345]",
list.accumulate((prev, current)->prev*10 + current));
});
}
@Test
public void testRestate() {
run(IntFuncList.wholeNumbers(20).map(i -> i % 5).toFuncList(), list -> {
assertAsString("[0, 1, 2, 3, 4]", list.restate((head, tail) -> tail.filter(x -> x != head)));
});
}
@Test
public void testRestate_sieveOfEratosthenes() {
run(IntFuncList.naturalNumbers(300).filter(theInteger.thatIsNotOne()).toFuncList(), list -> {
assertAsString(
"["
+ "2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, "
+ "101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, "
+ "211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293"
+ "]",
list.restate((head, tail) -> tail.filter(x -> x % head != 0)));
});
}
@Test
public void testSpawn() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val timePrecision = 100;
val first = new AtomicLong(-1);
val logs = new ArrayList<String>();
list
.spawn(i -> TimeFuncs.Sleep(i*timePrecision + 5).thenReturn(i).defer())
.forEach(element -> {
first.compareAndSet(-1, System.currentTimeMillis());
val start = first.get();
val end = System.currentTimeMillis();
val duration = Math.round((end - start)/(1.0 * timePrecision))*timePrecision;
logs.add(element + " -- " + duration);
});
assertEquals("["
+ "Result:{ Value: 2 } -- 0, "
+ "Result:{ Value: 3 } -- " + (1*timePrecision) + ", "
+ "Result:{ Value: 4 } -- " + (2*timePrecision) + ", "
+ "Result:{ Value: 11 } -- " + (9*timePrecision) + ""
+ "]",
logs.toString());
});
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val timePrecision = 100;
val first = new AtomicLong(-1);
val logs = new ArrayList<String>();
list
.spawn(i -> DeferAction.from(() -> {
Thread.sleep(i*timePrecision + 5);
return i;
}))
.forEach(element -> {
first.compareAndSet(-1, System.currentTimeMillis());
val start = first.get();
val end = System.currentTimeMillis();
val duration = Math.round((end - start)/(1.0 * timePrecision))*timePrecision;
logs.add(element + " -- " + duration);
});
assertEquals("["
+ "Result:{ Value: 2 } -- 0, "
+ "Result:{ Value: 3 } -- " + (1*timePrecision) + ", "
+ "Result:{ Value: 4 } -- " + (2*timePrecision) + ", "
+ "Result:{ Value: 11 } -- " + (9*timePrecision) + ""
+ "]",
logs.toString());
});
}
@Test
public void testSpawn_limit() {
run(IntFuncList.of(Two, Three, Four, Eleven), list -> {
val first = new AtomicLong(-1);
val actions = new ArrayList<DeferAction<Integer>>();
val logs = new ArrayList<String>();
list
.spawn(i -> {
DeferAction<Integer> action = Sleep(i*50 + 5).thenReturn(i).defer();
actions.add(action);
return action;
})
.limit(1)
.forEach(element -> {
first.compareAndSet(-1, System.currentTimeMillis());
val start = first.get();
val end = System.currentTimeMillis();
val duration = Math.round((end - start)/50.0)*50;
logs.add(element + " -- " + duration);
});
assertEquals("[Result:{ Value: 2 } -- 0]",
logs.toString());
assertEquals(
"Result:{ Value: 2 }, " +
"Result:{ Cancelled: Stream closed! }, " +
"Result:{ Cancelled: Stream closed! }, " +
"Result:{ Cancelled: Stream closed! }",
actions.stream().map(DeferAction::getResult).map(String::valueOf).collect(Collectors.joining(", ")));
});
}
//-- FuncListWithPeek --
@Test
public void testPeekAs() {
run(IntFuncList.of(0, One, 2, Three, 4, Five), list -> {
val elementStrings = new ArrayList<String>();
list
.peekAs(e -> "<" + e + ">", e -> elementStrings.add(e))
.join() // To terminate the stream
;
assertAsString("[<0>, <1>, <2>, <3>, <4>, <5>]", elementStrings);
});
}
@Test
public void testPeekBy_map() {
run(IntFuncList.of(0, One, 2, Three, 4, Five), list -> {
val elementStrings = new ArrayList<String>();
list
.peekBy(s -> !("" + s).contains("2"), e -> elementStrings.add("" + e))
.join() // To terminate the stream
;
assertAsString("[0, 1, 3, 4, 5]", elementStrings);
elementStrings.clear();
list
.peekBy(e -> "<" + e + ">", s -> !s.contains("2"), e -> elementStrings.add("" + e))
.join() // To terminate the stream
;
assertAsString("[0, 1, 3, 4, 5]", elementStrings);
});
}
@Test
public void testPeekAs_map() {
run(IntFuncList.of(0, One, 2, Three, 4, Five), list -> {
val elementStrings = new ArrayList<String>();
list
.peekAs(e -> "<" + e + ">", s -> !s.contains("2"), e -> elementStrings.add((String)e))
.join() // To terminate the stream
;
assertAsString("[<0>, <1>, <3>, <4>, <5>]", elementStrings);
});
}
//-- FuncListWithPipe --
@Test
public void testPipeable() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"[1, 3, 5, 7, 11]",
list
.pipable()
.pipeTo(IntFuncList::toListString));
});
}
@Test
public void testPipe() {
run(IntFuncList.of(One, Three, Five, Seven, Eleven), list -> {
assertAsString(
"[1, 3, 5, 7, 11]",
list.pipe(IntFuncList::toListString));
});
}
//-- FuncListWithReshape --
@Test
public void testSegment() {
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"["
+ "[0, 1, 2, 3, 4, 5], "
+ "[6, 7, 8, 9, 10, 11], "
+ "[12, 13, 14, 15, 16, 17], "
+ "[18, 19]"
+ "]",
list
.segment(6)
.mapToObj(IntFuncList::toString));
});
}
@Test
public void testSegment_sizeFunction() {
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"["
+ "[1], "
+ "[2, 3], "
+ "[4, 5, 6, 7], "
+ "[8, 9, 10, 11, 12, 13, 14, 15], "
+ "[16, 17, 18, 19]"
+ "]",
list
.segment(i -> i));
});
// Empty
run(IntFuncList.wholeNumbers(0), list -> {
assertAsString(
"[]",
list
.segment(i -> i));
});
// End at exact boundary
run(IntFuncList.wholeNumbers(8), list -> {
assertAsString(
"["
+ "[1], "
+ "[2, 3], "
+ "[4, 5, 6, 7]"
+ "]",
list
.segment(i -> i));
});
}
@Test
public void testSegmentWhen() {
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"["
+ "[0, 1, 2], "
+ "[3, 4, 5], "
+ "[6, 7, 8], "
+ "[9, 10, 11], "
+ "[12, 13, 14], "
+ "[15, 16, 17], "
+ "[18, 19]"
+ "]",
list
.segmentWhen(theInteger.thatIsDivisibleBy(3))
.map (IntFuncList::toListString)
);
});
}
@Test
public void testSegmentAfter() {
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"["
+ "[0], "
+ "[1, 2, 3], "
+ "[4, 5, 6], "
+ "[7, 8, 9], "
+ "[10, 11, 12], "
+ "[13, 14, 15], "
+ "[16, 17, 18], "
+ "[19]"
+ "]",
list
.segmentAfter(theInteger.thatIsDivisibleBy(3))
.map (IntFuncList::toListString)
);
});
}
@Test
public void testSegmentBetween() {
IntPredicate startCondition = i ->(i % 10) == 3;
IntPredicate endCondition = i ->(i % 10) == 6;
run(IntFuncList.wholeNumbers(75), list -> {
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66], "
+ "[73, 74]"
+ "]",
list
.segmentBetween(startCondition, endCondition)
.skip (5)
.limit (3));
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66], "
+ "[73, 74]"
+ "]",
list
.segmentBetween(startCondition, endCondition, true)
.skip (5)
.limit (3));
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66], "
+ "[73, 74]"
+ "]",
list
.segmentBetween(startCondition, endCondition, IncompletedSegment.included)
.skip (5)
.limit (3));
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66]"
+ "]",
list
.segmentBetween(startCondition, endCondition, IncompletedSegment.excluded)
.skip (5)
.limit (3));
});
// Edge cases
// Empty
run(IntFuncList.wholeNumbers(0), list -> {
assertAsString(
"[]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
});
// Not enough
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"[]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
});
// Exact
run(IntFuncList.wholeNumbers(67), list -> {
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
});
// Exact - 1
run(IntFuncList.wholeNumbers(66), list -> {
assertAsString(
"["
+ "[53, 54, 55, 56]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
});
// Exact + 1
run(IntFuncList.wholeNumbers(68), list -> {
assertAsString(
"["
+ "[53, 54, 55, 56], "
+ "[63, 64, 65, 66]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false)
.skip (5)
.limit (3));
});
// From start
run(IntFuncList.wholeNumbers(30), list -> {
assertAsString(
"["
+ "[3, 4, 5, 6], "
+ "[13, 14, 15, 16], "
+ "[23, 24, 25, 26]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false));
});
// Incomplete start
run(IntFuncList.wholeNumbers(30).skip(5), list -> {
assertAsString(
"["
+ "[13, 14, 15, 16], "
+ "[23, 24, 25, 26]"
+ "]",
list
.segmentBetween(startCondition, endCondition, false));
});
}
@Test
public void testSegmentByPercentiles() {
run(IntFuncList.wholeNumbers(50).toFuncList(), list -> {
assertAsString(
"[" +
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], " +
"[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], " +
"[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" +
"]", list.segmentByPercentiles(30, 80));
assertAsString(
"[" +
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], " +
"[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], " +
"[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" +
"]", list.segmentByPercentiles(30.0, 80.0));
assertAsString(
"[" +
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], " +
"[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], " +
"[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" +
"]", list.segmentByPercentiles(IntFuncList .of(30, 80)));
assertAsString(
"[" +
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], " +
"[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], " +
"[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]" +
"]", list.segmentByPercentiles(DoubleFuncList.of(30.0, 80.0)));
});
}
@Test
public void testSegmentByPercentiles_mapper() {
run(IntFuncList.wholeNumbers(50), list -> {
assertAsString(
"["
+ "[49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35], "
+ "[34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], "
+ "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, 30, 80));
assertAsString(
"["
+ "[49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35], "
+ "[34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], "
+ "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, 30.0, 80.0));
assertAsString(
"["
+ "[49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35], "
+ "[34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], "
+ "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, IntFuncList.of(30, 80)));
assertAsString(
"["
+ "[49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35], "
+ "[34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10], "
+ "[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, DoubleFuncList.of(30.0, 80.0)));
});
}
@Test
public void testSegmentByPercentiles_mapper_comparator() {
run(IntFuncList.wholeNumbers(50).toFuncList(), list -> {
assertAsString(
"["
+ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], "
+ "[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], "
+ "[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, (a, b) -> b - a, 30, 80));
assertAsString(
"["
+ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], "
+ "[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], "
+ "[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, (a, b) -> b - a, 30.0, 80.0));
assertAsString(
"["
+ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], "
+ "[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], "
+ "[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, (a, b) -> b - a, IntFuncList .of(30, 80)));
assertAsString(
"["
+ "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], "
+ "[15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39], "
+ "[40, 41, 42, 43, 44, 45, 46, 47, 48, 49]"
+ "]",
list.segmentByPercentiles(x -> 100 - x, (a, b) -> b - a, DoubleFuncList.of(30.0, 80.0)));
});
}
//-- FuncListWithSort --
@Test
public void testSortedBy() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString(
"[1, 2, 3, 4]",
list.sortedBy(theInteger.plus(2).square()));
});
}
@Test
public void testSortedByComparator() {
run(IntFuncList.of(One, Two, Three, Four), list -> {
assertAsString(
"[4, 3, 2, 1]",
list.sortedBy(
i -> (i + 2)*(i + 2),
(a,b)->b-a));
// Using comparable access.
assertAsString(
"[4, 3, 2, 1]",
list.sortedBy(
theInteger.plus(2).square(),
(a,b)->b-a));
});
}
//-- FuncListWithSplit --
@Test
public void testSplitTuple() {
run(IntFuncList.wholeNumbers(20).toFuncList(), list -> {
assertAsString(
"("
+ "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18],"
+ "[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]"
+ ")",
list
.split(theInteger.thatIsDivisibleBy(2))
.toString());
});
}
@Test
public void testSplit() {
run(IntFuncList.wholeNumbers(20), list -> {
String Other = "Other";
assertAsString(
"{"
+ "Other:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
Other)
.sorted()
.toString());
assertAsString(
"{"
+ "Other:[1, 5, 7, 11, 13, 17, 19], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
Other)
.sorted()
.toString());
assertAsString(
"{"
+ "Five:[5], "
+ "Other:[1, 7, 11, 13, 17, 19], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
Other)
.sorted()
.toString());
assertAsString(
"{"
+ "Five:[5], "
+ "Seven:[7], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18], "
+ "Three:[3, 9, 15], "
+ "Other:[1, 11, 13, 17, 19]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
"Seven", theInteger.thatIsDivisibleBy(7),
Other)
.toString());
assertAsString(
"{"
+ "Eleven:[11], "
+ "Five:[5], "
+ "Other:[1, 13, 17, 19], "
+ "Seven:[7], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
"Seven", theInteger.thatIsDivisibleBy(7),
"Eleven", theInteger.thatIsDivisibleBy(11),
Other)
.sorted()
.toString());
// Ignore some values
assertAsString(
"{"
+ "Eleven:[11], "
+ "Five:[5], "
+ "Other:[1, 13, 17, 19], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
null, theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
null, theInteger.thatIsDivisibleBy(7),
"Eleven", theInteger.thatIsDivisibleBy(11),
Other)
.sorted()
.toString());
// Ignore others
assertAsString(
"{"
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3))
.sorted()
.toString());
assertAsString(
"{"
+ "Five:[5], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5))
.sorted()
.toString());
assertAsString(
"{"
+ "Five:[5], "
+ "Seven:[7], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
"Seven", theInteger.thatIsDivisibleBy(7))
.sorted()
.toString());
assertAsString(
"{"
+ "Eleven:[11], "
+ "Five:[5], "
+ "Seven:[7], "
+ "Three:[3, 9, 15], Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
"Seven", theInteger.thatIsDivisibleBy(7),
"Eleven", theInteger.thatIsDivisibleBy(11))
.sorted()
.toString());
assertAsString(
"{"
+ "Eleven:[11], "
+ "Five:[5], "
+ "Seven:[7], "
+ "Thirteen:[13], "
+ "Three:[3, 9, 15], "
+ "Two:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
+ "}",
list
.split("Two", theInteger.thatIsDivisibleBy(2),
"Three", theInteger.thatIsDivisibleBy(3),
"Five", theInteger.thatIsDivisibleBy(5),
"Seven", theInteger.thatIsDivisibleBy(7),
"Eleven", theInteger.thatIsDivisibleBy(11),
"Thirteen", theInteger.thatIsDivisibleBy(13))
.sorted()
.toString());
});
}
@Test
public void testSplit_ignore() {
run(IntFuncList.wholeNumbers(20), list -> {
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null)
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null)
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null)
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null, theInteger.thatIsDivisibleBy(7),
(String)null)
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null, theInteger.thatIsDivisibleBy(7),
(String)null, theInteger.thatIsDivisibleBy(11),
(String)null)
.sorted()
.toString());
// No other
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2))
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3))
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5))
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null, theInteger.thatIsDivisibleBy(7))
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null, theInteger.thatIsDivisibleBy(7),
(String)null, theInteger.thatIsDivisibleBy(11))
.sorted()
.toString());
assertAsString(
"{}",
list
.split((String)null, theInteger.thatIsDivisibleBy(2),
(String)null, theInteger.thatIsDivisibleBy(3),
(String)null, theInteger.thatIsDivisibleBy(5),
(String)null, theInteger.thatIsDivisibleBy(7),
(String)null, theInteger.thatIsDivisibleBy(11),
(String)null, theInteger.thatIsDivisibleBy(13))
.sorted()
.toString());
});
}
@Test
public void testFizzBuzz() {
Function<IntFuncList, IntFuncList> listToList = s -> s.toImmutableList();
run(IntFuncList.wholeNumbers(20), list -> {
String toString = With(FuncMap.underlineMap.butWith(FuncMap.UnderlineMap.LinkedHashMap))
.run(() -> {
FuncMap<String, IntFuncList> splited
= list
.split(
"FizzBuzz", i -> i % (3*5) == 0,
"Buzz", i -> i % 5 == 0,
"Fizz", i -> i % 3 == 0,
null);
val string
= splited
.mapValue(listToList)
.toString();
return string;
});
assertEquals(
"{"
+ "FizzBuzz:[0, 15], "
+ "Buzz:[5, 10], "
+ "Fizz:[3, 6, 9, 12, 18]"
+ "}",
toString);
});
}
}
| 38.091441 | 167 | 0.433792 |
1bd47e4fbd554159dd9cb8a26bf62cbc960fe460 | 198 | package seedu.planner.model.module;
/**
* Class to represent a Laboratory-type Lesson.
*/
public class Laboratory extends Lesson {
public ModuleTime getTime() {
return null;
}
}
| 16.5 | 47 | 0.676768 |
08fc1fe871ccfbf653f5877a808e426a4c4872a0 | 21,951 | /*
* This file is generated by jOOQ.
*/
package cn.vertxup.ambient.domain.tables.records;
import cn.vertxup.ambient.domain.tables.XEmailServer;
import cn.vertxup.ambient.domain.tables.interfaces.IXEmailServer;
import io.github.jklingsporn.vertx.jooq.shared.internal.VertxPojo;
import java.time.LocalDateTime;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record19;
import org.jooq.Row19;
import org.jooq.impl.UpdatableRecordImpl;
import static io.github.jklingsporn.vertx.jooq.shared.internal.VertxPojo.*;
/**
* This class is generated by jOOQ.
*/
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class XEmailServerRecord extends UpdatableRecordImpl<XEmailServerRecord> implements VertxPojo, Record19<String, String, String, String, String, Integer, String, String, String, String, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime, String>, IXEmailServer {
private static final long serialVersionUID = 1L;
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.KEY</code>. 「key」- 邮件服务器主键
*/
@Override
public XEmailServerRecord setKey(String value) {
set(0, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.KEY</code>. 「key」- 邮件服务器主键
*/
@Override
public String getKey() {
return (String) get(0);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.NAME</code>. 「name」- 邮件服务器名称
*/
@Override
public XEmailServerRecord setName(String value) {
set(1, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.NAME</code>. 「name」- 邮件服务器名称
*/
@Override
public String getName() {
return (String) get(1);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.IP_V4</code>. 「ipV4」- IP v4地址
*/
@Override
public XEmailServerRecord setIpV4(String value) {
set(2, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.IP_V4</code>. 「ipV4」- IP v4地址
*/
@Override
public String getIpV4() {
return (String) get(2);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.IP_V6</code>. 「ipV6」- IP v6地址
*/
@Override
public XEmailServerRecord setIpV6(String value) {
set(3, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.IP_V6</code>. 「ipV6」- IP v6地址
*/
@Override
public String getIpV6() {
return (String) get(3);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.HOSTNAME</code>. 「hostname」-
* 主机地址
*/
@Override
public XEmailServerRecord setHostname(String value) {
set(4, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.HOSTNAME</code>. 「hostname」-
* 主机地址
*/
@Override
public String getHostname() {
return (String) get(4);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.PORT</code>. 「port」- 端口号
*/
@Override
public XEmailServerRecord setPort(Integer value) {
set(5, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.PORT</code>. 「port」- 端口号
*/
@Override
public Integer getPort() {
return (Integer) get(5);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.PROTOCOL</code>.
* 「protocol」协议类型,POP3, STMP 等
*/
@Override
public XEmailServerRecord setProtocol(String value) {
set(6, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.PROTOCOL</code>.
* 「protocol」协议类型,POP3, STMP 等
*/
@Override
public String getProtocol() {
return (String) get(6);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.SENDER</code>. 「sender」- 发送者账号
*/
@Override
public XEmailServerRecord setSender(String value) {
set(7, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.SENDER</code>. 「sender」- 发送者账号
*/
@Override
public String getSender() {
return (String) get(7);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.PASSWORD</code>. 「password」-
* 口令
*/
@Override
public XEmailServerRecord setPassword(String value) {
set(8, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.PASSWORD</code>. 「password」-
* 口令
*/
@Override
public String getPassword() {
return (String) get(8);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.OPTIONS</code>. 「options」-
* 连接字符串中的配置key=value
*/
@Override
public XEmailServerRecord setOptions(String value) {
set(9, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.OPTIONS</code>. 「options」-
* 连接字符串中的配置key=value
*/
@Override
public String getOptions() {
return (String) get(9);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.APP_ID</code>. 「appId」- 所属应用ID
*/
@Override
public XEmailServerRecord setAppId(String value) {
set(10, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.APP_ID</code>. 「appId」- 所属应用ID
*/
@Override
public String getAppId() {
return (String) get(10);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.ACTIVE</code>. 「active」- 是否启用
*/
@Override
public XEmailServerRecord setActive(Boolean value) {
set(11, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.ACTIVE</code>. 「active」- 是否启用
*/
@Override
public Boolean getActive() {
return (Boolean) get(11);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.SIGMA</code>. 「sigma」- 统一标识
*/
@Override
public XEmailServerRecord setSigma(String value) {
set(12, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.SIGMA</code>. 「sigma」- 统一标识
*/
@Override
public String getSigma() {
return (String) get(12);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.METADATA</code>. 「metadata」-
* 附加配置
*/
@Override
public XEmailServerRecord setMetadata(String value) {
set(13, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.METADATA</code>. 「metadata」-
* 附加配置
*/
@Override
public String getMetadata() {
return (String) get(13);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.LANGUAGE</code>. 「language」-
* 使用的语言
*/
@Override
public XEmailServerRecord setLanguage(String value) {
set(14, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.LANGUAGE</code>. 「language」-
* 使用的语言
*/
@Override
public String getLanguage() {
return (String) get(14);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.CREATED_AT</code>.
* 「createdAt」- 创建时间
*/
@Override
public XEmailServerRecord setCreatedAt(LocalDateTime value) {
set(15, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.CREATED_AT</code>.
* 「createdAt」- 创建时间
*/
@Override
public LocalDateTime getCreatedAt() {
return (LocalDateTime) get(15);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.CREATED_BY</code>.
* 「createdBy」- 创建人
*/
@Override
public XEmailServerRecord setCreatedBy(String value) {
set(16, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.CREATED_BY</code>.
* 「createdBy」- 创建人
*/
@Override
public String getCreatedBy() {
return (String) get(16);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.UPDATED_AT</code>.
* 「updatedAt」- 更新时间
*/
@Override
public XEmailServerRecord setUpdatedAt(LocalDateTime value) {
set(17, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.UPDATED_AT</code>.
* 「updatedAt」- 更新时间
*/
@Override
public LocalDateTime getUpdatedAt() {
return (LocalDateTime) get(17);
}
/**
* Setter for <code>DB_ETERNAL.X_EMAIL_SERVER.UPDATED_BY</code>.
* 「updatedBy」- 更新人
*/
@Override
public XEmailServerRecord setUpdatedBy(String value) {
set(18, value);
return this;
}
/**
* Getter for <code>DB_ETERNAL.X_EMAIL_SERVER.UPDATED_BY</code>.
* 「updatedBy」- 更新人
*/
@Override
public String getUpdatedBy() {
return (String) get(18);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<String> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record19 type implementation
// -------------------------------------------------------------------------
@Override
public Row19<String, String, String, String, String, Integer, String, String, String, String, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime, String> fieldsRow() {
return (Row19) super.fieldsRow();
}
@Override
public Row19<String, String, String, String, String, Integer, String, String, String, String, String, Boolean, String, String, String, LocalDateTime, String, LocalDateTime, String> valuesRow() {
return (Row19) super.valuesRow();
}
@Override
public Field<String> field1() {
return XEmailServer.X_EMAIL_SERVER.KEY;
}
@Override
public Field<String> field2() {
return XEmailServer.X_EMAIL_SERVER.NAME;
}
@Override
public Field<String> field3() {
return XEmailServer.X_EMAIL_SERVER.IP_V4;
}
@Override
public Field<String> field4() {
return XEmailServer.X_EMAIL_SERVER.IP_V6;
}
@Override
public Field<String> field5() {
return XEmailServer.X_EMAIL_SERVER.HOSTNAME;
}
@Override
public Field<Integer> field6() {
return XEmailServer.X_EMAIL_SERVER.PORT;
}
@Override
public Field<String> field7() {
return XEmailServer.X_EMAIL_SERVER.PROTOCOL;
}
@Override
public Field<String> field8() {
return XEmailServer.X_EMAIL_SERVER.SENDER;
}
@Override
public Field<String> field9() {
return XEmailServer.X_EMAIL_SERVER.PASSWORD;
}
@Override
public Field<String> field10() {
return XEmailServer.X_EMAIL_SERVER.OPTIONS;
}
@Override
public Field<String> field11() {
return XEmailServer.X_EMAIL_SERVER.APP_ID;
}
@Override
public Field<Boolean> field12() {
return XEmailServer.X_EMAIL_SERVER.ACTIVE;
}
@Override
public Field<String> field13() {
return XEmailServer.X_EMAIL_SERVER.SIGMA;
}
@Override
public Field<String> field14() {
return XEmailServer.X_EMAIL_SERVER.METADATA;
}
@Override
public Field<String> field15() {
return XEmailServer.X_EMAIL_SERVER.LANGUAGE;
}
@Override
public Field<LocalDateTime> field16() {
return XEmailServer.X_EMAIL_SERVER.CREATED_AT;
}
@Override
public Field<String> field17() {
return XEmailServer.X_EMAIL_SERVER.CREATED_BY;
}
@Override
public Field<LocalDateTime> field18() {
return XEmailServer.X_EMAIL_SERVER.UPDATED_AT;
}
@Override
public Field<String> field19() {
return XEmailServer.X_EMAIL_SERVER.UPDATED_BY;
}
@Override
public String component1() {
return getKey();
}
@Override
public String component2() {
return getName();
}
@Override
public String component3() {
return getIpV4();
}
@Override
public String component4() {
return getIpV6();
}
@Override
public String component5() {
return getHostname();
}
@Override
public Integer component6() {
return getPort();
}
@Override
public String component7() {
return getProtocol();
}
@Override
public String component8() {
return getSender();
}
@Override
public String component9() {
return getPassword();
}
@Override
public String component10() {
return getOptions();
}
@Override
public String component11() {
return getAppId();
}
@Override
public Boolean component12() {
return getActive();
}
@Override
public String component13() {
return getSigma();
}
@Override
public String component14() {
return getMetadata();
}
@Override
public String component15() {
return getLanguage();
}
@Override
public LocalDateTime component16() {
return getCreatedAt();
}
@Override
public String component17() {
return getCreatedBy();
}
@Override
public LocalDateTime component18() {
return getUpdatedAt();
}
@Override
public String component19() {
return getUpdatedBy();
}
@Override
public String value1() {
return getKey();
}
@Override
public String value2() {
return getName();
}
@Override
public String value3() {
return getIpV4();
}
@Override
public String value4() {
return getIpV6();
}
@Override
public String value5() {
return getHostname();
}
@Override
public Integer value6() {
return getPort();
}
@Override
public String value7() {
return getProtocol();
}
@Override
public String value8() {
return getSender();
}
@Override
public String value9() {
return getPassword();
}
@Override
public String value10() {
return getOptions();
}
@Override
public String value11() {
return getAppId();
}
@Override
public Boolean value12() {
return getActive();
}
@Override
public String value13() {
return getSigma();
}
@Override
public String value14() {
return getMetadata();
}
@Override
public String value15() {
return getLanguage();
}
@Override
public LocalDateTime value16() {
return getCreatedAt();
}
@Override
public String value17() {
return getCreatedBy();
}
@Override
public LocalDateTime value18() {
return getUpdatedAt();
}
@Override
public String value19() {
return getUpdatedBy();
}
@Override
public XEmailServerRecord value1(String value) {
setKey(value);
return this;
}
@Override
public XEmailServerRecord value2(String value) {
setName(value);
return this;
}
@Override
public XEmailServerRecord value3(String value) {
setIpV4(value);
return this;
}
@Override
public XEmailServerRecord value4(String value) {
setIpV6(value);
return this;
}
@Override
public XEmailServerRecord value5(String value) {
setHostname(value);
return this;
}
@Override
public XEmailServerRecord value6(Integer value) {
setPort(value);
return this;
}
@Override
public XEmailServerRecord value7(String value) {
setProtocol(value);
return this;
}
@Override
public XEmailServerRecord value8(String value) {
setSender(value);
return this;
}
@Override
public XEmailServerRecord value9(String value) {
setPassword(value);
return this;
}
@Override
public XEmailServerRecord value10(String value) {
setOptions(value);
return this;
}
@Override
public XEmailServerRecord value11(String value) {
setAppId(value);
return this;
}
@Override
public XEmailServerRecord value12(Boolean value) {
setActive(value);
return this;
}
@Override
public XEmailServerRecord value13(String value) {
setSigma(value);
return this;
}
@Override
public XEmailServerRecord value14(String value) {
setMetadata(value);
return this;
}
@Override
public XEmailServerRecord value15(String value) {
setLanguage(value);
return this;
}
@Override
public XEmailServerRecord value16(LocalDateTime value) {
setCreatedAt(value);
return this;
}
@Override
public XEmailServerRecord value17(String value) {
setCreatedBy(value);
return this;
}
@Override
public XEmailServerRecord value18(LocalDateTime value) {
setUpdatedAt(value);
return this;
}
@Override
public XEmailServerRecord value19(String value) {
setUpdatedBy(value);
return this;
}
@Override
public XEmailServerRecord values(String value1, String value2, String value3, String value4, String value5, Integer value6, String value7, String value8, String value9, String value10, String value11, Boolean value12, String value13, String value14, String value15, LocalDateTime value16, String value17, LocalDateTime value18, String value19) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
value9(value9);
value10(value10);
value11(value11);
value12(value12);
value13(value13);
value14(value14);
value15(value15);
value16(value16);
value17(value17);
value18(value18);
value19(value19);
return this;
}
// -------------------------------------------------------------------------
// FROM and INTO
// -------------------------------------------------------------------------
@Override
public void from(IXEmailServer from) {
setKey(from.getKey());
setName(from.getName());
setIpV4(from.getIpV4());
setIpV6(from.getIpV6());
setHostname(from.getHostname());
setPort(from.getPort());
setProtocol(from.getProtocol());
setSender(from.getSender());
setPassword(from.getPassword());
setOptions(from.getOptions());
setAppId(from.getAppId());
setActive(from.getActive());
setSigma(from.getSigma());
setMetadata(from.getMetadata());
setLanguage(from.getLanguage());
setCreatedAt(from.getCreatedAt());
setCreatedBy(from.getCreatedBy());
setUpdatedAt(from.getUpdatedAt());
setUpdatedBy(from.getUpdatedBy());
}
@Override
public <E extends IXEmailServer> E into(E into) {
into.from(this);
return into;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached XEmailServerRecord
*/
public XEmailServerRecord() {
super(XEmailServer.X_EMAIL_SERVER);
}
/**
* Create a detached, initialised XEmailServerRecord
*/
public XEmailServerRecord(String key, String name, String ipV4, String ipV6, String hostname, Integer port, String protocol, String sender, String password, String options, String appId, Boolean active, String sigma, String metadata, String language, LocalDateTime createdAt, String createdBy, LocalDateTime updatedAt, String updatedBy) {
super(XEmailServer.X_EMAIL_SERVER);
setKey(key);
setName(name);
setIpV4(ipV4);
setIpV6(ipV6);
setHostname(hostname);
setPort(port);
setProtocol(protocol);
setSender(sender);
setPassword(password);
setOptions(options);
setAppId(appId);
setActive(active);
setSigma(sigma);
setMetadata(metadata);
setLanguage(language);
setCreatedAt(createdAt);
setCreatedBy(createdBy);
setUpdatedAt(updatedAt);
setUpdatedBy(updatedBy);
}
/**
* Create a detached, initialised XEmailServerRecord
*/
public XEmailServerRecord(cn.vertxup.ambient.domain.tables.pojos.XEmailServer value) {
super(XEmailServer.X_EMAIL_SERVER);
if (value != null) {
setKey(value.getKey());
setName(value.getName());
setIpV4(value.getIpV4());
setIpV6(value.getIpV6());
setHostname(value.getHostname());
setPort(value.getPort());
setProtocol(value.getProtocol());
setSender(value.getSender());
setPassword(value.getPassword());
setOptions(value.getOptions());
setAppId(value.getAppId());
setActive(value.getActive());
setSigma(value.getSigma());
setMetadata(value.getMetadata());
setLanguage(value.getLanguage());
setCreatedAt(value.getCreatedAt());
setCreatedBy(value.getCreatedBy());
setUpdatedAt(value.getUpdatedAt());
setUpdatedBy(value.getUpdatedBy());
}
}
public XEmailServerRecord(io.vertx.core.json.JsonObject json) {
this();
fromJson(json);
}
}
| 23.756494 | 349 | 0.585076 |
98dea07424fb2037e4a33f9cbce6ebc0c94343b1 | 5,825 | /*****************************************************************************
* 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. *
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* Patrick Niemeyer ([email protected]) *
* Author of Learning Java, O'Reilly & Associates *
* *
*****************************************************************************/
package bsh;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import static bsh.TestUtil.eval;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(FilteredTestRunner.class)
@Category(ProjectCoinFeature.class)
public class Project_Coin_Test {
@Test
@Category(ProjectCoinFeature.class)
public void integer_literal_enhancements() throws Exception {
final Interpreter interpreter = new Interpreter();
assertEquals("0x99", 153, interpreter.eval("return 0x99;"));
assertEquals("0231", 153, interpreter.eval("return 0231;"));
assertEquals("0b10011001", 153, interpreter.eval("return 0b10011001;"));
assertEquals("0b_1001_1001", 153, interpreter.eval("return 0b_1001_1001;"));
assertEquals("0x_9_9", 153, interpreter.eval("return 0x_9_9;"));
assertEquals("15_500_000_000L", 15500000000L, interpreter.eval("return 15_500_000_000L;"));
}
@Test
@Category(ProjectCoinFeature.class)
public void diamond_operator() throws Exception {
eval("List<String> list = new ArrayList<>()");
final Object anagrams = eval(
"Map<String, List<String>> anagrams = new HashMap<>();" +
"return anagrams;");
assertNotNull(anagrams);
assertTrue(anagrams.getClass().getName(), anagrams instanceof HashMap);
}
@SuppressWarnings({"JUnitTestMethodWithNoAssertions"})
@Test
@Category(Project_Coin_Test.class)
public void try_with_resource_parsing() throws Exception {
eval(
"try {",
" ByteArrayOutputStream x = new ByteArrayOutputStream();",
"} catch (Exception e) {",
"}\n"
);
eval(
"try {",
" ByteArrayOutputStream x = new ByteArrayOutputStream(); ByteArrayOutputStream y = new ByteArrayOutputStream();",
"} catch (Exception e) {",
"}\n"
);
eval(
"try {",
" x = new ByteArrayOutputStream(); y = new ByteArrayOutputStream();",
"} catch (Exception e) {",
"}\n"
);
}
@Test
@Category(Project_Coin_Test.class)
public void try_with_resource() throws Exception {
final Interpreter interpreter = new Interpreter();
final AtomicBoolean closed = new AtomicBoolean(false);
final IOException fromWrite = new IOException("exception from write");
final IOException fromClose = new IOException("exception from close");
final OutputStream autoclosable = new OutputStream() {
@Override
public void write(final int b) throws IOException {
throw fromWrite;
}
@Override
public void close() throws IOException {
closed.set(true);
throw fromClose;
}
};
try {
interpreter.set("autoclosable", autoclosable);
interpreter.eval(
"try {\n" +
" x = new BufferedOutputStream(autoclosable);\n" +
" x.write(42);\n" +
"} catch (Exception e) {\n" +
" thrownException = e;\n" +
"}\n"
);
fail("expected exception");
} catch (final EvalError evalError) {
if (evalError instanceof ParseException) {
throw evalError;
}
final Throwable e = evalError.getCause();
assertSame(fromWrite, e);
interpreter.set("exception", e);
final Object suppressed = interpreter.eval("return exception.getSuppressed();"); // avoid java 7 syntax in java code ;)
assertSame(fromClose, suppressed);
}
assertTrue("stream should be closed", closed.get());
}
@Test
@Category(Project_Coin_Test.class)
public void switch_on_strings() throws Exception {
final Object result = eval(
"switch(\"hurz\") {\n",
" case \"bla\": return 1;",
" case \"foo\": return 2;",
" case \"hurz\": return 3;",
" case \"igss\": return 4;",
" default: return 5;",
"}\n");
assertEquals(result, 3);
}
}
| 36.40625 | 122 | 0.601717 |
bc1d70d08d22ab1b9d1169b877f6b0b6c258ce8d | 917 | package example.spring.filter;
import example.spring.ApplicationStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class ApplicationStatusInterceptor extends HandlerInterceptorAdapter {
private final ApplicationStatus status;
@Autowired
public ApplicationStatusInterceptor(ApplicationStatus status) {
this.status = status;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!status.ready()) {
response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return false;
}
return true;
}
}
| 30.566667 | 121 | 0.769902 |
34ff5e0696810d2a5ef63ac5d3c3c71d38eacc98 | 1,249 | package com.oceanbase.foldermonitor.executor;
import lombok.Getter;
import org.springframework.util.StreamUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
/**
* @Author: Knox
* @Date: 2020/5/31 11:41 上午
* @Description: You Know
* @Version 1.0
*/
public abstract class AbstractFolderSpaceComputer implements FolderSpaceComputer {
@Getter
private final String normalDirSpaceInstruction = "du -s %s | awk '{print $1}'";
@Override
public double usedSpace(Path path) {
try {
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c",
String.format(getNormalDirSpaceInstruction(), path.toFile().getAbsolutePath()));
Process process = builder.start();
return Double.parseDouble(StreamUtils.copyToString(process.getInputStream(), StandardCharsets.UTF_8));
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
@Override
public double diskFreeSpace(Path path) {
return 0;
}
@Override
public String diskName(Path path) {
return null;
}
@Override
public double diskTotalSpace(Path path) {
return 0;
}
}
| 25.489796 | 114 | 0.651721 |
5cbb8863ba475bd20459659efd26f6c748f84882 | 386 | package me.inassar.didemo.services.impl;
import me.inassar.didemo.services.interfaces.GreetingService;
import org.springframework.stereotype.Service;
@Service
public class GreetingServiceImpl implements GreetingService {
public static final String HELLO_NASSAR = "Hello Nassar!! - Original";
@Override
public String sayGreetings() {
return HELLO_NASSAR;
}
}
| 24.125 | 74 | 0.764249 |
aedaf5b95118e153ddaa3434abaa67ae6defe8da | 191 | package ro.ase.csie.cts.g1067.seminar14.state;
public class StareNormala implements InterfataStareSuperErou{
@Override
public void deplasare() {
System.out.println("Alearga !");
}
}
| 17.363636 | 61 | 0.753927 |
a523e7ea1bbd36ee6348ee7d1b908dc694100c47 | 828 | package authzplay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.AuditAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.CacheStatisticsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.TraceWebFilterAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(exclude = {TraceWebFilterAutoConfiguration.class, MetricFilterAutoConfiguration.class,
AuditAutoConfiguration.class, CacheStatisticsAutoConfiguration.class})
public class WebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(WebApplication.class, args);
}
}
| 46 | 109 | 0.850242 |
aa688859445c5d4073e55a24a7a178e8d8670741 | 5,569 | package io.opensphere.featureactions.editor.ui;
import java.util.List;
import javafx.scene.control.ListCell;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import io.opensphere.featureactions.editor.model.SimpleFeatureAction;
import io.opensphere.featureactions.editor.model.SimpleFeatureActionGroup;
import io.opensphere.featureactions.editor.model.SimpleFeatureActions;
/**
* Handles the dragging and dropping of items from list views to other list
* views.
*/
public class DragDropHandler
{
/**
* The index of the item being dragged.
*/
private static int myDragIndex = -1;
/**
* The row being dragged.
*/
private SimpleFeatureAction myDragAction;
/**
* The group being dragged.
*/
private SimpleFeatureActionGroup myDragGroup;
/**
* The list the drag item is coming from.
*/
private List<SimpleFeatureAction> myListSource;
/**
* The main accordion.
*/
private final SimpleFeatureActions myMainModel;
/**
* Constructs a new drag and drop handler.
*
* @param mainModel The main model containing all groups and actions.
*/
public DragDropHandler(SimpleFeatureActions mainModel)
{
myMainModel = mainModel;
}
/**
* Starts listening to drag and drop of the passed in cell.
*
* @param group The group this cell belongs too.
* @param cell The cell to potentially handle drag and drop for.
*/
public void handleNewCell(SimpleFeatureActionGroup group, ListCell<SimpleFeatureAction> cell)
{
cell.setOnDragDetected(event ->
{
if (!cell.isEmpty())
{
Dragboard db = cell.startDragAndDrop(TransferMode.COPY_OR_MOVE);
ClipboardContent cc = new ClipboardContent();
cc.putString(cell.getItem().toString());
db.setContent(cc);
myDragIndex = cell.getIndex();
myListSource = group.getActions();
myDragAction = cell.getItem();
}
});
cell.setOnDragOver(event ->
{
Dragboard db = event.getDragboard();
if (db.hasString())
{
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
});
cell.setOnDragDropped(event ->
{
Dragboard db = event.getDragboard();
if (db.hasString() && myDragAction != null)
{
SimpleFeatureAction action = myDragAction;
SimpleFeatureAction cellAction = cell.getItem();
group.getActions().remove(myDragIndex);
if (cellAction == null)
{
group.getActions().add(action);
}
else
{
int featureIndex = group.getActions().indexOf(cellAction);
featureIndex += featureIndex < myDragIndex ? 0 : 1;
group.getActions().add(featureIndex, action);
}
event.setDropCompleted(true);
myDragAction = null;
}
else
{
event.setDropCompleted(false);
}
});
}
/**
* Handles dragging and dropping actions to other groups.
*
* @param pane The titled pane representing a feature action group.
* @param group The group the pane represents.
*/
public void handlePane(FeatureActionTitledPane pane, SimpleFeatureActionGroup group)
{
pane.setOnDragDetected(event ->
{
Dragboard db = pane.startDragAndDrop(TransferMode.COPY_OR_MOVE);
ClipboardContent cc = new ClipboardContent();
cc.putString(pane.toString());
db.setContent(cc);
myDragIndex = myMainModel.getFeatureGroups().indexOf(group);
myListSource = group.getActions();
myDragGroup = group;
});
pane.setOnDragOver(event ->
{
Dragboard db = event.getDragboard();
if (db.hasString())
{
event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
});
pane.setOnDragDropped(event ->
{
Dragboard db = event.getDragboard();
if (db.hasString())
{
if (myDragAction != null)
{
SimpleFeatureAction action = myDragAction;
myListSource.remove(myDragIndex);
group.getActions().add(action);
event.setDropCompleted(true);
myDragAction = null;
}
else if (myDragGroup != null)
{
int newIndex = myMainModel.getFeatureGroups().indexOf(group);
myMainModel.getFeatureGroups().remove(myDragIndex);
myMainModel.getFeatureGroups().add(newIndex, myDragGroup);
event.setDropCompleted(true);
myDragGroup = null;
}
}
else
{
event.setDropCompleted(false);
}
});
}
}
| 31.642045 | 98 | 0.530795 |
8c25888d9df4e4a02a31ccc6fe5b175b07326f76 | 1,981 | package io.github.bananapuncher714.ngui.objects;
import java.io.Serializable;
/**
* Comparable, with top left corner being the least and bottom right being the greatest
*
* @author BananaPuncher714
*/
public class BoxCoord implements Comparable< BoxCoord >, Cloneable, Serializable {
protected int x, y, height, width;
public BoxCoord( int x, int y, int height, int width ) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
public BoxCoord( int x, int y ) {
this( x, y, 0, 0 );
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + height;
result = prime * result + width;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BoxCoord other = (BoxCoord) obj;
if (height != other.height)
return false;
if (width != other.width)
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int compareTo( BoxCoord arg0 ) {
int value = ( y * 310 ) + x;
int other = ( arg0.getY() * 310 ) + arg0.getX();
if ( value > other ) {
return 1;
} else if ( value == other ) {
return 0;
} else {
return -1;
}
}
@Override
public BoxCoord clone() {
return new BoxCoord( x, y, width, height );
}
@Override
public String toString() {
return "{" + x + "," + y + "," + width + "," + height + "}";
}
}
| 18.009091 | 87 | 0.610298 |
3daf98c7b21632019cb2a9452d0cebaac2bb659b | 2,842 | package ewhine.http.api;
import java.io.File;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.Request;
import spark.Response;
import ewhine.config.Config;
import ewhine.tools.SU;
public class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
private Runnable _run = null;
public Main() {
}
public void config(Runnable run) {
this._run = run;
}
public void start() {
int maxThreads = Integer.parseInt(Config.getPropertyConfig(
"server.properties").get("server.max_thread", "32"));
int minThreads = 2;
int timeOutMillis = 30000;
int port = Integer.parseInt(Config.getPropertyConfig(
"server.properties").get("http.port", "3001"));
spark.Spark.port(port);
spark.Spark.threadPool(maxThreads, minThreads, timeOutMillis);
String public_file = Config.getServerRootDir() + File.separator
+ "public";
File public_file_dir = new File(public_file);
if (public_file_dir.exists()) {
spark.Spark.staticFiles.externalLocation(public_file);
}
if (_run != null) {
_run.run();
LOG.info("load run code finished!");
}
spark.Spark.afterAfter((request, response) -> {
String requestTag = getLogTag(request);
logRequest(requestTag, request, response);
});
spark.Spark.exception(Exception.class,
(exception, request, response) -> {
String requestTag = getLogTag(request);
RestService.logEorror(requestTag, request, response,
exception);
response.body("Server error!");
response.status(500);
});
LOG.info("load exception process.");
spark.Spark.awaitInitialization();
if (LOG.isInfoEnabled())
LOG.info(SU.cat("server started. port:", port,", max_thread:",maxThreads));
// LOG.info("server started. port:{}", port);
}
public void stop() {
spark.Spark.stop();
}
public String getLogTag(Request request) {
Object rtag = request.attribute("request_tag");
if (rtag == null) {
return "";
}
return rtag.toString();
}
public void logRequest(String tag, Request request, Response response) {
if (LOG.isInfoEnabled()) {
StringBuilder params = new StringBuilder();
Map<String, String[]> _map = request.queryMap().toMap();
_map.forEach((k, v) -> {
params.append(k);
params.append("=<");
if ("password".equals(k)) {
params.append("******>, ");
return;
}
String[] _o = _map.get(k);
if (_o != null) {
params.append(String.join(",", _o));
}
params.append(">, ");
});
if (params.length() > 0) {
params.deleteCharAt(params.length() - 2);
}
LOG.info(SU.cat(tag, request.requestMethod(), " ",
response.status(), " ", request.url(), " params[",
params.toString(), "] ", request.headers("X-Real-IP")));
}
}
public static void main(String[] args) {
}
}
| 21.530303 | 78 | 0.651654 |
7d84a7f875c728f5850d289ee579882ea5052c88 | 740 | package models;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class DecodeTest {
@Test
public void runEncryption_ifInputIsString() {
Encode testEncryption = new Encode("abc",3);
assertEquals("abc", testEncryption.getmInputString());
}
@Test
public void runDecrypt_ifKeyIsInt() {
Encode testEncrypt = new Encode("abc",3);
assertEquals(3, testEncrypt.getmShift());
}
//
// @Test
// public void runDecrypt_ifDecryptsVariousInputs() {
// Decode testDecryption = new Decode("!ODCB EURZQ IRA MXPSV RYHU D ODCB GRJ2", 3);
// assertEquals("!fA@? Bliqh Fi> dogjm ipEl A fA@? DiG2", Decode.decrypt(testDecryption));
// }
}
| 25.517241 | 97 | 0.659459 |
100e0521861e67e538a20f56d7543426b1403e0e | 1,374 | package com.example.canta.project3;
/**
* Created by a_tur on 2/25/2017.
*/
public class QuestionHolder {
private static QuestionHolder ourInstance = new QuestionHolder();
public static QuestionHolder getInstance() {
return ourInstance;
}
public static int questionList[] = new int[15];
private QuestionHolder() {
}
public static void questionListReset(){
for (int i = 0; i < questionList.length; i++) {
questionList[i] = 0;
}
}
public static void questionSetter(int index, int statue){
questionList[index] = statue;
}
public static int[] getQuestionList() {
return questionList;
}
public static int getCurrentQuestionNumberForChallange() {
return currentQuestionNumberForChallange;
}
public static void setCurrentQuestionNumberForChallange(int currentQuestionNumberForChallange) {
QuestionHolder.currentQuestionNumberForChallange = currentQuestionNumberForChallange;
}
public static int currentQuestionNumberForChallange;
public static String getCategoryforChallange() {
return categoryforChallange;
}
public static void setCategoryforChallange(String categoryforChallange) {
QuestionHolder.categoryforChallange = categoryforChallange;
}
public static String categoryforChallange;
}
| 25.444444 | 100 | 0.703057 |
501ec99219aae3b756d3c2eec52339fa8db62e91 | 2,369 | // Copyright (c) 2020-2022 ginlo.net GmbH
package eu.ginlo_apps.ginlo.fragment;
import android.app.Activity;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import eu.ginlo_apps.ginlo.R;
import eu.ginlo_apps.ginlo.model.backend.ServiceListModel;
/**
* Created by SGA on 26.01.2017.
*/
public class ServiceItemFragment
extends Fragment {
private ServiceListModel mModel;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
LinearLayout root = (LinearLayout) inflater.inflate(R.layout.fragment_service_list_item, container,
false);
final Activity activity = getActivity();
if (mModel != null && activity != null) {
final String serviceID = mModel.serviceId;
final int imageResourceId = activity.getResources().getIdentifier(serviceID + "_bg", "drawable", activity.getPackageName());
final int titleId = activity.getResources().getIdentifier(serviceID + "_title", "string", activity.getPackageName());
final int textId = activity.getResources().getIdentifier(serviceID + "_text", "string", activity.getPackageName());
final int hintId = activity.getResources().getIdentifier(serviceID + "_hint", "string", activity.getPackageName());
ImageView imageView = root.findViewById(R.id.service_list_item_image);
TextView header = root.findViewById(R.id.service_list_item_text_header);
TextView text = root.findViewById(R.id.service_list_item_text);
TextView hint = root.findViewById(R.id.service_list_item_hint);
imageView.setImageResource(imageResourceId);
header.setText(activity.getResources().getString(titleId));
text.setText(activity.getResources().getString(textId));
hint.setText(activity.getResources().getString(hintId));
}
return root;
}
public ServiceListModel getModel() {
return mModel;
}
public void setModel(ServiceListModel model) {
mModel = model;
}
}
| 37.603175 | 136 | 0.68721 |
bac08c9b5387396487977a03f75f970859c5c269 | 1,093 | package com.company;
public class Snack
{
private int id;
private String name;
private int quantity;
private double cost;
private int vendingMachineId;
public Snack(int id, String name, int quantity, double cost, int vendingMachineId)
{
this.id = id;
this.name = name;
this.quantity = quantity;
this.cost = cost;
this.vendingMachineId = vendingMachineId;
}
public void setName(String name)
{
this.name = name;
}
public int getQuantity()
{
return quantity;
}
public void addQuantity(int givenQuantity)
{
this.quantity = quantity + givenQuantity;
}
public double getCost(int givenQuantity)
{
return cost * givenQuantity;
}
@Override
public String toString()
{
return "Snack{" +
"id=" + id +
", name='" + name + '\'' +
", quantity=" + quantity +
", cost=" + cost +
", vendingMachineId=" + vendingMachineId +
'}';
}
}
| 21.019231 | 86 | 0.535224 |
716c2ae7564339f1d5a43fe6870b102da62d7da4 | 3,921 | /*
* Copyright 2017 Urs Fässler
* SPDX-License-Identifier: Apache-2.0
*/
package world.bilo.stack;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class Vector_operation_Test {
@Test
public void rotate_0_degree() {
assertEquals(new Vector(0, 0, 0), new Vector(0, 0, 0).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(0, 0, 1), new Vector(0, 0, 1).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(0, 1, 0), new Vector(0, 1, 0).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(0, 1, 1), new Vector(0, 1, 1).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(1, 0, 0), new Vector(1, 0, 0).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(1, 0, 1), new Vector(1, 0, 1).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(1, 1, 0), new Vector(1, 1, 0).rotateOnZeroBy(Rotation.Deg0));
assertEquals(new Vector(1, 1, 1), new Vector(1, 1, 1).rotateOnZeroBy(Rotation.Deg0));
}
@Test
public void rotate_90_degree() {
assertEquals(new Vector(+0, +0, 0), new Vector(+0, +0, 0).rotateOnZeroBy(Rotation.Deg90));
assertEquals(new Vector(-1, +0, 0), new Vector(+0, +1, 0).rotateOnZeroBy(Rotation.Deg90));
assertEquals(new Vector(+0, +1, 0), new Vector(+1, +0, 0).rotateOnZeroBy(Rotation.Deg90));
assertEquals(new Vector(+1, +0, 0), new Vector(+0, -1, 0).rotateOnZeroBy(Rotation.Deg90));
assertEquals(new Vector(+0, -1, 0), new Vector(-1, +0, 0).rotateOnZeroBy(Rotation.Deg90));
}
@Test
public void rotate_180_degree() {
assertEquals(new Vector(+0, +0, 0), new Vector(+0, +0, 0).rotateOnZeroBy(Rotation.Deg180));
assertEquals(new Vector(-0, -1, 0), new Vector(+0, +1, 0).rotateOnZeroBy(Rotation.Deg180));
assertEquals(new Vector(-1, -0, 0), new Vector(+1, +0, 0).rotateOnZeroBy(Rotation.Deg180));
assertEquals(new Vector(+0, +1, 0), new Vector(+0, -1, 0).rotateOnZeroBy(Rotation.Deg180));
assertEquals(new Vector(+1, +0, 0), new Vector(-1, +0, 0).rotateOnZeroBy(Rotation.Deg180));
}
@Test
public void rotate_270_degree() {
assertEquals(new Vector(+0, +0, 0), new Vector(+0, +0, 0).rotateOnZeroBy(Rotation.Deg270));
assertEquals(new Vector(+1, +0, 0), new Vector(+0, +1, 0).rotateOnZeroBy(Rotation.Deg270));
assertEquals(new Vector(+0, -1, 0), new Vector(+1, +0, 0).rotateOnZeroBy(Rotation.Deg270));
assertEquals(new Vector(-1, +0, 0), new Vector(+0, -1, 0).rotateOnZeroBy(Rotation.Deg270));
assertEquals(new Vector(+0, +1, 0), new Vector(-1, +0, 0).rotateOnZeroBy(Rotation.Deg270));
}
@Test
public void rotation_does_not_change_the_original_vector() {
Vector testee = new Vector(0, 1, 0);
testee.rotateOnZeroBy(Rotation.Deg90);
assertEquals(new Vector(0, 1, 0), testee);
}
@Test
public void translate() {
assertEquals(new Vector(0, 0, 0), new Vector(0, 0, 0).translate(new Vector(0, 0, 0)));
assertEquals(new Vector(1, 0, 0), new Vector(1, 0, 0).translate(new Vector(0, 0, 0)));
assertEquals(new Vector(0, 1, 0), new Vector(0, 1, 0).translate(new Vector(0, 0, 0)));
assertEquals(new Vector(0, 0, 1), new Vector(0, 0, 1).translate(new Vector(0, 0, 0)));
assertEquals(new Vector(1, 0, 0), new Vector(0, 0, 0).translate(new Vector(1, 0, 0)));
assertEquals(new Vector(0, 1, 0), new Vector(0, 0, 0).translate(new Vector(0, 1, 0)));
assertEquals(new Vector(0, 0, 1), new Vector(0, 0, 0).translate(new Vector(0, 0, 1)));
}
@Test
public void translation_does_not_change_the_original_vector() {
Vector testee = new Vector(0, 1, 0);
testee.translate(new Vector(1, 1, 1));
assertEquals(new Vector(0, 1, 0), testee);
}
@Test
public void translation_does_not_change_the_displacement_vector() {
Vector testee = new Vector(0, 1, 0);
Vector displacement = new Vector(1, 1, 1);
testee.translate(displacement);
assertEquals(new Vector(1, 1, 1), displacement);
}
}
| 43.087912 | 95 | 0.669217 |
2e5fdcd6122a26e27d22b7dac391d6d9d536a92c | 3,495 | package com.nightlycommit.idea.twigextendedplugin.tests.stubs.indexes;
import com.intellij.ide.highlighter.XmlFileType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexImpl;
import com.nightlycommit.idea.twigextendedplugin.stubs.dict.FileResource;
import com.nightlycommit.idea.twigextendedplugin.stubs.indexes.FileResourcesIndex;
import com.nightlycommit.idea.twigextendedplugin.tests.SymfonyLightCodeInsightFixtureTestCase;
import org.jetbrains.yaml.YAMLFileType;
import java.util.List;
/**
* @author Daniel Espendiller <[email protected]>
*
* @see com.nightlycommit.idea.twigextendedplugin.stubs.indexes.FileResourcesIndex
*/
public class FileResourcesIndexTest extends SymfonyLightCodeInsightFixtureTestCase {
public void setUp() throws Exception {
super.setUp();
myFixture.configureByText(YAMLFileType.YML, "" +
"app:\n" +
" resource: \"@AppBundle/Controller/\"\n" +
" prefix: \"/foo\"\n" +
"\n" +
"app1:\n" +
" resource: \"@AcmeOtherBundle/Resources/config/routing1.yml\"\n" +
"app2:\n" +
" resource: '@AcmeOtherBundle/Resources/config/routing2.yml'\n" +
"app3:\n" +
" resource: '@AcmeOtherBundle/Resources/config/routing3.yml'\n" +
"app4:\n" +
" resource: '@AcmeOtherBundle///Resources/config\\\\\\routing4.yml'\n"
);
myFixture.configureByText(XmlFileType.INSTANCE, "" +
"<routes>\n" +
" <import resource=\"@AcmeOtherBundle/Resources/config/routing.xml\" prefix=\"/foo2\"/>\n" +
" <import resource=\"@AcmeOtherBundle//Resources/config/routing1.xml\" />\n" +
" <import resource=\"@AcmeOtherBundle\\\\\\Resources/config///routing2.xml\" />\n" +
"</routes>"
);
}
public void testYamlResourcesImport() {
assertIndexContains(FileResourcesIndex.KEY, "@AppBundle/Controller");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing1.yml");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing2.yml");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing3.yml");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing4.yml");
}
public void testXmlResourcesImport() {
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing.xml");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing1.xml");
assertIndexContains(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing2.xml");
}
public void testIndexValue() {
FileResource item = ContainerUtil.getFirstItem(FileBasedIndex.getInstance().getValues(FileResourcesIndex.KEY, "@AppBundle/Controller", GlobalSearchScope.allScope(getProject())));
assertEquals("/foo", item.getPrefix());
item = ContainerUtil.getFirstItem(FileBasedIndex.getInstance().getValues(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing.xml", GlobalSearchScope.allScope(getProject())));
assertEquals("/foo2", item.getPrefix());
}
}
| 48.541667 | 197 | 0.688412 |
a28fcaac97c03ac5c21a12cd9ab20bf8944783cf | 1,443 | /*
* Copyright 2009-2017 University of Hildesheim, Software Systems Engineering
*
* 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 de.uni_hildesheim.sse.qmApp.tabbedViews;
import net.ssehub.easy.varModel.model.datatypes.Compound;
/**
* Compound helper methods.
* @author Holger Eichelberger
*/
public class CompoundUtil {
/**
* Returns the refinement basis, i.e., the topmost refined compound.
*
* @param cmp the compound to investigate
* @return the topmost refined compound or <b>this</b> if this compound does not refine another compound
*/
public static Compound getRefinementBasis(Compound cmp) {
// for legacy reasons we just consider the first refined compound here
Compound basis = cmp;
while (basis.getRefinesCount() > 0) {
basis = basis.getRefines(0);
}
return basis;
}
}
| 34.357143 | 109 | 0.682606 |
03b07667fb557d5cf716ad058f589ec4cfe8082f | 375 | package com.knowledge_network.user.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by pentonbin on 18-3-20
*/
@Controller
@RequestMapping(value = "")
public class LoginController {
@RequestMapping(value = "/login")
public String login() {
return "login";
}
}
| 20.833333 | 62 | 0.725333 |
40de30f3a405e68c9b27c07c5b4a7e9524d3a96f | 1,171 | package Unitex;
import java.util.ArrayList;
import java.util.List;
/**
* Created by spyridons on 8/18/2016.
*/
public class UnitexJniResult {
private String term;
private String concept;
private List<String> BabelNet;
private List<String> DBPedia;
public UnitexJniResult()
{
this.BabelNet = new ArrayList<>();
this.DBPedia = new ArrayList<>();
}
public String getTerm() {
return term;
}
public void setTerm(String term) {
this.term = term;
}
public String getConcept() {
return concept;
}
public void setConcept(String concept) {
this.concept = concept;
}
public List<String> getBabelNet() {
return BabelNet;
}
public void setBabelNet(List<String> babelNet) {
BabelNet = babelNet;
}
public List<String> getDBPedia() {
return DBPedia;
}
public void setDBPedia(List<String> DBPedia) {
this.DBPedia = DBPedia;
}
public void addToBabelNet(String url)
{
this.BabelNet.add(url);
}
public void addToDBPedia(String url)
{
this.DBPedia.add(url);
}
}
| 17.742424 | 52 | 0.600342 |
8b228a8532295c031acd63fa3f68a73d30ffb7b3 | 127 | package mujina.ping;
public class OpenTokenException extends Exception {
public OpenTokenException(String s) {super(s);}
}
| 18.142857 | 51 | 0.779528 |
3b4cf9bf662199d8643fbbc8ddfafb2310ef8684 | 10,501 | /*
* 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 swim.sim.uwswarm.intelli.brain.struct.artif;
import com.jme3.math.FastMath;
import java.util.ArrayList;
import java.util.HashMap;
import swim.core.AgentControl;
import swim.core.motion.CompositeTurnSequence;
import swim.sim.uwswarm.UWVehicleControl;
import swim.util.Pair;
/**
*
* @author Sherif
*/
public class SequenceRepository {
// Constants - START
private final float MAX_TRAVEL_DIST = 30;
private final int MAX_NUM_OF_SWEEPS = 5;
private final float MAX_SWEEP_LENGTH = 30;
private final int MAX_NUM_OF_CIRCLINGS = 10;
// Constants - END
private HashMap<String, CompositeTurnSequence> sequences;
private CompositeTurnSequence sequence;
private ArrayList<String> seqToDelete, sequenceNames;
private AgentControl agentController;
public SequenceRepository( AgentControl agentController ) {
this.sequences = new HashMap<String, CompositeTurnSequence>();
this.seqToDelete = new ArrayList<String>();
this.sequenceNames = new ArrayList<String>();
this.agentController = agentController;
createSequences();
}
private void createSequences() {
// Shared
float angle, distance;
// Turn backwards
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", (FastMath.rand.nextFloat() > 0.5f ? "right" : "left"));
sequence.add("turn_angle", FastMath.PI);
sequence.setName("Backwards Turn");
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Turn right
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "right");
sequence.add("turn_angle", FastMath.HALF_PI);
sequence.setName("Right Turn");
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Turn left
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "left");
sequence.add("turn_angle", FastMath.HALF_PI);
sequence.setName("Left Turn");
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Turn right with random angle
angle = FastMath.PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "right");
sequence.add("turn_angle", angle);
sequence.setName("Random Right Turn");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Turn left with random angle
angle = FastMath.PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "left");
sequence.add("turn_angle", angle);
sequence.setName("Random Left Turn");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Maneuver right (right with random angle less than 45 deg then revert it twice)
angle = FastMath.QUARTER_PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "right");
sequence.add("turn_angle", angle);
sequence.add("turn_direction", "left");
sequence.add("turn_angle", 2*angle);
sequence.add("turn_direction", "right");
sequence.add("turn_angle", angle);
sequence.setName("Random Right Maneuver");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Maneuver left (left with random angle less than 45 deg then revert it twice)
angle = FastMath.QUARTER_PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "left");
sequence.add("turn_angle", angle);
sequence.add("turn_direction", "right");
sequence.add("turn_angle", 2*angle);
sequence.add("turn_direction", "left");
sequence.add("turn_angle", angle);
sequence.setName("Random Left Maneuver");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Diverge right (right with random angle less than 45 deg then revert it once)
angle = FastMath.QUARTER_PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "right");
sequence.add("turn_angle", angle);
sequence.add("turn_direction", "left");
sequence.add("turn_angle", angle);
sequence.setName("Random Right Divergence");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Diverge left (left with random angle less than 45 deg then revert it once)
angle = FastMath.QUARTER_PI * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("turn_direction", "left");
sequence.add("turn_angle", angle);
sequence.add("turn_direction", "right");
sequence.add("turn_angle", angle);
sequence.setName("Random Left Divergence");
sequence.setRandAngle(angle);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Travel random distance then return
distance = MAX_TRAVEL_DIST * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
sequence.add("travel", distance);
sequence.add("turn_direction", (FastMath.rand.nextFloat() > 0.5f ? "right" : "left"));
sequence.add("turn_angle", FastMath.PI);
sequence.add("travel", distance);
sequence.setName("Reconnaissance");
sequence.setRandDist(distance);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Sweep along AUV's travel direction
// ----====
// ====
//@ToDo: implement
// Sweep normal to AUV's travel direction
// ----||||||
// ||||||
boolean turnRight = false,
firstSweep = true;
int numTurns = MAX_NUM_OF_SWEEPS - 1;
String turnDir;
distance = MAX_TRAVEL_DIST * FastMath.rand.nextFloat();
sequence = new CompositeTurnSequence();
for(int i = 1; i <= MAX_NUM_OF_SWEEPS; i++) {
turnDir = (turnRight ? "right" : "left");
if(firstSweep) {
distance = MAX_SWEEP_LENGTH/2;
firstSweep = false;
} else {
distance = MAX_SWEEP_LENGTH;
}
sequence.add(new Pair<String,Object>("travel", distance));
if(i < MAX_NUM_OF_SWEEPS) {
sequence.add("turn_direction", turnDir);
sequence.add("turn_angle", FastMath.PI);
turnRight = !turnRight;
} else {
turnRight = !turnRight;
turnDir = (turnRight ? "right" : "left");
sequence.add("turn_direction", turnDir);
sequence.add("turn_angle", FastMath.HALF_PI);
if(MAX_NUM_OF_SWEEPS % 2 == 0) { // Do further investigation here
distance = (numTurns - 1) * ((UWVehicleControl)agentController).getActiveTurnRadius()
* ((UWVehicleControl)agentController).getMinVehicleSpeed();
} else {
distance = numTurns * ((UWVehicleControl)agentController).getActiveTurnRadius()
* ((UWVehicleControl)agentController).getMinVehicleSpeed();
}
sequence.add("travel", distance);
sequence.add("turn_direction", turnDir);
sequence.add("turn_angle", FastMath.HALF_PI);
sequence.add("travel", MAX_SWEEP_LENGTH/2);
}
}
sequence.setName("Simple Sweeping");
sequence.setRandDist(distance);
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
// Circle for a number of times
sequence = new CompositeTurnSequence();
turnDir = (FastMath.rand.nextFloat() > 0.5f ? "right" : "left");
for(int i = 1; i <= MAX_NUM_OF_CIRCLINGS; i++) {
sequence.add("turn_direction", turnDir);
sequence.add("turn_angle", FastMath.TWO_PI);
}
sequence.setName("Repeated Circling");
sequences.put(sequence.getName(), sequence);
sequenceNames.add(sequence.getName());
}
public void addSequence(CompositeTurnSequence sequence) {
sequences.put(sequence.getName(), sequence);
}
public CompositeTurnSequence getRandomSequence() {
if( sequenceNames.isEmpty() ) {
return null;
}
int index = FastMath.rand.nextInt(sequenceNames.size());
CompositeTurnSequence seq = sequences.get(sequenceNames.get(index));
while( seqToDelete.contains(seq.getName()) ) {
sequences.remove(sequenceNames.get(index));
sequenceNames.remove(index);
index = FastMath.rand.nextInt(sequenceNames.size());
seq = sequences.get(sequenceNames.get(index));
}
return seq;
}
public void deleteSequence(String name) {
seqToDelete.add(name);
}
public CompositeTurnSequence getSequence( String name ) {
return sequences.get(name);
}
public int getSequencesCount() {
return sequences.size();
}
}
| 38.892593 | 107 | 0.589182 |
b3bc88136faec067753fc1550fd5af308b034319 | 9,614 | package com.aboutsip.performance.config;
import io.parsenip.ArgParser;
import io.parsenip.Argument;
import io.parsenip.CommandLine;
import io.parsenip.Parsenip;
import io.pkts.buffer.Buffer;
import io.pkts.buffer.Buffers;
import io.pkts.packet.sip.impl.SipParser;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.impl.Arguments;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
import org.junit.Test;
import java.io.IOException;
import java.util.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;
/**
* Created by jonas on 3/3/16.
*/
public class ScenarioConfigTest extends ConfigTestBase {
@Test
public void testLoadConfig() throws Exception {
final ScenarioConfig scenario = loadConfiguration(ScenarioConfig.class, "test_scenario_001.yaml");
assertThat(scenario.getName(), is("Simple INVITE Scenario"));
assertThat(scenario.getClients().size(), is(3));
final SIPpInstanceConfig myUAS = scenario.getClient("myUAS").get();
assertThat(myUAS.getHost(), is("127.0.0.1"));
assertThat(myUAS.getPort(), is(5060));
final SIPpInstanceConfig theUAC = scenario.getClient("theUacDude").get();
assertThat(theUAC.getHost(), is("192.168.0.100"));
assertThat(theUAC.getPort(), is(5062));
assertThat(theUAC.getRemoteHost(), is("127.0.0.1"));
assertThat(theUAC.getRemotePort(), is(5060));
final SIPpInstanceConfig anotherUAC = scenario.getClient("anotherUacDude").get();
assertThat(anotherUAC.getHost(), is("62.63.64.65"));
assertThat(anotherUAC.getPort(), is(5060));
assertThat(anotherUAC.getRemoteHost(), is("127.0.0.1"));
assertThat(anotherUAC.getRemotePort(), is(5060));
// final List<String> actions = scenario.getActions();
// actions.forEach(this::doIt);
// doIt("monitor --type cpu myUAS");
doItMyWay("monitor --type cpu myUAS");
}
private void doItMyWay(final String cmd) {
try {
System.out.print(cmd + " --->");
System.out.println(parseArgumentMyWay(cmd));
} catch (ArgumentParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private CommandLine parseArgumentMyWay(final String cmd) throws IOException, ArgumentParserException {
final Map<String, ArgParser> parsers = new HashMap<>();
parsers.put("monitor", createMonitorParsenip());
// need to redo this...
final String[] args = splitCmd(cmd);
final ArgParser parser = parsers.get(args[0]);
return parser.parse(cmd);
}
private void doIt(final String cmd) {
try {
System.out.print(cmd + " --->");
System.out.println(parseArgument(cmd));
} catch (ArgumentParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Namespace parseArgument(final String cmd) throws ArgumentParserException, IOException {
final Map<String, ArgumentParser> parsers = new HashMap<>();
parsers.put("report", createReportParser());
parsers.put("stop", createStopParser());
parsers.put("start", createStartParser());
parsers.put("pause", createPauseParser());
parsers.put("monitor", createMonitorArgParser());
final String[] args = splitCmd(cmd);
final ArgumentParser parser = parsers.get(args[0]);
return parser.parseArgs(Arrays.copyOfRange(args, 1, args.length));
}
private String[] splitCmd(final String cmd) throws IOException, ArgumentParserException {
final List<String> parts = new ArrayList<>();
final Buffer buffer = Buffers.wrap(cmd);
int count = 0; // just to a prevent runaway loop in case the parsing is off
final int MAX = 100;
while (buffer.hasReadableBytes() && ++count < MAX) {
final Buffer result;
SipParser.consumeWS(buffer);
if (SipParser.isNext(buffer, SipParser.DQUOT)) {
result = SipParser.consumeQuotedString(buffer);
} else {
result = SipParser.consumeToken(buffer);
}
if (result != null) {
parts.add(result.toString());
}
}
if (count == MAX) {
throw new ArgumentParserException("Unable to parse due to internal error. Loop never finished", null);
}
return parts.toArray(new String[0]);
}
private ArgumentParser createStartParser() {
final ArgumentParser p = ArgumentParsers.newArgumentParser("start")
.description("Start a particular process");
p.addArgument("target").nargs("*").help("Which process to start");
return p;
}
private ArgumentParser createPauseParser() {
final ArgumentParser p = ArgumentParsers.newArgumentParser("pause")
.description("Pause a particular SIPp instance");
p.addArgument("target").nargs("*").help("Which sipp instance to pause");
return p;
}
private ArgumentParser createStopParser() {
final ArgumentParser p = ArgumentParsers.newArgumentParser("stop")
.description("Stop (quit) a particular process");
p.addArgument("target").nargs("*").help("Which process(es) to stop");
p.addArgument("--force")
.action(Arguments.storeConst())
.setConst(true)
.setDefault(false)
.help("Force the process to stop (will eventually kill it if it doesn't stop by itself)");
return p;
}
private ArgumentParser createReportParser() {
final ArgumentParser p = ArgumentParsers.newArgumentParser("report")
.description("Generate a report for a particular process(es)");
p.addArgument("target").nargs("*").help("Which process(es) to include in the report");
p.addArgument("--snapshot")
.action(Arguments.storeConst())
.setConst(true)
.setDefault(false)
.help("Generate a snapshot report");
p.addArgument("--include")
.choices("gc", "cpu", "iostat")
.nargs(1)
.setDefault("gc", "cpu")
.help("What type of information to include in the report");
p.addArgument("--format")
.choices("html", "text", "pdf")
.nargs(1)
.setDefault("text")
.help("The format of the report (not a valid option for snapshot)");
p.addArgument("--from")
.setDefault("start")
.help("From which point in time the report should be generated. Will be from the beginning of the run if not specified");
p.addArgument("--to")
.setDefault("now")
.help("To which point in time the report should be generated. Will be \"now\" if not specified.");
p.addArgument("--title")
.setDefault("Report")
.help("The title of the report");
p.addArgument("--name")
.setDefault("report")
.help("The name of the report");
return p;
}
private ArgParser createMonitorParsenip() {
Argument<Boolean> forceFlag = Argument.withShortName("-f")
.withLongName("--force")
.withDescription("force it")
.withNoArguments()
.withValueWhenPresent(true)
.build();
// Makes no sense having a constant parameter to be required.
// If it is required then you may just hard code the actual
// value into your code. The user has no choice anyway!
Argument<Boolean> forceFlag1 = Argument.withLongName("--force")
.withDescription("force it")
.withNoArguments()
.withValueWhenPresent(true) // will give us the type
.withValueWhenAbsent(false) // will give us the type
.build();
Argument<String> type = Argument.withLongName("--type")
.withDescription("The type of monitoring")
.withAtLeastOneArgument()
.ofType(String.class)
.isRequired()
.withDefaultValue("cpu")
.withChoices("cpu", "iostat", "gc")
.build();
ArgParser parser = ArgParser.forProgramNamed("monitor")
.withDescription("monitor a process")
.withArgument(forceFlag)
.withArgument(type)
.withAllowDoubleQuotedStrings()
.build();
return null;
}
/**
* Create the argument parser for the 'monitor'
* @return
*/
private ArgumentParser createMonitorArgParser() {
final ArgumentParser p = ArgumentParsers.newArgumentParser("monitor")
.description("Monitor a particular process");
p.addArgument("--type")
.choices("gc", "cpu", "iostat")
.nargs("*")
.setDefault("cpu")
.help("What type of monitor to use (you may use multiple)");
p.addArgument("target").nargs("+").help("Which process to monitor");
System.err.println(p.formatHelp());
return p;
}
}
| 37.40856 | 137 | 0.59871 |
dec7707934faab52d206b64c682e63dcd6f7688b | 4,203 | /*
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 com.ceos.merlot.das.drv.mb.command;
import com.ceos.merlot.api.DriverCallback;
import com.ceos.merlot.api.DriverEvent;
import com.ceos.merlot.das.drv.mb.api.MbDevice;
import com.ceos.merlot.das.drv.mb.impl.MbDeviceImpl;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;
import org.apache.karaf.shell.api.action.Action;
import org.apache.karaf.shell.api.action.Argument;
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.apache.karaf.shell.api.console.Session;
import org.apache.karaf.shell.api.console.SessionFactory;
import org.apache.plc4x.java.api.messages.PlcWriteResponse;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.device.Device;
/**
*
* @author cgarcia
*/
@Command(scope = "mb", name = "write", description = "Write one field to the PLC.")
@Service
public class MbWriteCommand implements Action, DriverCallback {
@Reference
BundleContext bc;
@Reference
Session session;
@Reference
SessionFactory sessionFactory;
@Argument(index = 0, name = "serial", description = "Device serial (like DEVICE_ID).", required = true, multiValued = false)
String serial;
@Argument(index = 1, name = "scalartype", description = "Scalar type ( ScalarType).", required = true, multiValued = false)
String scalarType;
@Argument(index = 2, name = "field", description = "Device field to read.", required = true, multiValued = false)
String userField;
@Argument(index = 3, name = "value", description = "Value or values to write.", required = true, multiValued = true)
List<String> values;
@Override
public Object execute() throws Exception {
String filter = "(&(|(" + org.osgi.framework.Constants.OBJECTCLASS + "=" + Device.class.getName() + ")" +
"(" + org.osgi.framework.Constants.OBJECTCLASS + "=" + com.ceos.merlot.api.Device.class.getName() + "))" +
"(&(" + org.osgi.service.device.Constants.DEVICE_CATEGORY + "=" + MbDeviceImpl.MB_DEVICE_CATEGORY + ")" +
"(" + org.osgi.service.device.Constants.DEVICE_SERIAL + "=" + serial + ")))";
ServiceReference[] refs = bc.getServiceReferences((String) null, filter);
if (refs == null){
System.out.println("Device not found. SERIAL: " + serial);
} else {
ServiceReference ref = refs[0];
MbDevice mbdevice = (MbDevice) bc.getService(ref);
mbdevice.WriteRequest(scalarType, userField, values, this);
}
return null;
}
@Override
public void execute(DriverEvent cb) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss:SSS");
try{
PlcWriteResponse response = cb.getPlcWriteResponse();
Collection<String> fields = response.getFieldNames();
String fieldname = (String) fields.toArray()[0];
System.out.println(fieldname + "/Response@["+LocalTime.now().format(dtf)+"]: " + response.getResponseCode(fieldname));
System.out.println("\r\n");
} catch (Exception ex){
ex.printStackTrace();
}
}
}
| 39.650943 | 130 | 0.681894 |
706529f46c0b99d6064091fb808a803d64c37e79 | 3,730 | package com.zuccessful.trueharmony.pojo;
import android.content.Context;
import java.io.Serializable;
public class Injection implements Serializable {
private String id;
private String name;
private String reminderStatus;
private String hour;
private String min;
private String day;
private String month;
private String year;
private String repeated;
private String title;
private String content;
private String status;
private String ReqCode;
private String type;
//private final String APP_SHARED_PREFS = "RemindMePref";
// private SharedPreferences appSharedPrefs;
// private SharedPreferences.Editor prefsEditor;
public Injection(Context context) {
//this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Context.MODE_PRIVATE);
//this.prefsEditor = appSharedPrefs.edit();
}
public Injection() {
}
/* public boolean getReminderStatus()
{
return appSharedPrefs.getBoolean(reminderStatus, false);
}*/
// Settings Page Reminder Time (Hour)
public String getReqCode() {
return ReqCode;
}
public void setReqCode(String reqCode) {
ReqCode = reqCode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReminderStatus() {
return reminderStatus;
}
public void setReminderStatus(String reminderStatus) {
this.reminderStatus = reminderStatus;
}
public String getHour() {
return hour;
}
public void setHour(String hour) {
this.hour = hour;
}
public String getMin() {
return min;
}
public void setMin(String min) {
this.min = min;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getMonth() {
return month;
}
public void setMonth(String month) {
this.month = month;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getRepeated() {
return repeated;
}
public void setRepeated(String repeated) {
this.repeated = repeated;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "Injection{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", reminderStatus='" + reminderStatus + '\'' +
", hour='" + hour + '\'' +
", min='" + min + '\'' +
", day='" + day + '\'' +
", month='" + month + '\'' +
", year='" + year + '\'' +
", repeated='" + repeated + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", status='" + status + '\'' +
", type='" + type + '\'' +
'}';
}
}
| 21.436782 | 101 | 0.542627 |
689f7bf14d86e0478ce41fdd5eeb6f2fe65401c4 | 8,531 | /*
* Copyright (c) 2010-2017, Numdata BV, The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Numdata nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NUMDATA BV BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.numdata.oss.velocity;
import java.lang.reflect.*;
import java.util.*;
import com.numdata.oss.*;
import org.apache.velocity.context.*;
import org.jetbrains.annotations.*;
/**
* This Velocity {@link Context} implementation uses bean properties as
* variables. This is useful if a single object described the complete context;
* in such situations prefixing all variables references with a name for that
* one bean is a bit useless.
*
* @author Peter S. Heijnen
*/
public class VelocityBeanContext
implements Context
{
/**
* Bean to get properties from.
*/
private Object _bean = null;
/**
* Bean we're caching data for. If a bean of another class is set, this
* will get updated and the cached reflection objects will be cleared.
*/
private Class<?> _beanClass = null;
/**
* Cached property getters for the current bean class.
*/
private final Map<String, Method> _getters = new HashMap<>();
/**
* Cached property setters for the current bean class.
*/
private final Map<String, Method> _setters = new HashMap<>();
/**
* Cached fields for the current bean class.
*/
private final Map<String, Field> _fields = new HashMap<>();
/**
* Cached bean property names.
*/
private final Set<String> _beanPropertyNames = new HashSet<>();
/**
* Variables that are automatically created by the velocity template.
*/
private final Map<String, Object> _variables = new HashMap<>();
/**
* Construct context.
*/
public VelocityBeanContext()
{
}
/**
* Construct context.
*
* @param bean Bean to get properties from.
*/
public VelocityBeanContext( final Object bean )
{
setBean( bean );
}
/**
* Set bean to get properties from.
*
* @param bean Bean to get properties from.
*/
public void setBean( final Object bean )
{
_bean = bean;
}
/**
* Internal method to inspect the current bean properties.
*/
private void inspectBean()
{
final Object bean = _bean;
final Class<?> beanClass = ( bean != null ) ? bean.getClass() : null;
if ( beanClass != _beanClass )
{
final Map<String, Method> getters = _getters;
final Map<String, Method> setters = _setters;
final Map<String, Field> fields = _fields;
final Set<String> beanPropertyNames = _beanPropertyNames;
getters.clear();
setters.clear();
fields.clear();
if ( beanClass != null )
{
_beanClass = beanClass;
for ( final Method method : beanClass.getMethods() )
{
final int modifiers = method.getModifiers();
final String name = method.getName();
final Class<?>[] parameterTypes = method.getParameterTypes();
if ( !Modifier.isStatic( modifiers ) && ( name.length() > 2 ) )
{
if ( parameterTypes.length == 0 )
{
if ( ( name.length() > 3 ) && name.startsWith( "get" ) )
{
getters.put( TextTools.decapitalize( name.substring( 3 ) ), method );
}
else if ( name.startsWith( "is" ) )
{
getters.put( TextTools.decapitalize( name.substring( 2 ) ), method );
}
}
else if ( parameterTypes.length == 1 )
{
if ( ( name.length() > 3 ) && name.startsWith( "set" ) )
{
setters.put( TextTools.decapitalize( name.substring( 3 ) ), method );
}
}
}
}
final Set<String> setterNames = setters.keySet();
setterNames.retainAll( getters.keySet() );
beanPropertyNames.clear();
beanPropertyNames.addAll( getters.keySet() );
for ( final Field field : beanClass.getFields() )
{
final int modifiers = field.getModifiers();
if ( !Modifier.isStatic( modifiers ) )
{
final String name = field.getName();
if ( beanPropertyNames.add( name ) )
{
fields.put( name, field );
}
}
}
}
}
}
@Nullable
@Override
public Object get( final String key )
{
final Object result;
if ( key.startsWith( ".literal." ) )
{
result = null;
}
else
{
inspectBean();
if ( _beanPropertyNames.contains( key ) )
{
final Object bean = _bean;
try
{
final Method getter = _getters.get( key );
if ( getter != null )
{
result = getter.invoke( bean );
}
else
{
final Field field = _fields.get( key );
if ( field != null )
{
result = field.get( bean );
}
else
{
throw new AssertionError( "No getter or field for known property '" + key + "' in " + bean );
}
}
}
catch ( final IllegalAccessException e )
{
throw new IllegalArgumentException( '\'' + key + "' not accessible", e );
}
catch ( final InvocationTargetException e )
{
throw new IllegalArgumentException( "Getting '" + key + "' caused an internal error", e );
}
}
else
{
result = _variables.get( key );
}
}
return result;
}
@Override
public boolean containsKey( final String key )
{
boolean result = _variables.containsKey( key );
if ( !result && ( key != null ) )
{
inspectBean();
result = _beanPropertyNames.contains( key );
}
return result;
}
@Override
public Object put( final String key, final Object value )
{
final Object result;
inspectBean();
if ( _beanPropertyNames.contains( key ) )
{
final Object bean = _bean;
try
{
final Method getter = _getters.get( key );
if ( getter != null )
{
final Method setter = _setters.get( key );
if ( setter == null )
{
throw new IllegalArgumentException( "Trying to set read-only property '" + key + "' in " + bean + " to " + value );
}
result = getter.invoke( bean );
setter.invoke( bean, value );
}
else
{
final Field field = _fields.get( key );
if ( field != null )
{
result = field.get( bean );
field.set( bean, value );
}
else
{
throw new AssertionError( "No getter or field for known property '" + key + "' in " + bean );
}
}
}
catch ( final IllegalAccessException e )
{
throw new IllegalArgumentException( '\'' + key + "' not accessible", e );
}
catch ( final InvocationTargetException e )
{
throw new IllegalArgumentException( "Getting '" + key + "' caused an internal error", e );
}
}
else
{
result = _variables.put( key, value );
}
return result;
}
@Override
public String[] getKeys()
{
inspectBean();
final HashSet<String> result = new HashSet<>();
result.addAll( _beanPropertyNames );
result.addAll( _variables.keySet() );
return result.toArray( new String[ 0 ] );
}
@Nullable
@Override
public Object remove( final String key )
{
final Object result;
if ( _variables.containsKey( key ) )
{
result = _variables.remove( key );
}
else if ( _beanPropertyNames.contains( key ) )
{
throw new IllegalArgumentException( "Can't remove bean property '" + key + '\'' );
}
else
{
result = null;
}
return result;
}
}
| 24.944444 | 121 | 0.635564 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.