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
|
---|---|---|---|---|---|
14dc58636167fe356ba0203ca8f658af15880025 | 1,508 | package io.nerv.config;
import io.nerv.core.license.LicenseCheckInterceptor;
import io.nerv.properties.EvaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.nio.charset.Charset;
@Configuration
@ConditionalOnProperty(prefix = "eva.license", name = "enable", havingValue = "true")
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private LicenseCheckInterceptor licenseCheckInterceptor;
@Autowired
private EvaConfig evaConfig;
/**
* 配置license鉴权拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(licenseCheckInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(evaConfig.getSecurity().getPermit());
}
// 解决乱码问题 StringHttpMessageConverter默认编码为ISO-8859-1
@Bean
public HttpMessageConverter<String> responseBodyConverter() {
return new StringHttpMessageConverter(Charset.forName("UTF-8"));
}
}
| 35.069767 | 85 | 0.778515 |
c4cef1d076a36fb343304c6f7944a984300ab546 | 911 | package net.linxingyang.diary.mapper;
import java.util.List;
import net.linxingyang.diary.pojo.FutureTask;
import net.linxingyang.diary.pojo.FutureTaskExample;
import org.apache.ibatis.annotations.Param;
public interface FutureTaskMapper {
int countByExample(FutureTaskExample example);
int deleteByExample(FutureTaskExample example);
int deleteByPrimaryKey(Integer id);
int insert(FutureTask record);
int insertSelective(FutureTask record);
List<FutureTask> selectByExample(FutureTaskExample example);
FutureTask selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") FutureTask record, @Param("example") FutureTaskExample example);
int updateByExample(@Param("record") FutureTask record, @Param("example") FutureTaskExample example);
int updateByPrimaryKeySelective(FutureTask record);
int updateByPrimaryKey(FutureTask record);
} | 30.366667 | 114 | 0.789243 |
756249a9cafe22680dff12afe955d66c57460edb | 2,490 | package app.retake;
import app.retake.controllers.AnimalAidController;
import app.retake.controllers.AnimalController;
import app.retake.controllers.ProcedureController;
import app.retake.controllers.VetController;
import app.retake.io.api.ConsoleIO;
import app.retake.io.api.FileIO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Terminal implements CommandLineRunner {
private final AnimalAidController animalAidController;
private final AnimalController animalController;
private final VetController vetController;
private final ProcedureController procedureController;
private final FileIO fileIO;
private final ConsoleIO consoleIO;
@Autowired
public Terminal(AnimalAidController animalAidController,
AnimalController animalController,
VetController vetController,
ProcedureController procedureController,
FileIO fileIO,
ConsoleIO consoleIO) {
this.animalAidController = animalAidController;
this.animalController = animalController;
this.vetController = vetController;
this.procedureController = procedureController;
this.fileIO = fileIO;
this.consoleIO = consoleIO;
}
@Override
public void run(String... strings) throws Exception {
this.consoleIO.write(this.animalAidController
.importDataFromJSON(
this.fileIO
.read(Config.ANIMAL_AIDS_IMPORT_JSON)));
this.consoleIO.write(this.animalController
.importDataFromJSON(
this.fileIO
.read(Config.ANIMALS_IMPORT_JSON)));
this.consoleIO.write(this.vetController
.importDataFromXML(
this.fileIO
.read(Config.VETS_IMPORT_XML)));
this.consoleIO.write(this.procedureController
.importDataFromXML(
this.fileIO
.read(Config.PROCEDURES_IMPORT_XML)));
this.fileIO.write(this.animalController.exportAnimalsByOwnerPhoneNumber("0887446123"),"exportAnimalsByOwnerPhoneNumber.json");
this.fileIO.write(this.procedureController.exportProcedures(),"exportProcedures.xml");
}
}
| 40.16129 | 134 | 0.669478 |
c121d3d9787a4ee9b2b88cc332d0dbc0de05ab74 | 1,217 | /*
* Copyright 2021 DataCanvas
*
* 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.dingodb.net.netty;
public class Versions {
public static final byte[] MAGIC_CODE = new byte[]{'D', 'I', 'N', 'G', 'O'};
public static final byte VERSION_1 = 0x01;
public static byte currentVersion() {
return VERSION_1;
}
public static boolean checkCode(byte[] bytes, int start) {
try {
for (int i = 0; i < MAGIC_CODE.length; i++) {
if (MAGIC_CODE[i] != bytes[i + start]) {
return false;
}
}
return true;
} catch (Exception e) {
return false;
}
}
}
| 27.659091 | 80 | 0.615448 |
5e85ef710ac012b7b9f8f4c328b6c1094c029d31 | 695 | package seedu.savenus.model.info;
import seedu.savenus.logic.commands.BuyCommand;
//@@author robytanama
/**
* Contains information on Buy command.
*/
public class BuyInfo {
public static final String COMMAND_WORD = BuyCommand.COMMAND_WORD;
public static final String INFORMATION = "Buy command allows you to buy a Food item from the food list using your"
+ " wallet.\n\n"
+ "The buy information will depend on the following factor:\n"
+ "Index of food you want to buy.\n\n";
public static final String USAGE = "buy 2";
public static final String OUTPUT = "Money from your wallet will be deducted according to price of Food item 2.";
}
| 31.590909 | 118 | 0.696403 |
be2e664aac86d354e43b0074d038dcfcafd86319 | 1,015 |
import java.awt.*;
import java.util.Random;
/**
* @brief This class represents single slice data of pie chart
*
*/
public class SliceData
{
private int value;
private Color color;
/**
* @brief ctor of SliceData value
* @param slice value
*/
public SliceData(int value)
{
Random numGen = new Random();
int R = numGen.nextInt(256);
int G = numGen.nextInt(256);
int B = numGen.nextInt(256);
this.setColor(new Color(R,G,B));
this.value = value;
}
/**
* @brief function set color value
* @param color value
*/
public void setColor(Color color)
{
this.color = color;
}
/**
* @brief function get sliceData value
* @return sliceData value
*/
public int getValue()
{
return value;
}
/**
* @brief function get collor
* @return sliceData color
*/
public Color getColor()
{
return color;
}
} // class SliceData
| 17.807018 | 62 | 0.553695 |
76ac21e27a44374b6a2f01c7b313f1651bc82e3e | 2,867 | /*******************************************************************************
* ENdoSnipe 5.0 - (https://github.com/endosnipe)
*
* The MIT License (MIT)
*
* Copyright (c) 2012 Acroquest Technology Co.,Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
package jp.co.acroquest.endosnipe.web.dashboard.form;
import java.util.List;
/**
* 期間データ取得用のメソッド。
* @author nakagawa
*/
public class TermDataForm
{
/**
* 開始時間
*/
private String startTime_;
/**
* 終了時間
*/
private String endTime_;
/**
* データグループIDのリスト
*/
private List<String> dataGroupIdList_;
/**
* コンストラクタ。
*/
public TermDataForm()
{
}
/**
* 開始時間を取得する。
* @return 開始時間
*/
public String getStartTime()
{
return startTime_;
}
/**
* 開始時間を設定する。
* @param startTime 開始時間
*/
public void setStartTime(final String startTime)
{
this.startTime_ = startTime;
}
/**
* 終了時間を取得する。
* @return 終了時間
*/
public String getEndTime()
{
return endTime_;
}
/**
* 終了時間を設定する。
* @param endTime 終了時間
*/
public void setEndTime(final String endTime)
{
this.endTime_ = endTime;
}
/**
* データグループIDのリストを取得する。
* @return データグループIDのリスト
*/
public List<String> getDataGroupIdList()
{
return dataGroupIdList_;
}
/**
* データグループIDのリストを設定する。
* @param dataGroupIdList データグループIDのリスト
*/
public void setDataGroupIdList(final List<String> dataGroupIdList)
{
this.dataGroupIdList_ = dataGroupIdList;
}
}
| 25.371681 | 81 | 0.584234 |
e9fe34b1fd59caad337c10567f9228f438b45490 | 11,509 | package fr.craftechmc.environment.common.blocks;
import java.util.Random;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.init.Blocks;
import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidClassic;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidContainerRegistry;
/**
* Created by arisu on 03/08/2016.
*/
public class BlockFluid extends BlockFluidClassic
{
@SideOnly(Side.CLIENT)
protected IIcon stillIcon;
@SideOnly(Side.CLIENT)
protected IIcon flowingIcon;
private final String texturePrefix;
// BlockDynamicLiquid Fields
private int adjacentSourceBlocks;
boolean[] field_149814_b = new boolean[4];
int[] field_149816_M = new int[4];
public BlockFluid(final Fluid fluid, final Material material, final String texturePrefix)
{
super(fluid, material);
this.texturePrefix = texturePrefix;
this.setFluidStackAmount(FluidContainerRegistry.BUCKET_VOLUME);
}
@Override
public IIcon getIcon(final int side, final int meta)
{
return (side == 0 || side == 1) ? this.stillIcon : this.flowingIcon;
}
@Override
public void registerIcons(final IIconRegister register)
{
this.stillIcon = register.registerIcon("craftechenvironment:" + this.texturePrefix + "_still");
this.flowingIcon = register.registerIcon("craftechenvironment:" + this.texturePrefix + "_flow");
}
@Override
public boolean canDisplace(final IBlockAccess world, final int x, final int y, final int z)
{
if (world.getBlock(x, y, z).getMaterial().isLiquid())
return false;
return super.canDisplace(world, x, y, z);
}
@Override
public boolean displaceIfPossible(final World world, final int x, final int y, final int z)
{
if (world.getBlock(x, y, z).getMaterial().isLiquid())
return false;
return super.displaceIfPossible(world, x, y, z);
}
/**
* Returns a integer with hex for 0xrrggbb with this color multiplied
* against the blocks color. Note only called when first determining what to
* render.
*/
@SideOnly(Side.CLIENT)
@Override
public int colorMultiplier(final IBlockAccess blockAccess, final int x, final int y, final int z)
{
int l = 0;
int i1 = 0;
int j1 = 0;
for (int zOffset = -1; zOffset <= 1; ++zOffset)
for (int xOffset = -1; xOffset <= 1; ++xOffset)
{
final int i2 = blockAccess.getBiomeGenForCoords(x + xOffset, z + zOffset).getWaterColorMultiplier();
l += (i2 & 16711680) >> 16;
i1 += (i2 & 65280) >> 8;
j1 += i2 & 255;
}
return (l / 9 & 255) << 16 | (i1 / 9 & 255) << 8 | j1 / 9 & 255;
}
@Override
public void updateTick(final World world, final int x, final int y, final int z, final Random rand)
{
int metadataOrZero = this.getBlockMetadataOrZero(world, x, y, z);
final byte flowLevelOffset = 1;
final int tickRate = this.tickRate(world);
int metadataBasedFlowLevel;
if (metadataOrZero > 0)
{
final byte b1 = -100;
this.adjacentSourceBlocks = 0;
int metadataSum = this.metadataMin(world, x - 1, y, z, b1);
metadataSum = this.metadataMin(world, x + 1, y, z, metadataSum);
metadataSum = this.metadataMin(world, x, y, z - 1, metadataSum);
metadataSum = this.metadataMin(world, x, y, z + 1, metadataSum);
metadataBasedFlowLevel = metadataSum + flowLevelOffset;
if (metadataBasedFlowLevel >= 8 || metadataSum < 0)
metadataBasedFlowLevel = -1;
if (this.getBlockMetadataOrZero(world, x, y + 1, z) >= 0)
{
final int metadata = this.getBlockMetadataOrZero(world, x, y + 1, z);
if (metadata >= 8)
metadataBasedFlowLevel = metadata;
else
metadataBasedFlowLevel = metadata + 8;
}
if (this.adjacentSourceBlocks >= 2)
if (world.getBlock(x, y - 1, z).getMaterial().isSolid())
metadataBasedFlowLevel = 0;
else if (world.getBlock(x, y - 1, z).getMaterial() == this.blockMaterial
&& world.getBlockMetadata(x, y - 1, z) == 0)
metadataBasedFlowLevel = 0;
if (metadataBasedFlowLevel == metadataOrZero)
this.shiftBlockId(world, x, y, z);
else
{
metadataOrZero = metadataBasedFlowLevel;
if (metadataBasedFlowLevel < 0)
world.setBlockToAir(x, y, z);
else
{
world.setBlockMetadataWithNotify(x, y, z, metadataBasedFlowLevel, 2);
world.scheduleBlockUpdate(x, y, z, this, tickRate);
world.notifyBlocksOfNeighborChange(x, y, z, this);
}
}
}
else
this.shiftBlockId(world, x, y, z);
if (this.notSameMaterialAndCanPassThrough(world, x, y - 1, z))
{
if (metadataOrZero >= 8)
this.bulldozeFluidWayIfStrongEnough(world, x, y - 1, z, metadataOrZero);
else
this.bulldozeFluidWayIfStrongEnough(world, x, y - 1, z, metadataOrZero + 8);
}
else if (metadataOrZero >= 0 && (metadataOrZero == 0 || this.cantPassThrough(world, x, y - 1, z)))
{
final boolean[] aboolean = this.func_149808_o(world, x, y, z);
metadataBasedFlowLevel = metadataOrZero + flowLevelOffset;
if (metadataOrZero >= 8)
metadataBasedFlowLevel = 1;
if (metadataBasedFlowLevel >= 8)
return;
if (aboolean[0])
this.bulldozeFluidWayIfStrongEnough(world, x - 1, y, z, metadataBasedFlowLevel);
if (aboolean[1])
this.bulldozeFluidWayIfStrongEnough(world, x + 1, y, z, metadataBasedFlowLevel);
if (aboolean[2])
this.bulldozeFluidWayIfStrongEnough(world, x, y, z - 1, metadataBasedFlowLevel);
if (aboolean[3])
this.bulldozeFluidWayIfStrongEnough(world, x, y, z + 1, metadataBasedFlowLevel);
}
}
protected int getBlockMetadataOrZero(final World world, final int x, final int y, final int z)
{
return world.getBlock(x, y, z).getMaterial() == this.blockMaterial ? world.getBlockMetadata(x, y, z) : -1;
}
protected int metadataMin(final World world, final int x, final int y, final int z, final int metadataToCompare)
{
int metadata = this.getBlockMetadataOrZero(world, x, y, z);
if (metadata < 0)
return metadataToCompare;
else
{
if (metadata == 0)
++this.adjacentSourceBlocks;
if (metadata >= 8)
metadata = 0;
return metadataToCompare >= 0 && metadata >= metadataToCompare ? metadataToCompare : metadata;
}
}
private void shiftBlockId(final World world, final int x, final int y, final int z)
{
final int metadata = world.getBlockMetadata(x, y, z);
world.setBlock(x, y, z,
Block.getBlockById(Block.getIdFromBlock(this) /* + 1 */), metadata, 2);
}
private boolean notSameMaterialAndCanPassThrough(final World world, final int x, final int y, final int z)
{
final Material material = world.getBlock(x, y, z).getMaterial();
return material != this.blockMaterial && !this.cantPassThrough(world, x, y, z);
}
private void bulldozeFluidWayIfStrongEnough(final World world, final int x, final int y, final int z,
final int metadata)
{
if (this.notSameMaterialAndCanPassThrough(world, x, y, z))
{
final Block block = world.getBlock(x, y, z);
block.dropBlockAsItem(world, x, y, z, world.getBlockMetadata(x, y, z), 0);
world.setBlock(x, y, z, this, metadata, 3);
}
}
private boolean cantPassThrough(final World world, final int x, final int y, final int z)
{
final Block block = world.getBlock(x, y, z);
return !(block != Blocks.wooden_door && block != Blocks.iron_door && block != Blocks.standing_sign
&& block != Blocks.ladder && block != Blocks.reeds)
|| (block.getMaterial() == Material.portal || block.getMaterial().blocksMovement());
}
private boolean[] func_149808_o(final World world, final int x, final int y, final int z)
{
int i;
int x1;
for (i = 0; i < 4; ++i)
{
this.field_149816_M[i] = 1000;
x1 = x;
int z1 = z;
if (i == 0)
x1 = x - 1;
if (i == 1)
++x1;
if (i == 2)
z1 = z - 1;
if (i == 3)
++z1;
if (!this.cantPassThrough(world, x1, y, z1)
&& (world.getBlock(x1, y, z1).getMaterial() != this.blockMaterial
|| world.getBlockMetadata(x1, y, z1) != 0))
if (this.cantPassThrough(world, x1, y - 1, z1))
this.field_149816_M[i] = this.func_149812_c(world, x1, y, z1, 1, i);
else
this.field_149816_M[i] = 0;
}
i = this.field_149816_M[0];
for (x1 = 1; x1 < 4; ++x1)
if (this.field_149816_M[x1] < i)
i = this.field_149816_M[x1];
for (x1 = 0; x1 < 4; ++x1)
this.field_149814_b[x1] = this.field_149816_M[x1] == i;
return this.field_149814_b;
}
private int func_149812_c(final World world, final int x, final int y, final int z, final int metadata,
final int p_149812_6_)
{
int j1 = 1000;
for (int i = 0; i < 4; ++i)
if ((i != 0 || p_149812_6_ != 1) && (i != 1 || p_149812_6_ != 0) && (i != 2 || p_149812_6_ != 3)
&& (i != 3 || p_149812_6_ != 2))
{
int x1 = x;
int z1 = z;
if (i == 0)
x1 = x - 1;
if (i == 1)
++x1;
if (i == 2)
z1 = z - 1;
if (i == 3)
++z1;
if (!this.cantPassThrough(world, x1, y, z1)
&& (world.getBlock(x1, y, z1).getMaterial() != this.blockMaterial
|| world.getBlockMetadata(x1, y, z1) != 0))
{
if (!this.cantPassThrough(world, x1, y - 1, z1))
return metadata;
if (metadata < 4)
{
final int j2 = this.func_149812_c(world, x1, y, z1, metadata + 1, i);
if (j2 < j1)
j1 = j2;
}
}
}
return j1;
}
}
| 34.770393 | 116 | 0.545225 |
e96275181e17ce8ae499c7a447b1e21014c16c09 | 2,625 | // Copyright 2017, 2019, Oracle Corporation and/or its affiliates. All rights reserved.
// Licensed under the Universal Permissive License v 1.0 as shown at
// http://oss.oracle.com/licenses/upl.
package oracle.kubernetes.operator.rest.resource;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import oracle.kubernetes.operator.logging.LoggingFacade;
import oracle.kubernetes.operator.logging.LoggingFactory;
import oracle.kubernetes.operator.rest.backend.VersionUtils;
import oracle.kubernetes.operator.rest.model.VersionModel;
/**
* VersionResource is a jaxrs resource that implements the REST api for the /operator/{version}
* path. It can be used to describe a version of the WebLogic operator REST api and to traverse to
* its child resources.
*/
public class VersionResource extends BaseResource {
private static final LoggingFacade LOGGER = LoggingFactory.getLogger("Operator", "Operator");
/**
* Construct a VersionResource.
*
* @param parent - the jaxrs resource that parents this resource.
* @param pathSegment - the last path segment in the url to this resource.
*/
public VersionResource(BaseResource parent, String pathSegment) {
super(parent, pathSegment);
}
/**
* Get a description of this version of the WebLogic Operator REST api.
*
* @return a VersionModel describing this version.
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public VersionModel get() {
LOGGER.entering(href());
String version = getVersion();
VersionModel item =
new VersionModel(
VersionUtils.getVersion(version),
VersionUtils.isLatest(version),
VersionUtils.getLifecycle(version));
addSelfAndParentLinks(item);
addLink(item, "domains");
addLink(item, "swagger");
LOGGER.exiting(item);
return item;
}
/**
* Construct and return the 'domains' jaxrs child resource.
*
* @return the domains sub resource.
*/
@Path("domains")
public DomainsResource getDomainsResource() {
LOGGER.entering(href());
DomainsResource result = new DomainsResource(this, "domains");
LOGGER.exiting(result);
return result;
}
/**
* Construct and return the 'swagger' jaxrs child resource.
*
* @return the swagger sub resource.
*/
@Path("swagger")
public SwaggerResource getSwaggerResource() {
LOGGER.entering(href());
SwaggerResource result = new SwaggerResource(this, "swagger");
LOGGER.exiting(result);
return result;
}
private String getVersion() {
return getPathSegment();
}
}
| 29.829545 | 98 | 0.713143 |
b37814e3a1f41c41ba1270a7685aacaa5eb47353 | 6,006 | package com.fitpay.android.paymentdevice.impl.ble;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import com.fitpay.android.api.models.apdu.ApduCommand;
import com.fitpay.android.api.models.apdu.ApduPackage;
import com.fitpay.android.paymentdevice.constants.States;
import com.fitpay.android.paymentdevice.enums.NFC;
import com.fitpay.android.paymentdevice.enums.SecureElement;
import com.fitpay.android.paymentdevice.impl.PaymentDeviceConnector;
import com.fitpay.android.paymentdevice.impl.ble.message.SecurityStateMessage;
import com.fitpay.android.utils.FPLog;
import com.fitpay.android.utils.StringUtils;
/**
* BLE implementation
*/
public final class BluetoothPaymentDeviceConnector extends PaymentDeviceConnector {
private final static String TAG = BluetoothPaymentDeviceConnector.class.getSimpleName();
public final static String EXTRA_BLUETOOTH_ADDRESS = "BLUETOOTH_ADDRESS";
private BluetoothAdapter mBluetoothAdapter;
private GattManager mGattManager;
private String mAddress;
public BluetoothPaymentDeviceConnector(Context context) {
super(context);
initBluetooth();
}
public BluetoothPaymentDeviceConnector(Context context, String deviceAddress) {
super(context);
mAddress = deviceAddress;
initBluetooth();
}
protected void initBluetooth() {
BluetoothManager mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
FPLog.e(TAG, "unable to initialize bluetooth manager");
return;
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
FPLog.e(TAG, "unable to obtain bluetooth adapter");
return;
}
if (null != mAddress) {
setState(States.INITIALIZED);
}
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* connection result is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
@Override
public void connect() {
FPLog.d(TAG, "initiate connect to device: " + mAddress);
if (mBluetoothAdapter == null || StringUtils.isEmpty(mAddress)) {
FPLog.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return;
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mAddress);
if (device == null) {
FPLog.w(TAG, "Device not found. Unable to connect.");
return;
}
mGattManager = new GattManager(this, mContext, device);
mGattManager.queue(new GattSubscribeOperation());
}
@Override
public void disconnect() {
FPLog.d(TAG, "initiate disconnect from to device: " + mAddress);
if (mGattManager != null) {
mGattManager.disconnect();
} else {
FPLog.w(TAG, "GattManager is null");
}
}
public void reconnect() {
if (mGattManager != null) {
mGattManager.reconnect();
} else {
FPLog.w(TAG, "GattManager is null");
}
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
mGattManager.close();
mGattManager = null;
}
@Override
public void readDeviceInfo() {
FPLog.d(TAG, "initiate readDeviceInfo request");
GattOperation readDeviceInfoOperation = new GattDeviceCharacteristicsOperation(connectorId, mAddress);
mGattManager.queue(readDeviceInfoOperation);
}
public void readNFCState() {
FPLog.d(TAG, "initiate readNFCState request");
GattOperation getNFCOperation = new GattCharacteristicReadOperation(
PaymentServiceConstants.SERVICE_UUID,
PaymentServiceConstants.CHARACTERISTIC_SECURITY_STATE,
data -> postData(new SecurityStateMessage().withData(data)));
mGattManager.queue(getNFCOperation);
}
public void setNFCState(@NFC.Action byte state) {
FPLog.d(TAG, "initiate setNFCState request. Target state: " + state);
GattOperation setNFCOperation = new GattCharacteristicWriteOperation(
PaymentServiceConstants.SERVICE_UUID,
PaymentServiceConstants.CHARACTERISTIC_SECURITY_WRITE,
new byte[]{state}
);
mGattManager.queue(setNFCOperation);
}
@Override
public void executeApduPackage(ApduPackage apduPackage) {
FPLog.d(TAG, "initiate executeApduPackage request");
GattOperation sendApduOperation = new GattApduOperation(id(), apduPackage);
mGattManager.queue(sendApduOperation);
}
@Override
public void executeApduCommand(long apduPkgNumber, ApduCommand apduCommand) {
}
public void sendNotification(byte[] data) {
FPLog.d(TAG, "initiate sendNotification request. data: " + data);
GattOperation setTransactionOperation = new GattCharacteristicWriteOperation(
PaymentServiceConstants.SERVICE_UUID,
PaymentServiceConstants.CHARACTERISTIC_NOTIFICATION,
data
);
mGattManager.queue(setTransactionOperation);
}
public void setSecureElementState(@SecureElement.Action byte state) {
FPLog.d(TAG, "initiate setSecureElementState request. Target state: " + state);
GattOperation resetOperation = new GattCharacteristicWriteOperation(
PaymentServiceConstants.SERVICE_UUID,
PaymentServiceConstants.CHARACTERISTIC_DEVICE_RESET,
new byte[]{state}
);
mGattManager.queue(resetOperation);
}
}
| 34.918605 | 117 | 0.67649 |
e02558a49a897a8060aa149c855aec0a4aaf6b22 | 1,762 |
import java.util.ArrayList;
import java.util.List;
public class Laptop {
String retailer;
String name;
String id;
String image;
String condition;
String discount;
int price;
List<String> accessories;
public Laptop(String retailer,String name, String id, String image, String condition, String discount, int price, List<String> accessories){
this.retailer = retailer;
this.price = price;
this.name = name;
this.id = id;
this.image = image;
this.condition = condition;
this.discount = discount;
this.setAccessories(accessories);
}
public Laptop(){
accessories=new ArrayList<String>();
}
public String getRetailer() {
return retailer;
}
public void setRetailer(String retailer) {
this.retailer = retailer;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public List<String> getAccessories() {
return accessories;
}
public void setAccessories(List<String> accessories) {
this.accessories = accessories;
}
}
| 18.164948 | 145 | 0.634506 |
c95af4f27b436ea7ec6be964d044af097d3540f4 | 3,869 | /*******************************************************************************
* Copyright (c) 2014, 2015, 2020 Sergiy Yevtushenko
*
* 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.baremetalstudios.minicam.simulator;
public class FullPlotter extends AbstractPlotter {
@Override
public void setCenter(String string, String string2) {
System.out.format("setCenter(%s, %s)\n", string, string2);
}
@Override
public void setPosition(String string, String string2) {
System.out.format("setPosition(%s, %s)\n", string, string2);
}
@Override
public void done() {
System.out.format("done()\n");
}
@Override
public void setExposure(ExposureMode mode) {
System.out.format("setExposure(%s)\n", mode);
super.setExposure(mode);
}
@Override
public void setMode(PlotterMode mode) {
System.out.format("setMode(%s)\n", mode);
super.setMode(mode);
}
@Override
public void resetMode(PlotterMode mode) {
System.out.format("resetMode(%s)\n", mode);
super.resetMode(mode);
}
@Override
public void comment(int beginLine, String image) {
System.out.format("comment(%d, %s)\n", beginLine, image);
super.comment(beginLine, image);
}
@Override
public void addFlash() {
System.out.format("addFlash()\n");
super.addFlash();
}
@Override
public void setAperture(int parseInt) {
System.out.format("setAperture(%d)\n", parseInt);
super.setAperture(parseInt);
}
@Override
public void setFormatX(int parseInt, int parseInt2) {
System.out.format("setFormatX(%d, %d)\n", parseInt, parseInt2);
super.setFormatX(parseInt, parseInt2);
}
@Override
public void setFormatY(int parseInt, int parseInt2) {
System.out.format("setFormatY(%s, %s)\n", parseInt, parseInt2);
super.setFormatY(parseInt, parseInt2);
}
@Override
public ApertureMacro getMacro(String id) {
System.out.format("getMacro(%s)\n", id);
return super.getMacro(id);
}
@Override
public void addAperture(Aperture aperture) {
System.out.format("addAperture(%s)\n", aperture);
super.addAperture(aperture);
}
@Override
public void addMacro(ApertureMacro macro) {
System.out.format("addMacro(%s)\n", macro);
super.addMacro(macro);
}
@Override
public void selectAxis(String image, String image2) {
System.out.format("selectAxis(%s, %s)\n", image, image2);
}
@Override
public void setImagePolarity(String image) {
System.out.format("setImagePolarity(%s)\n", image);
}
@Override
public void setLayerPolarity(String image) {
System.out.format("setLayerPolarity(%s)\n", image);
}
@Override
public void setOffset(String a, String b) {
System.out.format("setOffset(%s, %s)\n", a, b);
}
@Override
public void setScaleFactor(String a, String b) {
System.out.format("setScaleFactor(%s, %s)\n", a, b);
}
@Override
public void stepAndRepeat(String x, String y, String i, String j) {
System.out.format("stepAndRepeat(%s, %s, %s, %s)\n", x, y, i, j);
}
}
| 29.534351 | 80 | 0.611011 |
e18fea464dacc2a212e70a21aebf9a901f6cc708 | 627 | package io.logz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Created by ofer_v on 8/11/15.
*/
public class Main {
final static Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
// UNCOMMENT THE FOLLOWING WHEN RUNNING HTTP APPENDER CONF
logger.info("Hello World from Logback!");
// UNCOMMENT THE FOLLOWING WHEN RUNNING SOCKET APPENDER CONF
// while(true) {
// logger.info("[YFZTkfMHvHadJihIrMoDumZHjUXJAyuK][type=logback] Hello World from Logback!");
// }
}
}
| 20.225806 | 104 | 0.663477 |
e0bc70abba21a77ce66d29e69745c877d7a3f8a7 | 352 | package org.evomaster.client.java.instrumentation.example.methodreplacement.strings;
import com.foo.somedifferentpackage.examples.methodreplacement.strings.StringsExampleImp;
public class SEnotInstrumentedTest extends StringsExampleTestBase{
@Override
protected StringsExample getInstance() {
return new StringsExampleImp();
}
}
| 29.333333 | 89 | 0.809659 |
ad73dc7b84d766fe4c735a3851a51fa2638ebd75 | 582 | package com.tortuousroad.admin.security.entity;
import com.tortuousroad.framework.base.entity.BaseEntity;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.Date;
/**
* AdminRoleFunction
*/
@NoArgsConstructor
@AllArgsConstructor
public class AdminRoleFunction extends BaseEntity {
@Getter @Setter private Long adminRoleId; //角色ID
@Getter @Setter private Long adminFunctionId; // 功能ID
@Getter @Setter private Date createTime; //创建时间
@Getter @Setter private Date updateTime; //修改时间
}
| 24.25 | 57 | 0.781787 |
cd781e8709c67ff034d42a326927ac9ab72df3c1 | 384 | package com.alibaba.csp.sentinel.dashboard.config;
import java.util.ArrayList;
import java.util.List;
/**
* 拦截记录请求日志URL
* @author Yaosh
* @version 1.0
* @commpany 星瑞国际
* @date 2020/6/3 16:04
* @return
*/
public class LogInterceptorConfig {
public static final List<String> LogURL = new ArrayList<String>(){
{
this.add("setRules");
}
};
}
| 17.454545 | 70 | 0.635417 |
142bb1f5bc4d9373c6af131c000e5f9793ec3e4d | 2,573 | /*
* Copyright 2017-2018 Adobe.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adobe.testing.s3mock.domain;
import com.adobe.testing.s3mock.dto.Owner;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import javax.xml.bind.annotation.XmlElement;
/**
* Contents are the XMLElements of ListBucketResult see http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
*/
@XStreamAlias("Contents")
public class BucketContents {
@XStreamAlias("Key")
private String key;
@XStreamAlias("LastModified")
private String lastModified;
@XStreamAlias("ETag")
private String etag;
@XStreamAlias("Size")
private String size;
@XStreamAlias("StorageClass")
private String storageClass;
@XStreamAlias("Owner")
private Owner owner;
/**
* Constructs a new {@link BucketContents}.
*/
public BucketContents() {
// empty here
}
/**
* Constructs a new {@link BucketContents}.
*
* @param key {@link String}
* @param lastModified {@link String}
* @param etag {@link String}
* @param size {@link String}
* @param storageClass {@link String}
* @param owner {@link Owner}
*/
public BucketContents(final String key,
final String lastModified,
final String etag,
final String size,
final String storageClass,
final Owner owner) {
super();
this.key = key;
this.lastModified = lastModified;
this.etag = etag;
this.size = size;
this.storageClass = storageClass;
this.owner = owner;
}
@XmlElement(name = "Key")
public String getKey() {
return key;
}
@XmlElement(name = "LastModified")
public String getLastModified() {
return lastModified;
}
@XmlElement(name = "ETag")
public String getEtag() {
return etag;
}
@XmlElement(name = "Size")
public String getSize() {
return size;
}
@XmlElement(name = "StorageClass")
public String getStorageClass() {
return storageClass;
}
@XmlElement(name = "Owner")
public Owner getOwner() {
return owner;
}
}
| 23.605505 | 121 | 0.682083 |
38b8c3bd702202d709bae95d3a55122b1bc3dba8 | 2,513 | /*
* Copyright [2021] [Doric.Pub]
*
* 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 pub.doric.resource;
import com.github.pengfeizhou.jscore.JSArrayBuffer;
import com.github.pengfeizhou.jscore.JSObject;
import java.util.HashMap;
import java.util.Map;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.UiThread;
import pub.doric.DoricContext;
/**
* @Description: This manages all resource loaders
* @Author: pengfei.zhou
* @CreateDate: 2021/10/20
*/
public class DoricResourceManager {
private final Map<String, DoricResourceLoader> mResourceLoaders = new HashMap<>();
public synchronized void registerLoader(DoricResourceLoader loader) {
mResourceLoaders.put(loader.resourceType(), loader);
}
public synchronized void unRegisterLoader(DoricResourceLoader loader) {
mResourceLoaders.remove(loader.resourceType());
}
@Nullable
@UiThread
public synchronized DoricResource load(@NonNull DoricContext doricContext,
@NonNull JSObject resource) {
String resId = resource.getProperty("resId").asString().value();
String type = resource.getProperty("type").asString().value();
String identifier = resource.getProperty("identifier").asString().value();
DoricResource doricResource = doricContext.getCachedResource(resId);
if (doricResource == null) {
DoricResourceLoader loader = mResourceLoaders.get(type);
if (loader != null) {
doricResource = loader.load(doricContext, identifier);
if (doricResource instanceof DoricArrayBufferResource) {
JSArrayBuffer buffer = resource.getProperty("data").asArrayBuffer();
((DoricArrayBufferResource) doricResource).setValue(buffer);
}
doricContext.cacheResource(resId, doricResource);
}
}
return doricResource;
}
}
| 37.507463 | 88 | 0.692797 |
f868cad144d50ba54f627d161d26c72814769769 | 36,587 | package mage.sets;
import mage.cards.ExpansionSet;
import mage.collation.BoosterCollator;
import mage.collation.BoosterStructure;
import mage.collation.CardRun;
import mage.collation.RarityConfiguration;
import mage.constants.Rarity;
import mage.constants.SetType;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author nantuko84
*/
public final class ScarsOfMirrodin extends ExpansionSet {
private static final ScarsOfMirrodin instance = new ScarsOfMirrodin();
public static ScarsOfMirrodin getInstance() {
return instance;
}
private ScarsOfMirrodin() {
super("Scars of Mirrodin", "SOM", ExpansionSet.buildDate(2010, 10, 1), SetType.EXPANSION);
this.blockName = "Scars of Mirrodin";
this.hasBoosters = true;
this.numBoosterLands = 1;
this.numBoosterCommon = 10;
this.numBoosterUncommon = 3;
this.numBoosterRare = 1;
this.ratioBoosterMythic = 8;
cards.add(new SetCardInfo("Abuna Acolyte", 1, Rarity.UNCOMMON, mage.cards.a.AbunaAcolyte.class));
cards.add(new SetCardInfo("Accorder's Shield", 136, Rarity.COMMON, mage.cards.a.AccordersShield.class));
cards.add(new SetCardInfo("Acid Web Spider", 108, Rarity.UNCOMMON, mage.cards.a.AcidWebSpider.class));
cards.add(new SetCardInfo("Alpha Tyrranax", 109, Rarity.COMMON, mage.cards.a.AlphaTyrranax.class));
cards.add(new SetCardInfo("Arc Trail", 81, Rarity.UNCOMMON, mage.cards.a.ArcTrail.class));
cards.add(new SetCardInfo("Argent Sphinx", 28, Rarity.RARE, mage.cards.a.ArgentSphinx.class));
cards.add(new SetCardInfo("Argentum Armor", 137, Rarity.RARE, mage.cards.a.ArgentumArmor.class));
cards.add(new SetCardInfo("Arrest", 2, Rarity.COMMON, mage.cards.a.Arrest.class));
cards.add(new SetCardInfo("Asceticism", 110, Rarity.RARE, mage.cards.a.Asceticism.class));
cards.add(new SetCardInfo("Assault Strobe", 82, Rarity.COMMON, mage.cards.a.AssaultStrobe.class));
cards.add(new SetCardInfo("Auriok Edgewright", 3, Rarity.UNCOMMON, mage.cards.a.AuriokEdgewright.class));
cards.add(new SetCardInfo("Auriok Replica", 138, Rarity.COMMON, mage.cards.a.AuriokReplica.class));
cards.add(new SetCardInfo("Auriok Sunchaser", 4, Rarity.COMMON, mage.cards.a.AuriokSunchaser.class));
cards.add(new SetCardInfo("Barbed Battlegear", 139, Rarity.UNCOMMON, mage.cards.b.BarbedBattlegear.class));
cards.add(new SetCardInfo("Barrage Ogre", 83, Rarity.UNCOMMON, mage.cards.b.BarrageOgre.class));
cards.add(new SetCardInfo("Bellowing Tanglewurm", 111, Rarity.UNCOMMON, mage.cards.b.BellowingTanglewurm.class));
cards.add(new SetCardInfo("Blackcleave Cliffs", 224, Rarity.RARE, mage.cards.b.BlackcleaveCliffs.class));
cards.add(new SetCardInfo("Blackcleave Goblin", 54, Rarity.COMMON, mage.cards.b.BlackcleaveGoblin.class));
cards.add(new SetCardInfo("Bladed Pinions", 140, Rarity.COMMON, mage.cards.b.BladedPinions.class));
cards.add(new SetCardInfo("Blade-Tribe Berserkers", 84, Rarity.COMMON, mage.cards.b.BladeTribeBerserkers.class));
cards.add(new SetCardInfo("Bleak Coven Vampires", 55, Rarity.COMMON, mage.cards.b.BleakCovenVampires.class));
cards.add(new SetCardInfo("Blight Mamba", 112, Rarity.COMMON, mage.cards.b.BlightMamba.class));
cards.add(new SetCardInfo("Blistergrub", 56, Rarity.COMMON, mage.cards.b.Blistergrub.class));
cards.add(new SetCardInfo("Bloodshot Trainee", 85, Rarity.UNCOMMON, mage.cards.b.BloodshotTrainee.class));
cards.add(new SetCardInfo("Blunt the Assault", 113, Rarity.COMMON, mage.cards.b.BluntTheAssault.class));
cards.add(new SetCardInfo("Bonds of Quicksilver", 29, Rarity.COMMON, mage.cards.b.BondsOfQuicksilver.class));
cards.add(new SetCardInfo("Carapace Forger", 114, Rarity.COMMON, mage.cards.c.CarapaceForger.class));
cards.add(new SetCardInfo("Carnifex Demon", 57, Rarity.RARE, mage.cards.c.CarnifexDemon.class));
cards.add(new SetCardInfo("Carrion Call", 115, Rarity.UNCOMMON, mage.cards.c.CarrionCall.class));
cards.add(new SetCardInfo("Cerebral Eruption", 86, Rarity.RARE, mage.cards.c.CerebralEruption.class));
cards.add(new SetCardInfo("Chimeric Mass", 141, Rarity.RARE, mage.cards.c.ChimericMass.class));
cards.add(new SetCardInfo("Chrome Steed", 142, Rarity.COMMON, mage.cards.c.ChromeSteed.class));
cards.add(new SetCardInfo("Clone Shell", 143, Rarity.UNCOMMON, mage.cards.c.CloneShell.class));
cards.add(new SetCardInfo("Contagion Clasp", 144, Rarity.UNCOMMON, mage.cards.c.ContagionClasp.class));
cards.add(new SetCardInfo("Contagion Engine", 145, Rarity.RARE, mage.cards.c.ContagionEngine.class));
cards.add(new SetCardInfo("Contagious Nim", 58, Rarity.COMMON, mage.cards.c.ContagiousNim.class));
cards.add(new SetCardInfo("Copperhorn Scout", 116, Rarity.COMMON, mage.cards.c.CopperhornScout.class));
cards.add(new SetCardInfo("Copperline Gorge", 225, Rarity.RARE, mage.cards.c.CopperlineGorge.class));
cards.add(new SetCardInfo("Copper Myr", 146, Rarity.COMMON, mage.cards.c.CopperMyr.class));
cards.add(new SetCardInfo("Corpse Cur", 147, Rarity.COMMON, mage.cards.c.CorpseCur.class));
cards.add(new SetCardInfo("Corrupted Harvester", 59, Rarity.UNCOMMON, mage.cards.c.CorruptedHarvester.class));
cards.add(new SetCardInfo("Culling Dais", 148, Rarity.UNCOMMON, mage.cards.c.CullingDais.class));
cards.add(new SetCardInfo("Cystbearer", 117, Rarity.COMMON, mage.cards.c.Cystbearer.class));
cards.add(new SetCardInfo("Darkslick Drake", 30, Rarity.UNCOMMON, mage.cards.d.DarkslickDrake.class));
cards.add(new SetCardInfo("Darkslick Shores", 226, Rarity.RARE, mage.cards.d.DarkslickShores.class));
cards.add(new SetCardInfo("Darksteel Axe", 149, Rarity.UNCOMMON, mage.cards.d.DarksteelAxe.class));
cards.add(new SetCardInfo("Darksteel Juggernaut", 150, Rarity.RARE, mage.cards.d.DarksteelJuggernaut.class));
cards.add(new SetCardInfo("Darksteel Myr", 151, Rarity.UNCOMMON, mage.cards.d.DarksteelMyr.class));
cards.add(new SetCardInfo("Darksteel Sentinel", 152, Rarity.UNCOMMON, mage.cards.d.DarksteelSentinel.class));
cards.add(new SetCardInfo("Dispense Justice", 5, Rarity.UNCOMMON, mage.cards.d.DispenseJustice.class));
cards.add(new SetCardInfo("Disperse", 31, Rarity.COMMON, mage.cards.d.Disperse.class));
cards.add(new SetCardInfo("Dissipation Field", 32, Rarity.RARE, mage.cards.d.DissipationField.class));
cards.add(new SetCardInfo("Dross Hopper", 60, Rarity.COMMON, mage.cards.d.DrossHopper.class));
cards.add(new SetCardInfo("Echo Circlet", 153, Rarity.COMMON, mage.cards.e.EchoCirclet.class));
cards.add(new SetCardInfo("Elspeth Tirel", 6, Rarity.MYTHIC, mage.cards.e.ElspethTirel.class));
cards.add(new SetCardInfo("Embersmith", 87, Rarity.UNCOMMON, mage.cards.e.Embersmith.class));
cards.add(new SetCardInfo("Engulfing Slagwurm", 118, Rarity.RARE, mage.cards.e.EngulfingSlagwurm.class));
cards.add(new SetCardInfo("Etched Champion", 154, Rarity.RARE, mage.cards.e.EtchedChampion.class));
cards.add(new SetCardInfo("Exsanguinate", 61, Rarity.UNCOMMON, mage.cards.e.Exsanguinate.class));
cards.add(new SetCardInfo("Ezuri, Renegade Leader", 119, Rarity.RARE, mage.cards.e.EzuriRenegadeLeader.class));
cards.add(new SetCardInfo("Ezuri's Archers", 120, Rarity.COMMON, mage.cards.e.EzurisArchers.class));
cards.add(new SetCardInfo("Ezuri's Brigade", 121, Rarity.RARE, mage.cards.e.EzurisBrigade.class));
cards.add(new SetCardInfo("Ferrovore", 88, Rarity.COMMON, mage.cards.f.Ferrovore.class));
cards.add(new SetCardInfo("Flameborn Hellion", 89, Rarity.COMMON, mage.cards.f.FlamebornHellion.class));
cards.add(new SetCardInfo("Flesh Allergy", 62, Rarity.UNCOMMON, mage.cards.f.FleshAllergy.class));
cards.add(new SetCardInfo("Flight Spellbomb", 155, Rarity.COMMON, mage.cards.f.FlightSpellbomb.class));
cards.add(new SetCardInfo("Forest", 246, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 247, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 248, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Forest", 249, Rarity.LAND, mage.cards.basiclands.Forest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Fulgent Distraction", 7, Rarity.COMMON, mage.cards.f.FulgentDistraction.class));
cards.add(new SetCardInfo("Fume Spitter", 63, Rarity.COMMON, mage.cards.f.FumeSpitter.class));
cards.add(new SetCardInfo("Furnace Celebration", 90, Rarity.UNCOMMON, mage.cards.f.FurnaceCelebration.class));
cards.add(new SetCardInfo("Galvanic Blast", 91, Rarity.COMMON, mage.cards.g.GalvanicBlast.class));
cards.add(new SetCardInfo("Genesis Wave", 122, Rarity.RARE, mage.cards.g.GenesisWave.class));
cards.add(new SetCardInfo("Geth, Lord of the Vault", 64, Rarity.MYTHIC, mage.cards.g.GethLordOfTheVault.class));
cards.add(new SetCardInfo("Ghalma's Warden", 8, Rarity.COMMON, mage.cards.g.GhalmasWarden.class));
cards.add(new SetCardInfo("Glimmerpoint Stag", 9, Rarity.UNCOMMON, mage.cards.g.GlimmerpointStag.class));
cards.add(new SetCardInfo("Glimmerpost", 227, Rarity.COMMON, mage.cards.g.Glimmerpost.class));
cards.add(new SetCardInfo("Glint Hawk", 10, Rarity.COMMON, mage.cards.g.GlintHawk.class));
cards.add(new SetCardInfo("Glint Hawk Idol", 156, Rarity.COMMON, mage.cards.g.GlintHawkIdol.class));
cards.add(new SetCardInfo("Goblin Gaveleer", 92, Rarity.COMMON, mage.cards.g.GoblinGaveleer.class));
cards.add(new SetCardInfo("Golden Urn", 158, Rarity.COMMON, mage.cards.g.GoldenUrn.class));
cards.add(new SetCardInfo("Gold Myr", 157, Rarity.COMMON, mage.cards.g.GoldMyr.class));
cards.add(new SetCardInfo("Golem Artisan", 159, Rarity.UNCOMMON, mage.cards.g.GolemArtisan.class));
cards.add(new SetCardInfo("Golem Foundry", 160, Rarity.COMMON, mage.cards.g.GolemFoundry.class));
cards.add(new SetCardInfo("Golem's Heart", 161, Rarity.UNCOMMON, mage.cards.g.GolemsHeart.class));
cards.add(new SetCardInfo("Grafted Exoskeleton", 162, Rarity.UNCOMMON, mage.cards.g.GraftedExoskeleton.class));
cards.add(new SetCardInfo("Grand Architect", 33, Rarity.RARE, mage.cards.g.GrandArchitect.class));
cards.add(new SetCardInfo("Grasp of Darkness", 65, Rarity.COMMON, mage.cards.g.GraspOfDarkness.class));
cards.add(new SetCardInfo("Grindclock", 163, Rarity.RARE, mage.cards.g.Grindclock.class));
cards.add(new SetCardInfo("Halt Order", 34, Rarity.UNCOMMON, mage.cards.h.HaltOrder.class));
cards.add(new SetCardInfo("Hand of the Praetors", 66, Rarity.RARE, mage.cards.h.HandOfThePraetors.class));
cards.add(new SetCardInfo("Heavy Arbalest", 164, Rarity.UNCOMMON, mage.cards.h.HeavyArbalest.class));
cards.add(new SetCardInfo("Hoard-Smelter Dragon", 93, Rarity.RARE, mage.cards.h.HoardSmelterDragon.class));
cards.add(new SetCardInfo("Horizon Spellbomb", 165, Rarity.COMMON, mage.cards.h.HorizonSpellbomb.class));
cards.add(new SetCardInfo("Ichorclaw Myr", 166, Rarity.COMMON, mage.cards.i.IchorclawMyr.class));
cards.add(new SetCardInfo("Ichor Rats", 67, Rarity.UNCOMMON, mage.cards.i.IchorRats.class));
cards.add(new SetCardInfo("Indomitable Archangel", 11, Rarity.MYTHIC, mage.cards.i.IndomitableArchangel.class));
cards.add(new SetCardInfo("Inexorable Tide", 35, Rarity.RARE, mage.cards.i.InexorableTide.class));
cards.add(new SetCardInfo("Infiltration Lens", 167, Rarity.UNCOMMON, mage.cards.i.InfiltrationLens.class));
cards.add(new SetCardInfo("Instill Infection", 68, Rarity.COMMON, mage.cards.i.InstillInfection.class));
cards.add(new SetCardInfo("Iron Myr", 168, Rarity.COMMON, mage.cards.i.IronMyr.class));
cards.add(new SetCardInfo("Island", 234, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 235, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 236, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Island", 237, Rarity.LAND, mage.cards.basiclands.Island.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Kemba, Kha Regent", 12, Rarity.RARE, mage.cards.k.KembaKhaRegent.class));
cards.add(new SetCardInfo("Kemba's Skyguard", 13, Rarity.COMMON, mage.cards.k.KembasSkyguard.class));
cards.add(new SetCardInfo("Koth of the Hammer", 94, Rarity.MYTHIC, mage.cards.k.KothOfTheHammer.class));
cards.add(new SetCardInfo("Kuldotha Forgemaster", 169, Rarity.RARE, mage.cards.k.KuldothaForgemaster.class));
cards.add(new SetCardInfo("Kuldotha Phoenix", 95, Rarity.RARE, mage.cards.k.KuldothaPhoenix.class));
cards.add(new SetCardInfo("Kuldotha Rebirth", 96, Rarity.COMMON, mage.cards.k.KuldothaRebirth.class));
cards.add(new SetCardInfo("Leaden Myr", 170, Rarity.COMMON, mage.cards.l.LeadenMyr.class));
cards.add(new SetCardInfo("Leonin Arbiter", 14, Rarity.RARE, mage.cards.l.LeoninArbiter.class));
cards.add(new SetCardInfo("Liege of the Tangle", 123, Rarity.MYTHIC, mage.cards.l.LiegeOfTheTangle.class));
cards.add(new SetCardInfo("Lifesmith", 124, Rarity.UNCOMMON, mage.cards.l.Lifesmith.class));
cards.add(new SetCardInfo("Liquimetal Coating", 171, Rarity.UNCOMMON, mage.cards.l.LiquimetalCoating.class));
cards.add(new SetCardInfo("Livewire Lash", 172, Rarity.RARE, mage.cards.l.LivewireLash.class));
cards.add(new SetCardInfo("Loxodon Wayfarer", 15, Rarity.COMMON, mage.cards.l.LoxodonWayfarer.class));
cards.add(new SetCardInfo("Lumengrid Drake", 36, Rarity.COMMON, mage.cards.l.LumengridDrake.class));
cards.add(new SetCardInfo("Lux Cannon", 173, Rarity.MYTHIC, mage.cards.l.LuxCannon.class));
cards.add(new SetCardInfo("Melt Terrain", 97, Rarity.COMMON, mage.cards.m.MeltTerrain.class));
cards.add(new SetCardInfo("Memnite", 174, Rarity.UNCOMMON, mage.cards.m.Memnite.class));
cards.add(new SetCardInfo("Memoricide", 69, Rarity.RARE, mage.cards.m.Memoricide.class));
cards.add(new SetCardInfo("Mimic Vat", 175, Rarity.RARE, mage.cards.m.MimicVat.class));
cards.add(new SetCardInfo("Mindslaver", 176, Rarity.MYTHIC, mage.cards.m.Mindslaver.class));
cards.add(new SetCardInfo("Molder Beast", 125, Rarity.COMMON, mage.cards.m.MolderBeast.class));
cards.add(new SetCardInfo("Molten Psyche", 98, Rarity.RARE, mage.cards.m.MoltenPsyche.class));
cards.add(new SetCardInfo("Molten-Tail Masticore", 177, Rarity.MYTHIC, mage.cards.m.MoltenTailMasticore.class));
cards.add(new SetCardInfo("Moriok Reaver", 70, Rarity.COMMON, mage.cards.m.MoriokReaver.class));
cards.add(new SetCardInfo("Moriok Replica", 178, Rarity.COMMON, mage.cards.m.MoriokReplica.class));
cards.add(new SetCardInfo("Mountain", 242, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 243, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 244, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mountain", 245, Rarity.LAND, mage.cards.basiclands.Mountain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mox Opal", 179, Rarity.MYTHIC, mage.cards.m.MoxOpal.class));
cards.add(new SetCardInfo("Myr Battlesphere", 180, Rarity.RARE, mage.cards.m.MyrBattlesphere.class));
cards.add(new SetCardInfo("Myr Galvanizer", 181, Rarity.UNCOMMON, mage.cards.m.MyrGalvanizer.class));
cards.add(new SetCardInfo("Myr Propagator", 182, Rarity.RARE, mage.cards.m.MyrPropagator.class));
cards.add(new SetCardInfo("Myr Reservoir", 183, Rarity.RARE, mage.cards.m.MyrReservoir.class));
cards.add(new SetCardInfo("Myrsmith", 16, Rarity.UNCOMMON, mage.cards.m.Myrsmith.class));
cards.add(new SetCardInfo("Necrogen Censer", 184, Rarity.COMMON, mage.cards.n.NecrogenCenser.class));
cards.add(new SetCardInfo("Necrogen Scudder", 71, Rarity.UNCOMMON, mage.cards.n.NecrogenScudder.class));
cards.add(new SetCardInfo("Necropede", 185, Rarity.UNCOMMON, mage.cards.n.Necropede.class));
cards.add(new SetCardInfo("Necrotic Ooze", 72, Rarity.RARE, mage.cards.n.NecroticOoze.class));
cards.add(new SetCardInfo("Neurok Invisimancer", 37, Rarity.COMMON, mage.cards.n.NeurokInvisimancer.class));
cards.add(new SetCardInfo("Neurok Replica", 186, Rarity.COMMON, mage.cards.n.NeurokReplica.class));
cards.add(new SetCardInfo("Nihil Spellbomb", 187, Rarity.COMMON, mage.cards.n.NihilSpellbomb.class));
cards.add(new SetCardInfo("Nim Deathmantle", 188, Rarity.RARE, mage.cards.n.NimDeathmantle.class));
cards.add(new SetCardInfo("Ogre Geargrabber", 99, Rarity.UNCOMMON, mage.cards.o.OgreGeargrabber.class));
cards.add(new SetCardInfo("Origin Spellbomb", 189, Rarity.COMMON, mage.cards.o.OriginSpellbomb.class));
cards.add(new SetCardInfo("Oxidda Daredevil", 100, Rarity.COMMON, mage.cards.o.OxiddaDaredevil.class));
cards.add(new SetCardInfo("Oxidda Scrapmelter", 101, Rarity.UNCOMMON, mage.cards.o.OxiddaScrapmelter.class));
cards.add(new SetCardInfo("Painful Quandary", 73, Rarity.RARE, mage.cards.p.PainfulQuandary.class));
cards.add(new SetCardInfo("Painsmith", 74, Rarity.UNCOMMON, mage.cards.p.Painsmith.class));
cards.add(new SetCardInfo("Palladium Myr", 190, Rarity.UNCOMMON, mage.cards.p.PalladiumMyr.class));
cards.add(new SetCardInfo("Panic Spellbomb", 191, Rarity.COMMON, mage.cards.p.PanicSpellbomb.class));
cards.add(new SetCardInfo("Perilous Myr", 192, Rarity.COMMON, mage.cards.p.PerilousMyr.class));
cards.add(new SetCardInfo("Plague Stinger", 75, Rarity.COMMON, mage.cards.p.PlagueStinger.class));
cards.add(new SetCardInfo("Plains", 230, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 231, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 232, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plains", 233, Rarity.LAND, mage.cards.basiclands.Plains.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Plated Seastrider", 38, Rarity.COMMON, mage.cards.p.PlatedSeastrider.class));
cards.add(new SetCardInfo("Platinum Emperion", 193, Rarity.MYTHIC, mage.cards.p.PlatinumEmperion.class));
cards.add(new SetCardInfo("Precursor Golem", 194, Rarity.RARE, mage.cards.p.PrecursorGolem.class));
cards.add(new SetCardInfo("Prototype Portal", 195, Rarity.RARE, mage.cards.p.PrototypePortal.class));
cards.add(new SetCardInfo("Psychic Miasma", 76, Rarity.COMMON, mage.cards.p.PsychicMiasma.class));
cards.add(new SetCardInfo("Putrefax", 126, Rarity.RARE, mage.cards.p.Putrefax.class));
cards.add(new SetCardInfo("Quicksilver Gargantuan", 39, Rarity.MYTHIC, mage.cards.q.QuicksilverGargantuan.class));
cards.add(new SetCardInfo("Ratchet Bomb", 196, Rarity.RARE, mage.cards.r.RatchetBomb.class));
cards.add(new SetCardInfo("Razorfield Thresher", 197, Rarity.COMMON, mage.cards.r.RazorfieldThresher.class));
cards.add(new SetCardInfo("Razor Hippogriff", 17, Rarity.UNCOMMON, mage.cards.r.RazorHippogriff.class));
cards.add(new SetCardInfo("Razorverge Thicket", 228, Rarity.RARE, mage.cards.r.RazorvergeThicket.class));
cards.add(new SetCardInfo("Relic Putrescence", 77, Rarity.COMMON, mage.cards.r.RelicPutrescence.class));
cards.add(new SetCardInfo("Revoke Existence", 18, Rarity.COMMON, mage.cards.r.RevokeExistence.class));
cards.add(new SetCardInfo("Riddlesmith", 40, Rarity.UNCOMMON, mage.cards.r.Riddlesmith.class));
cards.add(new SetCardInfo("Rusted Relic", 199, Rarity.UNCOMMON, mage.cards.r.RustedRelic.class));
cards.add(new SetCardInfo("Rust Tick", 198, Rarity.UNCOMMON, mage.cards.r.RustTick.class));
cards.add(new SetCardInfo("Saberclaw Golem", 200, Rarity.COMMON, mage.cards.s.SaberclawGolem.class));
cards.add(new SetCardInfo("Salvage Scout", 19, Rarity.COMMON, mage.cards.s.SalvageScout.class));
cards.add(new SetCardInfo("Scoria Elemental", 102, Rarity.COMMON, mage.cards.s.ScoriaElemental.class));
cards.add(new SetCardInfo("Scrapdiver Serpent", 41, Rarity.COMMON, mage.cards.s.ScrapdiverSerpent.class));
cards.add(new SetCardInfo("Screeching Silcaw", 42, Rarity.COMMON, mage.cards.s.ScreechingSilcaw.class));
cards.add(new SetCardInfo("Seachrome Coast", 229, Rarity.RARE, mage.cards.s.SeachromeCoast.class));
cards.add(new SetCardInfo("Seize the Initiative", 20, Rarity.COMMON, mage.cards.s.SeizeTheInitiative.class));
cards.add(new SetCardInfo("Semblance Anvil", 201, Rarity.RARE, mage.cards.s.SemblanceAnvil.class));
cards.add(new SetCardInfo("Shape Anew", 43, Rarity.RARE, mage.cards.s.ShapeAnew.class));
cards.add(new SetCardInfo("Shatter", 103, Rarity.COMMON, mage.cards.s.Shatter.class));
cards.add(new SetCardInfo("Silver Myr", 202, Rarity.COMMON, mage.cards.s.SilverMyr.class));
cards.add(new SetCardInfo("Skinrender", 78, Rarity.UNCOMMON, mage.cards.s.Skinrender.class));
cards.add(new SetCardInfo("Skithiryx, the Blight Dragon", 79, Rarity.MYTHIC, mage.cards.s.SkithiryxTheBlightDragon.class));
cards.add(new SetCardInfo("Sky-Eel School", 44, Rarity.COMMON, mage.cards.s.SkyEelSchool.class));
cards.add(new SetCardInfo("Slice in Twain", 127, Rarity.UNCOMMON, mage.cards.s.SliceInTwain.class));
cards.add(new SetCardInfo("Snapsail Glider", 203, Rarity.COMMON, mage.cards.s.SnapsailGlider.class));
cards.add(new SetCardInfo("Soliton", 204, Rarity.COMMON, mage.cards.s.Soliton.class));
cards.add(new SetCardInfo("Soul Parry", 21, Rarity.COMMON, mage.cards.s.SoulParry.class));
cards.add(new SetCardInfo("Spikeshot Elder", 104, Rarity.RARE, mage.cards.s.SpikeshotElder.class));
cards.add(new SetCardInfo("Steady Progress", 45, Rarity.COMMON, mage.cards.s.SteadyProgress.class));
cards.add(new SetCardInfo("Steel Hellkite", 205, Rarity.RARE, mage.cards.s.SteelHellkite.class));
cards.add(new SetCardInfo("Stoic Rebuttal", 46, Rarity.COMMON, mage.cards.s.StoicRebuttal.class));
cards.add(new SetCardInfo("Strata Scythe", 206, Rarity.RARE, mage.cards.s.StrataScythe.class));
cards.add(new SetCardInfo("Strider Harness", 207, Rarity.COMMON, mage.cards.s.StriderHarness.class));
cards.add(new SetCardInfo("Sunblast Angel", 22, Rarity.RARE, mage.cards.s.SunblastAngel.class));
cards.add(new SetCardInfo("Sunspear Shikari", 23, Rarity.COMMON, mage.cards.s.SunspearShikari.class));
cards.add(new SetCardInfo("Swamp", 238, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 239, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 240, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swamp", 241, Rarity.LAND, mage.cards.basiclands.Swamp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Sword of Body and Mind", 208, Rarity.MYTHIC, mage.cards.s.SwordOfBodyAndMind.class));
cards.add(new SetCardInfo("Sylvok Lifestaff", 209, Rarity.COMMON, mage.cards.s.SylvokLifestaff.class));
cards.add(new SetCardInfo("Sylvok Replica", 210, Rarity.COMMON, mage.cards.s.SylvokReplica.class));
cards.add(new SetCardInfo("Tainted Strike", 80, Rarity.COMMON, mage.cards.t.TaintedStrike.class));
cards.add(new SetCardInfo("Tangle Angler", 128, Rarity.UNCOMMON, mage.cards.t.TangleAngler.class));
cards.add(new SetCardInfo("Tel-Jilad Defiance", 129, Rarity.COMMON, mage.cards.t.TelJiladDefiance.class));
cards.add(new SetCardInfo("Tel-Jilad Fallen", 130, Rarity.COMMON, mage.cards.t.TelJiladFallen.class));
cards.add(new SetCardInfo("Tempered Steel", 24, Rarity.RARE, mage.cards.t.TemperedSteel.class));
cards.add(new SetCardInfo("Throne of Geth", 211, Rarity.UNCOMMON, mage.cards.t.ThroneOfGeth.class));
cards.add(new SetCardInfo("Thrummingbird", 47, Rarity.UNCOMMON, mage.cards.t.Thrummingbird.class));
cards.add(new SetCardInfo("Tower of Calamities", 212, Rarity.RARE, mage.cards.t.TowerOfCalamities.class));
cards.add(new SetCardInfo("Trigon of Corruption", 213, Rarity.UNCOMMON, mage.cards.t.TrigonOfCorruption.class));
cards.add(new SetCardInfo("Trigon of Infestation", 214, Rarity.UNCOMMON, mage.cards.t.TrigonOfInfestation.class));
cards.add(new SetCardInfo("Trigon of Mending", 215, Rarity.UNCOMMON, mage.cards.t.TrigonOfMending.class));
cards.add(new SetCardInfo("Trigon of Rage", 216, Rarity.UNCOMMON, mage.cards.t.TrigonOfRage.class));
cards.add(new SetCardInfo("Trigon of Thought", 217, Rarity.UNCOMMON, mage.cards.t.TrigonOfThought.class));
cards.add(new SetCardInfo("Trinket Mage", 48, Rarity.UNCOMMON, mage.cards.t.TrinketMage.class));
cards.add(new SetCardInfo("True Conviction", 25, Rarity.RARE, mage.cards.t.TrueConviction.class));
cards.add(new SetCardInfo("Tumble Magnet", 218, Rarity.COMMON, mage.cards.t.TumbleMagnet.class));
cards.add(new SetCardInfo("Tunnel Ignus", 105, Rarity.RARE, mage.cards.t.TunnelIgnus.class));
cards.add(new SetCardInfo("Turn Aside", 49, Rarity.COMMON, mage.cards.t.TurnAside.class));
cards.add(new SetCardInfo("Turn to Slag", 106, Rarity.COMMON, mage.cards.t.TurnToSlag.class));
cards.add(new SetCardInfo("Twisted Image", 50, Rarity.UNCOMMON, mage.cards.t.TwistedImage.class));
cards.add(new SetCardInfo("Untamed Might", 131, Rarity.COMMON, mage.cards.u.UntamedMight.class));
cards.add(new SetCardInfo("Vault Skyward", 51, Rarity.COMMON, mage.cards.v.VaultSkyward.class));
cards.add(new SetCardInfo("Vector Asp", 219, Rarity.COMMON, mage.cards.v.VectorAsp.class));
cards.add(new SetCardInfo("Vedalken Certarch", 52, Rarity.COMMON, mage.cards.v.VedalkenCertarch.class));
cards.add(new SetCardInfo("Venser's Journal", 220, Rarity.RARE, mage.cards.v.VensersJournal.class));
cards.add(new SetCardInfo("Venser, the Sojourner", 135, Rarity.MYTHIC, mage.cards.v.VenserTheSojourner.class));
cards.add(new SetCardInfo("Vigil for the Lost", 26, Rarity.UNCOMMON, mage.cards.v.VigilForTheLost.class));
cards.add(new SetCardInfo("Viridian Revel", 132, Rarity.UNCOMMON, mage.cards.v.ViridianRevel.class));
cards.add(new SetCardInfo("Volition Reins", 53, Rarity.UNCOMMON, mage.cards.v.VolitionReins.class));
cards.add(new SetCardInfo("Vulshok Heartstoker", 107, Rarity.COMMON, mage.cards.v.VulshokHeartstoker.class));
cards.add(new SetCardInfo("Vulshok Replica", 221, Rarity.COMMON, mage.cards.v.VulshokReplica.class));
cards.add(new SetCardInfo("Wall of Tanglecord", 222, Rarity.COMMON, mage.cards.w.WallOfTanglecord.class));
cards.add(new SetCardInfo("Whitesun's Passage", 27, Rarity.COMMON, mage.cards.w.WhitesunsPassage.class));
cards.add(new SetCardInfo("Wing Puncture", 133, Rarity.COMMON, mage.cards.w.WingPuncture.class));
cards.add(new SetCardInfo("Withstand Death", 134, Rarity.COMMON, mage.cards.w.WithstandDeath.class));
cards.add(new SetCardInfo("Wurmcoil Engine", 223, Rarity.MYTHIC, mage.cards.w.WurmcoilEngine.class));
}
@Override
public BoosterCollator createCollator() {
return new ScarsOfMirrodinCollator();
}
}
// Booster collation info from https://www.lethe.xyz/mtg/collation/som.html
// Using USA collation
class ScarsOfMirrodinCollator implements BoosterCollator {
private final CardRun commonA = new CardRun(true, "70", "8", "189", "38", "106", "166", "65", "23", "221", "112", "138", "75", "84", "168", "13", "29", "157", "68", "117", "156", "89", "210", "70", "44", "200", "10", "170", "63", "130", "4", "168", "38", "157", "88", "8", "204", "65", "29", "221", "106", "23", "200", "130", "166", "75", "36", "189", "89", "13", "204", "4", "138", "68", "44", "202", "84", "112", "210", "63", "10", "156", "36", "88", "202", "117", "170");
private final CardRun commonB = new CardRun(true, "114", "58", "207", "109", "18", "146", "107", "37", "142", "114", "147", "41", "2", "192", "107", "52", "146", "125", "18", "209", "129", "178", "58", "91", "192", "55", "52", "207", "125", "2", "186", "91", "142", "129", "37", "209", "109", "103", "178", "41", "18", "207", "58", "186", "103", "129", "146", "41", "91", "178", "55", "37", "147", "125", "186", "114", "52", "209", "55", "103", "192", "109", "107", "147", "2", "142");
private final CardRun commonC1 = new CardRun(true, "116", "54", "184", "97", "15", "160", "113", "51", "203", "54", "153", "82", "21", "155", "120", "45", "187", "60", "97", "153", "46", "15", "133", "45", "165", "227", "92", "184", "31", "7", "60", "116", "187", "227", "96", "219", "51", "21", "191", "120", "77", "165", "82", "219", "133", "92", "203", "46", "77", "155", "113", "7", "96", "31", "191");
private final CardRun commonC2 = new CardRun(true, "197", "56", "27", "102", "136", "19", "140", "20", "76", "49", "131", "222", "158", "56", "136", "80", "20", "131", "140", "100", "158", "160", "80", "49", "20", "134", "222", "27", "218", "42", "100", "76", "197", "140", "102", "131", "42", "80", "218", "19", "197", "158", "134", "42", "56", "100", "19", "222", "136", "27", "49", "102", "134", "76", "218");
private final CardRun uncommonA = new CardRun(true, "78", "108", "171", "90", "47", "185", "101", "132", "217", "3", "214", "71", "167", "127", "53", "159", "85", "161", "71", "216", "26", "149", "62", "164", "124", "47", "161", "61", "81", "3", "185", "26", "143", "62", "50", "213", "90", "216", "124", "214", "30", "167", "17", "139", "61", "1", "171", "85", "30", "217", "81", "108", "139", "1", "149", "78", "127", "159", "101", "53", "213", "17", "132", "164", "50", "143");
private final CardRun uncommonB = new CardRun(true, "59", "151", "115", "9", "211", "40", "144", "59", "198", "83", "174", "128", "48", "199", "5", "9", "152", "148", "67", "99", "151", "34", "16", "211", "174", "87", "115", "198", "40", "74", "181", "215", "83", "111", "190", "34", "162", "16", "144", "67", "152", "111", "181", "87", "148", "5", "74", "199", "128", "190", "99", "215", "48", "162");
private final CardRun rareA = new CardRun(true, "180", "95", "119", "201", "177", "66", "122", "14", "205", "226", "220", "43", "223", "95", "121", "69", "212", "22", "183", "229", "173", "28", "73", "194", "33", "98", "205", "25", "179", "224", "182", "122", "93", "201", "22", "180", "43", "64", "188", "229", "212", "119", "145", "28", "69", "194", "14", "135", "163", "93", "183", "224", "220", "25", "39", "188", "66", "182", "121", "98", "145", "73", "11", "226", "163", "33");
private final CardRun rareB = new CardRun(true, "154", "104", "225", "193", "24", "172", "118", "105", "175", "72", "169", "228", "141", "208", "35", "150", "86", "126", "118", "12", "195", "176", "72", "32", "137", "105", "123", "150", "24", "196", "225", "141", "57", "154", "206", "6", "228", "104", "110", "137", "126", "175", "35", "169", "94", "195", "172", "57", "12", "86", "206", "79", "110", "196", "32");
private final CardRun land = new CardRun(false, "230", "231", "232", "233", "234", "235", "236", "237", "238", "239", "240", "241", "242", "243", "244", "245", "246", "247", "248", "249");
private final BoosterStructure AAABC1C1C1C1C1C1 = new BoosterStructure(
commonA, commonA, commonA,
commonB,
commonC1, commonC1, commonC1, commonC1, commonC1, commonC1
);
private final BoosterStructure AAABBC1C1C1C1C1 = new BoosterStructure(
commonA, commonA, commonA,
commonB, commonB,
commonC1, commonC1, commonC1, commonC1, commonC1
);
private final BoosterStructure AAABC2C2C2C2C2C2 = new BoosterStructure(
commonA, commonA, commonA,
commonB,
commonC2, commonC2, commonC2, commonC2, commonC2, commonC2
);
private final BoosterStructure AAABBC2C2C2C2C2 = new BoosterStructure(
commonA, commonA, commonA,
commonB, commonB,
commonC2, commonC2, commonC2, commonC2, commonC2
);
private final BoosterStructure AAABBBC2C2C2C2 = new BoosterStructure(
commonA, commonA, commonA,
commonB, commonB, commonB,
commonC2, commonC2, commonC2, commonC2
);
private final BoosterStructure AAABBBBC2C2C2 = new BoosterStructure(
commonA, commonA, commonA,
commonB, commonB, commonB, commonB,
commonC2, commonC2, commonC2
);
private final BoosterStructure AAAABBBC2C2C2 = new BoosterStructure(
commonA, commonA, commonA, commonA,
commonB, commonB, commonB,
commonC2, commonC2, commonC2
);
private final BoosterStructure AAAABBBBC2C2 = new BoosterStructure(
commonA, commonA, commonA, commonA,
commonB, commonB, commonB, commonB,
commonC2, commonC2
);
private final BoosterStructure AAB = new BoosterStructure(uncommonA, uncommonA, uncommonB);
private final BoosterStructure ABB = new BoosterStructure(uncommonA, uncommonB, uncommonB);
private final BoosterStructure R1 = new BoosterStructure(rareA);
private final BoosterStructure R2 = new BoosterStructure(rareB);
private final BoosterStructure L1 = new BoosterStructure(land);
// In order for equal numbers of each common to exist, the average booster must contain:
// 3.27 A commons (36 / 11)
// 2.18 B commons (24 / 11)
// 2.73 C1 commons (30 / 11, or 60 / 11 in each C1 booster)
// 1.82 C2 commons (20 / 11, or 40 / 11 in each C2 booster)
// These numbers are the same for all sets with 101 commons in A/B/C1/C2 print runs
// and with 10 common slots per booster
private final RarityConfiguration commonRuns = new RarityConfiguration(
AAABC1C1C1C1C1C1,
AAABC1C1C1C1C1C1,
AAABC1C1C1C1C1C1,
AAABC1C1C1C1C1C1,
AAABC1C1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABBC1C1C1C1C1,
AAABC2C2C2C2C2C2,
AAABBC2C2C2C2C2,
AAABBC2C2C2C2C2,
AAABBBC2C2C2C2,
AAABBBBC2C2C2,
AAAABBBC2C2C2,
AAAABBBC2C2C2,
AAAABBBC2C2C2,
AAAABBBC2C2C2,
AAAABBBC2C2C2,
AAAABBBBC2C2
);
// In order for equal numbers of each uncommon to exist, the average booster must contain:
// 1.65 A uncommons (33 / 20)
// 1.35 B uncommons (27 / 20)
// These numbers are the same for all sets with 60 uncommons in asymmetrical A/B print runs
private final RarityConfiguration uncommonRuns = new RarityConfiguration(
AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB, AAB,
ABB, ABB, ABB, ABB, ABB, ABB, ABB
);
private final RarityConfiguration rareRuns = new RarityConfiguration(
R1, R1, R1, R1, R1, R1,
R2, R2, R2, R2, R2
);
private final RarityConfiguration landRuns = new RarityConfiguration(L1);
@Override
public List<String> makeBooster() {
List<String> booster = new ArrayList<>();
booster.addAll(commonRuns.getNext().makeRun());
booster.addAll(uncommonRuns.getNext().makeRun());
booster.addAll(rareRuns.getNext().makeRun());
booster.addAll(landRuns.getNext().makeRun());
return booster;
}
}
| 89.894349 | 489 | 0.684068 |
bb7bbc9603320f4748dbe5666eae31b871ef689a | 497 | package com.ilemontech.ldcos.system.service.impl;
import com.ilemontech.ldcos.system.entity.Role;
import com.ilemontech.ldcos.system.mapper.RoleMapper;
import com.ilemontech.ldcos.system.service.IRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author zhaicl
* @since 2017-08-03
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
}
| 23.666667 | 92 | 0.778672 |
0c0c57920da0617b4f7d8a8facdc11b7a915044d | 2,081 | package com.app.zine.zine;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import java.util.Objects;
public class TeamActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.teamactivity);
Toolbar toolbar =findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Team");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("2nd Year"));
tabLayout.addTab(tabLayout.newTab().setText("3rd Year"));
tabLayout.addTab(tabLayout.newTab().setText("4th Year"));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager =findViewById(R.id.view_pager);
TabsAdapter tabsAdapter = new TabsAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(tabsAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
} | 37.836364 | 104 | 0.681884 |
e8af56f1bdd191ed0966cde2fd3df31afea6f70d | 3,554 | /*
* #!
* Ontopoly Editor
* #-
* Copyright (C) 2001 - 2013 The Ontopia 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 ontopoly.components;
import java.util.Collection;
import java.util.Iterator;
import ontopoly.model.Topic;
import ontopoly.models.TopicModel;
import ontopoly.pages.AbstractOntopolyPage;
import ontopoly.pages.ModalConfirmPage;
import ontopoly.utils.WicketHacks;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.ResourceModel;
public abstract class DeleteTopicFunctionBoxPanel extends Panel {
public DeleteTopicFunctionBoxPanel(String id) {
super(id);
add(new Label("title", new ResourceModel("delete.this.topic")));
final ModalWindow deleteModal = new ModalWindow("deleteModal");
ModalConfirmPage modalDeletePanel = new ModalConfirmPage(deleteModal.getContentId()) {
@Override
protected void onCloseCancel(AjaxRequestTarget target) {
// close modal
deleteModal.close(target);
}
@Override
protected void onCloseOk(AjaxRequestTarget target) {
// close modal
deleteModal.close(target);
// notify listeners
Topic instance = (Topic)getTopicModel().getObject();
onDeleteConfirmed(instance);
// remove dependent objects
AbstractOntopolyPage page = (AbstractOntopolyPage)getPage();
Collection<Topic> dependentObjects = instance.getDependentObjects();
Iterator<Topic> diter = dependentObjects.iterator();
while (diter.hasNext()) {
Topic dtopic = diter.next();
dtopic.remove(page);
}
// remove topic
instance.remove(page);
}
@Override
protected Component getTitleComponent(String id) {
return new Label(id, new ResourceModel("delete.confirm"));
}
@Override
protected Component getMessageComponent(String id) {
return new Label(id, new ResourceModel("delete.message.topic"));
}
};
deleteModal.setContent(modalDeletePanel);
deleteModal.setTitle(new ResourceModel("ModalWindow.title.delete.topic").getObject().toString());
deleteModal.setCookieName("deleteModal");
add(deleteModal);
Button createButton = new Button("deleteButton");
createButton.add(new AjaxFormComponentUpdatingBehavior("onclick") {
@Override
protected void onUpdate(AjaxRequestTarget target) {
WicketHacks.disableWindowUnloadConfirmation(target);
deleteModal.show(target);
}
});
add(createButton);
}
public abstract TopicModel<Topic> getTopicModel();
public abstract void onDeleteConfirmed(Topic topic);
}
| 34.504854 | 101 | 0.709904 |
1ab603c1c055394ac7d74279e807e568a294549e | 2,213 | package com.georef.api.provincias.controller;
import com.georef.api.provincias.service.ProvinciaService;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.lang.String;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
@RequestMapping(value="/georef", method=RequestMethod.GET)
@CrossOrigin(origins = "http://localhost:4200")
public class ProvinciaController {
@Autowired
ProvinciaService provinciaService;
@PostMapping("/provincia/{nombre}")
public ResponseEntity<Object> listref(@PathVariable String nombre){
RestTemplate restTemplate = new RestTemplate();
String Url = "https://apis.datos.gob.ar/georef/api/provincias?nombre=" + nombre ;
// List<Producto> list = provinciaService.list();
ResponseEntity<String> response = restTemplate.getForEntity(Url ,String.class);
System.out.println(response.getBody().toString());
System.out.println();
return new ResponseEntity(response.getBody(), HttpStatus.OK);
}
public RestTemplate restTemplate() { return new RestTemplate(); }
/*
* @EnableWebSecurity
*
* public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
*
* @Override protected void configure(HttpSecurity http) throws Exception { http
* .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); }
*
* }
*/
}
| 29.905405 | 101 | 0.749209 |
598bce8d97ccc2e91f4b6345cf810d518091ba06 | 3,586 | /*
* Copyright (c) 2013-2018, Bingo.Chen ([email protected]).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.corant.modules.query;
import java.util.List;
import org.corant.modules.query.mapping.Query;
import org.corant.modules.query.mapping.QueryHint;
import org.corant.modules.query.spi.ResultHintHandler;
/**
* corant-modules-query-api
*
* <p>
* This interface is used to process normal queries, provide processing of the query parameters, and
* provide processing of the query result set.
*
* @author bingo 下午4:56:52
*
*/
public interface QueryHandler {
/**
* Return the QueryObjectMapper to process result type conversion or query script conversion.
*
* @return getObjectMapper
*/
QueryObjectMapper getObjectMapper();
/**
* Returns the querier configuration.
*
* @return the querier configuration
*/
QuerierConfig getQuerierConfig();
/**
* Handle a single result, perform the hint handler and convert the result to the expected typed
* object.
*
* @param <T> the result type
* @param result the original results, currently is <b> Map<String,Object></b>
* @param query the query object
* @param parameter the query parameter
*
* @see #handleResultHints(Object, Class, Query, QueryParameter)
* @see QueryHint
* @see Query
* @see ResultHintHandler
*/
<T> T handleResult(Object result, Query query, QueryParameter parameter);
/**
* Handle query hints, in this step the result set may be adjusted or inserted with certain
* values.
*
* @param result the result may be single object or list objects
* @param originalResultClass the query result class
* @param query the query object
* @param parameter the query parameter
*
* @see ResultHintHandler
*/
void handleResultHints(Object result, Class<?> originalResultClass, Query query,
QueryParameter parameter);
/**
* Handle result list, The steps are as follows:
*
* <pre>
* 1.Handle query hints, in this step the result set may be adjusted or inserted with
* certain values.
*
* 2.Convert result by result class.
* </pre>
*
* @param <T> the result class
* @param results the original results, currently is <b> List<Map<String,Object>></b>
* @param query the query object
* @param parameter the query parameter
*
*
* @see #handleResultHints(Object, Class, Query, QueryParameter)
* @see QueryHint
* @see Query
* @see ResultHintHandler
*/
<T> List<T> handleResults(List<Object> results, Query query, QueryParameter parameter);
/**
* Resolve query parameter. If QueryParameterReviser exists, the given parameter may be adjusted.
*
* <p>
* NOTE: If the given parameter is not an instance of QueryParameter then the given parameter is
* regarded as the criteria of the normal query parameter.
*
* @param query the query
* @param parameter the original query parameter
* @return normal query parameter object
*/
QueryParameter resolveParameter(Query query, Object parameter);
}
| 31.734513 | 100 | 0.70831 |
b4c1f2478409ab4a8ce94ec6dd1163b8f8821228 | 2,686 | /* Copyright 2020 Braden Farmer
*
* 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.farmerbb.taskbar.backup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONBackupAgent implements BackupAgent {
private final JSONObject json;
public JSONBackupAgent(JSONObject json) {
this.json = json;
}
@Override
public void putString(String key, String value) {
try {
json.put(key, value);
} catch (JSONException ignored) {}
}
@Override
public void putStringArray(String key, String[] value) {
try {
JSONArray array = new JSONArray();
for(String v : value) {
array.put(v);
}
json.put(key, array);
} catch (JSONException ignored) {}
}
@Override
public void putLongArray(String key, long[] value) {
try {
JSONArray array = new JSONArray();
for(long v : value) {
array.put(v);
}
json.put(key, array);
} catch (JSONException ignored) {}
}
@Override
public String getString(String key) {
try {
return json.getString(key);
} catch (JSONException e) {
return null;
}
}
@Override
public String[] getStringArray(String key) {
try {
JSONArray array = json.getJSONArray(key);
String[] returnValue = new String[array.length()];
for(int i = 0; i < array.length(); i++) {
returnValue[i] = array.getString(i);
}
return returnValue;
} catch (JSONException e) {
return null;
}
}
@Override
public long[] getLongArray(String key) {
try {
JSONArray array = json.getJSONArray(key);
long[] returnValue = new long[array.length()];
for(int i = 0; i < array.length(); i++) {
returnValue[i] = array.getLong(i);
}
return returnValue;
} catch (JSONException e) {
return null;
}
}
} | 26.07767 | 75 | 0.572971 |
9d85925a3a41ceede75592982a5eae28ab661e87 | 863 | package model.executable;
import java.util.List;
import exception.SyntacticErrorException;
import model.Executable;
import model.LogHolder;
import model.SemanticsRegistry;
/**
* Dynamic binding at runtime through semantics registry
* @author CharlesXu
*/
public class ProcedureStub extends Command {
private SemanticsRegistry semanticsRegistry;
public ProcedureStub(List<Executable> argv)
throws SyntacticErrorException {
super(argv);
}
@Override
public double execute(LogHolder log) throws SyntacticErrorException {
return semanticsRegistry.getImpl(name).execute(log, getArgs());
}
@Override
public String getName() {
return name;
}
@Override
protected void validateArgv() throws SyntacticErrorException {
}
public void setSemantics(SemanticsRegistry semanticsRegistry) {
this.semanticsRegistry = semanticsRegistry;
}
}
| 20.547619 | 70 | 0.782155 |
75400658655b16eb946a0f2f5546996382f271ee | 5,633 | package org.aries.common.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.StringEscapeUtils;
import org.aries.common.EmailMessage;
import org.aries.util.BaseUtil;
import org.aries.util.ObjectUtil;
import org.aries.util.Validator;
public class EmailMessageUtil extends BaseUtil {
public static boolean isEmpty(EmailMessage emailMessage) {
if (emailMessage == null)
return true;
boolean status = false;
status |= EmailAddressUtil.isEmpty(emailMessage.getFromAddress());
return status;
}
public static boolean isEmpty(Collection<EmailMessage> emailMessageList) {
if (emailMessageList == null || emailMessageList.size() == 0)
return true;
Iterator<EmailMessage> iterator = emailMessageList.iterator();
while (iterator.hasNext()) {
EmailMessage emailMessage = iterator.next();
if (!isEmpty(emailMessage))
return false;
}
return true;
}
public static String toString(EmailMessage emailMessage) {
if (isEmpty(emailMessage))
return "EmailMessage: [uninitialized] "+emailMessage.toString();
String text = emailMessage.toString();
return text;
}
public static String toString(Collection<EmailMessage> emailMessageList) {
if (isEmpty(emailMessageList))
return "";
StringBuffer buf = new StringBuffer();
Iterator<EmailMessage> iterator = emailMessageList.iterator();
for (int i=0; iterator.hasNext(); i++) {
EmailMessage emailMessage = iterator.next();
if (i > 0)
buf.append(", ");
String text = toString(emailMessage);
buf.append(text);
}
String text = StringEscapeUtils.escapeJavaScript(buf.toString());
return text;
}
public static EmailMessage create() {
EmailMessage emailMessage = new EmailMessage();
initialize(emailMessage);
return emailMessage;
}
public static void initialize(EmailMessage emailMessage) {
if (emailMessage.getSendAsHtml() == null)
emailMessage.setSendAsHtml(false);
}
public static boolean validate(EmailMessage emailMessage) {
if (emailMessage == null)
return false;
Validator validator = Validator.getValidator();
validator.isFalse(EmailAddressUtil.isEmpty(emailMessage.getFromAddress()), "\"FromAddress\" must be specified");
EmailAddressListUtil.validate(emailMessage.getAdminAddresses());
AttachmentUtil.validate(emailMessage.getAttachments());
EmailAddressListUtil.validate(emailMessage.getBccAddresses());
EmailAddressListUtil.validate(emailMessage.getCcAddresses());
EmailAddressUtil.validate(emailMessage.getFromAddress());
EmailAddressListUtil.validate(emailMessage.getReplytoAddresses());
EmailAddressListUtil.validate(emailMessage.getToAddresses());
boolean isValid = validator.isValid();
return isValid;
}
public static boolean validate(Collection<EmailMessage> emailMessageList) {
Validator validator = Validator.getValidator();
Iterator<EmailMessage> iterator = emailMessageList.iterator();
while (iterator.hasNext()) {
EmailMessage emailMessage = iterator.next();
//TODO break or accumulate?
validate(emailMessage);
}
boolean isValid = validator.isValid();
return isValid;
}
public static void sortRecords(List<EmailMessage> emailMessageList) {
Collections.sort(emailMessageList, createEmailMessageComparator());
}
public static Collection<EmailMessage> sortRecords(Collection<EmailMessage> emailMessageCollection) {
List<EmailMessage> list = new ArrayList<EmailMessage>(emailMessageCollection);
Collections.sort(list, createEmailMessageComparator());
return list;
}
public static Comparator<EmailMessage> createEmailMessageComparator() {
return new Comparator<EmailMessage>() {
public int compare(EmailMessage emailMessage1, EmailMessage emailMessage2) {
int status = emailMessage1.compareTo(emailMessage2);
return status;
}
};
}
public static EmailMessage clone(EmailMessage emailMessage) {
if (emailMessage == null)
return null;
EmailMessage clone = create();
clone.setId(ObjectUtil.clone(emailMessage.getId()));
clone.setContent(ObjectUtil.clone(emailMessage.getContent()));
clone.setSubject(ObjectUtil.clone(emailMessage.getSubject()));
clone.setTimestamp(ObjectUtil.clone(emailMessage.getTimestamp()));
clone.setSourceId(ObjectUtil.clone(emailMessage.getSourceId()));
clone.setSmtpHost(ObjectUtil.clone(emailMessage.getSmtpHost()));
clone.setSmtpPort(ObjectUtil.clone(emailMessage.getSmtpPort()));
clone.setFromAddress(EmailAddressUtil.clone(emailMessage.getFromAddress()));
clone.setToAddresses(EmailAddressListUtil.clone(emailMessage.getToAddresses()));
clone.setBccAddresses(EmailAddressListUtil.clone(emailMessage.getBccAddresses()));
clone.setCcAddresses(EmailAddressListUtil.clone(emailMessage.getCcAddresses()));
clone.setReplytoAddresses(EmailAddressListUtil.clone(emailMessage.getReplytoAddresses()));
clone.setAdminAddresses(EmailAddressListUtil.clone(emailMessage.getAdminAddresses()));
clone.setAttachments(AttachmentUtil.clone(emailMessage.getAttachments()));
clone.setSendAsHtml(ObjectUtil.clone(emailMessage.getSendAsHtml()));
return clone;
}
public static List<EmailMessage> clone(List<EmailMessage> emailMessageList) {
if (emailMessageList == null)
return null;
List<EmailMessage> newList = new ArrayList<EmailMessage>();
Iterator<EmailMessage> iterator = emailMessageList.iterator();
while (iterator.hasNext()) {
EmailMessage emailMessage = iterator.next();
EmailMessage clone = clone(emailMessage);
newList.add(clone);
}
return newList;
}
}
| 36.108974 | 114 | 0.77188 |
cfc0fdf89196977638dbebaa31ec591e6d9e26bc | 4,309 | package com.danikula.android.garden.utils;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;
import android.os.Environment;
import com.danikula.android.garden.io.IoUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class AndroidUtils {
private static final String APP_EXTERNAL_STORAGE_DIR_FORMAT = Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/Android/data/%s/files/";
public static String getApplicationExternalStorageDirectory(Context context) {
return String.format(APP_EXTERNAL_STORAGE_DIR_FORMAT, context.getPackageName());
}
public static File getApplicationExternalStorageSubDirectory(Context context, String subfolderName) {
return new File(getApplicationExternalStorageDirectory(context), subfolderName);
}
public static Properties loadPropertiesFromAssets(Context context, String propertiesFileName) {
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(propertiesFileName);
Properties properties = new Properties();
properties.load(inputStream);
return properties;
} catch (IOException e) {
throw new IllegalStateException(String.format("Can't load application properties"));
} finally {
IoUtils.closeSilently(inputStream);
}
}
/**
* Checks is device has access to Internet at the moment.
* <p>
* Permission "android.permission.ACCESS_NETWORK_STATE" is required
* </p>
*
* @param context Context an android context
* @return <code>true</code> if device has access to Internet at the moment
*/
public static boolean isOnline(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static String getApplicationVersionName(Context context) {
return getPackageInfo(context).versionName;
}
public static int getApplicationVersionCode(Context context) {
return getPackageInfo(context).versionCode;
}
private static PackageInfo getPackageInfo(Context context) {
try {
String packageName = context.getPackageName();
return context.getPackageManager().getPackageInfo(packageName, 0);
} catch (NameNotFoundException e) {
throw new IllegalStateException("Error retrieving package info", e);
}
}
public static boolean isInMobileRoaming(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null &&
activeNetworkInfo.isConnected() &&
activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE &&
activeNetworkInfo.isRoaming();
}
public static float getBatteryLevel(Context context) {
Intent batteryInfo = getBatteryInfo(context);
int level = batteryInfo.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryInfo.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
return level / (float) scale;
}
public static boolean isCharging(Context context) {
Intent batteryInfo = getBatteryInfo(context);
int status = batteryInfo.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
return status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
}
private static Intent getBatteryInfo(Context context) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
return context.registerReceiver(null, filter);
}
}
| 39.172727 | 127 | 0.718496 |
c9aa4a35cad21ecceaae6cd583b2625edc8bec9b | 99,189 | /*
* Copyright 2014-2021 The Ideal Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
package ideal.development.transformers;
import ideal.library.elements.*;
import javax.annotation.Nullable;
import ideal.runtime.elements.*;
import ideal.runtime.logs.*;
import ideal.development.elements.*;
import ideal.development.comments.*;
import ideal.development.actions.*;
import ideal.development.constructs.*;
import ideal.development.modifiers.*;
import static ideal.development.elements.access_modifier.*;
import static ideal.development.modifiers.general_modifier.*;
import ideal.development.flavors.*;
import static ideal.development.flavors.flavor.*;
import ideal.development.names.*;
import static ideal.development.names.common_names.*;
import ideal.development.kinds.*;
import static ideal.development.kinds.type_kinds.*;
import static ideal.development.kinds.subtype_tags.*;
import ideal.development.types.*;
import static ideal.development.types.common_types.*;
import ideal.development.declarations.*;
import ideal.development.scanners.*;
import ideal.development.analyzers.*;
import ideal.development.extensions.*;
import ideal.development.notifications.*;
import ideal.development.values.*;
import static ideal.development.values.common_values.*;
import ideal.development.origins.*;
import ideal.development.literals.*;
public class to_java_transformer extends base_transformer {
private static enum mapping {
MAP_TO_PRIMITIVE_TYPE,
MAP_TO_WRAPPER_TYPE,
MAP_PRESERVE_ALIAS,
NO_MAPPING;
}
private final java_library java_library;
private list<construct> common_headers;
private set<principal_type> implicit_names;
private set<principal_type> imported_names;
private mapping mapping_strategy;
private principal_type package_type;
private @Nullable principal_type enclosing_type;
private @Nullable procedure_declaration the_enclosing_procedure;
private static simple_name OBJECTS_EQUAL_NAME = simple_name.make("values_equal");
private static simple_name INT_TO_STRING_NAME = simple_name.make("int_to_string");
private static simple_name CONCATENATE_NAME = simple_name.make("concatenate");
private static simple_name COMPARE_NAME = simple_name.make("compare");
private static simple_name BASE_STRING_NAME = simple_name.make("base_string");
private static simple_name ORDINAL_NAME = simple_name.make("ordinal");
private static simple_name TO_STRING_JAVA = simple_name.make("toString");
private static simple_name START_NAME = simple_name.make("start");
private static simple_name MAIN_NAME = simple_name.make("main");
private static simple_name ARGS_NAME = simple_name.make("args");
public to_java_transformer(java_library java_library) {
this.java_library = java_library;
this.mapping_strategy = mapping.MAP_TO_PRIMITIVE_TYPE;
common_headers = new base_list<construct>();
implicit_names = new hash_set<principal_type>();
implicit_names.add(root_type());
implicit_names.add(java_library.lang_package());
implicit_names.add(java_library.builtins_package());
imported_names = new hash_set<principal_type>();
//principal_type runtime_util_type = action_utilities.lookup_type(get_context(),
// new base_string("ideal.machine.elements.runtime_util"));
}
public void set_type_context(principal_type main_type, readonly_list<import_declaration> imports,
origin the_origin) {
package_type = main_type.get_parent();
assert package_type == root_type() || package_type.short_name() instanceof simple_name;
common_headers.append(make_newline(the_origin));
if (package_type != root_type()) {
common_headers.append(new package_construct(make_type(package_type, the_origin), the_origin));
common_headers.append(make_newline(the_origin));
implicit_names.add(package_type);
}
if (imports.is_not_empty()) {
list<construct> import_headers = new base_list<construct>();
// TODO: refactor as a filter
for (int i = 0; i < imports.size(); ++i) {
import_declaration the_import_declaration = imports.get(i);
import_construct the_import = process_import(the_import_declaration);
principal_type imported_type = (principal_type) the_import_declaration.get_type();
if (imported_type == java_library.builtins_package() ||
imported_type.get_parent() == java_library.builtins_package()) {
continue;
}
if (the_import_declaration.is_implicit()) {
implicit_names.add(imported_type);
} else {
imported_names.add(imported_type);
}
import_headers.append(the_import);
}
if (import_headers.is_not_empty()) {
common_headers.append_all(import_headers);
common_headers.append(make_newline(the_origin));
}
}
}
@Override
protected modifier_kind process_modifier(modifier_kind the_modifier_kind,
annotation_category category) {
if (category == annotation_category.VARIABLE) {
if (the_modifier_kind == implement_modifier || the_modifier_kind == override_modifier) {
// Drop override on variables
return null;
}
}
if (the_modifier_kind == implement_modifier) {
return override_modifier;
} else if (general_modifier.supported_by_java.contains(the_modifier_kind)) {
return the_modifier_kind;
} else {
return null;
}
}
protected construct transform_analyzable(analyzable the_analyzable) {
return transform_action(analyzer_utilities.to_action(the_analyzable));
}
protected construct transform_analyzable_or_null(analyzable the_analyzable, origin the_origin) {
action the_action = analyzer_utilities.to_action(the_analyzable);
if (is_nothing(the_action)) {
return new empty_construct(the_origin);
} else {
return transform_action(the_action);
}
}
protected type get_type(action the_action) {
assert the_action instanceof type_action : "Action: " + the_action;
return ((type_action) the_action).get_type();
}
private type result_type(action the_action) {
type the_type = the_action.result().type_bound();
if (is_reference_type(the_type)) {
return get_reference_parameter(the_type);
} else {
return the_type;
}
}
private boolean should_introduce_cast(type the_original_type, type the_narrowed_type) {
if (the_narrowed_type == the_original_type) {
return false;
}
if (the_original_type == immutable_integer_type()) {
return false;
}
if (type_utilities.is_union(the_original_type)) {
immutable_list<abstract_value> the_values =
type_utilities.get_union_parameters(the_original_type);
assert the_values.size() == 2;
if (the_values.get(0) == the_narrowed_type ||
the_values.get(1) == the_narrowed_type) {
return false;
}
}
return true;
}
private readonly_list<construct> transform_parameters_with_mapping(
readonly_list<type_parameter_declaration> the_analyzables, mapping new_mapping) {
mapping old_mapping_strategy = mapping_strategy;
mapping_strategy = new_mapping;
readonly_list<construct> result = transform_list(the_analyzables);
mapping_strategy = old_mapping_strategy;
return result;
}
public construct process_list_initializer_action(list_initializer_action initializer) {
origin the_origin = initializer;
type element_type = initializer.element_type;
// Java doesn't like array creation with generic params.
// javac complains with: "error: generic array creation".
construct type_name_no_params = make_type(element_type, false, the_origin);
construct alloc = new operator_construct(operator.ALLOCATE, type_name_no_params, the_origin);
construct alloc_array = new parameter_construct(alloc, new empty<construct>(),
grouping_type.BRACKETS, the_origin);
// TODO: handle promotions
construct alloc_call = new parameter_construct(alloc_array,
transform_parameters(initializer.parameter_actions), grouping_type.BRACES, the_origin);
construct type_name = make_type(element_type, the_origin);
construct array_name = make_type(java_library.array_class(), the_origin);
construct param_array = new parameter_construct(array_name, new base_list<construct>(type_name),
grouping_type.ANGLE_BRACKETS, the_origin);
construct alloc_array2 = new operator_construct(operator.ALLOCATE, param_array, the_origin);
construct array_call = new parameter_construct(alloc_array2,
new base_list<construct>(alloc_call), grouping_type.PARENS, the_origin);
// TODO: import type if needed
// construct list_name = make_type(java_library.base_immutable_list_class(), the_origin);
construct list_name = new name_construct(simple_name.make("base_immutable_list"), the_origin);
construct param_list = new parameter_construct(list_name, new base_list<construct>(type_name),
grouping_type.ANGLE_BRACKETS, the_origin);
construct alloc_list = new operator_construct(operator.ALLOCATE, param_list, the_origin);
return new parameter_construct(alloc_list, new base_list<construct>(array_call),
grouping_type.PARENS, the_origin);
}
public @Nullable list_construct process_parameters(
@Nullable readonly_list<variable_declaration> the_parameters, origin the_origin) {
if (the_parameters == null) {
return null;
} else {
return new list_construct(transform_list(the_parameters), grouping_type.PARENS, false,
the_origin);
}
}
private boolean is_null_subtype(type the_type) {
return the_type.principal() == missing_type();
}
private action_name map_name(action_name the_name) {
if (the_name == special_name.THIS_CONSTRUCTOR) {
return special_name.THIS;
} else if (the_name == special_name.SUPER_CONSTRUCTOR) {
return special_name.SUPER;
} else {
return the_name;
}
}
private construct process_narrow_action(narrow_action the_narrow_action, construct expression,
origin the_origin) {
type the_original_type = result_type(the_narrow_action.expression);
type the_narrowed_type = the_narrow_action.the_type;
if (should_introduce_cast(the_original_type, the_narrowed_type)) {
construct cast = new operator_construct(operator.HARD_CAST, expression,
make_type(the_narrowed_type, the_origin), the_origin);
return new list_construct(new base_list<construct>(cast), grouping_type.PARENS, false,
the_origin);
} else {
return expression;
}
}
private construct maybe_call(action the_action, construct the_construct, origin the_origin) {
declaration the_declaration = declaration_util.get_declaration(the_action);
if (the_declaration != null && should_call_as_procedure(the_declaration)) {
return make_call(the_construct, new empty<construct>(), the_origin);
} else {
return the_construct;
}
}
private boolean should_call_as_procedure(declaration the_declaration) {
if (the_declaration instanceof variable_declaration) {
variable_declaration the_variable = (variable_declaration) the_declaration;
if (has_override(the_variable.annotations())) {
return true;
}
kind parent_kind = the_variable.declared_in_type().get_kind();
if (!is_concrete_kind(parent_kind) &&
parent_kind != block_kind &&
parent_kind != namespace_kind) {
return true;
}
if (parent_kind == enum_kind && the_variable instanceof field_declaration) {
return true;
}
} else if (the_declaration instanceof procedure_declaration) {
procedure_declaration the_procedure = (procedure_declaration) the_declaration;
return the_procedure.overrides_variable();
}
return false;
}
private boolean has_override(annotation_set the_annotations) {
return the_annotations.has(override_modifier) || the_annotations.has(implement_modifier);
}
private construct make_parametrized_type(construct main, readonly_list<construct> parameters,
origin the_origin) {
return new parameter_construct(main, parameters, grouping_type.ANGLE_BRACKETS, the_origin);
}
private boolean should_use_wrapper_in_return(procedure_declaration the_declaration) {
readonly_list<declaration> overriden = the_declaration.get_overriden();
// TODO: use list.has()
for (int i = 0; i < overriden.size(); ++i) {
declaration overriden_declaration = overriden.get(i);
if (overriden_declaration instanceof type_declaration) {
assert ((type_declaration) overriden_declaration).get_kind() == procedure_kind;
return true;
} else if (overriden_declaration instanceof procedure_declaration) {
procedure_declaration super_procedure = (procedure_declaration) overriden_declaration;
if (super_procedure instanceof specialized_procedure) {
super_procedure = ((specialized_procedure) super_procedure).master_declaration();
}
type return_type = super_procedure.get_return_type();
if (return_type.principal().get_declaration() instanceof type_parameter_declaration) {
return true;
}
if (should_use_wrapper_in_return(super_procedure)) {
return true;
}
} else if (overriden_declaration instanceof variable_declaration) {
variable_declaration super_variable = (variable_declaration) overriden_declaration;
if (super_variable instanceof specialized_variable) {
super_variable = ((specialized_variable) super_variable).get_main();
}
type return_type = super_variable.value_type();
if (return_type.principal().get_declaration() instanceof type_parameter_declaration) {
return true;
}
}
}
return false;
}
private boolean skip_access(principal_type declared_in_type) {
return !is_concrete_kind(declared_in_type.get_kind());
}
@Override
public construct process_procedure(procedure_declaration the_procedure) {
origin the_origin = the_procedure;
list<annotation_construct> annotations = to_annotations(the_procedure.annotations(),
annotation_category.PROCEDURE, skip_access(the_procedure.declared_in_type()), the_origin);
return process_procedure(the_procedure, annotations);
}
private boolean is_unreachable_result(procedure_declaration the_procedure) {
return the_procedure.get_body_action() != null &&
the_procedure.get_body_action().result().type_bound() == unreachable_type();
}
public construct process_procedure(procedure_declaration the_procedure,
list<annotation_construct> annotations) {
origin the_origin = the_procedure;
action_name name = the_procedure.original_name();
@Nullable list_construct the_list_construct = process_parameters(
the_procedure.get_parameter_variables(), the_origin);
if (the_list_construct == null) {
the_list_construct = make_parens(the_origin);
}
readonly_list<construct> parameters = the_list_construct.the_elements;
@Nullable readonly_list<construct> body_statements = null;
if (the_procedure.get_body_action() != null) {
boolean is_constructor = the_procedure.get_category() == procedure_category.CONSTRUCTOR;
boolean void_return = the_procedure.get_return_type().principal() == void_type();
boolean unreachable_result = is_unreachable_result(the_procedure);
boolean add_return = !is_constructor && !unreachable_result && void_return &&
should_use_wrapper_in_return(the_procedure);
the_enclosing_procedure = the_procedure;
list<construct> body = transform_action_list(the_procedure.get_body_action());
the_enclosing_procedure = null;
if (add_return) {
body.append(new return_construct(make_null(the_origin), the_origin));
} else if (body.size() == 1) {
// TODO: use analyzables instead of constructs here
construct body_construct = body.first();
if (body_construct instanceof block_construct) {
body = new base_list<construct>(body_construct);
} else if (!is_constructor && !void_return && !unreachable_result) {
body = new base_list<construct>(new return_construct(body_construct, the_origin));
}
}
body_statements = body;
}
@Nullable construct ret;
if (the_procedure.get_category() == procedure_category.CONSTRUCTOR) {
ret = null;
} else {
type return_type = the_procedure.get_return_type();
if (type_utilities.is_union(return_type)) {
annotations.append(make_nullable(the_origin));
ret = make_type_with_mapping(remove_null_type(return_type), the_origin,
mapping.MAP_TO_WRAPPER_TYPE);
} else if (is_reference_type(return_type)) {
type_flavor ref_flavor = return_type.get_flavor();
ret = make_type(return_type, the_origin);
if (ref_flavor != mutable_flavor) {
if (ret instanceof flavor_construct) {
ret = ((flavor_construct) ret).expr;
}
assert ret instanceof parameter_construct;
readonly_list<construct> ret_parameters = ((parameter_construct) ret).parameters;
assert ret_parameters.size() == 1;
ret = ret_parameters.first();
if (ref_flavor == writeonly_flavor) {
// TODO: use copy ctor.
list<construct> new_parameters = new base_list<construct>(parameters);
new_parameters.append(
new variable_construct(new empty<annotation_construct>(), ret, value_name,
new empty<annotation_construct>(), null, the_origin));
parameters = new_parameters;
ret = make_type(void_type(), the_origin);
}
}
} else {
if (should_use_wrapper_in_return(the_procedure)) {
ret = make_type_with_mapping(the_procedure.get_return_type(), the_origin,
mapping.MAP_TO_WRAPPER_TYPE);
// Note: if Java return type is 'Void' (with the capital V),
// then we may need to insert "return null" to keep javac happy.
} else {
if (the_procedure.get_return_type() == unreachable_type()) {
ret = make_type(void_type(), the_origin);
} else {
if (is_object_type(the_procedure.get_return_type())) {
ret = make_object_type(the_origin);
} else {
ret = make_type(the_procedure.get_return_type(), the_origin);
}
}
}
}
}
construct body = null;
if (body_statements != null) {
body = new block_construct(maybe_unwrap_block(body_statements), the_origin);
}
// Note: the flavor is always missing.
return new procedure_construct(annotations, ret, name, parameters,
new empty<annotation_construct>(), body, the_origin);
}
modifier_construct make_nullable(origin the_origin) {
return new modifier_construct(nullable_modifier, the_origin);
}
protected construct make_type_with_mapping(type the_type, origin the_origin,
mapping new_mapping) {
mapping old_mapping_strategy = mapping_strategy;
mapping_strategy = new_mapping;
construct result = make_type(the_type, the_origin);
mapping_strategy = old_mapping_strategy;
return result;
}
@Override
protected construct make_type(type the_type, origin the_origin) {
return make_type(the_type, true, the_origin);
}
protected construct make_type(type the_type, boolean include_parameters, origin the_origin) {
principal_type principal = the_type.principal();
type_flavor the_flavor = the_type.get_flavor();
switch (mapping_strategy) {
case MAP_TO_PRIMITIVE_TYPE:
if (principal == void_type()) {
break;
} else if (principal == boolean_type()) {
principal = java_library.boolean_type();
break;
} else if (principal == character_type()) {
principal = java_library.char_type();
break;
}
/*
@Nullable principal_type mapped = java_library.map_to_primitive(principal);
if (mapped != null) {
principal = mapped;
}
break;
*/
case MAP_TO_WRAPPER_TYPE:
case MAP_PRESERVE_ALIAS:
@Nullable simple_name mapped_name = java_library.map_to_wrapper(principal);
if (mapped_name != null) {
return new name_construct(mapped_name, the_origin);
}
break;
case NO_MAPPING:
if (java_library.is_mapped(principal)) {
utilities.panic("No mapping expected for " + principal);
}
break;
}
if (type_utilities.is_union(principal)) {
type removed_null = remove_null_type(principal);
principal = removed_null.principal();
the_flavor = removed_null.get_flavor();
}
action_name the_name = make_name(get_simple_name(principal), principal, the_flavor);
construct name = make_resolve(make_parent_name(principal, false, the_origin), the_name,
the_origin);
if (include_parameters && principal instanceof parametrized_type) {
immutable_list<abstract_value> type_params =
((parametrized_type) principal).get_parameters().the_list;
list<construct> params = new base_list<construct>();
for (int i = 0; i < type_params.size(); ++i) {
abstract_value av = type_params.get(i);
assert av instanceof type;
type the_param_type = (type) av;
boolean object_parameter = is_object_type(the_param_type);
if (object_parameter) {
params.append(make_object_type(the_origin));
} else {
params.append(make_type_with_mapping(the_param_type, the_origin,
mapping.MAP_TO_WRAPPER_TYPE));
}
}
return make_parametrized_type(name, params, the_origin);
} else {
return name;
}
}
protected construct make_object_type(origin the_origin) {
return make_type(java_library.object_type(), the_origin);
}
protected construct make_flavored_and_parametrized_type(principal_type principal,
type_flavor flavor, @Nullable readonly_list<construct> type_parameters, origin the_origin) {
construct name = new name_construct(make_name(get_simple_name(principal), principal,
flavor), the_origin);
if (type_parameters != null) {
list<construct> parameters = new base_list<construct>();
for (int i = 0; i < type_parameters.size(); ++i) {
construct parameter = type_parameters.get(i);
if (parameter instanceof variable_construct) {
parameters.append(new name_construct(((variable_construct) parameter).name, the_origin));
} else {
parameters.append(parameter);
}
}
return make_parametrized_type(name, parameters, the_origin);
} else {
return name;
}
}
@Override
protected simple_name get_simple_name(principal_type the_type) {
if (type_utilities.is_union(the_type)) {
the_type = remove_null_type(the_type).principal();
}
if (the_type.short_name() instanceof simple_name) {
simple_name the_name = (simple_name) the_type.short_name();
if (the_type.get_kind() == procedure_kind && the_type instanceof parametrized_type) {
int arity = ((parametrized_type) the_type).get_parameters().the_list.size() - 1;
return make_procedure_name(the_name, arity);
} else {
return the_name;
}
}
assert the_type.get_parent() != null;
return get_simple_name(the_type.get_parent());
}
protected boolean is_top_package(type the_type) {
return the_type == java_library.java_package() || the_type == java_library.javax_package();
}
protected @Nullable construct make_parent_name(principal_type the_type, boolean is_import,
origin the_origin) {
if (!is_import) {
if (imported_names.contains(the_type)) {
return null;
}
if (the_type instanceof parametrized_type) {
master_type the_master_type = ((parametrized_type) the_type).get_master();
if (imported_names.contains(the_master_type)) {
return null;
}
}
}
if (the_type.get_declaration() instanceof type_parameter_declaration) {
return null;
}
if (is_top_package(the_type)) {
return null;
}
@Nullable principal_type parent = the_type.get_parent();
if (parent == null || parent == root_type() ||
(!is_import && implicit_names.contains(parent))) {
return null;
}
if (! (parent.short_name() instanceof simple_name)) {
utilities.panic("Full name of " + the_type + ", parent " + parent);
}
return make_resolve(make_parent_name(parent, is_import, the_origin), parent.short_name(),
the_origin);
}
protected construct make_imported_type(principal_type the_type, origin the_origin) {
action_name the_name = get_simple_name(the_type);
return make_resolve(make_parent_name(the_type, true, the_origin), the_name, the_origin);
}
@Override
protected simple_name make_name(simple_name type_name, principal_type the_type,
type_flavor flavor) {
type_utilities.prepare(the_type, declaration_pass.FLAVOR_PROFILE);
if (flavor == nameonly_flavor || flavor == the_type.get_flavor_profile().default_flavor()) {
return type_name;
} else {
return name_utilities.join(flavor.name(), type_name);
}
}
protected readonly_list<annotation_construct> make_annotations(access_modifier access,
origin the_origin) {
if (access != local_modifier) {
return new base_list<annotation_construct>(new modifier_construct(access, the_origin));
} else {
return new empty<annotation_construct>();
}
}
private void append_static(list<annotation_construct> annotations, origin the_origin) {
// TODO: replace with collection.has()
for (int i = 0; i < annotations.size(); ++i) {
annotation_construct the_annotation = annotations.get(i);
if (the_annotation instanceof modifier_construct &&
((modifier_construct) the_annotation).the_kind == static_modifier) {
return;
}
}
// TODO: should modifier list be sorted?...
annotations.append(new modifier_construct(static_modifier, the_origin));
}
private readonly_list<construct> transform_static(readonly_list<declaration> declarations) {
list<construct> result = new base_list<construct>();
for (int i = 0; i < declarations.size(); ++i) {
declaration decl = declarations.get(i);
origin the_origin = decl;
if (decl instanceof variable_declaration) {
variable_declaration the_variable = (variable_declaration) decl;
list<annotation_construct> annotations = to_annotations(the_variable.annotations(),
annotation_category.VARIABLE, false, the_origin);
append_static(annotations, the_origin);
// TODO: do we need to handle null?
result.append(process_variable(the_variable, annotations));
} else if (decl instanceof procedure_declaration) {
procedure_declaration the_procedure = (procedure_declaration) decl;
list<annotation_construct> annotations = to_annotations(the_procedure.annotations(),
annotation_category.PROCEDURE, false, the_origin);
if (the_procedure.get_category() != procedure_category.CONSTRUCTOR) {
append_static(annotations, the_origin);
}
result.append(process_procedure(the_procedure, annotations));
} else if (decl instanceof block_declaration) {
// TODO: make sure this is a static block...
result.append_all(transform1(decl));
} else if (decl instanceof import_declaration) {
// Skip imports: they should have been declared at the top level.
} else {
utilities.panic("Unexpected declaration in a namespace: " + decl);
}
}
return result;
}
private boolean skip_type_declaration(principal_type the_type) {
if (java_library.is_mapped(the_type) || the_type.is_subtype_of(null_type())) {
return true;
}
kind the_kind = the_type.get_kind();
assert the_kind != procedure_kind;
return false; // the_kind == reference_kind;
}
private immutable_list<type_flavor> supported_no_raw(flavor_profile profile) {
list<type_flavor> result = new base_list<type_flavor>();
immutable_list<type_flavor> supported_flavors = profile.supported_flavors();
// TODO: use list.filter()
for (int i = 0; i < supported_flavors.size(); ++i) {
type_flavor flavor = supported_flavors.get(i);
if (flavor != raw_flavor) {
result.append(flavor);
}
}
return result.frozen_copy();
}
@Override
public Object process_type(type_declaration the_type_declaration) {
origin the_origin = the_type_declaration;
list<annotation_construct> annotations = to_annotations(
the_type_declaration.annotations(), annotation_category.TYPE, false, the_origin);
kind the_kind = the_type_declaration.get_kind();
principal_type declared_in_type = the_type_declaration.declared_in_type();
if (the_kind.is_namespace()) {
assert the_type_declaration.get_parameters() == null;
if (declared_in_type != package_type) {
append_static(annotations, the_origin);
}
// TODO: add a private constructor
return new type_declaration_construct(
annotations,
class_kind,
the_type_declaration.short_name(),
null,
transform_static(the_type_declaration.get_signature()),
the_origin);
}
if (the_kind == procedure_kind) {
return make_procedure_declarations(annotations, the_type_declaration);
}
principal_type declared_type = the_type_declaration.get_declared_type();
if (false) { // Looks like this never happens. TODO: retire this
if (declared_type.get_declaration() != the_type_declaration) {
// This happens when specializes declaration, e.g. for collection[data]
return null;
}
}
if (skip_type_declaration(declared_type)) {
return null;
}
@Nullable principal_type old_enclosing_type = enclosing_type;
enclosing_type = declared_type;
if (is_concrete_kind(declared_in_type.get_kind())) {
// Introduce inner type.
append_static(annotations, the_origin);
}
if (the_kind == test_suite_kind || the_kind == program_kind) {
the_kind = class_kind;
}
boolean concrete_mode = is_concrete_kind(the_kind);
flavor_profile profile = the_kind == class_kind ? class_profile :
declared_type.get_flavor_profile();
// TODO: implement namespaces
assert profile != flavor_profiles.nameonly_profile;
simple_name type_name = (simple_name) the_type_declaration.short_name();
@Nullable readonly_list<construct> type_parameters = null;
if (the_type_declaration.get_parameters() != null) {
type_parameters = transform_parameters_with_mapping(the_type_declaration.get_parameters(),
mapping.MAP_TO_WRAPPER_TYPE);
}
dictionary<type_flavor, list<construct>> flavored_bodies =
new list_dictionary<type_flavor, list<construct>>();
dictionary<type_flavor, list<construct>> supertype_lists =
new list_dictionary<type_flavor, list<construct>>();
@Nullable construct superclass = null;
immutable_list<type_flavor> supported_flavors = supported_no_raw(profile);
for (int i = 0; i < supported_flavors.size(); ++i) {
type_flavor flavor = supported_flavors.get(i);
flavored_bodies.put(flavor, new base_list<construct>());
supertype_lists.put(flavor, new base_list<construct>());
}
readonly_list<declaration> body = the_type_declaration.get_signature();
boolean generate_to_string = true;
for (int i = 0; i < body.size(); ++i) {
declaration decl = body.get(i);
if (decl instanceof supertype_declaration) {
supertype_declaration supertype_decl = (supertype_declaration) decl;
// TODO: retire this when there is no need to match legacy output
if (supertype_decl.annotations().has(synthetic_modifier)) {
continue;
}
type supertype = supertype_decl.get_supertype();
kind supertype_kind = supertype.principal().get_kind();
if (concrete_mode) {
// TODO: use NO_MAPPING here.
construct transformed_supertype = make_type_with_mapping(
supertype_decl.get_supertype(), the_origin, mapping.MAP_PRESERVE_ALIAS);
if (supertype_kind == class_kind) {
if (superclass != null) {
// TODO: do not panic!
utilities.panic("Oh no. Two superclasses!");
}
superclass = transformed_supertype;
} else {
list<construct> supertype_list = supertype_lists.get(profile.default_flavor());
assert supertype_list != null;
supertype_list.append(transformed_supertype);
}
} else {
origin the_origin2 = supertype_decl;
if (supertype_decl.subtype_flavor() == null &&
supertype instanceof principal_type) {
immutable_list<type_flavor> type_flavors = flavored_bodies.keys().elements();
for (int k = 0; k < type_flavors.size(); ++k) {
type_flavor flavor = type_flavors.get(k);
flavor_profile supertype_profile = supertype.principal().get_flavor_profile();
// TODO: iterate over supertype_lists?
if (supertype_profile.supports(flavor)) {
construct flavored_supertype;
if (flavor == supertype_profile.default_flavor()) {
flavored_supertype = make_type_with_mapping(supertype_decl.get_supertype(),
the_origin2, mapping.MAP_PRESERVE_ALIAS);
} else {
flavored_supertype = make_type_with_mapping(supertype.get_flavored(flavor),
the_origin2, mapping.MAP_PRESERVE_ALIAS);
}
list<construct> supertype_list = supertype_lists.get(flavor);
assert supertype_list != null;
supertype_list.append(flavored_supertype);
}
}
} else {
type_flavor subtype_flavor = supertype_decl.subtype_flavor();
if (subtype_flavor == null) {
subtype_flavor = supertype.get_flavor();
}
construct flavored_supertype = make_type_with_mapping(supertype_decl.get_supertype(),
the_origin2, mapping.MAP_PRESERVE_ALIAS);
list<construct> supertype_list = supertype_lists.get(profile.map(subtype_flavor));
assert supertype_list != null;
supertype_list.append(flavored_supertype);
}
}
} else if (decl instanceof procedure_declaration) {
procedure_declaration proc_decl = (procedure_declaration) decl;
if (proc_decl.short_name() == to_string_name) {
generate_to_string = false;
}
@Nullable procedure_construct proc_construct = (procedure_construct) transform(proc_decl);
if (proc_construct == null) {
continue;
}
type_flavor flavor = proc_decl.get_flavor();
if (flavor == nameonly_flavor || flavor == raw_flavor) {
flavor = profile.default_flavor();
} else {
flavor = profile.map(flavor);
}
flavored_bodies.get(flavor).append(proc_construct);
} else if (decl instanceof enum_value_analyzer) {
assert the_kind == enum_kind;
flavored_bodies.get(profile.default_flavor()).append(
process_enum_value((enum_value_analyzer) decl));
} else if (decl instanceof variable_declaration) {
variable_declaration var_decl = (variable_declaration) decl;
@Nullable variable_construct var_construct = (variable_construct) transform(decl);
if (var_construct == null) {
continue;
}
if (concrete_mode || var_decl.annotations().has(static_modifier)) {
flavored_bodies.get(profile.default_flavor()).append(var_construct);
} else {
procedure_construct proc_decl = var_to_proc(var_decl);
type_flavor target_flavor = var_decl.reference_type().get_flavor();
if (is_readonly_flavor(target_flavor)) {
target_flavor = readonly_flavor;
}
flavored_bodies.get(profile.map(target_flavor)).append(proc_decl);
}
} else if (decl instanceof type_declaration) {
flavored_bodies.get(profile.default_flavor()).append_all(transform1(decl));
} else if (decl instanceof import_declaration) {
// Skip imports: they should have been declared at the top level.
} else if (decl instanceof block_declaration) {
// TODO: make sure this is a static block...
flavored_bodies.get(profile.default_flavor()).append_all(transform1(decl));
} else {
utilities.panic("Unknown declaration: " + decl);
}
}
// TODO: move this into type_declaration_analyzer or enum_kind.
if (the_kind == enum_kind && generate_to_string) {
list<annotation_construct> modifier_list = new base_list<annotation_construct>(
new modifier_construct(public_modifier, the_origin));
block_construct to_string_body = new block_construct(
new base_list<construct>(
new return_construct(
base_string_wrap(
new parameter_construct(
new name_construct(TO_STRING_JAVA, the_origin),
new empty<construct>(),
grouping_type.PARENS,
the_origin
),
the_origin
),
the_origin
)
),
the_origin
);
procedure_construct to_string_procedure = new procedure_construct(
modifier_list,
new name_construct(string_name, the_origin),
to_string_name,
new empty<construct>(),
new empty<annotation_construct>(),
to_string_body,
the_origin);
flavored_bodies.get(profile.default_flavor()).append(to_string_procedure);
}
if (the_type_declaration.get_kind() == program_kind) {
list<annotation_construct> modifier_list = new base_list<annotation_construct>(
new modifier_construct(public_modifier, the_origin),
new modifier_construct(static_modifier, the_origin));
block_construct main_body = new block_construct(
new base_list<construct>(
new parameter_construct(
new resolve_construct(
new parameter_construct(
new operator_construct(
operator.ALLOCATE,
new name_construct(
type_name,
the_origin
),
the_origin
),
new empty<construct>(),
grouping_type.PARENS,
the_origin
),
START_NAME,
the_origin
),
new empty<construct>(),
grouping_type.PARENS,
the_origin
)
),
the_origin
);
procedure_construct main_procedure = new procedure_construct(
modifier_list,
make_type(immutable_void_type(), the_origin),
MAIN_NAME,
new base_list<construct>(
new variable_construct(
new empty<annotation_construct>(),
new parameter_construct(
make_type(java_library.string_type(), the_origin),
new empty<construct>(),
grouping_type.BRACKETS,
the_origin
),
ARGS_NAME,
new empty<annotation_construct>(),
null,
the_origin
)
),
new empty<annotation_construct>(),
main_body,
the_origin);
flavored_bodies.get(profile.default_flavor()).append(main_procedure);
}
list<construct> type_decls = new base_list<construct>();
immutable_list<type_flavor> type_flavors = supported_no_raw(profile);
for (int i = 0; i < type_flavors.size(); ++i) {
type_flavor flavor = type_flavors.get(i);
list<construct> flavored_body = flavored_bodies.get(flavor);
assert flavored_body != null;
list<construct> supertype_list = supertype_lists.get(flavor);
assert supertype_list != null;
immutable_list<type_flavor> superflavors = flavor.get_superflavors();
for (int j = 0; j < superflavors.size(); ++j) {
type_flavor superflavor = superflavors.get(j);
if (profile.supports(superflavor)) {
supertype_list.append(make_flavored_and_parametrized_type(declared_type, superflavor,
type_parameters, the_origin));
}
}
if (supertype_list.is_not_empty()) {
subtype_tag the_subtype_tag = concrete_mode ? implements_tag : extends_tag;
flavored_body.prepend(new supertype_construct(new empty<annotation_construct>(),
null, the_subtype_tag, supertype_list, the_origin));
}
simple_name flavored_name;
if (concrete_mode) {
flavored_name = type_name;
if (superclass != null) {
flavored_body.prepend(new supertype_construct(new empty<annotation_construct>(), null,
extends_tag, new base_list<construct>(superclass), the_origin));
}
} else {
flavored_name = make_name(type_name, declared_type, flavor);
}
type_decls.append(new type_declaration_construct(annotations,
concrete_mode ? the_kind : interface_kind, flavored_name, type_parameters,
flavored_body, the_origin));
}
enclosing_type = old_enclosing_type;
return type_decls;
}
private static boolean is_readonly_flavor(type_flavor the_flavor) {
return the_flavor == readonly_flavor ||
the_flavor == immutable_flavor ||
the_flavor == deeply_immutable_flavor;
}
private static boolean is_concrete_kind(kind the_kind) {
return the_kind == class_kind || the_kind == enum_kind || the_kind == test_suite_kind ||
the_kind == program_kind;
}
private procedure_construct var_to_proc(variable_declaration the_variable) {
origin the_origin = the_variable;
type return_type = is_readonly_flavor(the_variable.reference_type().get_flavor()) ?
the_variable.value_type() : the_variable.reference_type();
// TODO: should we inherit attotaions from the_variable?
list<annotation_construct> annotations = new base_list<annotation_construct>();
if (type_utilities.is_union(return_type)) {
annotations.append(make_nullable(the_origin));
// make_type() strips null from union type
}
// This is a hack to get gregorian_month to work.
if (the_variable.short_name() == ORDINAL_NAME &&
return_type == immutable_nonnegative_type()) {
return_type = java_library.int_type().get_flavored(deeply_immutable_flavor);
}
return new procedure_construct(annotations,
make_type(return_type, the_origin),
the_variable.short_name(),
new empty<construct>(),
new empty<annotation_construct>(),
null,
the_origin);
}
private list_construct make_parens(origin the_origin) {
return new list_construct(new base_list<construct>(), grouping_type.PARENS, false, the_origin);
}
private list_construct in_parens(construct the_construct, origin the_origin) {
return new list_construct(new base_list<construct>(the_construct), grouping_type.PARENS,
false, the_origin);
}
private Object make_procedure_declarations(readonly_list<annotation_construct> annotations,
type_declaration the_type_declaration) {
action_name the_name = the_type_declaration.short_name();
boolean is_function;
if (utilities.eq(the_name, procedure_name)) {
is_function = false;
} else if (utilities.eq(the_name, function_name)) {
is_function = true;
} else {
utilities.panic("Unexpected procedure type " + the_name);
return null;
}
list<construct> result = new base_list<construct>();
result.append(make_procedure_construct(annotations, the_type_declaration, is_function, 0));
result.append(make_procedure_construct(annotations, the_type_declaration, is_function, 1));
result.append(make_procedure_construct(annotations, the_type_declaration, is_function, 2));
return result;
}
private type_declaration_construct make_procedure_construct(
readonly_list<annotation_construct> annotations,
type_declaration the_type_declaration,
boolean is_function, int arity) {
origin the_origin = the_type_declaration;
readonly_list<annotation_construct> empty_annotations = new empty<annotation_construct>();
simple_name return_name = simple_name.make("R");
construct return_construct = new name_construct(return_name, the_origin);
list<construct> type_parameters = new base_list<construct>();
type_parameters.append(new variable_construct(empty_annotations, null, return_name,
empty_annotations, null, the_origin));
list<construct> call_parameters = new base_list<construct>();
list<construct> supertype_parameters = new base_list<construct>();
supertype_parameters.append(return_construct);
for (int i = 0; i < arity; ++i) {
simple_name argument_type = simple_name.make("A" + i);
type_parameters.append(new variable_construct(empty_annotations, null, argument_type,
empty_annotations, null, the_origin));
supertype_parameters.append(new name_construct(argument_type, the_origin));
simple_name argument_name = make_numbered_name(i);
call_parameters.append(new variable_construct(empty_annotations,
new name_construct(argument_type, the_origin), argument_name, empty_annotations, null,
the_origin));
}
list<construct> extends_types = new base_list<construct>();
if (is_function) {
construct superprocedure = new parameter_construct(
new name_construct(make_procedure_name(false, arity), the_origin),
supertype_parameters, grouping_type.ANGLE_BRACKETS, the_origin);
extends_types.append(superprocedure);
}
readonly_list<declaration> body = the_type_declaration.get_signature();
for (int i = 0; i < body.size(); ++i) {
declaration decl = body.get(i);
if (decl instanceof supertype_declaration) {
supertype_declaration supertype_decl = (supertype_declaration) decl;
type supertype = supertype_decl.get_supertype();
if (supertype.principal().get_kind() != procedure_kind) {
extends_types.append(make_type(supertype_decl.get_supertype(), the_origin));
}
}
}
list<construct> type_body = new base_list<construct>();
type_body.append(new supertype_construct(new empty<annotation_construct>(), null,
extends_tag, extends_types, the_origin));
if (!is_function) {
type_body.append(new procedure_construct(empty_annotations, return_construct,
call_name, call_parameters, empty_annotations, null, the_origin));
}
simple_name type_name = make_procedure_name(is_function, arity);
return new type_declaration_construct(annotations, interface_kind, type_name, type_parameters,
type_body, the_origin);
}
private simple_name make_procedure_name(boolean is_function, int arity) {
simple_name base_name = is_function ? function_name : procedure_name;
return make_procedure_name(base_name, arity);
}
private simple_name make_procedure_name(simple_name base_name, int arity) {
return simple_name.make(new base_string(base_name.to_string(), String.valueOf(arity)));
}
@Override
public construct process_variable(variable_declaration the_variable) {
if (the_variable instanceof enum_value_analyzer) {
return process_enum_value((enum_value_analyzer) the_variable);
}
origin the_origin = the_variable;
principal_type declared_in_type = the_variable.declared_in_type();
list<annotation_construct> annotations = to_annotations(the_variable.annotations(),
annotation_category.VARIABLE, skip_access(declared_in_type), the_origin);
return process_variable(the_variable, annotations);
}
public construct process_variable(variable_declaration the_variable,
list<annotation_construct> annotations) {
origin the_origin = the_variable;
principal_type declared_in_type = the_variable.declared_in_type();
boolean is_mutable = the_variable.reference_type().get_flavor() == mutable_flavor;
if (!is_mutable &&
!the_variable.annotations().has(final_modifier) &&
!is_procedure_with_no_body(declared_in_type.get_declaration())) {
annotations.append(new modifier_construct(final_modifier, the_origin));
}
type var_type = the_variable.value_type();
construct type;
if (type_utilities.is_union(var_type)) {
annotations.append(make_nullable(the_origin));
type not_null_type = remove_null_type(var_type);
if (is_object_type(not_null_type)) {
type = make_object_type(the_origin);
} else {
type = make_type_with_mapping(not_null_type, the_origin, mapping.MAP_TO_WRAPPER_TYPE);
}
} else {
if (is_object_type(var_type)) {
type = make_object_type(the_origin);
} else {
type = make_type(var_type, the_origin);
}
}
@Nullable construct init = the_variable.init_action() != null ?
transform_and_maybe_rewrite(the_variable.init_action()) : null;
return new variable_construct(annotations, type, the_variable.short_name(),
new empty<annotation_construct>(), init, the_origin);
}
private boolean is_procedure_reference(action the_action) {
if (the_action instanceof dispatch_action) {
return is_procedure_declaration(((dispatch_action) the_action).get_declaration());
}
if (the_action instanceof chain_action) {
action second = ((chain_action) the_action).second;
if (second instanceof dereference_action ||
second instanceof dispatch_action ||
second instanceof variable_action) {
return is_procedure_declaration(((chain_action) the_action).get_declaration());
}
}
if (the_action instanceof data_value_action) {
Object the_value = ((data_value_action) the_action).the_value;
if (the_value instanceof base_data_value) {
return is_procedure_declaration(((base_data_value) the_value).get_declaration());
}
}
return false;
}
private boolean is_procedure_declaration(declaration the_declaration) {
return the_declaration instanceof procedure_declaration &&
!should_call_as_procedure(the_declaration);
}
private construct make_procedure_class(action the_action, origin the_origin) {
assert is_procedure_reference(the_action);
procedure_declaration the_procedure =
(procedure_declaration) declaration_util.get_declaration(the_action);
@Nullable principal_type old_enclosing_type = enclosing_type;
enclosing_type = the_procedure.get_procedure_type().principal();
construct procedure_type = make_type(the_procedure.get_procedure_type(), the_origin);
construct new_construct = new operator_construct(operator.ALLOCATE, procedure_type, the_origin);
construct with_parens = new parameter_construct(new_construct, new base_list<construct>(),
grouping_type.PARENS, the_origin);
readonly_list<annotation_construct> annotations = new base_list<annotation_construct>(
new modifier_construct(override_modifier, the_origin),
new modifier_construct(public_modifier, the_origin));
list<construct> declaration_arguments = new base_list<construct>();
list<construct> call_arguments = new base_list<construct>();
readonly_list<type> argument_types = the_procedure.get_argument_types();
for (int i = 0; i < argument_types.size(); ++i) {
simple_name argument_name = make_numbered_name(i);
type argument_type = argument_types.get(i);
declaration_arguments.append(new variable_construct(
new empty<annotation_construct>(),
make_type_with_mapping(argument_type, the_origin, mapping.MAP_TO_WRAPPER_TYPE),
argument_name, new empty<annotation_construct>(), null, the_origin));
call_arguments.append(new name_construct(argument_name, the_origin));
}
list<construct> body = new base_list<construct>();
construct body_call = new parameter_construct(transform_action(the_action), call_arguments,
grouping_type.PARENS, the_origin);
if (the_procedure.get_return_type() == immutable_void_type()) {
// We need this because the return type is Void, not void
body.append(body_call);
body.append(new return_construct(make_null(the_origin), the_origin));
} else {
body.append(new return_construct(body_call, the_origin));
}
construct the_call = new procedure_construct(
annotations,
make_type_with_mapping(the_procedure.get_return_type(), the_origin,
mapping.MAP_TO_WRAPPER_TYPE),
call_name,
declaration_arguments,
new empty<annotation_construct>(),
new block_construct(body, the_origin),
the_origin);
enclosing_type = old_enclosing_type;
return new parameter_construct(with_parens, new base_list<construct>(the_call),
grouping_type.BRACES, the_origin);
}
protected readonly_list<construct> maybe_unwrap_block(readonly_list<construct> body) {
if (body.size() == 1 && body.first() instanceof block_construct) {
block_construct the_block_construct = (block_construct) body.first();
if (the_block_construct.annotations.is_empty()) {
return maybe_unwrap_block(the_block_construct.body);
}
}
return body;
}
@Override
public construct process_block(block_declaration the_block) {
origin the_origin = the_block;
readonly_list<construct> body = maybe_unwrap_block(transform_action_list(
the_block.get_body_action()));
return new block_construct(to_annotations(the_block.annotations(),
annotation_category.BLOCK, true, the_origin), body, the_origin);
}
private boolean is_explicit_reference(action the_action) {
// TODO: this needs to be fixed/cleaned up.
declaration the_declaration = get_procedure_declaration(the_action);
if (the_declaration instanceof variable_declaration) {
variable_declaration the_variable = (variable_declaration) the_declaration;
if (the_variable.reference_type().get_flavor() == mutable_flavor) {
kind the_kind = the_variable.declared_in_type().get_kind();
return !the_kind.is_namespace() && !is_concrete_kind(the_kind);
}
}
if (the_declaration instanceof procedure_declaration) {
procedure_declaration the_procedure = (procedure_declaration) the_declaration;
type return_type = the_procedure.get_return_type();
return is_reference_type(return_type) && return_type.get_flavor() == mutable_flavor;
}
return false;
}
private construct do_explicitly_derefence(construct the_construct, origin the_origin) {
construct get_construct = new resolve_construct(the_construct, get_name, the_origin);
return new parameter_construct(get_construct, new empty<construct>(), grouping_type.PARENS,
the_origin);
}
private boolean is_procedure_with_no_body(@Nullable declaration the_declaration) {
return the_declaration instanceof procedure_declaration &&
((procedure_declaration) the_declaration).get_body_action() == null;
}
private boolean is_object_type(type the_type) {
principal_type the_principal_type = the_type.principal();
return the_principal_type == value_type() ||
the_principal_type == equality_comparable_type() ||
the_principal_type == data_type();
}
@Override
public construct process_type_parameter(type_parameter_declaration the_type_parameter) {
origin the_origin = the_type_parameter;
type type_bound = the_type_parameter.variable_type();
if (!type_bound.is_subtype_of(value_type().get_flavored(any_flavor))) {
utilities.panic("Type bound is not a value but " + type_bound);
}
@Nullable construct type_construct;
if (is_object_type(type_bound)) {
type_construct = null;
} else {
type_construct = make_type_with_mapping(type_bound, the_origin, mapping.MAP_TO_WRAPPER_TYPE);
}
return new variable_construct(new empty<annotation_construct>(), type_construct,
the_type_parameter.short_name(), new empty<annotation_construct>(), null, the_origin);
}
private list<construct> transform_parameters(readonly_list<action> actions) {
list<construct> result = new base_list<construct>();
for (int i = 0; i < actions.size(); ++i) {
result.append(transform_and_maybe_rewrite(actions.get(i)));
}
return result;
}
// TODO: better way to detect procedure variables?
private boolean is_procedure_variable(@Nullable declaration the_declaration) {
return the_declaration instanceof type_declaration &&
is_reference_type(((type_declaration) the_declaration).get_declared_type());
}
private construct make_default_return(type the_type, boolean is_constructor, origin the_origin) {
@Nullable construct return_value = is_constructor ? null :
make_default_value(the_type, the_origin);
return new return_construct(return_value, the_origin);
}
private construct make_default_value(type the_type, origin the_origin) {
if (the_type == immutable_boolean_type()) {
return new name_construct(false_value().short_name(), the_origin);
} else {
// TODO: handle other non-Object types
return make_null(the_origin);
}
}
public construct process_operator(bound_procedure the_bound_procedure, operator the_operator) {
origin the_origin = the_bound_procedure;
readonly_list<action> arguments = the_bound_procedure.parameters.parameters;
// TODO: handle other assignment operators.
if (the_operator == operator.ASSIGN) {
action lhs = arguments.get(0);
construct rhs = transform_and_maybe_rewrite(arguments.get(1));
if (lhs instanceof bound_procedure) {
bound_procedure lhs2 = (bound_procedure) lhs;
readonly_list<action> plhs = lhs2.parameters.parameters;
@Nullable declaration the_declaration = declaration_util.get_declaration(lhs2);
if (the_declaration instanceof procedure_declaration) {
procedure_declaration proc_decl = (procedure_declaration) the_declaration;
if (proc_decl.annotations().has(implicit_modifier) && plhs.size() == 1) {
construct main = transform_action(lhs2.the_procedure_action);
readonly_list<construct> set_params =
new base_list<construct>(transform_action(plhs.first()), rhs);
construct set = new resolve_construct(main, set_name, the_origin);
return make_call(set, set_params, the_origin);
}
}
}
if (is_explicit_reference(lhs)) {
construct main = transform_action(lhs);
readonly_list<construct> set_params = new base_list<construct>(rhs);
construct set = new resolve_construct(main, set_name, the_origin);
return make_call(set, set_params, the_origin);
}
// TODO: this should be generic...
base_list<construct> arguments_constructs =
new base_list<construct>(transform_action(lhs), rhs);
return new operator_construct(operator.ASSIGN, arguments_constructs, the_origin);
} else if (the_operator instanceof cast_type) {
return transform_cast(arguments.get(0), get_type(arguments.get(1)), (cast_type) the_operator,
the_origin);
} else if (the_operator == operator.IS_OPERATOR) {
return transform_is(false, arguments.get(0), get_type(arguments.get(1)), the_origin);
} else if (the_operator == operator.IS_NOT_OPERATOR) {
return transform_is(true, arguments.get(0), get_type(arguments.get(1)), the_origin);
} else if (the_operator == operator.EQUAL_TO) {
if (use_objects_equal(arguments)) {
return objects_equal(arguments, the_origin);
}
} else if (the_operator == operator.NOT_EQUAL_TO) {
if (use_objects_equal(arguments)) {
return new operator_construct(operator.LOGICAL_NOT, objects_equal(arguments, the_origin),
the_origin);
}
// TODO: convert into an equivalence function call if the argument is not a primitive.
} else if (the_operator == operator.COMPARE) {
construct comparison = new resolve_construct(make_type(java_library.runtime_util_class(),
the_origin), COMPARE_NAME, the_origin);
return make_call(comparison, transform_parameters(arguments), the_origin);
} else if (the_operator == operator.CONCATENATE) {
if (!is_string_type(arguments.get(0)) || !is_string_type(arguments.get(1))) {
construct concatenation = new resolve_construct(make_type(java_library.runtime_util_class(),
the_origin), CONCATENATE_NAME, the_origin);
return make_call(concatenation, transform_parameters(arguments), the_origin);
}
}
/*else if (the_operator == operator.GENERAL_OR) {
action the_action = get_action(the_parameter);
if (the_action instanceof type_action && mapping_strategy == mapping.MAP_TO_WRAPPER_TYPE) {
return make_type(remove_null_type(((type_action) the_action).get_type()), the_origin);
}
utilities.panic("Unexpected 'or' operator " + the_parameter);
}*/
return new operator_construct(map_operator(the_operator), transform_parameters(arguments),
the_origin);
}
private boolean use_objects_equal(readonly_list<action> arguments) {
assert arguments.size() == 2;
boolean is_primitive =
is_java_primitive(arguments.get(0)) || is_java_primitive(arguments.get(1));
boolean is_reference_equality =
is_reference_equality(arguments.get(0)) || is_reference_equality(arguments.get(1));
return !is_primitive && !is_reference_equality;
}
private construct objects_equal(readonly_list<action> arguments, origin the_origin) {
construct values_equal = new resolve_construct(make_type(java_library.runtime_util_class(),
the_origin), OBJECTS_EQUAL_NAME, the_origin);
return make_call(values_equal, transform_parameters(arguments), the_origin);
}
private construct int_to_string(construct int_value, origin the_origin) {
construct to_string = new resolve_construct(make_type(java_library.runtime_util_class(),
the_origin), INT_TO_STRING_NAME, the_origin);
return make_call(to_string, new base_list<construct>(int_value), the_origin);
}
public construct transform_cast(action expression, type the_type, cast_type the_cast_type,
origin the_origin) {
type expression_type = result_type(expression);
construct transformed_expression = transform_action(expression);
construct transformed_type = make_type(the_type, the_origin);
if (the_type == nonnegative_type() &&
expression_type == immutable_integer_type()) {
// we drop the integer -> nonnegative cast
return transformed_expression;
}
principal_type expression_principal = expression_type.principal();
principal_type type_principal = the_type.principal();
if (expression_principal instanceof parametrized_type &&
type_principal instanceof parametrized_type) {
// && ((parametrized_type) expression_principal).get_master() ==
// ((parametrized_type) type_principal).get_master()
// Note that with the above constraints, some Java generic casts
// do not work. Rather than trying to figure out when exactly double casts
// are necessary with generic types, we always introduce double casts.
// There shouldn't be semantic problems with it, just minor overhead.
master_type the_master = ((parametrized_type) type_principal).get_master();
type intermediate_type = the_master.get_flavored(the_type.get_flavor());
transformed_expression = new operator_construct(operator.HARD_CAST,
new base_list<construct>(transformed_expression, make_type(intermediate_type, the_origin)),
the_origin);
}
return new operator_construct(the_cast_type,
new base_list<construct>(transformed_expression, transformed_type), the_origin);
}
public operator map_operator(operator the_operator) {
if (the_operator == operator.CONCATENATE) {
return operator.ADD;
} else if (the_operator == operator.CONCATENATE_ASSIGN) {
return operator.ADD_ASSIGN;
} else {
return the_operator;
}
}
// TODO: make three methods below into a generic function.
private boolean is_string_type(action the_action) {
boolean result = result_type(the_action).principal() == java_library.string_type();
if (result) {
return true;
}
if (is_promotion_action(the_action)) {
the_action = unwrap_promotion(the_action);
return result_type(the_action).principal() == java_library.string_type();
}
return false;
}
private boolean is_promotion_action(action the_action) {
return the_action instanceof chain_action &&
((chain_action) the_action).second instanceof promotion_action;
}
private action unwrap_promotion(action the_action) {
assert the_action instanceof chain_action &&
((chain_action) the_action).second instanceof promotion_action;
do {
the_action = ((chain_action) the_action).first;
} while (is_promotion_action(the_action));
return the_action;
}
private boolean is_reference_equality(action the_action) {
type reference_equality = reference_equality_type().get_flavored(any_flavor);
boolean result = result_type(the_action).is_subtype_of(reference_equality);
if (result) {
return true;
}
if (is_promotion_action(the_action)) {
the_action = unwrap_promotion(the_action);
return result_type(the_action).is_subtype_of(reference_equality);
}
return false;
}
public boolean is_mapped(principal_type the_type) {
return the_type == boolean_type() ||
the_type == character_type() ||
the_type == void_type();
}
private boolean is_java_primitive(action the_action) {
boolean result = is_mapped(result_type(the_action).principal());
if (result) {
return true;
}
if (is_promotion_action(the_action)) {
the_action = unwrap_promotion(the_action);
return is_mapped(result_type(the_action).principal());
}
return false;
}
@Override
public import_construct process_import(import_declaration the_import) {
origin the_origin = the_import;
list<annotation_construct> annotations = new base_list<annotation_construct>();
if (the_import.is_implicit()) {
annotations.append(new modifier_construct(implicit_modifier, the_origin));
principal_type the_principal = the_import.get_type().principal();
kind the_kind = the_principal.get_kind();
if ((the_kind.is_namespace() || the_kind == type_kinds.class_kind) &&
(the_principal.get_parent().get_kind() == type_kinds.package_kind)) {
annotations.append(new modifier_construct(static_modifier, the_origin));
}
}
return new import_construct(annotations,
make_imported_type((principal_type) the_import.get_type(), the_origin), the_origin);
}
public construct process_loop_action(loop_action the_loop_action) {
origin the_origin = the_loop_action;
construct true_construct = new name_construct(true_value().short_name(), the_origin);
return new while_construct(true_construct, transform_action(the_loop_action.get_body()),
the_origin);
}
public construct process_return_action(return_action the_return) {
origin the_origin = the_return;
if (the_return.return_type.principal() == void_type()) {
@Nullable procedure_declaration the_procedure = the_return.the_procedure;
return_construct the_return_construct;
// We rewrite return constructs of procedures that return 'Void' with capital 'V'
if (should_use_wrapper_in_return(the_procedure)) {
the_return_construct = new return_construct(make_null(the_origin), the_origin);
} else {
the_return_construct = new return_construct(null, the_origin);
}
if (is_nothing(the_return.expression)) {
return the_return_construct;
} else {
return new block_construct(new empty<annotation_construct>(),
new base_list<construct>(transform_action(the_return.expression),
the_return_construct), the_origin);
}
}
construct the_expression;
if (is_reference_type(the_return.return_type)) {
the_expression = transform_action(the_return.expression);
} else {
the_expression = transform_and_maybe_rewrite(the_return.expression);
}
return new return_construct(the_expression, the_origin);
}
public construct process_extension_action(extension_action the_extension_action) {
extension_analyzer the_extension = the_extension_action.get_extension();
if (the_extension instanceof grouping_analyzer) {
return process_grouping((grouping_analyzer) the_extension);
} else if (the_extension instanceof while_analyzer) {
return process_while((while_analyzer) the_extension);
} else if (the_extension instanceof for_analyzer) {
return process_for((for_analyzer) the_extension);
}
return transform_action(the_extension_action.extended_action);
}
public construct process_variable_initializer(variable_initializer the_variable_initializer) {
variable_declaration the_declaration =
the_variable_initializer.the_variable_action.the_declaration;
return process_variable(the_declaration);
}
public @Nullable construct transform_or_null(action the_action) {
if (is_nothing(the_action)) {
return null;
} else {
return transform_action(the_action);
}
}
protected boolean is_value(action the_action, value the_value) {
return the_action instanceof base_value_action &&
((base_value_action) the_action).the_value == the_value;
}
public construct process_conditional_action(conditional_action the_conditional) {
origin the_origin = the_conditional;
if (is_value(the_conditional.else_action, false_value())) {
return new operator_construct(operator.LOGICAL_AND,
transform_action(the_conditional.condition),
transform_action(the_conditional.then_action), the_origin);
} else if (is_value(the_conditional.then_action, true_value())) {
return new operator_construct(operator.LOGICAL_OR,
transform_action(the_conditional.condition),
transform_action(the_conditional.else_action), the_origin);
}
// TODO: infer is_statement from conditional_action
boolean is_statement = true;
construct the_construct = get_construct(the_conditional);
if (the_construct instanceof conditional_construct) {
is_statement = ((conditional_construct) the_construct).is_statement;
}
return new conditional_construct(transform_action(the_conditional.condition),
transform_action(the_conditional.then_action),
transform_or_null(the_conditional.else_action),
is_statement, the_origin);
}
public construct process_list_action(list_action the_list_action) {
utilities.panic("list_action: " + the_list_action);
origin the_origin = the_list_action;
return new block_construct(transform_parameters(the_list_action.elements()), the_origin);
}
public construct process_constraint_action(constraint_action the_constraint_action) {
origin the_origin = the_constraint_action;
return new constraint_construct(constraint_category.ASSERT_CONSTRAINT,
transform_action(the_constraint_action.expression), the_origin);
}
public construct process_block_action(block_action the_block_action) {
origin the_origin = the_block_action;
return process_block(the_block_action.get_declaration());
}
private simple_name get_simple_name(construct c) {
name_construct identifier = (name_construct) c;
return (simple_name) identifier.the_name;
}
public readonly_list<construct> make_headers(type_declaration_construct the_declaration) {
origin the_origin = the_declaration;
list<construct> headers = new base_list<construct>();
headers.append(make_comment(the_origin));
headers.append_all(common_headers);
boolean add_newline = false;
if (deep_has(the_declaration, modifier_of_type(nullable_modifier))) {
// TODO: kill empty line after common imports but before nullable import?
headers.append(make_import(java_library.nullable_type(), the_origin));
add_newline = true;
}
if (deep_has(the_declaration, modifier_of_type(dont_display_modifier))) {
headers.append(make_import(java_library.dont_display_type(), the_origin));
add_newline = true;
}
if (add_newline) {
headers.append(make_newline(the_origin));
}
return headers;
}
private boolean deep_has(type_declaration_construct the_declaration,
predicate<construct> the_predicate) {
predicate<construct> deep_traverse = new predicate<construct>() {
public @Override Boolean call(construct the_construct) {
if (the_predicate.call(the_construct)) {
return true;
}
return the_construct.children().has(this);
}
};
return deep_traverse.call(the_declaration);
}
private predicate<construct> modifier_of_type(modifier_kind the_modifier_kind) {
return new predicate<construct>() {
public @Override Boolean call(construct the_construct) {
return the_construct instanceof modifier_construct &&
((modifier_construct) the_construct).the_kind == the_modifier_kind;
}
};
}
private import_construct make_import(principal_type the_type, origin the_origin) {
return new import_construct(new empty<annotation_construct>(), make_type(the_type, the_origin),
the_origin);
}
private static construct make_call(construct main, readonly_list<construct> parameters,
origin the_origin) {
return new parameter_construct(main, parameters, grouping_type.PARENS, the_origin);
}
private static construct make_null(origin the_origin) {
return new name_construct(null_name, the_origin);
}
private static construct make_zero(origin the_origin) {
return new literal_construct(new integer_literal(0), the_origin);
}
private static comment_construct make_comment(origin the_origin) {
source_content src = origin_utilities.get_source(the_origin);
string comment;
if (src != null) {
comment = new base_string("Autogenerated from ", src.name.to_string());
} else {
comment = new base_string("Autogenerated");
}
return new comment_construct(new comment(comment_type.LINE_COMMENT, comment,
new base_string("// ", comment)), null, the_origin);
}
private static comment_construct make_newline(origin the_origin) {
string newline = new base_string("\n");
return new comment_construct(new comment(comment_type.NEWLINE, newline, newline), null,
the_origin);
}
public final static base_flavor_profile class_profile =
new base_flavor_profile(new base_string("class_profile"),
new function1<type_flavor, type_flavor>() {
@Override public type_flavor call(type_flavor first) {
if (first == flavor.nameonly_flavor) {
return first;
} else {
return flavor.DEFAULT_FLAVOR;
}
}
});
public construct process_analyzable_action(analyzable_action the_analyzable_action) {
return transform_action(the_analyzable_action.get_action());
}
public construct base_string_wrap(construct the_construct, origin the_origin) {
// TODO: handle both string and character literals correctly.
// TODO: also, convert inline literals into constants.
// TODO: use fully qualified type name?
principal_type runtime_elements = java_library.runtime_elements_namespace();
construct base_string_name;
if (implicit_names.contains(runtime_elements)) {
base_string_name = new name_construct(BASE_STRING_NAME, the_origin);
} else {
base_string_name = new resolve_construct(make_type(runtime_elements, the_origin),
BASE_STRING_NAME, the_origin);
}
construct alloc = new operator_construct(operator.ALLOCATE, base_string_name, the_origin);
return make_call(alloc, new base_list<construct>(the_construct), the_origin);
}
public construct process_value_action(base_value_action the_value_action) {
//System.out.println("PV: " + the_value);
origin the_origin = the_value_action;
Object the_value = the_value_action.the_value;
if (the_value instanceof singleton_value) {
principal_type singleton_type = ((singleton_value) the_value).type_bound().principal();
// Convert missing.instance to null literal
if (is_null_subtype(singleton_type)) {
return make_null(the_origin);
}
construct type_construct = make_type(singleton_type, the_origin);
return new resolve_construct(type_construct, instance_name, the_origin);
} else if (the_value instanceof integer_value) {
integer_value the_integer_value = (integer_value) the_value;
return new literal_construct(new integer_literal(the_integer_value.unwrap()), the_origin);
} else if (the_value instanceof enum_value) {
enum_value the_enum_value = (enum_value) the_value;
if (the_enum_value.type_bound() == immutable_boolean_type()) {
return new name_construct(the_enum_value.short_name(), the_origin);
} else {
return new resolve_construct(make_type(the_enum_value.type_bound(), the_origin),
the_enum_value.short_name(), the_origin);
}
} else if (the_value instanceof string_value) {
string_value the_string_value = (string_value) the_value;
type the_type = the_value_action.result().type_bound();
quote_type literal_type = (the_type == immutable_character_type()) ?
punctuation.SINGLE_QUOTE : punctuation.DOUBLE_QUOTE;
construct result = new literal_construct(new quoted_literal(the_string_value.unwrap(),
literal_type), the_origin);
if (the_type == immutable_string_type()) {
result = base_string_wrap(result, the_origin);
}
return result;
} else if (the_value instanceof base_procedure) {
base_procedure the_procedure = (base_procedure) the_value;
action_name the_name = map_name(the_procedure.name());
procedure_declaration the_procedure_declaration =
(procedure_declaration) the_procedure.get_declaration();
if (the_procedure_declaration == null) {
return new name_construct(the_name, the_origin);
} else {
return new resolve_construct(
make_type(the_procedure_declaration.declared_in_type(), the_origin),
the_name, the_origin);
}
} else if (the_value instanceof procedure_with_this) {
procedure_with_this the_procedure_with_this = (procedure_with_this) the_value;
action_name the_action_name = the_procedure_with_this.name();
// TODO: handle the_procedure_with_this.this_entity if set
assert the_procedure_with_this.this_action != null;
construct this_construct = process_action(the_procedure_with_this.this_action,
the_origin);
if (the_action_name == special_name.IMPLICIT_CALL) {
return this_construct;
} else {
return new resolve_construct(this_construct, map_name(the_action_name), the_origin);
}
} else if (the_value instanceof loop_jump_wrapper) {
loop_jump_wrapper the_loop_jump_wrapper = (loop_jump_wrapper) the_value;
return new jump_construct(the_loop_jump_wrapper.the_jump_category, the_origin);
}
utilities.panic("processing value " + the_value.getClass() + ": " + the_value);
return null;
}
@Override
public construct transform_action(action the_action) {
origin the_origin = the_action;
return process_action(the_action, the_origin);
}
private construct transform_and_maybe_rewrite(action the_action) {
origin the_origin = the_action;
construct transformed = transform_action(the_action);
if (is_explicit_reference(the_action)) {
return do_explicitly_derefence(transformed, the_origin);
} else if (is_procedure_reference(the_action)) {
return make_procedure_class(the_action, the_origin);
} else {
return transformed;
}
}
// This cleans up grouping_analyzers generated when processing please_construct.
private @Nullable construct strip_grouping(action the_action) {
if (the_action instanceof extension_action) {
analyzable extension_analyzable = ((extension_action) the_action).get_extension();
analyzable the_analyzable = extension_analyzable;
while (the_analyzable instanceof grouping_analyzer) {
the_analyzable = ((grouping_analyzer) the_analyzable).expression;
}
if (the_analyzable != extension_analyzable) {
return transform_analyzable(the_analyzable);
}
}
return null;
}
private void transform_and_append(action the_action, list<construct> result) {
if (the_action instanceof list_action) {
readonly_list<action> actions = ((list_action) the_action).elements();
for (int i = 0; i < actions.size(); ++i) {
action element_action = actions.get(i);
@Nullable construct stripped_grouping = strip_grouping(element_action);
if (stripped_grouping != null) {
result.append(stripped_grouping);
} else {
transform_and_append(element_action, result);
}
}
} else {
result.append(transform_action(the_action));
}
}
public list<construct> transform_action_list(action the_action) {
list<construct> result = new base_list<construct>();
transform_and_append(the_action, result);
return result;
}
public construct process_action(action the_action, origin the_origin) {
if (the_action instanceof type_action) {
return make_type(((type_action) the_action).get_type(), the_origin);
}
if (the_action instanceof base_value_action) {
return process_value_action((base_value_action) the_action);
}
if (the_action instanceof narrow_action) {
narrow_action the_narrow_action = (narrow_action) the_action;
return process_narrow_action(the_narrow_action,
process_action(the_narrow_action.expression, the_origin), the_origin);
}
if (the_action instanceof variable_action) {
return process_variable_action(null, (variable_action) the_action, the_origin);
}
if (the_action instanceof chain_action) {
chain_action the_chain_action = (chain_action) the_action;
if (the_chain_action.second instanceof variable_action) {
return process_variable_action(the_chain_action.first,
(variable_action) the_chain_action.second, the_origin);
} else if (the_chain_action.second instanceof dispatch_action) {
return process_dispatch_action(the_chain_action.first,
(dispatch_action) the_chain_action.second, the_origin);
} else if (the_chain_action.second instanceof dereference_action) {
return process_action(the_chain_action.first, the_origin);
} else if (the_chain_action.second instanceof promotion_action) {
return process_promotion_action(the_chain_action.first,
(promotion_action) the_chain_action.second, the_origin);
} else if (the_chain_action.second instanceof proc_as_ref_action) {
return process_proc_as_ref_action(the_chain_action.first,
(proc_as_ref_action) the_chain_action.second, the_origin);
}
utilities.panic("Unrecognized chain action: " + the_chain_action);
}
if (the_action instanceof bound_procedure) {
return process_bound_procedure((bound_procedure) the_action, the_origin);
}
if (the_action instanceof allocate_action) {
allocate_action the_allocate_action = (allocate_action) the_action;
return new operator_construct(operator.ALLOCATE,
make_type(the_allocate_action.the_type, the_origin), the_origin);
}
if (the_action instanceof extension_action) {
return process_extension_action((extension_action) the_action);
}
if (the_action instanceof cast_action) {
return process_cast((cast_action) the_action, the_origin);
}
if (the_action instanceof list_initializer_action) {
return process_list_initializer_action((list_initializer_action) the_action);
}
if (the_action instanceof is_action) {
return process_is_operator((is_action) the_action, the_origin);
}
if (the_action instanceof return_action) {
return process_return_action((return_action) the_action);
}
if (the_action instanceof variable_initializer) {
return process_variable_initializer((variable_initializer) the_action);
}
if (the_action instanceof conditional_action) {
return process_conditional_action((conditional_action) the_action);
}
if (the_action instanceof list_action) {
return process_list_action((list_action) the_action);
}
if (the_action instanceof constraint_action) {
return process_constraint_action((constraint_action) the_action);
}
if (the_action instanceof block_action) {
return process_block_action((block_action) the_action);
}
if (the_action instanceof loop_action) {
return process_loop_action((loop_action) the_action);
}
utilities.panic("processing action " + the_action.getClass() + ": " + the_action);
return null;
}
private construct process_variable_action(@Nullable action from,
variable_action the_variable_action, origin the_origin) {
action_name the_name = map_name(the_variable_action.short_name());
if (the_variable_action instanceof static_variable) {
return new resolve_construct(
make_type(the_variable_action.the_declaration.declared_in_type(), the_origin),
the_name, the_origin);
} else if (the_variable_action instanceof instance_variable) {
assert from != null;
construct from_construct = transform_and_maybe_rewrite(from);
construct result = new resolve_construct(from_construct, the_name, the_origin);
return maybe_call(the_variable_action, result, the_origin);
} else if (the_variable_action instanceof local_variable &&
the_variable_action.short_name() == special_name.THIS) {
principal_type this_type = the_variable_action.value_type().principal();
if (this_type != enclosing_type) {
name_construct from_name = new name_construct(this_type.short_name(), the_origin);
return new resolve_construct(from_name, the_name, the_origin);
}
}
return new name_construct(the_name, the_origin);
}
private construct process_promotion_action(action from_action,
promotion_action the_promotion_action, origin the_origin) {
type action_type = from_action.result().type_bound();
type promotion_type = the_promotion_action.the_type;
if (false && the_promotion_action.is_supertype &&
is_list_type(action_type) &&
is_list_type(promotion_type) &&
get_list_parameter(action_type) != get_list_parameter(promotion_type)) {
//System.out.println("68A " + action_type);
//System.out.println("68B " + promotion_type);
return in_parens(transform_cast(from_action, the_promotion_action.the_type, operator.SOFT_CAST,
the_origin), the_origin);
}
return process_action(from_action, the_origin);
}
private construct process_dispatch_action(action from_action,
dispatch_action the_dispatch_action, origin the_origin) {
construct from_construct = transform_and_maybe_rewrite(from_action);
action primary = the_dispatch_action.get_primary();
if (primary instanceof variable_action) {
variable_action the_variable_action = (variable_action) primary;
action_name the_name = map_name(the_variable_action.short_name());
if (the_name == to_string_name && is_promotion_action(from_action)) {
principal_type from_type = unwrap_promotion(from_action).result().type_bound().principal();
// TODO: implement less hacky way to implement Integer.to_string
if (from_type == integer_type() || from_type == nonnegative_type()) {
return int_to_string(from_construct, the_origin);
}
}
construct result;
if (from_construct == null) {
result = new name_construct(the_name, the_origin);
} else {
result = new resolve_construct(from_construct, the_name, the_origin);
}
return maybe_call(the_variable_action, result, the_origin);
} else if (primary instanceof data_value_action) {
base_procedure the_procedure = (base_procedure) ((data_value_action) primary).the_value;
action_name the_name = map_name(the_procedure.name());
if (the_name != special_name.IMPLICIT_CALL) {
if (from_construct == null) {
return new name_construct(the_name, the_origin);
} else {
return new resolve_construct(from_construct, the_name, the_origin);
}
} else {
return from_construct;
}
} else {
utilities.panic("processing dispatch action, primary " + primary);
return null;
}
}
private construct process_proc_as_ref_action(action from_action,
proc_as_ref_action the_proc_as_ref_action, origin the_origin) {
procedure_declaration the_procedure_declaration = the_proc_as_ref_action.the_declaration;
construct from_construct = transform_and_maybe_rewrite(from_action);
assert from_construct != null;
action_name the_name = map_name(the_procedure_declaration.short_name());
construct result = new resolve_construct(from_construct, the_name, the_origin);
return make_call(result, new empty<construct>(), the_origin);
}
private construct process_cast(cast_action the_cast_action, origin the_origin) {
return transform_cast(the_cast_action.expression, the_cast_action.the_type,
the_cast_action.the_cast_type, the_origin);
}
private construct process_is_operator(is_action the_is_action, origin the_origin) {
return transform_is(the_is_action.negated, the_is_action.expression, the_is_action.the_type,
the_origin);
}
private construct transform_is(boolean negated, action the_action, type the_type,
origin the_origin) {
construct expression = transform_action(the_action);
if (the_type.principal() == null_type()) {
return new operator_construct(negated ? operator.NOT_EQUAL_TO : operator.EQUAL_TO,
expression, make_null(the_origin), the_origin);
}
if (the_type.principal() == nonnegative_type()) {
// TODO: handle is_not
assert !negated;
return new operator_construct(operator.GREATER_EQUAL, expression, make_zero(the_origin),
the_origin);
}
principal_type type_principal = the_type.principal();
if (type_principal instanceof parametrized_type) {
master_type the_master = ((parametrized_type) type_principal).get_master();
the_type = the_master.get_flavored(the_type.get_flavor());
}
construct result = new operator_construct(operator.IS_OPERATOR, expression,
make_type_with_mapping(the_type, the_origin, mapping.MAP_TO_WRAPPER_TYPE), the_origin);
if (negated) {
return new operator_construct(operator.LOGICAL_NOT,
new list_construct(new base_list<construct>(result), grouping_type.PARENS, false,
the_origin),
the_origin);
} else {
return result;
}
}
private declaration get_procedure_declaration(action the_procedure_action) {
if (the_procedure_action instanceof data_value_action) {
base_data_value the_value =
(base_data_value) ((data_value_action) the_procedure_action).the_value;
return the_value.get_declaration();
} else if (the_procedure_action instanceof dispatch_action) {
return get_procedure_declaration(((dispatch_action) the_procedure_action).get_primary());
} else if (is_promotion_action(the_procedure_action)) {
return get_procedure_declaration(unwrap_promotion(the_procedure_action));
} else if (the_procedure_action instanceof variable_action) {
return ((variable_action) the_procedure_action).get_declaration();
} else if (the_procedure_action instanceof chain_action) {
chain_action the_chain_action = (chain_action) the_procedure_action;
if (the_chain_action.second instanceof dereference_action) {
return the_chain_action.first.get_declaration();
} else {
return the_chain_action.get_declaration();
}
} else if (the_procedure_action instanceof bound_procedure) {
return ((bound_procedure) the_procedure_action).get_declaration();
} else {
//System.out.println("get_procedure_declaration: " + the_procedure_action.getClass());
return null;
//utilities.panic("get_procedure_declaration failure: " + the_procedure_action);
}
}
private construct process_bound_procedure(bound_procedure the_bound_procedure,
origin the_origin) {
//System.out.println("\n===TBP: " + the_bound_procedure);
action the_procedure_action = the_bound_procedure.the_procedure_action;
construct main;
procedure_value the_procedure = null;
if (the_procedure_action instanceof data_value_action) {
base_data_value the_value =
(base_data_value) ((data_value_action) the_procedure_action).the_value;
assert the_value instanceof procedure_value;
the_procedure = (procedure_value) the_value;
action_name the_name = the_procedure.name();
if (the_name instanceof operator) {
operator the_operator = (operator) the_name;
return process_operator(the_bound_procedure, the_operator);
}
main = process_value_action((data_value_action) the_procedure_action);
} else {
main = process_action(the_procedure_action, the_origin);
}
readonly_list<construct> parameters =
transform_parameters(the_bound_procedure.parameters.parameters);
@Nullable declaration the_declaration = get_procedure_declaration(the_procedure_action);
if (the_declaration instanceof procedure_declaration) {
procedure_declaration proc_decl = (procedure_declaration) the_declaration;
if (proc_decl.get_category() != procedure_category.CONSTRUCTOR &&
proc_decl.annotations().has(implicit_modifier) &&
parameters.size() == 1) {
main = new resolve_construct(main, proc_decl.original_name(), the_origin);
} else if (proc_decl.short_name() == special_name.IMPLICIT_CALL) {
procedure_with_this the_procedure_with_this = (procedure_with_this) the_procedure;
assert the_procedure_with_this != null;
assert the_procedure_with_this.this_action != null;
main = process_action(the_procedure_with_this.this_action, the_origin);
}
}
// TODO: better way to detect procedure variables?
if (is_procedure_variable(declaration_util.get_declaration(the_procedure_action))) {
main = new resolve_construct(main, call_name, the_origin);
}
construct transformed = make_call(main, parameters, the_origin);
type procedure_return_type = the_procedure_action.result().type_bound();
if (is_procedure_type(procedure_return_type) &&
get_procedure_return(procedure_return_type) == unreachable_type()) {
assert the_enclosing_procedure != null;
type return_type = the_enclosing_procedure.get_return_type();
if (return_type != unreachable_type() &&
return_type != immutable_void_type()) {
list<construct> statements = new base_list<construct>();
statements.append(transformed);
boolean is_constructor =
the_enclosing_procedure.get_category() == procedure_category.CONSTRUCTOR;
statements.append(make_default_return(return_type, is_constructor, the_origin));
return new block_construct(statements, the_origin);
}
}
return transformed;
}
public construct process_enum_value(enum_value_analyzer the_enum_value) {
origin the_origin = the_enum_value;
name_construct the_name = new name_construct(the_enum_value.short_name(), the_origin);
if (the_enum_value.has_parameters()) {
grouping_type grouping = grouping_type.PARENS;
construct the_construct = get_construct(the_enum_value);
if (the_construct instanceof parameter_construct) {
grouping = ((parameter_construct) the_construct).grouping;
}
return new parameter_construct(the_name,
transform_parameters(the_enum_value.get_parameters().parameters), grouping, the_origin);
} else {
return the_name;
}
}
public construct process_grouping(grouping_analyzer the_grouping) {
origin the_origin = the_grouping;
return new list_construct(new base_list<construct>(
transform_analyzable(the_grouping.expression)),
grouping_type.PARENS, false, the_origin);
}
public construct process_while(while_analyzer the_while) {
origin the_origin = the_while;
return new while_construct(
transform_analyzable(the_while.condition),
transform_analyzable(the_while.body),
the_origin);
}
public construct process_for(for_analyzer the_for) {
origin the_origin = the_for;
return new for_construct(
transform_analyzable_or_null(the_for.init, the_origin),
transform_analyzable_or_null(the_for.condition, the_origin),
transform_analyzable_or_null(the_for.update, the_origin),
transform_analyzable_or_null(the_for.body, the_origin),
the_origin);
}
public construct process_supertype(supertype_declaration the_supertype) {
utilities.panic("Unexpected supertype_declaration");
return null;
}
}
| 41.397746 | 101 | 0.708909 |
54e27cfcafaddbe54d2f6250c3a324137fcb446b | 5,738 | package cn.tojintao.dao.impl;
import cn.tojintao.dao.UserDao;
import cn.tojintao.model.entity.Group;
import cn.tojintao.model.entity.User;
import cn.tojintao.util.DbUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
/**
* @author cjt
* @date 2021/6/19 16:48
*/
public class UserDaoImpl implements UserDao {
/**
* 头像路径前缀
*/
private static final String imgPath = "http://localhost:8080/MyChat/img/";
/**
* 连接数据库
*/
private Connection con;
private PreparedStatement stmt;
private ResultSet rs;
/**
* 登录
* @param user
* @return
*/
@Override
public User login(User user) {
try{
con= DbUtil.getConnection();
//寻找是否有与输入的用户名密码一致的用户
String sql="select * from user where user_name=? and password=?";
stmt = con.prepareStatement(sql);
stmt.setString(1, user.getUserName());
stmt.setString(2, user.getPassword());
rs = stmt.executeQuery();
//若返回结果集不为空,证明输入正确
if(rs.next()) {
//返回用户id
user.setUserId(rs.getInt("user_id"));
user.setAvatar(imgPath + rs.getString("avatar"));
return user;
}
else {
return null;
}
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally{
try{
DbUtil.close(rs,stmt, con);
} catch(SQLException e){
e.printStackTrace();
}
}
return null;
}
@Override
public User getUserById(Integer userId) {
try{
con= DbUtil.getConnection();
String sql="select * from user where user_id = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, userId);
rs = stmt.executeQuery();
//若返回结果集不为空,封装结果
if (rs.next()) {
//返回用户id
User user = new User();
user.setUserId(rs.getInt("user_id"));
user.setUserName(rs.getString("user_name"));
user.setAvatar(imgPath + rs.getString("avatar"));
return user;
}
else {
return null;
}
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally{
try{
DbUtil.close(rs,stmt, con);
} catch(SQLException e){
e.printStackTrace();
}
}
return null;
}
@Override
public User getUserByName(String userName) {
try{
con= DbUtil.getConnection();
String sql="select * from user where user_name = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, userName);
rs = stmt.executeQuery();
//若返回结果集不为空,证明输入正确
if(rs.next()) {
//返回用户id
User user = new User();
user.setUserId(rs.getInt("user_id"));
user.setUserName(rs.getString("user_name"));
user.setAvatar(imgPath + rs.getString("avatar"));
return user;
}
else {
return null;
}
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally{
try{
DbUtil.close(rs,stmt, con);
} catch(SQLException e){
e.printStackTrace();
}
}
return null;
}
/**
* 获取所有群聊
* @param userId
* @return
*/
@Override
public List<Group> getAllGroup(Integer userId) {
try{
con= DbUtil.getConnection();
String sql="select * from `group` where group_id in (select group_id from group_user where user_id=?)";
stmt = con.prepareStatement(sql);
stmt.setInt(1, userId);
rs = stmt.executeQuery();
List<Group> groupList = new LinkedList<>();
while(rs.next()) {
Group group = new Group();
group.setGroupId(rs.getInt("group_id"));
group.setGroupName(rs.getString("group_name"));
groupList.add(group);
}
return groupList;
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally{
try{
DbUtil.close(rs,stmt, con);
} catch(SQLException e){
e.printStackTrace();
}
}
return null;
}
/**
* 获取群聊中的所有用户id
* @param groupId
* @return
*/
@Override
public List<Integer> getGroupUser(Integer groupId) {
try{
con= DbUtil.getConnection();
String sql="select user_id from `group_user` where group_id=?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, groupId);
rs = stmt.executeQuery();
List<Integer> userIdList = new LinkedList<>();
while(rs.next()) {
Integer userId = rs.getInt("user_id");
userIdList.add(userId);
}
return userIdList;
}catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally{
try{
DbUtil.close(rs,stmt, con);
} catch(SQLException e){
e.printStackTrace();
}
}
return null;
}
}
| 28.69 | 115 | 0.501743 |
3025815de78158b1c3ce3a9ab35dd54cdc03da80 | 2,048 | package seedu.address.logic.commands;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandFailure;
import static seedu.address.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.address.logic.commands.CommandTestUtil.deleteFirstHealthWorker;
import static seedu.address.logic.commands.CommandTestUtil.deleteFirstRequest;
import static seedu.address.testutil.TypicalHealthWorkers.getTypicalHealthWorkerBook;
import static seedu.address.testutil.TypicalRequests.getTypicalRequestBook;
import org.junit.Before;
import org.junit.Test;
import seedu.address.logic.CommandHistory;
import seedu.address.model.Model;
import seedu.address.model.ModelManager;
import seedu.address.model.UserPrefs;
public class RedoCommandTest {
private final Model model = new ModelManager(getTypicalHealthWorkerBook(),
getTypicalRequestBook(), new UserPrefs());
private final Model expectedModel = new ModelManager(getTypicalHealthWorkerBook(),
getTypicalRequestBook(), new UserPrefs());
private final CommandHistory commandHistory = new CommandHistory();
@Before
public void setUp() {
// set up of both models' undo/redo history
deleteFirstHealthWorker(model);
deleteFirstRequest(model);
model.undo();
model.undo();
deleteFirstHealthWorker(expectedModel);
deleteFirstRequest(expectedModel);
expectedModel.undo();
expectedModel.undo();
}
@Test
public void execute() {
// multiple redoable states in model
expectedModel.redo();
assertCommandSuccess(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_SUCCESS, expectedModel);
// single redoable state in model
expectedModel.redo();
assertCommandSuccess(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_SUCCESS, expectedModel);
// no redoable state in model
assertCommandFailure(new RedoCommand(), model, commandHistory, RedoCommand.MESSAGE_FAILURE);
}
}
| 37.925926 | 115 | 0.750977 |
af6349ae8c21db56f38f979e788c39155683d462 | 4,287 | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.diff.evaluators;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.smithy.diff.ModelDiff;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StringShape;
import software.amazon.smithy.model.traits.DynamicTrait;
import software.amazon.smithy.model.traits.TraitDefinition;
import software.amazon.smithy.model.validation.ValidationEvent;
public class ModifiedTraitTest {
private static final String NAME = "com.foo#baz";
private static final class TestCaseData {
private Shape oldShape;
private Shape newShape;
public TestCaseData(String oldValue, String newValue) {
StringShape.Builder builder1 = StringShape.builder().id("com.foo#String");
if (oldValue != null) {
builder1.addTrait(new DynamicTrait(NAME, Node.from(oldValue)));
}
oldShape = builder1.build();
StringShape.Builder builder2 = StringShape.builder().id("com.foo#String");
if (newValue != null) {
builder2.addTrait(new DynamicTrait(NAME, Node.from(newValue)));
}
newShape = builder2.build();
}
}
@ParameterizedTest
@MethodSource("data")
public void testConst(String oldValue, String newValue, String tag, String searchString) {
TestCaseData data = new TestCaseData(oldValue, newValue);
TraitDefinition definition = createDefinition(ModifiedTrait.DIFF_ERROR_CONST);
Model modelA = Model.assembler().addTraitDefinition(definition).addShape(data.oldShape).assemble().unwrap();
Model modelB = Model.assembler().addTraitDefinition(definition).addShape(data.newShape).assemble().unwrap();
List<ValidationEvent> events = ModelDiff.compare(modelA, modelB);
assertThat(TestHelper.findEvents(events, "ModifiedTrait").size(), equalTo(1));
}
@ParameterizedTest
@MethodSource("data")
public void testWithTag(String oldValue, String newValue, String tag, String searchString) {
TestCaseData data = new TestCaseData(oldValue, newValue);
TraitDefinition definition = createDefinition(tag);
Model modelA = Model.assembler().addTraitDefinition(definition).addShape(data.oldShape).assemble().unwrap();
Model modelB = Model.assembler().addTraitDefinition(definition).addShape(data.newShape).assemble().unwrap();
List<ValidationEvent> events = ModelDiff.compare(modelA, modelB);
assertThat(TestHelper.findEvents(events, "ModifiedTrait").size(), equalTo(1));
assertThat(events.get(0).getMessage(), containsString(searchString));
}
public static Collection<String[]> data() {
return Arrays.asList(new String[][] {
{null, "hi", ModifiedTrait.DIFF_ERROR_ADD, "to add"},
{"hi", null, ModifiedTrait.DIFF_ERROR_REMOVE, "to remove"},
{"foo", "baz", ModifiedTrait.DIFF_ERROR_UPDATE, "to change"},
});
}
private static TraitDefinition createDefinition(String tag) {
return TraitDefinition.builder()
.name(NAME)
.addTag(tag)
.shape(ShapeId.from("smithy.api#String"))
.build();
}
}
| 42.445545 | 116 | 0.700257 |
de3f884598fc4428ca7013c7ebd5582dce7f727f | 3,325 | package io.github.aload0.spring.dva;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;
public class DvaProxy<T> implements FactoryBean {
private final Class<T> proxyInterface;
private final Context context;
private volatile Object proxyObject;
public DvaProxy(Class<T> proxyInterface, Context context) {
this.proxyInterface = proxyInterface;
this.context = context;
}
@Override
public synchronized Object getObject() throws Exception {
if (proxyObject == null) {
final Map<String, MethodAccessor> accessors = createMethodAccessors();
proxyObject = Proxy.newProxyInstance(context.getEnvironment().getClass().getClassLoader(),
new Class[]{proxyInterface}, (proxy, method, args) -> {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
}
String name = method.getName();
if (accessors.containsKey(name)) {
return accessors.get(name).get();
}
throw new RuntimeException("Cannot handle method " + name);
});
}
return proxyObject;
}
@Override
public Class<T> getObjectType() {
return proxyInterface;
}
@Override
public boolean isSingleton() {
return true;
}
private ObjectReader getObjectReader() {
String name = context.getObjectReaderName();
if (StringUtils.isEmpty(name)) {
return null;
}
return context.getBeanFactory().getBean(name, ObjectReader.class);
}
private PropertyReader getPropertyReader() {
String name = context.getPropertyReaderName();
if (StringUtils.isEmpty(name)) {
return new DefaultPropertyReader(context.getEnvironment());
}
return context.getBeanFactory().getBean(name, PropertyReader.class);
}
private Map<String, MethodAccessor> createMethodAccessors() {
final ObjectReader objectReader = getObjectReader();
final PropertyReader propertyReader = getPropertyReader();
String header = context.getHeader();
String scope = context.getNameConvention().classScope(proxyInterface);
final String prefix = header + "." + scope + ".";
MethodAccessorFactory.Context ctx = new MethodAccessorFactory.Context() {
@Override
public Class<?> clazz() {
return proxyInterface;
}
@Override
public String prefix() {
return prefix;
}
@Override
public PropertyReader propertyReader() {
return propertyReader;
}
@Override
public NameConvention nameConvention() {
return context.getNameConvention();
}
@Override
public ObjectReader objectReader() {
return objectReader;
}
};
MethodAccessorFactory factory = context.getMethodAccessorFactory();
Map<String, MethodAccessor> result = new HashMap<>();
for (Method method : proxyInterface.getMethods()) {
String name = method.getName();
if (result.containsKey(name)) {
throw new IllegalArgumentException("Method overwrite not allowed");
}
result.put(name, factory.getMethodAccessor(method, ctx));
}
return result;
}
}
| 29.6875 | 96 | 0.673083 |
8141607b3dccc33403f990e6c88bc4239133ec54 | 16,975 | /*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.stargate.sdk.rest;
import static com.datastax.stargate.sdk.core.ApiSupport.getHttpClient;
import static com.datastax.stargate.sdk.core.ApiSupport.getObjectMapper;
import static com.datastax.stargate.sdk.core.ApiSupport.handleError;
import static com.datastax.stargate.sdk.core.ApiSupport.startRequest;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.datastax.stargate.sdk.core.ApiResponse;
import com.datastax.stargate.sdk.core.ResultPage;
import com.datastax.stargate.sdk.rest.domain.ColumnDefinition;
import com.datastax.stargate.sdk.rest.domain.CreateIndex;
import com.datastax.stargate.sdk.rest.domain.CreateTable;
import com.datastax.stargate.sdk.rest.domain.IndexDefinition;
import com.datastax.stargate.sdk.rest.domain.Row;
import com.datastax.stargate.sdk.rest.domain.RowMapper;
import com.datastax.stargate.sdk.rest.domain.RowResultPage;
import com.datastax.stargate.sdk.rest.domain.SearchTableQuery;
import com.datastax.stargate.sdk.rest.domain.SortField;
import com.datastax.stargate.sdk.rest.domain.TableDefinition;
import com.datastax.stargate.sdk.rest.domain.TableOptions;
import com.datastax.stargate.sdk.rest.exception.TableNotFoundException;
import com.datastax.stargate.sdk.utils.Assert;
import com.datastax.stargate.sdk.utils.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
/**
* Operate on Tables in Cassandra.
*
* @author Cedrick LUNVEN (@clunven)
*/
public class TableClient {
/** Astra Client. */
private final ApiRestClient restClient;
/** Namespace. */
private final KeyspaceClient keyspaceClient;
/** Collection name. */
private final String tableName;
/** Hold a reference to client to keep singletons.*/
private Map <String, ColumnsClient> columnsClient = new HashMap<>();
/** Hold a reference to client to keep singletons.*/
private Map <String, IndexClient> indexsClient = new HashMap<>();
/**
* Full constructor.
*
* @param restClient ApiRestClient
* @param keyspaceClient KeyspaceClient
* @param tableName String
*/
public TableClient(ApiRestClient restClient, KeyspaceClient keyspaceClient, String tableName) {
this.restClient = restClient;
this.keyspaceClient = keyspaceClient;
this.tableName = tableName;
}
// ==============================================================
// ========================= SCHEMA TABLE =====================
// ==============================================================
/**
* Syntax sugar
*
* @return String
*/
public String getEndPointTableSchema() {
return keyspaceClient.getEndPointSchemaKeyspace() + "/tables/" + tableName;
}
/**
* Getter accessor for attribute 'tableName'.
*
* @return current value of 'tableName'
*/
public String getTableName() {
return tableName;
}
/**
* Get metadata of the collection. There is no dedicated resources we
* use the list and filter with what we need.
*
* @return metadata of the collection if its exist or empty
*/
public Optional<TableDefinition> find() {
return keyspaceClient.tables()
.filter(t -> tableName.equalsIgnoreCase(t.getName()))
.findFirst();
}
/**
* Check if the table exist.
*
* @return boolean
*/
public boolean exist() {
return keyspaceClient.tableNames()
.anyMatch(tableName::equals);
}
/**
* Create a table
* https://docs.datastax.com/en/astra/docs/_attachments/restv2.html#operation/createTable
*
* @param tcr creation request
*/
public void create(CreateTable tcr) {
Assert.notNull(tcr, "TableCreationRequest");
tcr.setName(this.tableName);
HttpResponse<String> response;
try {
String reqBody = getObjectMapper().writeValueAsString(tcr);
response = getHttpClient().send(
startRequest(keyspaceClient.getEndPointSchemaKeyspace() + "/tables/", restClient.getToken())
.POST(BodyPublishers.ofString(reqBody)).build(),
BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot save document:", e);
}
handleError(response);
}
/**
* updateOptions
*
* @param to TableOptions
*/
public void updateOptions(TableOptions to) {
Assert.notNull(to, "TableCreationRequest");
HttpResponse<String> response;
try {
CreateTable ct = CreateTable.builder().build();
ct.setPrimaryKey(null);
ct.setColumnDefinitions(null);
ct.setName(tableName);
ct.setTableOptions(to);
String reqBody = getObjectMapper().writeValueAsString(ct);
response = getHttpClient().send(
startRequest(getEndPointTableSchema() , restClient.getToken())
.PUT(BodyPublishers.ofString(reqBody)).build(),
BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot save document:", e);
}
handleError(response);
}
/*
* Delete a table
* https://docs.astra.datastax.com/reference#delete_api-rest-v2-schemas-keyspaces-keyspace-id-tables-table-id-1
*/
public void delete() {
HttpResponse<String> response;
try {
response = getHttpClient().send(
startRequest(getEndPointTableSchema(),
restClient.getToken()).DELETE().build(),
BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot delete table " + tableName, e);
}
if (HttpURLConnection.HTTP_NOT_FOUND == response.statusCode()) {
throw new TableNotFoundException(tableName);
}
handleError(response);
}
// ==============================================================
// ========================= SCHEMA COLUMNS =====================
// ==============================================================
/**
* Retrieve All columns.
*
* @return
* Sream of {@link ColumnDefinition} to describe a table
*/
public Stream<ColumnDefinition> columns() {
HttpResponse<String> response;
try {
// Invoke
response = getHttpClient().send(
startRequest(getEndPointTableSchema() + "/columns", restClient.getToken())
.GET().build(), BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot retrieve table list", e);
}
handleError(response);
try {
TypeReference<ApiResponse<List<ColumnDefinition>>> expectedType = new TypeReference<>(){};
return getObjectMapper().readValue(response.body(), expectedType)
.getData().stream()
.collect(Collectors.toSet()).stream();
} catch (Exception e) {
throw new RuntimeException("Cannot marshall collection list", e);
}
}
/**
* Retrieve All column names.
*
* @return
* a list of columns names;
*/
public Stream<String> columnNames() {
return columns().map(ColumnDefinition::getName);
}
/**
* createColumn
*
* @param colName String
* @param cd ColumnDefinition
*/
public void createColumn(String colName, ColumnDefinition cd) {
column(colName).create(cd);
}
/**
* Move to columns client
*
* @param columnId String
* @return ColumnsClient
*/
public ColumnsClient column(String columnId) {
Assert.hasLength(columnId, "columnName");
if (!columnsClient.containsKey(columnId)) {
columnsClient.put(columnId,
new ColumnsClient(restClient, keyspaceClient, this, columnId));
}
return columnsClient.get(columnId);
}
// ==============================================================
// ========================= SCHEMA INDEX =====================
// ==============================================================
/**
* Move to columns client
*
* @param indexName String
* @return IndexClient
*/
public IndexClient index(String indexName) {
Assert.hasLength(indexName, "indexName");
if (!indexsClient.containsKey(indexName)) {
indexsClient.put(indexName,
new IndexClient(restClient, keyspaceClient, this, indexName));
}
return indexsClient.get(indexName);
}
/**
* createIndex
*
* @param idxName String
* @param ci CreateIndex
*/
public void createIndex(String idxName, CreateIndex ci) {
index(idxName).create(ci);
}
/**
* Retrieve All indexes for a table.
*
* @return
* Stream of {@link IndexDefinition} to describe a table
*/
public Stream<IndexDefinition> indexes() {
HttpResponse<String> response;
try {
// Invoke
response = getHttpClient().send(
startRequest(getEndPointTableSchema() + "/indexes", restClient.getToken())
.GET().build(), BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot retrieve indexes list for a table", e);
}
handleError(response);
try {
TypeReference<List<IndexDefinition>> expectedType = new TypeReference<>(){};
return getObjectMapper().readValue(response.body(), expectedType)
.stream()
.collect(Collectors.toSet()).stream();
} catch (Exception e) {
throw new RuntimeException("Cannot marshall collection list", e);
}
}
/**
* Retrieve All column names.
*
* @return
* a list of columns names;
*/
public Stream<String> indexesNames() {
return indexes().map(IndexDefinition::getIndex_name);
}
// ==============================================================
// ========================= DATA ===============================
// ==============================================================
/**
* Syntax sugar
*
* @return String
*/
public String getEndPointTable() {
return restClient.getEndPointApiRest()
+ "/v2/keyspaces/" + keyspaceClient.getKeyspace()
+ "/" + tableName;
}
/**
* TODO: Can do better with a bean - SERIALIZATIO + look at target column type
*
* @param record Map
*/
public void upsert(Map<String, Object> record) {
Assert.notNull(record, "New Record");
Assert.isTrue(!record.isEmpty(), "New record should not be empty");
HttpResponse<String> response;
try {
String reqBody = getObjectMapper().writeValueAsString(record);
response = getHttpClient().send(
startRequest(getEndPointTable(), restClient.getToken())
.POST(BodyPublishers.ofString(reqBody)).build(),
BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot save document:", e);
}
handleError(response);
}
/**
* search
*
* @param query SearchTableQuery
* @return RowResultPage
*/
public RowResultPage search(SearchTableQuery query) {
HttpResponse<String> response;
try {
// Invoke as JSON
response = getHttpClient().send(startRequest(
buildQueryUrl(query), restClient.getToken()).GET().build(),
BodyHandlers.ofString());
} catch (Exception e) {
throw new RuntimeException("Cannot search for documents ", e);
}
handleError(response);
try {
ApiResponse<List<LinkedHashMap<String,?>>> result = getObjectMapper()
.readValue(response.body(),
new TypeReference<ApiResponse<List<LinkedHashMap<String,?>>>>(){});
return new RowResultPage(query.getPageSize(), result.getPageState(), result.getData()
.stream()
.map(map -> {
Row r = new Row();
for (Entry<String, ?> val: map.entrySet()) {
r.put(val.getKey(), val.getValue());
}
return r;
})
.collect(Collectors.toList()));
} catch (Exception e) {
throw new RuntimeException("Cannot marshall document results", e);
}
}
/**
* Retrieve a set of Rows from Primary key value.
*
* @param <T> ResultPage
* @param query SearchTableQuery
* @param mapper RowMapper
* @return ResultPage
*/
public <T> ResultPage<T> search(SearchTableQuery query, RowMapper<T> mapper) {
RowResultPage rrp = search(query);
return new ResultPage<T>(
rrp.getPageSize(),
rrp.getPageState().orElse(null),
rrp.getResults().stream()
.map(mapper::map)
.collect(Collectors.toList()));
}
/**
* buildQueryUrl
*
* @param query SearchTableQuery
* @return String
*/
private String buildQueryUrl(SearchTableQuery query) {
try {
StringBuilder sbUrl = new StringBuilder(getEndPointTable());
// Add query Params
sbUrl.append("?page-size=" + query.getPageSize());
// Depending on query you forge your URL
if (query.getPageState().isPresent()) {
sbUrl.append("&page-state=" +
URLEncoder.encode(query.getPageState().get(), StandardCharsets.UTF_8.toString()));
}
if (query.getWhere().isPresent()) {
sbUrl.append("&where=" +
URLEncoder.encode(query.getWhere().get(), StandardCharsets.UTF_8.toString()));
}
// Fields to retrieve
if (null != query.getFieldsToRetrieve() && !query.getFieldsToRetrieve().isEmpty()) {
sbUrl.append("&fields=" +
URLEncoder.encode(
String.join(",", query.getFieldsToRetrieve()), StandardCharsets.UTF_8.toString()));
}
// Fields to sort on
if (null != query.getFieldsToSort() && !query.getFieldsToSort().isEmpty()) {
Map<String, String> sortFields = new LinkedHashMap<>();
for (SortField sf : query.getFieldsToSort()) {
sortFields.put(sf.getFieldName(), sf.getOrder().name());
}
sbUrl.append("&sort=" + URLEncoder.encode(JsonUtils.mapAsJson(sortFields), StandardCharsets.UTF_8.toString()));
}
return sbUrl.toString();
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Cannot enode URL", e);
}
}
/**
* Move to the Table client
*
* @param keys Object
* @return KeyClient
*/
public KeyClient key(Object... keys) {
Assert.notNull(keys, "key");
return new KeyClient(restClient.getToken(), this, keys);
}
}
| 35.217842 | 127 | 0.562651 |
6af3c55ff4bf6ae0e4d3f6bfa0520ae756df08f1 | 1,577 | package com.walnuthillseagles.walnutlibrary;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
/**
* Created by Yan Vologzhanin on 1/2/2016.
*/
public class TimedMotor extends LinearMotor implements Runnable, Auto {
public static final int MSECSINSEC = 1000;
public static final int NSECSINSEC = 1000000;
private int numMSecs;
private Thread runner;
public TimedMotor(DcMotor myMotor, String name,boolean encoderCheck, boolean isReversed){
super(myMotor, name, encoderCheck,isReversed);
numMSecs = 0;
}
//Seconds precise up to three decimal places
//@ENSURE(Seconds > 0)
public void operate(double seconds, double mySpeedLimit){
numMSecs = (int) (seconds*MSECSINSEC);
speedLimit = mySpeedLimit * orientation;
//Start parrallel Process
runner = new Thread(this);
runner.start();
}
public void operate(double seconds){
if(seconds < 0)
this.operate(seconds,-1);
else
this.operate(seconds, 1);
}
public void run(){
this.setPower(speedLimit);
try{
synchronized (this){
this.wait(numMSecs);
}
}
catch(InterruptedException e){
Thread.currentThread().interrupt();
}
finally {
fullStop();
}
}
public void waitForCompletion() throws InterruptedException{
runner.join();
}
}
| 27.666667 | 94 | 0.603044 |
90c8fd8219f74895d0e16df0b9d4ae771f4f9057 | 883 | package com.example.run.room;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.DatabaseConfiguration;
import androidx.room.InvalidationTracker;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteOpenHelper;
@Database( entities = {Address.class},version = 1,exportSchema = false)
public abstract class AddressDataBase extends RoomDatabase {
private static AddressDataBase addressDataBase;
public static AddressDataBase getInstance(Context context){
if(addressDataBase == null){
addressDataBase = Room.databaseBuilder(context.getApplicationContext(),AddressDataBase.class,"address")
.build();
}
return addressDataBase;
}
abstract AddressDao getAddressDao();
}
| 32.703704 | 116 | 0.734994 |
45b2fd150a9ba623adb21e4d0bad04cceeecb98a | 1,398 | interface Graphic {
void accept(Visitor v);
}
interface Visitor {
void visitShape(Shape shape);
void visitDot(Dot dot);
void visitRectangle(Rectangle rectangle);
void visitCircle(Circle circle);
}
final class ConcreteVisitor implements Visitor {
@Override
public void visitShape(Shape shape) {
System.out.println("Shape visited");
}
@Override
public void visitDot(Dot dot) {
System.out.println("Dot visited");
}
@Override
public void visitRectangle(Rectangle rectangle) {
System.out.println("Rectangle visited");
}
@Override
public void visitCircle(Circle circle) {
System.out.println("Circle visited");
}
}
class Shape implements Graphic {
@Override
public void accept(Visitor v) {
v.visitShape(this);
}
}
class Dot extends Shape {
@Override
public void accept(Visitor v) {
v.visitDot(this);
}
}
class Rectangle extends Dot {
@Override
public void accept(Visitor v) {
v.visitRectangle(this);
}
}
final class Circle extends Shape {
@Override
public void accept(Visitor v) {
v.visitCircle(this);
}
}
public final class GeometricShapes {
public static void main(String[] args) {
Visitor visitor = new ConcreteVisitor();
Graphic[] graphics = new Graphic[4];
graphics[0] = new Shape();
graphics[1] = new Dot();
graphics[2] = new Rectangle();
graphics[3] = new Circle();
for (Graphic g : graphics) g.accept(visitor);
}
} | 16.642857 | 50 | 0.705293 |
f439afec60b09c47576c911c83bd4dc2d739171d | 1,000 | import com.jaunt.*;
import com.jaunt.component.*;
public class Example19{
public static void main(String[] args){
try{
UserAgent userAgent = new UserAgent();
String url = "http://northernbushcraft.com";
userAgent.setCacheEnabled(true); //caching turned on
userAgent.visit(url); //cache empty, so HTML page requested via http & saved in cache.
userAgent.visit(url); //when revisiting, page pulled from filesystem cache - no http request.
System.out.println(userAgent.response); //response object shows that content was cached, note no response headers
userAgent.setCacheEnabled(false); //caching turned off
userAgent.visit(url); //page is once again retrieved via http request.
System.out.println(userAgent.response); //print response object, which now shows response headers
}
catch(JauntException e){
System.err.println(e);
}
}
}
| 41.666667 | 120 | 0.647 |
7fd0318c4c42a70108f692e2231b13c3d554f927 | 746 | package io.github.hapjava.characteristics.impl.common;
import io.github.hapjava.characteristics.CharacteristicEnum;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
/** 0 ”Inactive” 1 ”Active” 2-255 ”Reserved” */
public enum ActiveEnum implements CharacteristicEnum {
INACTIVE(0),
ACTIVE(1);
private static final Map<Integer, ActiveEnum> reverse;
static {
reverse =
Arrays.stream(ActiveEnum.values()).collect(Collectors.toMap(ActiveEnum::getCode, t -> t));
}
public static ActiveEnum fromCode(Integer code) {
return reverse.get(code);
}
private final int code;
ActiveEnum(int code) {
this.code = code;
}
@Override
public int getCode() {
return code;
}
}
| 21.314286 | 98 | 0.710456 |
7728a32fb307f8236820b73737a17f1a7ac26370 | 2,066 | private void updateViewerContent(ScrollingGraphicalViewer viewer) {
BioPAXGraph graph = (BioPAXGraph) viewer.getContents().getModel();
if (!graph.isMechanistic()) return;
Map<String, Color> highlightMap = new HashMap<String, Color>();
for (Object o : graph.getNodes()) {
IBioPAXNode node = (IBioPAXNode) o;
if (node.isHighlighted()) {
highlightMap.put(node.getIDHash(), node.getHighlightColor());
}
}
for (Object o : graph.getEdges()) {
IBioPAXEdge edge = (IBioPAXEdge) o;
if (edge.isHighlighted()) {
highlightMap.put(edge.getIDHash(), edge.getHighlightColor());
}
}
HighlightLayer hLayer = (HighlightLayer) ((ChsScalableRootEditPart) viewer.getRootEditPart()).getLayer(HighlightLayer.HIGHLIGHT_LAYER);
hLayer.removeAll();
hLayer.highlighted.clear();
viewer.deselectAll();
graph.recordLayout();
PathwayHolder p = graph.getPathway();
if (withContent != null) {
p.updateContentWith(withContent);
}
BioPAXGraph newGraph = main.getRootGraph().excise(p);
newGraph.setAsRoot();
viewer.setContents(newGraph);
boolean layedout = newGraph.fetchLayout();
if (!layedout) {
new CoSELayoutAction(main).run();
}
viewer.deselectAll();
GraphAnimation.run(viewer);
for (Object o : newGraph.getNodes()) {
IBioPAXNode node = (IBioPAXNode) o;
if (highlightMap.containsKey(node.getIDHash())) {
node.setHighlightColor(highlightMap.get(node.getIDHash()));
node.setHighlight(true);
}
}
for (Object o : newGraph.getEdges()) {
IBioPAXEdge edge = (IBioPAXEdge) o;
if (highlightMap.containsKey(edge.getIDHash())) {
edge.setHighlightColor(highlightMap.get(edge.getIDHash()));
edge.setHighlight(true);
}
}
}
| 41.32 | 143 | 0.578896 |
2172d447036d8e528f854429fed09611b94c656f | 1,305 | /*
* Copyright 2014-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.rest.tests.mongodb;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.springframework.util.Assert;
/**
* Test helper methods.
*
* @author Oliver Gierke
* @author Christoph Strobl
*/
public class TestUtils {
private static final Charset UTF8 = Charset.forName("UTF-8");
/**
* Returns the given {@link String} as {@link InputStream}.
*
* @param source must not be {@literal null}.
* @return
*/
public static InputStream asStream(String source) {
Assert.notNull(source, "Source string must not be null!");
return new ByteArrayInputStream(source.getBytes(UTF8));
}
}
| 29 | 75 | 0.733333 |
1069f6fc244bff42dd61ac2d25d3b4bdb3496c76 | 684 | package work.icql.java.designpattern.structural.adapter;
import work.icql.java.designpattern.structural.adapter.adaptee.Adaptee1;
import work.icql.java.designpattern.structural.adapter.adaptee.Adaptee2;
import work.icql.java.designpattern.structural.adapter.clazz.ClazzAdaptor;
import work.icql.java.designpattern.structural.adapter.object.ObjectAdaptor;
public class AdapterClient {
public static void main(String[] args) {
ITarget target1 = new ClazzAdaptor();
target1.operationA();
target1.operationB();
ITarget target2 = new ObjectAdaptor(new Adaptee1(), new Adaptee2());
target2.operationA();
target2.operationB();
}
}
| 34.2 | 76 | 0.745614 |
587b973ba30abb42dde6919697214282743151af | 2,409 | /*
* #%L
* omakase-task
* %%
* Copyright (C) 2015 Project Omakase LLC
* %%
* 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%
*/
package org.projectomakase.omakase.task.providers.hash;
import org.projectomakase.omakase.commons.hash.Hash;
import org.assertj.core.groups.Tuple;
import org.junit.Test;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Richard Lucas
*/
public class HashTaskOutputTest {
@Test
public void shouldBuildOutputFromJson() {
String json = "{\"hashes\":[{\"hash_algorithm\":\"MD5\",\"hash\":\"123\"}]}";
HashTaskOutput output = new HashTaskOutput();
output.fromJson(json);
assertThat(output.getHashes()).extracting(Hash::getAlgorithm, Hash::getValue).containsExactly(new Tuple("MD5", "123"));
}
@Test
public void shouldBuildOutputFromJsonWithOffsetAndLength() {
String json = "{\"hashes\":[{\"hash_algorithm\":\"MD5\",\"offset\":100,\"length\":500,\"hash\":\"123\"}]}";
HashTaskOutput output = new HashTaskOutput();
output.fromJson(json);
assertThat(output.getHashes()).hasSize(1);
Hash hash = output.getHashes().get(0);
assertThat(hash).isEqualToComparingFieldByField(new Hash("MD5", "123", 100, 500));
}
@Test
public void shouldSerializeToJson() {
String expected = "{\"hashes\":[{\"hash_algorithm\":\"MD5\",\"hash\":\"123\"}]}";
assertThat(new HashTaskOutput(Collections.singletonList(new Hash("MD5", "123"))).toJson()).isEqualTo(expected);
}
@Test
public void shouldSerializeToJsonWithOffsetAndLength() {
String expected = "{\"hashes\":[{\"hash_algorithm\":\"MD5\",\"offset\":50,\"length\":100,\"hash\":\"123\"}]}";
assertThat(new HashTaskOutput(Collections.singletonList(new Hash("MD5", "123", 50, 100))).toJson()).isEqualTo(expected);
}
} | 37.061538 | 128 | 0.670818 |
6278d9c628019bf1810a63b3537f2c61f092fb05 | 1,455 | package dev.controller.vm;
import dev.domain.Product;
public class ProductVM {
private String name;
private String photo;
private String description;
private double price;
private String category;
private boolean state;
private int quantity;
public ProductVM(final Product product) {
name = product.getName();
photo = product.getPhoto();
description = product.getDescription();
price = product.getPrice();
category = product.getCategory();
state = product.isState();
quantity = product.getQuantity();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
| 18.1875 | 50 | 0.668729 |
011a13cb362a1c7aecb3510a712446b76c323c36 | 675 | package cn.stylefeng.guns.job;
import cn.stylefeng.guns.modular.game.warpper.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
/**
* Created by ccanrom7
* CreateDate on 2019/4/12 17:30.
* Email [email protected]
**/
@Component
public class GetDataJob {
@Autowired
private HttpClientUtil httpClientUtil;
/**
* 1秒一次
*
* @throws Exception
*/
@Scheduled(cron = "0/1 * * * * ? ")
public void updataDevicesStatus() {
httpClientUtil.toGetCanada28Data();
}
}
| 22.5 | 62 | 0.706667 |
c0a4b9a29812ffedfe11d86df5bfc043c1b1efda | 2,057 | package io.kodlama.hrms.api.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.kodlama.hrms.business.abstracts.ExperienceService;
import io.kodlama.hrms.core.utilities.results.DataResult;
import io.kodlama.hrms.core.utilities.results.Result;
import io.kodlama.hrms.entities.concretes.Experience;
@RestController
@RequestMapping("/api/experiences")
@CrossOrigin
public class ExperiencesController {
private ExperienceService experienceService;
@Autowired
public ExperiencesController(ExperienceService experienceService) {
this.experienceService = experienceService;
}
@PostMapping("/add")
public Result add(@RequestBody Experience experience) {
return experienceService.add(experience);
}
@PutMapping("/update")
public Result update(@RequestBody Experience experience) {
return experienceService.update(experience);
}
@DeleteMapping("/delete")
public Result delete(@RequestParam int id) {
return experienceService.delete(id);
}
@GetMapping("/getAll")
public DataResult<List<Experience>> getAll() {
return experienceService.getAll();
}
@GetMapping("/getById")
public DataResult<Experience> getById(@RequestParam int id) {
return experienceService.getById(id);
}
@GetMapping("/getAllByResumeIdSortedByTerminationDate")
public DataResult<List<Experience>> getAllByResumeIdSortedByTerminationDate(@RequestParam int resumeId) {
return experienceService.getAllByResumeIdSortedByTerminationDate(resumeId);
}
}
| 32.140625 | 106 | 0.819154 |
004e0ee4417cd5d31b3bc9e4998d53420c2cba99 | 7,158 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.stream.IntStream;
/**
* @class OneShotExecutorService
*
* @brief Customizes the SearchTaskGangCommon framework to process a
* one-shot List of tasks via a fixed-size pool of Threads
* created by the ExecutorService, which is also used as a
* barrier synchronizer to wait for all the Threads in the pool
* to shutdown. The unit of concurrency is invokeAll(), which
* creates a task for each input string. The results
* processing model uses a LinkedBlockingQueue that stores
* results for immediate concurrent processing per cycle.
*/
public class OneShotExecutorService
extends SearchTaskGangCommon {
/**
* Controls when the framework exits.
*/
protected CountDownLatch mExitBarrier = null;
/**
* Queue to store SearchResults of concurrent computations.
*/
private BlockingQueue<SearchResults> mResultsQueue =
new LinkedBlockingQueue<SearchResults>();
/**
* Number of Threads in the pool.
*/
protected final int MAX_THREADS = 4;
/**
* Constructor initializes the superclass.
*/
public OneShotExecutorService(String[] wordsToFind,
String[][] stringsToSearch) {
// Pass input to superclass constructor.
super(wordsToFind,
stringsToSearch);
}
/**
* Hook method that initiates the gang of Threads by using a
* fixed-size Thread pool managed by the ExecutorService.
*/
@Override
protected void initiateHook(int inputSize) {
System.out.println("@@@ starting cycle "
+ currentCycle()
+ " with "
+ inputSize
+ " tasks@@@");
// Initialize the exit barrier to inputSize, which causes
// awaitTasksDone() to block until the cycle is finished.
mExitBarrier = new CountDownLatch(inputSize);
// Create a fixed-size Thread pool.
if (getExecutor() == null)
setExecutor (Executors.newFixedThreadPool(MAX_THREADS));
}
/**
* Initiate the TaskGang to run each worker in the Thread pool.
*/
protected void initiateTaskGang(int inputSize) {
// Allow subclasses to customize their behavior before the
// Threads in the gang are spawned.
initiateHook(inputSize);
// Create a new collection that will contain all the
// Worker Runnables.
List<Callable<Object>> workerCollection =
new ArrayList<>(inputSize);
// Create a Runnable for each item in the input List and add
// it as a Callable adapter into the collection.
IntStream.range(1, inputSize)
.forEach(i -> workerCollection.add(Executors.callable(makeTask(i))));
try {
// Downcast to get the ExecutorService.
ExecutorService executorService =
(ExecutorService) getExecutor();
// Use invokeAll() to execute all items in the collection
// via the Executor's Thread pool.
executorService.invokeAll(workerCollection);
} catch (InterruptedException e) {
System.out.println("invokeAll() interrupted");
}
}
/**
* Runs as a background task and searches inputData for all
* occurrences of the words to find.
*/
@Override
protected boolean processInput (String inputData) {
// Iterate through each word we're searching for and try to
// find it in the inputData. Each time a match is found the
// queueResults() method is called to pass the search results
// to a background Thread for concurrent processing.
Arrays.stream(mWordsToFind).forEach
(word -> queueResults(searchForWord(word,
inputData)));
return true;
}
/**
* Hook method called when a worker task is done.
*/
@Override
protected void taskDone(int index) throws IndexOutOfBoundsException {
// Decrements the CountDownLatch, which releases the main
// Thread when count drops to 0.
mExitBarrier.countDown();
}
/**
* Used by processInput() to queue results for processing in a
* background Thread.
*/
protected void queueResults(SearchResults results) {
getQueue().add(results);
}
/**
* Hook method that shuts down the ExecutorService's Thread pool
* and waits for all the tasks to exit before returning.
*/
@Override
protected void awaitTasksDone() {
do {
// Start processing this cycle of results concurrently in
// a background Thread.
processQueuedResults(getInput().size()
* mWordsToFind.length);
try {
// Wait until the exit barrier has been tripped.
mExitBarrier.await();
} catch (InterruptedException e) {
System.out.println("await() interrupted");
}
// Keep looping as long as there's another cycle's
// worth of input.
} while (advanceTaskToNextCycle());
// Call up to the super class to await for ExecutorService's
// Threads to shutdown.
super.awaitTasksDone();
}
/**
* Set the BlockingQueue and return the existing queue.
*/
protected BlockingQueue<SearchResults> setQueue(BlockingQueue<SearchResults> q) {
BlockingQueue<SearchResults> old = mResultsQueue;
mResultsQueue = q;
return old;
}
/**
* Get the BlockingQueue.
*/
protected BlockingQueue<SearchResults> getQueue() {
return mResultsQueue;
}
/**
* Process all the queued results concurrently in a background
* Thread.
*/
protected void processQueuedResults(final int resultCount) {
// Create a new Thread that will process all the
// queued results concurrently in the background.
Thread t = new Thread(() -> {
try {
for (int i = 0; i < resultCount; ++i)
// Extract each SearchResults from the
// queue (blocking if necessary) until
// we're done.
getQueue().take().print();
} catch (InterruptedException e) {
System.out.println("run() interrupted");
}
});
t.start();
try {
// Simple barrier that waits for the Thread processing
// SearchResults to exit.
t.join();
} catch (InterruptedException e) {
System.out.println("processQueuedResults() interrupted");
}
}
}
| 33.924171 | 85 | 0.605616 |
f44ce2743746f246a270233a6b454691b4b7590e | 1,924 | /**
* (c) 2009 Microsoft corp.
* This software is distributed under Microsoft Public License (MSPL)
* see http://opensource.org/licenses/ms-pl.html
*
* @author Microsoft, Vincent Simonetti
*/
package bing.requests;
/**
* Request object to be used when requesting mobile web results.
*/
public class BingMobileWebRequest extends BingRequest
{
public static String MOBILE_WEB_SEARCH_OPTIONS_SEPERATOR = BingRequest.OPTION_SEPERATOR;
public static String MOBILE_WEB_SEARCH_OPTIONS_DISABLE_HOST_COLLAPSING = "DisableHostCollapsing";
public static String MOBILE_WEB_SEARCH_OPTIONS_DISABLE_QUERY_ALTERATIONS = "DisableQueryAlterations";
public String sourceType()
{
return "MobileWeb";
}
public String requestOptions()
{
StringBuffer options = new StringBuffer(super.requestOptions());
if(super.attrDict.containsKey("count"))
{
options.append(bing.Bing.format("&MobileWeb.Count={0,number,integer}", new Object[]{ super.attrDict.get("count") }));
}
if(super.attrDict.containsKey("offset"))
{
options.append(bing.Bing.format("&MobileWeb.Offset={0,number,integer}", new Object[]{ super.attrDict.get("offset") }));
}
if(super.attrDict.containsKey("mobileWebOptions"))
{
options.append(bing.Bing.format("&MobileWeb.Options={0}", new Object[]{ super.attrDict.get("webOptions") }));
}
return options.toString();
}
public void setCount(long count)
{
super.attrDict.put("count", new Long(count & 0xFFFFFFFFL));
}
public void setOffset(long offset)
{
super.attrDict.put("offset", new Long(offset & 0xFFFFFFFFL));
}
/**
* @param options One or more combinations of the <code>MOBILE_WEB_SEARCH_OPTIONS_<code> options separated by <code>MOBILE_WEB_SEARCH_OPTIONS_SEPERATOR<code>.
*/
public void setMobileWebOptions(String options)
{
super.attrDict.put("mobileWebOptions", options);
}
}
| 30.0625 | 160 | 0.713617 |
51f77add4811bf74a8077734b1c1574bad15402f | 220 | package com.checkmarx.flow.exception;
public class ADOClientException extends MachinaException {
public ADOClientException() {
}
public ADOClientException(String message) {
super(message);
}
}
| 18.333333 | 58 | 0.713636 |
0b9e9118c2c6bc7036e4488209f2bd3afc9424ad | 2,052 | package com.dev.base.util;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import com.dev.base.utils.PropertiesUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
*
* <p>Title: 模板工具类</p>
* <p>Description: 描述(简要描述类的职责、实现方式、使用注意事项等)</p>
* <p>CreateDate: 2015年10月25日下午10:21:16</p>
*/
public class FreeMarkerUtil {
// 配置信息
private final static Properties cfgProperties = PropertiesUtils.getProperties("freemarker.properties");
//配置信息
private static Configuration config = initFtlCfg();
//模板
private static Template apiDocTemplate = null;
static{
try {
apiDocTemplate = config.getTemplate("doc.ftl");
}
catch (Exception e) {
e.printStackTrace();
}
}
//初始化配置信息
private static Configuration initFtlCfg(){
//编码
String encoding = cfgProperties.getProperty("encoding");
//模板读取目录
String ftlDir = cfgProperties.getProperty("ftl.dir");
Resource resource = new ClassPathResource(ftlDir);
config = new Configuration(Configuration.VERSION_2_3_22);
config.setDefaultEncoding(encoding);
config.setOutputEncoding(encoding);
config.setClassicCompatible(true);
try {
config.setDirectoryForTemplateLoading(resource.getFile());
}
catch (IOException e) {
e.printStackTrace();
}
return config;
}
/**
*
*@name 渲染模板
*@Description
*@CreateDate 2015年10月25日下午10:50:06
*/
public static void process(String tmplName,Object dataModel,Writer output){
Template template = null;
try {
template = config.getTemplate(tmplName);
template.process(dataModel, output);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
*
*@name 渲染api文档
*@Description
*@CreateDate 2016年1月14日下午8:44:22
*/
public static void processApiDoc(Object dataModel,Writer output){
try {
apiDocTemplate.process(dataModel, output);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
| 21.6 | 104 | 0.711988 |
bd7406d2458bfffca4eb89472aebdd36b91b378b | 8,977 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package uk.co.etothepii.haddock.db.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Logger;
import uk.co.etothepii.db.DatabaseConduit;
import uk.co.etothepii.haddock.db.factories.BookmakerAccountFactory;
import uk.co.etothepii.haddock.db.factories.BookmakerFactory;
import uk.co.etothepii.haddock.db.factories.IdentityFactory;
import uk.co.etothepii.haddock.db.tables.Bookmaker;
import uk.co.etothepii.haddock.db.tables.BookmakerAccount;
import uk.co.etothepii.haddock.db.tables.Identity;
import uk.co.etothepii.haddock.db.gui.listcellrenderers.ListableCellRenderer;
/**
*
* @author jrrpl
*/
public class IdentityPanel extends JPanel implements Editor<Identity> {
private static final Logger LOG = Logger.getLogger(IdentityPanel.class);
private JLabel firstNameLabel;
private JLabel middleNameLabel;
private JLabel surnameLabel;
private JTextField firstNameField;
private JTextField middleNameField;
private JTextField surnameField;
private Identity activeIdentity;
private HaddockListModel<Bookmaker> bookmakersModel;
private JList bookmakerList;
private BookmakerAccountPanel bookmakerAccountPanel;
private final ArrayList<ChangeListener> changeListeners;
public IdentityPanel() {
super(new GridBagLayout());
setBackground(Color.WHITE);
// setBorder(new LineBorder(Color.BLACK, 1));
changeListeners = new ArrayList<ChangeListener>();
firstNameLabel = new JLabel("First name");
middleNameLabel = new JLabel("Middle name");
surnameLabel = new JLabel("Surname");
firstNameField = new JTextField();
middleNameField = new JTextField();
surnameField = new JTextField();
firstNameField.setDisabledTextColor(Color.BLACK);
middleNameField.setDisabledTextColor(Color.BLACK);
surnameField.setDisabledTextColor(Color.BLACK);
bookmakerAccountPanel = new BookmakerAccountPanel();
add(firstNameLabel, new GridBagConstraints(0, 0, 1, 1, 0d, 0d,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 5, 5), 0, 0));
add(middleNameLabel, new GridBagConstraints(1, 0, 1, 1, 0d, 0d,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 5, 5), 0, 0));
add(surnameLabel, new GridBagConstraints(2, 0, 1, 1, 0d, 0d,
GridBagConstraints.WEST, GridBagConstraints.NONE,
new Insets(0, 0, 5, 0), 0, 0));
add(firstNameField, new GridBagConstraints(0, 1, 1, 1, 1d, 0d,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 5));
add(middleNameField, new GridBagConstraints(1, 1, 1, 1, 1d, 0d,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 5), 0, 5));
add(surnameField, new GridBagConstraints(2, 1, 1, 1, 1d, 0d,
GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
new Insets(0, 0, 5, 0), 0, 5));
ArrayList<Bookmaker> allBookmakers;
try {
allBookmakers = BookmakerFactory.getFactory().getAll();
}
catch (SQLException se) {
DatabaseConduit.printSQLException(se);
allBookmakers = new ArrayList<Bookmaker>();
}
bookmakersModel = new HaddockListModel<Bookmaker>(allBookmakers,
BookmakerFactory.getFactory());
bookmakerList = new JList(bookmakersModel);
bookmakerList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
bookmakerList.setCellRenderer(new ListableCellRenderer());
bookmakerList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
int index = bookmakerList.getSelectedIndex();
if (index >= 0) {
Bookmaker bookmaker = (Bookmaker)bookmakersModel.get(index);
try {
BookmakerAccount account =
BookmakerAccountFactory.getFactory(
).getFromIdentityAndBookmaker(
activeIdentity, bookmaker);
LOG.debug(account);
bookmakerAccountPanel.save();
if (account != null)
bookmakerAccountPanel.set(account);
else {
BookmakerAccount newAcc = new BookmakerAccount(
bookmaker, activeIdentity, "", "",
null, null, null, null);
newAcc.snapshot();
bookmakerAccountPanel.set(newAcc);
}
}
catch (SQLException sqle) {
DatabaseConduit.printSQLException(sqle);
}
}
else
bookmakerAccountPanel.set(null);
}
});
JPanel bookmakerPanel = new JPanel(new GridBagLayout());
bookmakerPanel.add(new JScrollPane(bookmakerList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), new GridBagConstraints(0, 0, 1, 1,
1d, 1d, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 5), 0, 0));
bookmakerPanel.add(bookmakerAccountPanel, new GridBagConstraints(
1, 0, 1, 1, 1d, 0d, GridBagConstraints.NORTH,
GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0));
bookmakerPanel.setBackground(Color.WHITE);
add(bookmakerPanel, new GridBagConstraints(0, 2, 3, 1, 3d, 1d,
GridBagConstraints.NORTH, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
set(null);
}
public final void set(Identity activeIdentity) {
this.activeIdentity = activeIdentity;
if (activeIdentity == null) {
firstNameField.setText("");
middleNameField.setText("");
surnameField.setText("");
bookmakerList.setEnabled(false);
}
else {
firstNameField.setText(activeIdentity.getFirstName());
middleNameField.setText(activeIdentity.getMiddleNames());
surnameField.setText(activeIdentity.getSurname());
bookmakerList.setEnabled(true);
}
bookmakerList.clearSelection();
bookmakerAccountPanel.set(null);
setEditable(false);
}
public void setEditable(boolean editable) {
firstNameField.setEnabled(editable);
middleNameField.setEnabled(editable);
surnameField.setEnabled(editable);
bookmakerAccountPanel.setEditable(editable);
}
public void edit() {
setEditable(true);
}
public void save() {
if (activeIdentity != null) {
activeIdentity.setFirstName(firstNameField.getText());
activeIdentity.setMiddleNames(middleNameField.getText());
activeIdentity.setSurname(surnameField.getText());
try {
if (activeIdentity.hasChangedSinceSnapshot()) {
IdentityFactory.getFactory().save(activeIdentity);
activeIdentity.snapshot();
}
}
catch (SQLException sqle) {
DatabaseConduit.printSQLException(sqle);
}
bookmakerAccountPanel.save();
setEditable(false);
fireChangeEvent(new SavedEvent(this));
// repaint();
}
}
public void addChangeListener(ChangeListener l) {
synchronized (changeListeners) {
changeListeners.add(l);
}
}
public void removeChangeListener(ChangeListener l) {
synchronized (changeListeners) {
changeListeners.remove(l);
}
}
public void fireChangeEvent(ChangeEvent e) {
synchronized (changeListeners) {
for (ChangeListener l : changeListeners)
l.stateChanged(e);
}
}
}
class SavedEvent extends ChangeEvent {
public SavedEvent(Object source) {
super(source);
}
}
| 39.546256 | 91 | 0.619361 |
7c33d6bd426eff8f1613f7aaff3b70e24a864de3 | 3,022 | /*
* Copyright 2014 David Morrissey
*
* 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 uk.co.visalia.brightpearl.apiclient.auth;
import uk.co.visalia.brightpearl.apiclient.account.Account;
import uk.co.visalia.brightpearl.apiclient.util.StringUtils;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Contains a legacy authentication token related to a staff member and not any developer or app.
*/
public class LegacyAuthorisation implements AppAuthorisation {
private final Account account;
private final String authToken;
private LegacyAuthorisation(Account account, String authToken) {
this.account = account;
this.authToken = authToken;
}
/**
* Create legacy authentication details using an account and staff token.
* @param account Brightpearl customer account details.
* @param authToken Staff authentication token.
*/
public static LegacyAuthorisation staff(Account account, String authToken) {
if (account == null) { throw new IllegalArgumentException("Account is required"); }
if (StringUtils.isBlank(authToken)) { throw new IllegalArgumentException("Auth token is required"); }
return new LegacyAuthorisation(account, authToken);
}
@Override
public Account getAccount() {
return account;
}
@Override
public Map<String, String> getHeaders() {
Map<String, String> headerMap = new HashMap<String, String>();
headerMap.put(LEGACY_AUTH_HEADER, authToken);
return Collections.unmodifiableMap(headerMap);
}
@Override
public String toString() {
return "LegacyAuthorisation{" +
"account=" + account +
", authToken='" + (authToken == null ? "null" : "[redacted]") + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
LegacyAuthorisation that = (LegacyAuthorisation) o;
if (account != null ? !account.equals(that.account) : that.account != null) return false;
if (authToken != null ? !authToken.equals(that.authToken) : that.authToken != null) return false;
return true;
}
@Override
public int hashCode() {
int result = account != null ? account.hashCode() : 0;
result = 31 * result + (authToken != null ? authToken.hashCode() : 0);
return result;
}
}
| 34.340909 | 109 | 0.671079 |
a1821f9104d038783f6e0acaef525f50dff0c22a | 677 | package fi.aalto.dmg.exceptions;
import java.io.Serializable;
/**
* Window time duration exception
* cast util.TimeDurations to duration in different platforms
* Created by jun on 11/3/15.
*/
public class DurationException extends Exception implements Serializable {
private static final long serialVersionUID = 8844332426042772132L;
public DurationException(String message)
{
super(message);
}
public DurationException()
{
super();
}
public DurationException(String message, Throwable cause)
{
super(message,cause);
}
public DurationException(Throwable cause)
{
super(cause);
}
} | 19.342857 | 74 | 0.682422 |
c3abbe331dcce75d10411711961ccd97f42adb0b | 4,057 | package com.bitbreeds.webrtc.sctp.impl.model;
/*
* Copyright (c) 29/06/16, Jonas Waage
* <p>
* 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:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
* <p>
* 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.
*/
import com.bitbreeds.webrtc.sctp.impl.SCTPReliability;
import com.bitbreeds.webrtc.sctp.impl.util.TSNUtil;
import com.bitbreeds.webrtc.sctp.model.SCTPOrderFlag;
import com.bitbreeds.webrtc.model.sctp.SCTPPayloadProtocolId;
import java.util.Arrays;
import java.util.Objects;
/**
* Stores data about a received message
*
* Needed for reassembly of fragmented messages and correct delivery to user.
*/
public class ReceivedData implements Comparable<ReceivedData> {
private final long TSN;
private final int streamId;
private final int streamSequence;
private final SCTPOrderFlag flags;
private final SCTPPayloadProtocolId protocolId;
private final SCTPReliability streamReliability;
private final byte[] payload;
public ReceivedData(long TSN,
int streamId,
int streamSequence,
SCTPOrderFlag flags,
SCTPPayloadProtocolId protocolId,
SCTPReliability streamReliability,
byte[] payload) {
this.TSN = TSN;
this.streamId = streamId;
this.streamSequence = streamSequence;
this.flags = flags;
this.protocolId = protocolId;
this.streamReliability = streamReliability;
this.payload = payload;
}
public long getTSN() {
return TSN;
}
public int getStreamId() {
return streamId;
}
public int getStreamSequence() {
return streamSequence;
}
public SCTPOrderFlag getFlag() {
return flags;
}
public SCTPPayloadProtocolId getProtocolId() {
return protocolId;
}
public byte[] getPayload() {
return payload;
}
public SCTPReliability getStreamReliability() {
return streamReliability;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ReceivedData that = (ReceivedData) o;
return TSN == that.TSN;
}
@Override
public int hashCode() {
return Objects.hash(TSN);
}
@Override
public int compareTo(ReceivedData dataStorage) {
if(this.getTSN() == dataStorage.getTSN()) {
return 0;
}
if(TSNUtil.isBelow(this.getTSN(),dataStorage.getTSN())) {
return -1;
}
else {
return 1;
}
}
@Override
public String toString() {
return "ReceivedData{" +
"TSN=" + TSN +
", streamId=" + streamId +
", streamSequence=" + streamSequence +
", flags=" + flags +
", protocolId=" + protocolId +
", streamReliability=" + streamReliability +
", payload=" + Arrays.toString(payload) +
'}';
}
}
| 32.456 | 129 | 0.638403 |
882087219866358d7b11de67d9077bbd3f6c7434 | 1,454 | package server.frame;
import java.awt.HeadlessException;
import java.sql.Date;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import server.dao.UserDao;
import server.entity.Users;
public class UserTableCahnged implements TableModelListener {
JTable table;
public UserTableCahnged(JTable table)
{
this.table=table;
}
public void tableChanged(TableModelEvent e) {
int row=e.getFirstRow();
int userId=Integer.parseInt(table.getValueAt(row, 0).toString());
String userName=table.getValueAt(row, 1).toString();
String pwdString=table.getValueAt(row, 2).toString();
//String IP=table.getValueAt(row, 3).toString();
//String state=table.getValueAt(row, 4).toString();
String userGender=table.getValueAt(row, 5).toString();
String userEmail=table.getValueAt(row, 6).toString();
//String userSignature=table.getValueAt(row, 5).toString();
Date userBirthday=Date.valueOf(table.getValueAt(row, 9).toString());
Users user=new Users(userId,userName,pwdString, userGender, userEmail,userBirthday);
UserDao userDao=new UserDao();
try {
if(userDao.update(user))
{
JOptionPane.showMessageDialog(null, "修改成功!");
}
else {
JOptionPane.showMessageDialog(null, "修改失败!");
}
} catch (HeadlessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| 28.509804 | 86 | 0.743466 |
7dde3ec90b5a329d48bf04264b48c831e935011c | 5,053 | package org.anasoid.jmc.plugins.utils;
import com.thoughtworks.xstream.converters.ConversionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.anasoid.jmc.plugins.component.java.AbstractJavaTestElement;
import org.anasoid.jmc.plugins.component.java.JavaTestElementExecutor;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
/**
* Executor utils, Helper to get instance of JavaTestElementExecutor from class name.
*
* @see JavaTestElementExecutor
*/
public final class ExecutorUtils {
private static final List<String> IGNORED_ATTRIBUTES =
Arrays.asList(
"parameters",
"TestElement.gui_class",
"TestElement.test_class",
"TestElement.name",
"TestElement.enabled",
"executorClass",
"TestPlan.comments");
private ExecutorUtils() {}
/**
* Extract attribute Properties.
*
* @param testElement testElement.
* @return filtered properties , converted to arguments
*/
public static Arguments extractAttributeArguments(AbstractJavaTestElement<?> testElement) {
Arguments defaultArgs = new Arguments();
PropertyIterator propertyIterator = testElement.propertyIterator();
while (propertyIterator.hasNext()) {
JMeterProperty property = propertyIterator.next();
if (!IGNORED_ATTRIBUTES.contains(property.getName())) {
defaultArgs.addArgument(property.getName(), property.getStringValue());
}
}
return defaultArgs;
}
/**
* get {@link JavaTestElementExecutor} instance.
*
* @param className className of {@link JavaTestElementExecutor}
* @param testElement testElement to initialize value.
* @return JavaTestElementExecutor instance.
*/
public static JavaTestElementExecutor getExecutor(String className, TestElement testElement) {
HashMap<String, Object> values = new HashMap<>();
PropertyIterator propertyIterator = testElement.propertyIterator();
while (propertyIterator.hasNext()) {
JMeterProperty property = propertyIterator.next();
values.put(property.getName(), property.getObjectValue());
}
return getExecutor(className, values);
}
/**
* get {@link JavaTestElementExecutor} instance.
*
* @param className className of {@link JavaTestElementExecutor}
* @param values fields values.
* @return JavaTestElementExecutor instance.
*/
public static JavaTestElementExecutor getExecutor(String className, Map<String, Object> values) {
try {
Class<?> wrapper = Class.forName(className);
Method builderMethod = wrapper.getDeclaredMethod("builder");
builderMethod.setAccessible(true); // NOSONAR
Object builder = builderMethod.invoke(null);
setFields(builder, values);
Method buildMethod = builder.getClass().getDeclaredMethod("build");
buildMethod.setAccessible(true); // NOSONAR
return (JavaTestElementExecutor) buildMethod.invoke(builder);
} catch (ClassNotFoundException
| NoSuchMethodException
| IllegalAccessException
| InvocationTargetException e) {
throw new ConversionException("Loading executor ", e);
}
}
private static void setFields(Object builder, Map<String, Object> values) {
Iterator<Entry<String, Object>> iterator = values.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> property = iterator.next();
setValue(builder, property.getKey(), property.getValue());
}
}
/**
* get All field with setter annotation.
*
* @return list all field.
*/
@SuppressWarnings("PMD.EmptyCatchBlock")
private static void setValue(Object source, String name, Object value) {
Method[] methods = source.getClass().getMethods();
String methodName = getWithMethod(name);
List<Method> methodList =
Arrays.stream(methods)
.filter(m -> m.getName().equals(methodName))
.collect(Collectors.toList());
if (methodList.isEmpty()) {
return;
}
Method methodFound = null;
for (Method method : methodList) {
try {
method.invoke(source, value);
methodFound = method;
break;
} catch (IllegalAccessException | InvocationTargetException e) {
// Nothing
}
}
if (methodFound == null) {
throw new IllegalStateException("No Mapping property found for : " + name);
}
}
/**
* get All field with setter annotation.
*
* @return list all field.
*/
private static String getWithMethod(String fieldName) {
return "with" + fieldName.substring(0, 1).toUpperCase(Locale.ROOT) + fieldName.substring(1);
}
}
| 32.184713 | 99 | 0.702355 |
047f59709bceeeaffece7f5d27a7083cede59599 | 128 | package com.bookstore.dto;
public interface AuthorNameEmailDto {
public String getName();
public String getEmail();
}
| 16 | 37 | 0.734375 |
b67974b0993bdbe7a10cf19bc820c3166ed26963 | 66,327 | package com.rbkmoney.eventstock.client.thrift; /**
* Autogenerated by Thrift Compiler (1.0.0-dev)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked", "unused"})
public class EventSinkSrv {
public interface Iface {
public List<SinkEvent> getEvents(EventRange range) throws org.apache.thrift.TException;
public long getLastEventID() throws NoLastEvent, org.apache.thrift.TException;
}
public interface AsyncIface {
public void getEvents(EventRange range, org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>> resultHandler) throws org.apache.thrift.TException;
public void getLastEventID(org.apache.thrift.async.AsyncMethodCallback<Long> resultHandler) throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot)
{
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public List<SinkEvent> getEvents(EventRange range) throws org.apache.thrift.TException
{
sendGetEvents(range);
return recvGetEvents();
}
public void sendGetEvents(EventRange range) throws org.apache.thrift.TException
{
GetEvents_args args = new GetEvents_args();
args.setRange(range);
sendBase("GetEvents", args);
}
public List<SinkEvent> recvGetEvents() throws org.apache.thrift.TException
{
GetEvents_result result = new GetEvents_result();
receiveBase(result, "GetEvents");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "GetEvents failed: unknown result");
}
public long getLastEventID() throws NoLastEvent, org.apache.thrift.TException
{
sendGetLastEventID();
return recvGetLastEventID();
}
public void sendGetLastEventID() throws org.apache.thrift.TException
{
GetLastEventID_args args = new GetLastEventID_args();
sendBase("GetLastEventID", args);
}
public long recvGetLastEventID() throws NoLastEvent, org.apache.thrift.TException
{
GetLastEventID_result result = new GetLastEventID_result();
receiveBase(result, "GetLastEventID");
if (result.isSetSuccess()) {
return result.success;
}
if (result.ex1 != null) {
throw result.ex1;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, "GetLastEventID failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void getEvents(EventRange range, org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>> resultHandler) throws org.apache.thrift.TException {
checkReady();
GetEvents_call method_call = new GetEvents_call(range, resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class GetEvents_call extends org.apache.thrift.async.TAsyncMethodCall<List<SinkEvent>> {
private EventRange range;
public GetEvents_call(EventRange range, org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.range = range;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("GetEvents", org.apache.thrift.protocol.TMessageType.CALL, 0));
GetEvents_args args = new GetEvents_args();
args.setRange(range);
args.write(prot);
prot.writeMessageEnd();
}
public List<SinkEvent> getResult() throws org.apache.thrift.TException {
if (getState() != State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recvGetEvents();
}
}
public void getLastEventID(org.apache.thrift.async.AsyncMethodCallback<Long> resultHandler) throws org.apache.thrift.TException {
checkReady();
GetLastEventID_call method_call = new GetLastEventID_call(resultHandler, this, ___protocolFactory, ___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class GetLastEventID_call extends org.apache.thrift.async.TAsyncMethodCall<Long> {
public GetLastEventID_call(org.apache.thrift.async.AsyncMethodCallback<Long> resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("GetLastEventID", org.apache.thrift.protocol.TMessageType.CALL, 0));
GetLastEventID_args args = new GetLastEventID_args();
args.write(prot);
prot.writeMessageEnd();
}
public Long getResult() throws NoLastEvent, org.apache.thrift.TException {
if (getState() != State.RESPONSE_READ) {
throw new IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recvGetLastEventID();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("GetEvents", new GetEvents());
processMap.put("GetLastEventID", new GetLastEventID());
return processMap;
}
public static class GetEvents<I extends Iface> extends org.apache.thrift.ProcessFunction<I, GetEvents_args> {
public GetEvents() {
super("GetEvents");
}
public GetEvents_args getEmptyArgsInstance() {
return new GetEvents_args();
}
protected boolean isOneway() {
return false;
}
public GetEvents_result getResult(I iface, GetEvents_args args) throws org.apache.thrift.TException {
GetEvents_result result = new GetEvents_result();
result.success = iface.getEvents(args.range);
return result;
}
}
public static class GetLastEventID<I extends Iface> extends org.apache.thrift.ProcessFunction<I, GetLastEventID_args> {
public GetLastEventID() {
super("GetLastEventID");
}
public GetLastEventID_args getEmptyArgsInstance() {
return new GetLastEventID_args();
}
protected boolean isOneway() {
return false;
}
public GetLastEventID_result getResult(I iface, GetLastEventID_args args) throws org.apache.thrift.TException {
GetLastEventID_result result = new GetLastEventID_result();
try {
result.success = iface.getLastEventID();
result.setSuccessIsSet(true);
} catch (NoLastEvent ex1) {
result.ex1 = ex1;
}
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("GetEvents", new GetEvents());
processMap.put("GetLastEventID", new GetLastEventID());
return processMap;
}
public static class GetEvents<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, GetEvents_args, List<SinkEvent>> {
public GetEvents() {
super("GetEvents");
}
public GetEvents_args getEmptyArgsInstance() {
return new GetEvents_args();
}
public org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>>() {
public void onComplete(List<SinkEvent> o) {
GetEvents_result result = new GetEvents_result();
result.success = o;
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
GetEvents_result result = new GetEvents_result();
if (e instanceof org.apache.thrift.transport.TTransportException) {
LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, GetEvents_args args, org.apache.thrift.async.AsyncMethodCallback<List<SinkEvent>> resultHandler) throws org.apache.thrift.TException {
iface.getEvents(args.range,resultHandler);
}
}
public static class GetLastEventID<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, GetLastEventID_args, Long> {
public GetLastEventID() {
super("GetLastEventID");
}
public GetLastEventID_args getEmptyArgsInstance() {
return new GetLastEventID_args();
}
public org.apache.thrift.async.AsyncMethodCallback<Long> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<Long>() {
public void onComplete(Long o) {
GetLastEventID_result result = new GetLastEventID_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (Exception e) {
LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
GetLastEventID_result result = new GetLastEventID_result();
if (e instanceof NoLastEvent) {
result.ex1 = (NoLastEvent) e;
result.setEx1IsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException)e;
} else {
LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb,msg,msgType,seqid);
} catch (Exception ex) {
LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, GetLastEventID_args args, org.apache.thrift.async.AsyncMethodCallback<Long> resultHandler) throws org.apache.thrift.TException {
iface.getLastEventID(resultHandler);
}
}
}
public static class GetEvents_args implements org.apache.thrift.TBase<GetEvents_args, GetEvents_args._Fields>, java.io.Serializable, Cloneable, Comparable<GetEvents_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetEvents_args");
private static final org.apache.thrift.protocol.TField RANGE_FIELD_DESC = new org.apache.thrift.protocol.TField("range", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final SchemeFactory STANDARD_SCHEME_FACTORY = new GetEvents_argsStandardSchemeFactory();
private static final SchemeFactory TUPLE_SCHEME_FACTORY = new GetEvents_argsTupleSchemeFactory();
public EventRange range; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
RANGE((short)1, "range");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // RANGE
return RANGE;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.RANGE, new org.apache.thrift.meta_data.FieldMetaData("range", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, EventRange.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetEvents_args.class, metaDataMap);
}
public GetEvents_args() {
}
public GetEvents_args(
EventRange range)
{
this();
this.range = range;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public GetEvents_args(GetEvents_args other) {
if (other.isSetRange()) {
this.range = new EventRange(other.range);
}
}
public GetEvents_args deepCopy() {
return new GetEvents_args(this);
}
@Override
public void clear() {
this.range = null;
}
public EventRange getRange() {
return this.range;
}
public GetEvents_args setRange(EventRange range) {
this.range = range;
return this;
}
public void unsetRange() {
this.range = null;
}
/** Returns true if field range is set (has been assigned a value) and false otherwise */
public boolean isSetRange() {
return this.range != null;
}
public void setRangeIsSet(boolean value) {
if (!value) {
this.range = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case RANGE:
if (value == null) {
unsetRange();
} else {
setRange((EventRange)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case RANGE:
return getRange();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case RANGE:
return isSetRange();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof GetEvents_args)
return this.equals((GetEvents_args)that);
return false;
}
public boolean equals(GetEvents_args that) {
if (that == null)
return false;
boolean this_present_range = true && this.isSetRange();
boolean that_present_range = true && that.isSetRange();
if (this_present_range || that_present_range) {
if (!(this_present_range && that_present_range))
return false;
if (!this.range.equals(that.range))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetRange()) ? 131071 : 524287);
if (isSetRange())
hashCode = hashCode * 8191 + range.hashCode();
return hashCode;
}
@Override
public int compareTo(GetEvents_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetRange()).compareTo(other.isSetRange());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetRange()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.range, other.range);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public _Fields[] getFields() {
return _Fields.values();
}
public Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> getFieldMetaData() {
return metaDataMap;
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("GetEvents_args(");
boolean first = true;
sb.append("range:");
if (this.range == null) {
sb.append("null");
} else {
sb.append(this.range);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
if (range != null) {
range.validate();
}
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class GetEvents_argsStandardSchemeFactory implements SchemeFactory {
public GetEvents_argsStandardScheme getScheme() {
return new GetEvents_argsStandardScheme();
}
}
private static class GetEvents_argsStandardScheme extends StandardScheme<GetEvents_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, GetEvents_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // RANGE
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.range = new EventRange();
struct.range.read(iprot);
struct.setRangeIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, GetEvents_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.range != null) {
oprot.writeFieldBegin(RANGE_FIELD_DESC);
struct.range.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class GetEvents_argsTupleSchemeFactory implements SchemeFactory {
public GetEvents_argsTupleScheme getScheme() {
return new GetEvents_argsTupleScheme();
}
}
private static class GetEvents_argsTupleScheme extends TupleScheme<GetEvents_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, GetEvents_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetRange()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetRange()) {
struct.range.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, GetEvents_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.range = new EventRange();
struct.range.read(iprot);
struct.setRangeIsSet(true);
}
}
}
private static <S extends IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
public static class GetEvents_result implements org.apache.thrift.TBase<GetEvents_result, GetEvents_result._Fields>, java.io.Serializable, Cloneable, Comparable<GetEvents_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetEvents_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.LIST, (short)0);
private static final SchemeFactory STANDARD_SCHEME_FACTORY = new GetEvents_resultStandardSchemeFactory();
private static final SchemeFactory TUPLE_SCHEME_FACTORY = new GetEvents_resultTupleSchemeFactory();
public List<SinkEvent> success; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, SinkEvent.class))));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetEvents_result.class, metaDataMap);
}
public GetEvents_result() {
}
public GetEvents_result(
List<SinkEvent> success)
{
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public GetEvents_result(GetEvents_result other) {
if (other.isSetSuccess()) {
List<SinkEvent> __this__success = new ArrayList<SinkEvent>(other.success.size());
for (SinkEvent other_element : other.success) {
__this__success.add(new SinkEvent(other_element));
}
this.success = __this__success;
}
}
public GetEvents_result deepCopy() {
return new GetEvents_result(this);
}
@Override
public void clear() {
this.success = null;
}
public int getSuccessSize() {
return (this.success == null) ? 0 : this.success.size();
}
public java.util.Iterator<SinkEvent> getSuccessIterator() {
return (this.success == null) ? null : this.success.iterator();
}
public void addToSuccess(SinkEvent elem) {
if (this.success == null) {
this.success = new ArrayList<SinkEvent>();
}
this.success.add(elem);
}
public List<SinkEvent> getSuccess() {
return this.success;
}
public GetEvents_result setSuccess(List<SinkEvent> success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((List<SinkEvent>)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof GetEvents_result)
return this.equals((GetEvents_result)that);
return false;
}
public boolean equals(GetEvents_result that) {
if (that == null)
return false;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
if (isSetSuccess())
hashCode = hashCode * 8191 + success.hashCode();
return hashCode;
}
@Override
public int compareTo(GetEvents_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public _Fields[] getFields() {
return _Fields.values();
}
public Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> getFieldMetaData() {
return metaDataMap;
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("GetEvents_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class GetEvents_resultStandardSchemeFactory implements SchemeFactory {
public GetEvents_resultStandardScheme getScheme() {
return new GetEvents_resultStandardScheme();
}
}
private static class GetEvents_resultStandardScheme extends StandardScheme<GetEvents_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, GetEvents_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
{
org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();
struct.success = new ArrayList<SinkEvent>(_list0.size);
SinkEvent _elem1;
for (int _i2 = 0; _i2 < _list0.size; ++_i2)
{
_elem1 = new SinkEvent();
_elem1.read(iprot);
struct.success.add(_elem1);
}
iprot.readListEnd();
}
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, GetEvents_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
{
oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size()));
for (SinkEvent _iter3 : struct.success)
{
_iter3.write(oprot);
}
oprot.writeListEnd();
}
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class GetEvents_resultTupleSchemeFactory implements SchemeFactory {
public GetEvents_resultTupleScheme getScheme() {
return new GetEvents_resultTupleScheme();
}
}
private static class GetEvents_resultTupleScheme extends TupleScheme<GetEvents_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, GetEvents_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
{
oprot.writeI32(struct.success.size());
for (SinkEvent _iter4 : struct.success)
{
_iter4.write(oprot);
}
}
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, GetEvents_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
{
org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
struct.success = new ArrayList<SinkEvent>(_list5.size);
SinkEvent _elem6;
for (int _i7 = 0; _i7 < _list5.size; ++_i7)
{
_elem6 = new SinkEvent();
_elem6.read(iprot);
struct.success.add(_elem6);
}
}
struct.setSuccessIsSet(true);
}
}
}
private static <S extends IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
public static class GetLastEventID_args implements org.apache.thrift.TBase<GetLastEventID_args, GetLastEventID_args._Fields>, java.io.Serializable, Cloneable, Comparable<GetLastEventID_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetLastEventID_args");
private static final SchemeFactory STANDARD_SCHEME_FACTORY = new GetLastEventID_argsStandardSchemeFactory();
private static final SchemeFactory TUPLE_SCHEME_FACTORY = new GetLastEventID_argsTupleSchemeFactory();
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
;
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetLastEventID_args.class, metaDataMap);
}
public GetLastEventID_args() {
}
/**
* Performs a deep copy on <i>other</i>.
*/
public GetLastEventID_args(GetLastEventID_args other) {
}
public GetLastEventID_args deepCopy() {
return new GetLastEventID_args(this);
}
@Override
public void clear() {
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof GetLastEventID_args)
return this.equals((GetLastEventID_args)that);
return false;
}
public boolean equals(GetLastEventID_args that) {
if (that == null)
return false;
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
return hashCode;
}
@Override
public int compareTo(GetLastEventID_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public _Fields[] getFields() {
return _Fields.values();
}
public Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> getFieldMetaData() {
return metaDataMap;
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("GetLastEventID_args(");
boolean first = true;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class GetLastEventID_argsStandardSchemeFactory implements SchemeFactory {
public GetLastEventID_argsStandardScheme getScheme() {
return new GetLastEventID_argsStandardScheme();
}
}
private static class GetLastEventID_argsStandardScheme extends StandardScheme<GetLastEventID_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, GetLastEventID_args struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, GetLastEventID_args struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class GetLastEventID_argsTupleSchemeFactory implements SchemeFactory {
public GetLastEventID_argsTupleScheme getScheme() {
return new GetLastEventID_argsTupleScheme();
}
}
private static class GetLastEventID_argsTupleScheme extends TupleScheme<GetLastEventID_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, GetLastEventID_args struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, GetLastEventID_args struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
}
}
private static <S extends IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
public static class GetLastEventID_result implements org.apache.thrift.TBase<GetLastEventID_result, GetLastEventID_result._Fields>, java.io.Serializable, Cloneable, Comparable<GetLastEventID_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("GetLastEventID_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField("success", org.apache.thrift.protocol.TType.I64, (short)0);
private static final org.apache.thrift.protocol.TField EX1_FIELD_DESC = new org.apache.thrift.protocol.TField("ex1", org.apache.thrift.protocol.TType.STRUCT, (short)1);
private static final SchemeFactory STANDARD_SCHEME_FACTORY = new GetLastEventID_resultStandardSchemeFactory();
private static final SchemeFactory TUPLE_SCHEME_FACTORY = new GetLastEventID_resultTupleSchemeFactory();
public long success; // required
public NoLastEvent ex1; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short)0, "success"),
EX1((short)1, "ex1");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 0: // SUCCESS
return SUCCESS;
case 1: // EX1
return EX1;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
private static final int __SUCCESS_ISSET_ID = 0;
private byte __isset_bitfield = 0;
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));
tmpMap.put(_Fields.EX1, new org.apache.thrift.meta_data.FieldMetaData("ex1", org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, NoLastEvent.class)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(GetLastEventID_result.class, metaDataMap);
}
public GetLastEventID_result() {
}
public GetLastEventID_result(
long success,
NoLastEvent ex1)
{
this();
this.success = success;
setSuccessIsSet(true);
this.ex1 = ex1;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public GetLastEventID_result(GetLastEventID_result other) {
__isset_bitfield = other.__isset_bitfield;
this.success = other.success;
if (other.isSetEx1()) {
this.ex1 = new NoLastEvent(other.ex1);
}
}
public GetLastEventID_result deepCopy() {
return new GetLastEventID_result(this);
}
@Override
public void clear() {
setSuccessIsSet(false);
this.success = 0;
this.ex1 = null;
}
public long getSuccess() {
return this.success;
}
public GetLastEventID_result setSuccess(long success) {
this.success = success;
setSuccessIsSet(true);
return this;
}
public void unsetSuccess() {
__isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
/** Returns true if field success is set (has been assigned a value) and false otherwise */
public boolean isSetSuccess() {
return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);
}
public void setSuccessIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);
}
public NoLastEvent getEx1() {
return this.ex1;
}
public GetLastEventID_result setEx1(NoLastEvent ex1) {
this.ex1 = ex1;
return this;
}
public void unsetEx1() {
this.ex1 = null;
}
/** Returns true if field ex1 is set (has been assigned a value) and false otherwise */
public boolean isSetEx1() {
return this.ex1 != null;
}
public void setEx1IsSet(boolean value) {
if (!value) {
this.ex1 = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((Long)value);
}
break;
case EX1:
if (value == null) {
unsetEx1();
} else {
setEx1((NoLastEvent)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
case EX1:
return getEx1();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
case EX1:
return isSetEx1();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof GetLastEventID_result)
return this.equals((GetLastEventID_result)that);
return false;
}
public boolean equals(GetLastEventID_result that) {
if (that == null)
return false;
boolean this_present_success = true;
boolean that_present_success = true;
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (this.success != that.success)
return false;
}
boolean this_present_ex1 = true && this.isSetEx1();
boolean that_present_ex1 = true && that.isSetEx1();
if (this_present_ex1 || that_present_ex1) {
if (!(this_present_ex1 && that_present_ex1))
return false;
if (!this.ex1.equals(that.ex1))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + org.apache.thrift.TBaseHelper.hashCode(success);
hashCode = hashCode * 8191 + ((isSetEx1()) ? 131071 : 524287);
if (isSetEx1())
hashCode = hashCode * 8191 + ex1.hashCode();
return hashCode;
}
@Override
public int compareTo(GetLastEventID_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetEx1()).compareTo(other.isSetEx1());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetEx1()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.ex1, other.ex1);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public _Fields[] getFields() {
return _Fields.values();
}
public Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> getFieldMetaData() {
return metaDataMap;
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("GetLastEventID_result(");
boolean first = true;
sb.append("success:");
sb.append(this.success);
first = false;
if (!first) sb.append(", ");
sb.append("ex1:");
if (this.ex1 == null) {
sb.append("null");
} else {
sb.append(this.ex1);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
// it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.
__isset_bitfield = 0;
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class GetLastEventID_resultStandardSchemeFactory implements SchemeFactory {
public GetLastEventID_resultStandardScheme getScheme() {
return new GetLastEventID_resultStandardScheme();
}
}
private static class GetLastEventID_resultStandardScheme extends StandardScheme<GetLastEventID_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, GetLastEventID_result struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.I64) {
struct.success = iprot.readI64();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 1: // EX1
if (schemeField.type == org.apache.thrift.protocol.TType.STRUCT) {
struct.ex1 = new NoLastEvent();
struct.ex1.read(iprot);
struct.setEx1IsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, GetLastEventID_result struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.isSetSuccess()) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeI64(struct.success);
oprot.writeFieldEnd();
}
if (struct.ex1 != null) {
oprot.writeFieldBegin(EX1_FIELD_DESC);
struct.ex1.write(oprot);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class GetLastEventID_resultTupleSchemeFactory implements SchemeFactory {
public GetLastEventID_resultTupleScheme getScheme() {
return new GetLastEventID_resultTupleScheme();
}
}
private static class GetLastEventID_resultTupleScheme extends TupleScheme<GetLastEventID_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, GetLastEventID_result struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
BitSet optionals = new BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
if (struct.isSetEx1()) {
optionals.set(1);
}
oprot.writeBitSet(optionals, 2);
if (struct.isSetSuccess()) {
oprot.writeI64(struct.success);
}
if (struct.isSetEx1()) {
struct.ex1.write(oprot);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, GetLastEventID_result struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
BitSet incoming = iprot.readBitSet(2);
if (incoming.get(0)) {
struct.success = iprot.readI64();
struct.setSuccessIsSet(true);
}
if (incoming.get(1)) {
struct.ex1 = new NoLastEvent();
struct.ex1.read(iprot);
struct.setEx1IsSet(true);
}
}
}
private static <S extends IScheme> S scheme(org.apache.thrift.protocol.TProtocol proto) {
return (StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY : TUPLE_SCHEME_FACTORY).getScheme();
}
}
}
| 34.545313 | 326 | 0.652329 |
ba1a0193b84b3fdfb215a29a1bb0020ce0f450f8 | 3,055 | package net.mgsx.game.examples.platformer.ai;
import com.badlogic.ashley.core.Engine;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import net.mgsx.game.core.GamePipeline;
import net.mgsx.game.core.GameScreen;
import net.mgsx.game.examples.platformer.inputs.PlayerController;
import net.mgsx.game.plugins.box2d.components.Box2DBodyModel;
import net.mgsx.game.plugins.core.components.ExpiryComponent;
import net.mgsx.game.plugins.core.components.Transform2DComponent;
import net.mgsx.game.plugins.g3d.components.G3DModel;
public class MortarSystem extends IteratingSystem
{
private GameScreen game;
private ImmutableArray<Entity> players;
public MortarSystem(GameScreen game) {
super(Family.all(MortarComponent.class, MortarState.class, Transform2DComponent.class, G3DModel.class).get(), GamePipeline.LOGIC);
this.game = game;
}
@Override
public void addedToEngine(Engine engine) {
super.addedToEngine(engine);
players = getEngine().getEntitiesFor(Family.all(PlayerController.class, Transform2DComponent.class).get());
}
@Override
protected void processEntity(Entity entity, float deltaTime) {
MortarComponent mortar = MortarComponent.components.get(entity);
MortarState state = MortarState.components.get(entity);
Transform2DComponent parentTransform = Transform2DComponent.components.get(entity);
G3DModel model = G3DModel.components.get(entity);
if(mortar.time > 0){
mortar.time -= deltaTime;
}else{
if(players.size() <= 0) return;
Entity playerEntity = players.first();
Transform2DComponent playerTransform = Transform2DComponent.components.get(playerEntity);
// if(playerTransform.position.dst(parentTransform.position) > mortar.distance) return;
state.count++;
model.animationController.allowSameAnimation = true;
model.animationController.animate(mortar.shootAnimation, 1, 4, null, 0.1f);
for(Entity child : mortar.projectile.group.create(game.assets, game.entityEngine)){
ExpiryComponent expiry = getEngine().createComponent(ExpiryComponent.class);
expiry.time = mortar.expiry;
child.add(expiry);
Box2DBodyModel childPhysics = Box2DBodyModel.components.get(child);
Transform2DComponent childTransform = Transform2DComponent.components.get(child);
if(childPhysics != null){
// body is null has it has not been created yet !
childPhysics.def.type = BodyType.DynamicBody; // TODO sure ??
if(childTransform != null){
childTransform.position.add(parentTransform.position).add(mortar.offset);
}
childPhysics.def.linearVelocity.set(new Vector2(mortar.speed, 0).setAngle(mortar.angle));
if(playerTransform.position.x < parentTransform.position.x)
childPhysics.def.linearVelocity.x = -childPhysics.def.linearVelocity.x;
}
}
mortar.time = mortar.reloadTime;
}
}
}
| 39.675325 | 132 | 0.771195 |
540d3c9f5c9f1958bc8bbdd4c9eb7dd608cbe75a | 4,999 | package org.usfirst.frc.team2506.robot;
import org.usfirst.frc.team2506.robot.XboxController.JoystickManager;
import org.usfirst.frc.team2506.robot.XboxController.XboxButtons;
import org.usfirst.frc.team2506.robot.XboxController.Events.IButtonPressed;
import org.usfirst.frc.team2506.robot.XboxHandlers.ButtonStartHandler;
import edu.wpi.first.wpilibj.*;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
public class Robot extends IterativeRobot {
private Joystick playerOne = new Joystick(PortConstants.PORT_JOYSTICK_ONE);
private Joystick playerTwo = new Joystick(PortConstants.PORT_JOYSTICK_TWO);
private JoystickManager joystickManager = new JoystickManager(playerOne);
private IButtonPressed startButtonPressedHandler = new ButtonStartHandler(this);
private WheelDrive backLeft = new WheelDrive(
WheelConstants.MOTOR_BACK_LEFT_SPEED,
WheelConstants.MOTOR_BACK_LEFT_ANGLE,
WheelConstants.MOTOR_BACK_LEFT_ENCODER,
WheelConstants.MOTOR_BACK_LEFT_OFFSET
);
private WheelDrive frontLeft = new WheelDrive(
WheelConstants.MOTOR_FRONT_LEFT_SPEED,
WheelConstants.MOTOR_FRONT_LEFT_ANGLE,
WheelConstants.MOTOR_FRONT_LEFT_ENCODER,
WheelConstants.MOTOR_FRONT_LEFT_OFFSET
);
private WheelDrive backRight = new WheelDrive(
WheelConstants.MOTOR_BACK_RIGHT_SPEED,
WheelConstants.MOTOR_BACK_RIGHT_ANGLE,
WheelConstants.MOTOR_BACK_RIGHT_ENCODER,
WheelConstants.MOTOR_BACK_RIGHT_OFFSET
);
private WheelDrive frontRight = new WheelDrive(
WheelConstants.MOTOR_FRONT_RIGHT_SPEED,
WheelConstants.MOTOR_FRONT_RIGHT_ANGLE,
WheelConstants.MOTOR_FRONT_RIGHT_ENCODER,
WheelConstants.MOTOR_FRONT_RIGHT_OFFSET
);
private SwerveDrive swerveDrive = new SwerveDrive(frontRight, backRight, frontLeft, backLeft);
//private Winch winch = new Winch(PortConstants.PORT_WINCH);
private Intake intake = new Intake(PortConstants.PORT_INTAKE);
//private Shooter shooter = new Shooter(PortConstants.PORT_SHOOTER_SHOOTER, PortConstants.PORT_SHOOTER_HOPPER);
private BadShooter shooter = new BadShooter(PortConstants.PORT_SHOOTER_SHOOTER, PortConstants.PORT_SHOOTER_HOPPER);
private ADXRS450_Gyro gyro = new ADXRS450_Gyro();
private GyroUtils gyroUtils = new GyroUtils(gyro, swerveDrive);
private Ultrasonic ultrasonic = new Ultrasonic(1, 0);
@Override
public void robotInit() {
gyro.calibrate();
gyro.setPIDSourceType(PIDSourceType.kDisplacement);
ultrasonic.setEnabled(true);
ultrasonic.setAutomaticMode(true);
}
@Override
public void autonomousInit() {
gyro.reset();
//AutonomousGear.init(gyro, swerveDrive, ultrasonic);
}
@Override
public void autonomousPeriodic() {
//AutonomousGear.run();
}
public void teleopInit() {
swerveDrive.drive(gyro, 0, 0, 0);
joystickManager.addButtonPressedListener(XboxButtons.BUTTON_A, startButtonPressedHandler);
joystickManager.start();
}
@Override
public void teleopPeriodic() {
System.out.println(ultrasonic.getRangeInches());
//winch.turnOn(playerTwo.getRawAxis(XboxButtons.AXIS_LEFT_TRIGGER));
intake.roll(playerTwo.getRawAxis(XboxButtons.AXIS_RIGHT_TRIGGER));
double yAxis = playerOne.getRawAxis(XboxButtons.AXIS_LEFT_Y);
double xAxis = playerOne.getRawAxis(XboxButtons.AXIS_LEFT_X);
double rotation = playerOne.getRawAxis(XboxButtons.AXIS_RIGHT_X);
if (yAxis > 0.1 || yAxis < -0.1 || xAxis > 0.1 || xAxis < -0.1 || rotation > 0.1 || rotation < -0.1) {
// Turbo, bitches! xD
if (playerOne.getRawButton(XboxButtons.BUTTON_LEFT_STICK))
swerveDrive.drive(gyro, yAxis, -xAxis, rotation, 0.8);
else if (playerOne.getRawButton(XboxButtons.BUTTON_RIGHT_STICK))
swerveDrive.drive(gyro, yAxis, -xAxis, rotation, 0.4);
else
swerveDrive.drive(gyro, yAxis, -xAxis, rotation);
} else {
swerveDrive.drive(gyro, 0, 0, 0);
}
if (playerTwo.getRawButton(XboxButtons.BUTTON_A)) {
shooter.startHopper();
} else {
shooter.stopHopper();
}
if (playerTwo.getRawAxis(XboxButtons.AXIS_LEFT_TRIGGER) > 0.1) {
shooter.startShooting();
} else {
shooter.stopShooting();
}
}
WheelDrive[] wheels = { frontRight, frontLeft, backRight, backLeft };
WheelDrive testWheel = wheels[0];
boolean b8 = false;
@Override
public void testPeriodic() {
swerveDrive.drive(gyro, 0, 0, 0);
for (int b = 1; b <= 4; b++) {
if (playerOne.getRawButton(b)) {
testWheel = wheels[b - 1];
System.out.println("calibrating wheel " + b);
}
}
double stick = playerOne.getRawAxis(1);
if (stick > .2)
testWheel.incrementOffset();
else if (stick < -0.2)
testWheel.decrementOffset();
if (playerOne.getRawButton(8)) {
if (!b8) {
System.out.println("front right " + frontRight.getOffset());
System.out.println("front left " + frontLeft.getOffset());
System.out.println("back right " + backRight.getOffset());
System.out.println("back left " + backLeft.getOffset());
}
b8 = true;
} else {
b8 = false;
}
}
}
| 33.777027 | 116 | 0.755751 |
3fafd691b51d59904b83ff05746991ba2451aa4c | 3,255 | package io.agrest.runtime;
import com.fasterxml.jackson.databind.JsonNode;
import io.agrest.AgModuleProvider;
import io.agrest.TestModuleProvider;
import io.agrest.converter.jsonvalue.JsonValueConverter;
import org.apache.cayenne.di.Binder;
import org.apache.cayenne.di.Key;
import org.apache.cayenne.di.Module;
import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class AgRuntimeBuilder_ModuleProviderTest {
static final String CONVERTER_KEY = X.class.getName();
@Test
public void testAgModule_Provider() {
inRuntime(
new AgRuntimeBuilder().module(new LocalTestModuleProvider()),
this::assertLocalTestModuleActive);
}
@Test
public void testModule() {
inRuntime(
new AgRuntimeBuilder().module(new LocalTestModule()),
this::assertLocalTestModuleActive);
}
@Test
public void testAutoLoading() {
inRuntime(
new AgRuntimeBuilder(),
this::assertTestModuleActive);
}
@Test
public void testSuppressAutoLoading() {
inRuntime(
new AgRuntimeBuilder().doNotAutoLoadModules(),
this::assertTestModuleNotActive);
}
private void assertLocalTestModuleActive(AgRuntime runtime) {
Map<String, JsonValueConverter> converters =
runtime.service(Key.getMapOf(String.class, JsonValueConverter.class));
assertTrue(converters.containsKey(CONVERTER_KEY));
}
private void assertTestModuleActive(AgRuntime runtime) {
Map<String, JsonValueConverter> converters =
runtime.service(Key.getMapOf(String.class, JsonValueConverter.class));
assertTrue(converters.containsKey(TestModuleProvider.CONVERTER_KEY), "Auto-loading was off");
}
private void assertTestModuleNotActive(AgRuntime runtime) {
Map<String, JsonValueConverter> converters =
runtime.service(Key.getMapOf(String.class, JsonValueConverter.class));
assertFalse(converters.containsKey(TestModuleProvider.CONVERTER_KEY), "Auto-loading was on");
}
private void inRuntime(AgRuntimeBuilder builder, Consumer<AgRuntime> test) {
AgRuntime r = builder.build();
try {
test.accept(r);
} finally {
r.shutdown();
}
}
static class LocalTestModuleProvider implements AgModuleProvider {
@Override
public Module module() {
return new LocalTestModule();
}
@Override
public Class<? extends Module> moduleType() {
return LocalTestModule.class;
}
}
public static class LocalTestModule implements Module {
@Override
public void configure(Binder binder) {
binder.bindMap(JsonValueConverter.class).put(CONVERTER_KEY, new XConverter());
}
}
public static class X {
}
public static class XConverter implements JsonValueConverter<X> {
@Override
public X value(JsonNode node) {
return null;
}
}
}
| 30.420561 | 101 | 0.664823 |
404f7908ba988ad4ea7b993cc34a3fe4700bdffd | 5,929 | /*
* 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.modules.refactoring.java.ui.tree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import javax.lang.model.element.Element;
import org.netbeans.api.java.source.CompilationInfo;
import org.netbeans.api.java.source.TreeUtilities;
import org.openide.filesystems.FileObject;
/**
*
* @author Jan Becicka
*/
public class ElementGripFactory {
private static ElementGripFactory instance;
private final Map<FileObject, Interval> map = new WeakHashMap<FileObject, Interval>();
private final Map<FileObject, Boolean> testFiles = new WeakHashMap<FileObject, Boolean>();
/**
* Creates a new instance of ElementGripFactory
*/
private ElementGripFactory() {
}
public static ElementGripFactory getDefault() {
if (instance == null) {
instance = new ElementGripFactory();
}
return instance;
}
public void cleanUp() {
map.clear();
testFiles.clear();
}
public ElementGrip get(FileObject fileObject, int position) {
Interval start = map.get(fileObject);
if (start == null) {
return null;
}
try {
return start.get(position).item;
} catch (RuntimeException e) {
return start.item;
}
}
public ElementGrip getParent(ElementGrip el) {
Interval start = map.get(el.getFileObject());
return start == null ? null : start.getParent(el);
}
public void put(FileObject parentFile, Boolean inTestfile) {
testFiles.put(parentFile, inTestfile);
}
public Boolean inTestFile(FileObject parentFile) {
return testFiles.get(parentFile);
}
public void put(FileObject parentFile, TreePath tp, CompilationInfo info) {
Interval root = map.get(parentFile);
Interval i = Interval.createInterval(tp, info, root, null, parentFile);
if (i != null) {
map.put(parentFile, i);
}
}
private static class Interval {
long from = -1, to = -1;
Set<Interval> subintervals = new HashSet<Interval>();
ElementGrip item = null;
Interval get(long position) {
if (from <= position && to >= position) {
for (Interval o : subintervals) {
Interval ob = o.get(position);
if (ob != null) {
return ob;
}
}
return this;
}
return null;
}
ElementGrip getParent(ElementGrip eh) {
for (Interval i : subintervals) {
if (i.item.equals(eh)) {
return this.item;
} else {
ElementGrip e = i.getParent(eh);
if (e != null) {
return e;
}
}
}
return null;
}
public static Interval createInterval(TreePath tp, CompilationInfo info, Interval root, Interval p, FileObject parentFile) {
Tree t = tp.getLeaf();
long start = info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), t);
long end = info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), t);
Element current = info.getTrees().getElement(tp);
Tree.Kind kind = tp.getLeaf().getKind();
if (!TreeUtilities.CLASS_TREE_KINDS.contains(kind) && kind != Tree.Kind.METHOD) {
if (tp.getParentPath() == null || tp.getParentPath().getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
//xxx: rather workaround. should be fixed better.
return null;
} else {
return createInterval(tp.getParentPath(), info, root, p, parentFile);
}
}
Interval i = null;
if (root != null) {
Interval o = root.get(start);
if (o != null && current != null && current.equals(o.item.resolveElement(info))) {
// Update start/end, from/to
o.from = start;
o.to = end;
if (p != null) {
o.subintervals.add(p);
}
return null;
}
}
if (i == null) {
i = new Interval();
}
if (i.from != start) {
i.from = start;
i.to = end;
ElementGrip currentHandle2 = new ElementGrip(tp, info);
i.item = currentHandle2;
}
if (p != null) {
i.subintervals.add(p);
}
if (tp.getParentPath().getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
return i;
}
return createInterval(tp.getParentPath(), info, root, i, parentFile);
}
}
}
| 34.47093 | 132 | 0.561646 |
b58249ba12544e4419fc3457600ebaa04eed7fe0 | 1,157 | package me.lesmtech.nestedcategoryview.lib;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* @Author te.lin
* @Since 9/8/16
*/
public abstract class SimpleViewHolder<T> extends RecyclerView.ViewHolder {
private boolean isSelected = false;
public SimpleViewHolder(final View itemView) {
super(itemView);
Dispatcher.put(this.getClass().getCanonicalName(), this);
System.out.println(this.getClass().getCanonicalName() + this.toString());
itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
if (isSelected()) return;
isSelected = true;
SimpleViewHolder.this.onClick();
invalidate(isSelected());
Dispatcher.dispatch(SimpleViewHolder.this);
}
});
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public abstract boolean invalidate(boolean isSelected);
public abstract boolean onClick();
public abstract void update(T obj);
public void invalidate(){
invalidate(isSelected());
}
}
| 23.14 | 77 | 0.699222 |
be9b471954975c69091ba81b496ef2c72e039db2 | 1,186 | //
// Copyright (c) 2011, Brian Frank and Andy Frank
// Licensed under the Academic Free License version 3.0
//
// History:
// 3 Jan 11 Brian Frank Creation
//
package fan.util;
import fan.sys.*;
import fan.std.*;
public class SeededRandomPeer
{
public static SeededRandomPeer make(SeededRandom self)
{
return new SeededRandomPeer();
}
public void init(SeededRandom self)
{
rand = new java.util.Random(self.seed);
}
public long next(SeededRandom self, Range r)
{
return nextRange(rand.nextLong(), r);
}
public static long nextRange(long v, Range r)
{
if (r == null) return v;
if (v < 0) v = -v;
long start = r.start();
long end = r.end();
if (r.inclusive()) ++end;
if (end <= start) throw ArgErr.make("Range end < start: " + r);
return start + (v % (end-start));
}
public boolean nextBool(SeededRandom self)
{
return rand.nextBoolean();
}
public double nextFloat(SeededRandom self)
{
return rand.nextDouble();
}
public Buf nextBuf(SeededRandom self, long size)
{
byte[] b = new byte[(int)size];
rand.nextBytes(b);
return MemBuf.makeBuf(b);
}
java.util.Random rand;
} | 19.766667 | 67 | 0.63575 |
6c6959ad4f51f5b1210b1ad803717975acf641fd | 390 | package org.nutz.lang.meta;
import java.util.Arrays;
import java.util.List;
public class IssueVarStringMethodC {
private IssueVarStringMethodC(){}
public List<String> names;
public static IssueVarStringMethodC make(String...names) {
IssueVarStringMethodC sm = new IssueVarStringMethodC();
sm.names = Arrays.asList(names);
return sm;
}
}
| 21.666667 | 63 | 0.687179 |
c7196b890f048922167620465d4374f54f8b72ad | 1,309 | package org.dhis2.data.service;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.google.firebase.perf.metrics.AddTrace;
import org.dhis2.App;
import javax.inject.Inject;
/**
* QUADRAM. Created by ppajuelo on 23/10/2018.
*/
public class SyncInitWorker extends Worker {
public static final String INIT_META = "INIT_META";
public static final String INIT_DATA = "INIT_DATA";
@Inject
SyncPresenter presenter;
public SyncInitWorker(
@NonNull Context context,
@NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
@AddTrace(name = "MetadataSyncTrace")
public Result doWork() {
if (((App) getApplicationContext()).userComponent() != null) {
((App) getApplicationContext()).userComponent().plus(new SyncInitWorkerModule()).inject(this);
if (getInputData().getBoolean(INIT_META, false))
presenter.startPeriodicMetaWork();
if (getInputData().getBoolean(INIT_DATA, false))
presenter.startPeriodicDataWork();
return Result.success();
} else {
return Result.failure();
}
}
}
| 24.240741 | 106 | 0.659282 |
dc9ab0f7031b6f300b3122638e4f1c1080874e8a | 1,413 | package com.glume.glumemall.product.service.impl;
import com.glume.common.mybatis.PageUtils;
import com.glume.common.mybatis.Query;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glume.glumemall.product.dao.SkuImagesDao;
import com.glume.glumemall.product.entity.SkuImagesEntity;
import com.glume.glumemall.product.service.SkuImagesService;
@Service("skuImagesService")
public class SkuImagesServiceImpl extends ServiceImpl<SkuImagesDao, SkuImagesEntity> implements SkuImagesService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SkuImagesEntity> page = this.page(
new Query<SkuImagesEntity>().getPage(params),
new QueryWrapper<SkuImagesEntity>()
);
return new PageUtils(page);
}
@Override
public void saveSkuImage(List<SkuImagesEntity> skuImagesEntityList) {
this.saveBatch(skuImagesEntityList);
}
@Override
public List<SkuImagesEntity> getImagesBySkuId(Long skuId) {
List<SkuImagesEntity> imagesEntities = baseMapper.selectList(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));
return imagesEntities;
}
} | 33.642857 | 126 | 0.757254 |
c08b073b86bf3799fcf942caa17927d76889a7d9 | 2,653 | /*
* Copyright © 2017-2021 Dominic Heutelbeck ([email protected])
*
* 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.sapl.spring.config;
import javax.servlet.http.HttpServletRequest;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.reactive.ServerHttpRequest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.sapl.spring.serialization.HttpServletRequestSerializer;
import io.sapl.spring.serialization.MethodInvocationSerializer;
import io.sapl.spring.serialization.ServerHttpRequestSerializer;
/**
* This configuration provides a Jackson ObjectMapper bean, if missing.
*
* In addition, the JDK8 Module is added for properly handling Optional and serializers
* for HttpServletRequest and MethodInvocation are added.
*
* These serializers are used in building authorization subscriptions, if no explicit
* values for the fields of the subscription (e.g., action, resource) are provided.
*/
@Configuration
public class ObjectMapperAutoConfiguration {
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Configuration
public static class ModuleRegistrationConfiguration {
@Autowired
void configureObjectMapper(final ObjectMapper mapper) {
var module = new SimpleModule();
module.addSerializer(HttpServletRequest.class, new HttpServletRequestSerializer());
module.addSerializer(MethodInvocation.class, new MethodInvocationSerializer());
module.addSerializer(ServerHttpRequest.class, new ServerHttpRequestSerializer());
mapper.registerModule(module);
mapper.registerModule(new Jdk8Module());
mapper.registerModule(new JavaTimeModule());
}
}
}
| 37.366197 | 87 | 0.802865 |
dff16b0aaf29350120f6c60887faf0a52d6a842b | 4,227 | // ssGAS.java
//
// Author:
// Antonio J. Nebro <[email protected]>
// Juan J. Durillo <[email protected]>
//
// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package jmetal.metaheuristics.singleObjective.geneticAlgorithm;
import jmetal.core.*;
import jmetal.operators.selection.WorstSolutionSelection;
import jmetal.util.JMException;
import jmetal.util.comparators.ObjectiveComparator;
import java.util.Comparator;
import java.util.HashMap;
/**
* Class implementing a steady-state genetic algorithm
*/
public class ssGA extends Algorithm {
/**
*
* Constructor
* Create a new SSGA instance.
* @param problem Problem to solve
*
*/
public ssGA(Problem problem){
super(problem) ;
} // SSGA
/**
* Execute the SSGA algorithm
* @throws JMException
*/
public SolutionSet execute() throws JMException, ClassNotFoundException {
int populationSize ;
int maxEvaluations ;
int evaluations ;
SolutionSet population ;
Operator mutationOperator ;
Operator crossoverOperator ;
Operator selectionOperator ;
Comparator comparator ;
comparator = new ObjectiveComparator(0) ; // Single objective comparator
Operator findWorstSolution ;
HashMap parameters ; // Operator parameters
parameters = new HashMap() ;
parameters.put("comparator", comparator) ;
findWorstSolution = new WorstSolutionSelection(parameters) ;
// Read the parameters
populationSize = ((Integer)this.getInputParameter("populationSize")).intValue();
maxEvaluations = ((Integer)this.getInputParameter("maxEvaluations")).intValue();
// Initialize the variables
population = new SolutionSet(populationSize);
evaluations = 0;
// Read the operators
mutationOperator = this.operators_.get("mutation");
crossoverOperator = this.operators_.get("crossover");
selectionOperator = this.operators_.get("selection");
// Create the initial population
Solution newIndividual;
for (int i = 0; i < populationSize; i++) {
newIndividual = new Solution(problem_);
problem_.evaluate(newIndividual);
evaluations++;
population.add(newIndividual);
} //for
// main loop
while (evaluations < maxEvaluations) {
Solution [] parents = new Solution[2];
// Selection
parents[0] = (Solution)selectionOperator.execute(population);
parents[1] = (Solution)selectionOperator.execute(population);
// Crossover
Solution [] offspring = (Solution []) crossoverOperator.execute(parents);
// Mutation
mutationOperator.execute(offspring[0]);
// Evaluation of the new individual
problem_.evaluate(offspring[0]);
evaluations ++;
// Replacement: replace the last individual is the new one is better
int worstIndividual = (Integer)findWorstSolution.execute(population) ;
if (comparator.compare(population.get(worstIndividual), offspring[0]) > 0) {
population.remove(worstIndividual) ;
population.add(offspring[0]);
} // if
} // while
// Return a population with the best individual
SolutionSet resultPopulation = new SolutionSet(1) ;
resultPopulation.add(population.best(comparator));
System.out.println("Evaluations: " + evaluations ) ;
return resultPopulation ;
} // execute
} // ssGA
| 31.544776 | 100 | 0.668086 |
e003f1a7f50466cd1ecea0810aa280e2fced963e | 988 | package lambda;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Calculator {
interface IntegerMath {
int operation(int a, int b);
}
public int operateBinary(int a, int b, IntegerMath op) {
return op.operation(a, b);
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
IntegerMath addition = (a, b) -> a + b;
IntegerMath subtraction = (a, b) -> a - b;
System.out.println("40 + 2 = " + calculator.operateBinary(40, 2, addition));
System.out.println("20 - 20 = " + calculator.operateBinary(20, 20, subtraction));
ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 10,
100, TimeUnit.SECONDS, null, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return null;
}
});
}
}
| 30.875 | 89 | 0.61336 |
c6027aa6886ece80f5680132b124429ddcb39dbf | 4,467 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.postprocessing.global.singleloop;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import javax.annotation.Nullable;
import org.sosy_lab.cpachecker.cfa.model.CFAEdge;
import org.sosy_lab.cpachecker.cfa.model.CFANode;
import org.sosy_lab.cpachecker.util.CFAUtils;
import com.google.common.base.Preconditions;
/**
* Instances of this class are the heads of the loops produced by the single
* loop transformation. They provide additional information relevant to the
* transformation and to handling its consequences.
*/
public class SingleLoopHead extends CFANode {
/**
* The program counter value assignment edges leading to the loop head.
*/
private final Map<Integer, ProgramCounterValueAssignmentEdge> enteringPCValueAssignmentEdges = new HashMap<>();
/**
* Creates a new loop head with line number 0 and an artificial function name.
*/
public SingleLoopHead() {
super(CFASingleLoopTransformation.ARTIFICIAL_PROGRAM_COUNTER_FUNCTION_NAME);
}
@Override
public void addEnteringEdge(CFAEdge pEnteringEdge) {
if (pEnteringEdge instanceof ProgramCounterValueAssignmentEdge) {
ProgramCounterValueAssignmentEdge edge = (ProgramCounterValueAssignmentEdge) pEnteringEdge;
int pcValue = edge.getProgramCounterValue();
Preconditions.checkArgument(!enteringPCValueAssignmentEdges.containsKey(pcValue), "All entering program counter value assignment edges must be unique.");
enteringPCValueAssignmentEdges.put(pcValue, edge);
} else {
assert false;
}
super.addEnteringEdge(pEnteringEdge);
}
@Override
public void removeEnteringEdge(CFAEdge pEnteringEdge) {
if (pEnteringEdge instanceof ProgramCounterValueAssignmentEdge
&& CFAUtils.enteringEdges(this).contains(pEnteringEdge)) {
ProgramCounterValueAssignmentEdge edge = (ProgramCounterValueAssignmentEdge) pEnteringEdge;
enteringPCValueAssignmentEdges.remove(edge.getProgramCounterValue());
}
super.removeEnteringEdge(pEnteringEdge);
}
/**
* Gets the entering assignment edge with the given program counter value.
*
* @param pPCValue the value assigned to the program counter.
* @return the entering assignment edge with the given program counter
* value or {@code null} if no such edge exists.
*/
public @Nullable ProgramCounterValueAssignmentEdge getEnteringAssignmentEdge(int pPCValue) {
return enteringPCValueAssignmentEdges.get(pPCValue);
}
/**
* Gets the names of functions the loop head is entered from.
*
* @return the names of functions the loop head is entered from.
*/
public Set<String> getEnteringFunctionNames() {
Set<String> results = new HashSet<>();
Set<CFANode> visited = new HashSet<>();
Queue<CFANode> waitlist = new ArrayDeque<>();
waitlist.offer(this);
while (!waitlist.isEmpty()) {
CFANode current = waitlist.poll();
if (visited.add(current)) {
if (current.getFunctionName().equals(CFASingleLoopTransformation.ARTIFICIAL_PROGRAM_COUNTER_FUNCTION_NAME)) {
waitlist.addAll(CFAUtils.allPredecessorsOf(current).toList());
} else {
results.add(current.getFunctionName());
}
}
}
return results;
}
/**
* Gets all program counter values.
*
* @return all program counter values.
*/
public Collection<Integer> getProgramCounterValues() {
return Collections.unmodifiableSet(enteringPCValueAssignmentEdges.keySet());
}
} | 34.898438 | 159 | 0.738751 |
629827c7dafe4e596bb7d717dee4bac51ae1e556 | 1,085 | package org.onetwo.boot.core.shutdown;
import java.util.Arrays;
import java.util.Collection;
import org.onetwo.boot.core.config.BootJFishConfig;
import org.onetwo.boot.core.shutdown.GraceKillSignalHandler.GraceKillProcessor;
import org.onetwo.common.log.JFishLoggerFactory;
import org.onetwo.common.utils.LangUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
/**
* windows:
* taskkill /f /pid pid
*
* linux:
* kill -s USR2 pid = kill -12 pid
*
* kill默认为SIGTERM,会执行shutdownHook
* @author wayshall
* <br/>
*/
abstract public class AbstractGraceKillProcessor implements GraceKillProcessor {
protected final Logger logger = JFishLoggerFactory.getCommonLogger();
@Autowired
private BootJFishConfig config;
public Collection<String> getSignals() {
if(LangUtils.isNotEmpty(config.getGraceKill().getSignals())){
return config.getGraceKill().getSignals();
}
String signal = LangUtils.getOsName().toLowerCase().startsWith("win") ? GraceKillProcessor.INT : GraceKillProcessor.USR2;
return Arrays.asList(signal);
}
}
| 27.820513 | 123 | 0.775115 |
582081a235bbb8145c69dc33328817ad1367f37e | 639 | package hulva.luva.wxx.platform.puzzle.backend.model;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Hulva Luva.H
* @since 2019-10-12
*
*/
@Data
@NoArgsConstructor
public class FileModel {
private String name;
private Long fileSize;
private String type;
private String modifyTime;
private String className; // frontend style
private String path;
public FileModel(String name, Long fileSize, String type, String modifyTime) {
super();
this.name = name;
this.fileSize = fileSize;
this.type = type;
this.modifyTime = modifyTime;
this.className = "file".equals(type) ? "t-file" : "t-folder";
}
}
| 21.3 | 79 | 0.72457 |
f83313f167e5668a91cd998be9cad1856f954a09 | 4,976 | package ca.uhn.fhirtest;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
import org.hl7.fhir.dstu3.model.Organization;
import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.dstu3.model.Subscription;
import org.hl7.fhir.dstu3.model.Subscription.SubscriptionChannelType;
import org.hl7.fhir.dstu3.model.Subscription.SubscriptionStatus;
import org.hl7.fhir.instance.model.api.IIdType;
public class UhnFhirTestApp {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UhnFhirTestApp.class);
public static void main(String[] args) throws Exception {
int myPort = 8889;
String base = "http://localhost:" + myPort + "/baseR4";
// new File("target/testdb").mkdirs();
System.setProperty("fhir.db.location", "./target/testdb");
System.setProperty("fhir.db.location.dstu2", "./target/testdb_dstu2");
System.setProperty("fhir.lucene.location.dstu2", "./target/testlucene_dstu2");
System.setProperty("fhir.db.location.dstu3", "./target/fhirtest_dstu3");
System.setProperty("fhir.lucene.location.dstu3", "./target/testlucene_dstu3");
System.setProperty("fhir.db.location.r4", "./target/fhirtest_r4");
System.setProperty("fhir.lucene.location.r4", "./target/testlucene_r4");
System.setProperty("fhir.db.location.r5", "./target/fhirtest_r5");
System.setProperty("fhir.lucene.location.r5", "./target/testlucene_r5");
System.setProperty("fhir.db.location.tdl2", "./target/testdb_tdl2");
System.setProperty("fhir.lucene.location.tdl2", "./target/testlucene_tdl2");
System.setProperty("fhir.db.location.tdl3", "./target/testdb_tdl3");
System.setProperty("fhir.lucene.location.tdl3", "./target/testlucene_tdl3");
System.setProperty("fhir.baseurl.dstu2", base);
System.setProperty("fhir.baseurl.dstu1", base.replace("Dstu2", "Dstu1"));
System.setProperty("fhir.baseurl.dstu3", base.replace("Dstu2", "Dstu3"));
System.setProperty("fhir.baseurl.r4", base.replace("Dstu2", "R4"));
System.setProperty("fhir.baseurl.r5", base.replace("Dstu2", "R5"));
System.setProperty("fhir.baseurl.tdl2", base.replace("baseDstu2", "testDataLibraryDstu2"));
System.setProperty("fhir.baseurl.tdl3", base.replace("baseDstu2", "testDataLibraryStu3"));
System.setProperty("fhir.tdlpass", "aa,bb");
System.setProperty("fhir.db.username", "SA");
System.setProperty("fhir.db.password", "SA");
System.setProperty("testmode.local", "true");
Server server = new Server(myPort);
WebAppContext root = new WebAppContext();
root.setContextPath("/");
root.setDescriptor("hapi-fhir-jpaserver-uhnfhirtest/src/main/webapp/WEB-INF/web.xml");
root.setResourceBase("hapi-fhir-jpaserver-uhnfhirtest/target/hapi-fhir-jpaserver");
root.setParentLoaderPriority(true);
server.setHandler(root);
try {
server.start();
} catch (Exception e) {
ourLog.error("Failure during startup", e);
}
// base = "http://fhir.healthintersections.com.au/open";
// base = "http://spark.furore.com/fhir";
if (false) {
FhirContext ctx = FhirContext.forDstu3();
IGenericClient client = ctx.newRestfulGenericClient(base);
// client.setLogRequestAndResponse(true);
Organization o1 = new Organization();
o1.getNameElement().setValue("Some Org");
MethodOutcome create = client.create().resource(o1).execute();
IIdType orgId = (IIdType) create.getId();
Patient p1 = new Patient();
p1.getMeta().addTag("http://hl7.org/fhir/tag", "urn:happytag", "This is a happy resource");
p1.addIdentifier().setSystem("foo:bar").setValue("12345");
p1.addName().setFamily("Smith").addGiven("John");
p1.getManagingOrganization().setReferenceElement(orgId.toUnqualifiedVersionless());
Subscription subs = new Subscription();
subs.setStatus(SubscriptionStatus.ACTIVE);
subs.getChannel().setType(SubscriptionChannelType.WEBSOCKET);
subs.setCriteria("Observation?");
client.create().resource(subs).execute();
// for (int i = 0; i < 1000; i++) {
//
// Patient p = (Patient) resources.get(0);
// p.addName().addFamily("Transaction"+i);
//
// ourLog.info("Transaction count {}", i);
// client.transaction(resources);
// }
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
client.create().resource(p1).execute();
}
}
}
| 40.455285 | 104 | 0.714429 |
2965fd56f15dac8de15a6cbcfd76a92c9079d062 | 96 | /**
* Pooling provides lower GC requirements by re-using components.
*/
package reactor.alloc; | 24 | 65 | 0.75 |
44fcd25c671200a224b1ed8896a88238a1650bee | 1,778 | package org.firstinspires.ftc.teamcode.libs;
import android.content.Context;
import com.arcrobotics.ftclib.geometry.Transform2d;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.spartronics4915.lib.T265Camera;
/*
* This file is made to be used in the CameraMain class so that the T265 camera and the internal
* imu do not get instantiated more than once, because keeping them static means
* THEY PRESERVE THEIR DATA!
* Isn't that crazy! All this time we had to deal with the camera being reset to 0,0 or the imu
* axis being reset all to 0, but with keeping that static, it doesn't happen!
* If you wish to use the camera or imu in OpMode classes, just import and use the get methods and
* assign that to a variable. For redundancy you can also run the setup methods, but the setup
* methods are ran inside the CameraMain class, so unless your autonomous class doesn't use the
* camera, it should already be setup!
*/
public class Globals {
private static T265Camera camera;
private static BNO055IMU imu;
public static void setupCamera(HardwareMap hardwareMap) {
if (camera == null) {
camera = new T265Camera(new Transform2d(), 0.1, hardwareMap.appContext);
}
}
public static void setupIMU(HardwareMap hardwareMap) {
if (imu == null) {
imu = hardwareMap.get(BNO055IMU.class, "imu");
BNO055IMU.Parameters params = new BNO055IMU.Parameters();
imu.initialize(params);
}
}
public static BNO055IMU getImu() { return imu; }
public static T265Camera getCamera() { return camera; }
public static void startCamera() { camera.start(); }
public static void stopCamera() { camera.stop(); }
}
| 38.652174 | 98 | 0.713161 |
cc251d7e8a2047479b8cda72bc5914de4648476f | 2,185 | package com.j2ooxml.pptx.html;
import java.awt.Color;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.sl.usermodel.TextParagraph.TextAlign;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.jsoup.nodes.Node;
import com.j2ooxml.pptx.GenerationException;
import com.j2ooxml.pptx.State;
import com.j2ooxml.pptx.css.Style;
public class LiSupport implements NodeSupport {
private Transformer transformer;
public LiSupport(Transformer transformer) {
super();
this.transformer = transformer;
}
@Override
public boolean supports(Node node) {
if (node instanceof org.jsoup.nodes.Element) {
return "li".equals(((org.jsoup.nodes.Element) node).tagName());
}
return false;
}
@Override
public void process(State state, Node node) throws GenerationException {
XSLFTextParagraph paragraph = state.getParagraph();
Style style = state.getStyle();
TextAlign textAlign = style.getTextAlign();
if (textAlign != null) {
paragraph.setTextAlign(textAlign);
}
double indent = style.getIndent();
if (indent > 0) {
paragraph.setIndent(indent);
}
double marginLeft = style.getMarginLeft();
if (marginLeft > 0) {
paragraph.setLeftMargin(marginLeft);
if (indent == 0) {
paragraph.setIndent(-marginLeft);
}
}
Color liColor = style.getLiColor();
if (liColor != null) {
paragraph.setBulletFontColor(liColor);
}
String bulletChar = StringUtils.isNotBlank(style.getLiChar()) ? style.getLiChar() : "\u2022";
paragraph.setBulletCharacter(bulletChar);
paragraph.setBulletFontSize(120);
transformer.iterate(state, node);
paragraph = state.getTextShape().addNewTextParagraph();
paragraph.setSpaceAfter(0.);
paragraph.setSpaceBefore(0.);
state.setParagraph(paragraph);
if (node.nextSibling() == null) {
if (textAlign != null) {
paragraph.setTextAlign(textAlign);
}
}
}
}
| 30.774648 | 101 | 0.627918 |
f774974c794efdb96d1cb3b41a7eb860c4aed28d | 1,177 | package com.example.amesingflank.rubixcube;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Shader;
import android.view.View;
/**
* Created by AmesingFlank on 16/1/9.
*/
public class StepsShower extends View{
Paint paint;
int width=1440;
int height=2308;
int steps=0;
String msg="";
public StepsShower(Context c,int w,int h){
super(c);
width=w;
height=h;
paint=new Paint();
paint.setTextSize(80 * w / 1440);
paint.setColor(Color.BLUE);
}
@Override
protected void onDraw(Canvas canvas) {
paint.setTextSize(80 * width / 1440);
paint.setColor(Color.WHITE);
canvas.drawText(" "+msg,0,getHeight()*19/20,paint);
Shader mShader = new LinearGradient(0,0,width*5/18,getHeight()/6,new int[] {Color.RED,Color.YELLOW,Color.RED},null, Shader.TileMode.REPEAT);
paint.setShader(mShader);
canvas.drawText("Steps: " + String.valueOf(steps),width/100,getHeight()/6,paint);
paint.reset();
}
}
| 22.634615 | 148 | 0.656754 |
f846466c31616b17605bbb882fa415004110fec5 | 2,988 | /*
* 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.fn.harness.test;
import com.google.common.util.concurrent.ForwardingExecutorService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* A {@link TestRule} that validates that all submitted tasks finished and were completed. This
* allows for testing that tasks have exercised the appropriate shutdown logic.
*/
public class TestExecutors {
public static TestExecutorService from(Supplier<ExecutorService> executorServiceSuppler) {
return new FromSupplier(executorServiceSuppler);
}
/** A union of the {@link ExecutorService} and {@link TestRule} interfaces. */
public interface TestExecutorService extends ExecutorService, TestRule {}
private static class FromSupplier extends ForwardingExecutorService
implements TestExecutorService {
private final Supplier<ExecutorService> executorServiceSupplier;
private ExecutorService delegate;
private FromSupplier(Supplier<ExecutorService> executorServiceSupplier) {
this.executorServiceSupplier = executorServiceSupplier;
}
@Override
public Statement apply(Statement statement, Description arg1) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
Throwable thrown = null;
delegate = executorServiceSupplier.get();
try {
statement.evaluate();
} catch (Throwable t) {
thrown = t;
}
shutdown();
if (!awaitTermination(5, TimeUnit.SECONDS)) {
shutdownNow();
IllegalStateException e =
new IllegalStateException("Test executor failed to shutdown cleanly.");
if (thrown != null) {
thrown.addSuppressed(e);
} else {
thrown = e;
}
}
if (thrown != null) {
throw thrown;
}
}
};
}
@Override
protected ExecutorService delegate() {
return delegate;
}
}
}
| 34.744186 | 95 | 0.690428 |
2f7a8595eb5430195de0632331d9dc58418f26e8 | 22,392 | package javatools.parsers;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;
/**
This class is part of the Java Tools (see http://mpii.de/yago-naga/javatools).
It is licensed under the Creative Commons Attribution License
(see http://creativecommons.org/licenses/by/3.0) by
the YAGO-NAGA team (see http://mpii.de/yago-naga).
The PlingStemmer stems an English noun (plural or singular) to its singular
form. It deals with "firemen"->"fireman", it knows Greek stuff like
"appendices"->"appendix" and yes, it was a lot of work to compile these exceptions.
Examples:
<PRE>
System.out.println(PlingStemmer.stem("boy"));
----> boy
System.out.println(PlingStemmer.stem("boys"));
----> boy
System.out.println(PlingStemmer.stem("biophysics"));
----> biophysics
System.out.println(PlingStemmer.stem("automata"));
----> automaton
System.out.println(PlingStemmer.stem("genus"));
----> genus
System.out.println(PlingStemmer.stem("emus"));
----> emu
</PRE><P>
There are a number of word forms that can either be plural or singular.
Examples include "physics" (the science or the plural of "physic" (the
medicine)), "quarters" (the housing or the plural of "quarter" (1/4))
or "people" (the singular of "peoples" or the plural of "person"). In
these cases, the stemmer assumes the word is a plural form and returns
the singular form. The methods isPlural, isSingular and isPluralAndSingular
can be used to differentiate the cases.<P>
It cannot be guaranteed that the stemmer correctly stems a plural word
or correctly ignores a singular word -- let alone that it treats an
ambiguous word form in the way expected by the user.<P>
The PlingStemmer uses material from <A HREF=http://wordnet.princeton.edu/>WordNet</A>.<P>
It requires the class FinalSet from the <A HREF=http://www.mpii.mpg.de/~suchanek/downloads/javatools>
Java Tools</A>.
*/
public class PlingStemmer {
/** Tells whether a word form is plural. This method just checks whether the
* stem method alters the word */
public static boolean isPlural(String s) {
return(!s.equals(stem(s)));
}
/** Tells whether a word form is singular. Note that a word can be both plural and singular */
public static boolean isSingular(String s) {
return(singAndPlur.contains(s.toLowerCase()) || !isPlural(s));
}
/** Tells whether a word form is the singular form of one word and at
* the same time the plural form of another.*/
public static boolean isSingularAndPlural(String s) {
return(singAndPlur.contains(s.toLowerCase()));
}
/** Cuts a suffix from a string (that is the number of chars given by the suffix) */
public static String cut(String s, String suffix) {
return(s.substring(0,s.length()-suffix.length()));
}
/** Returns true if a word is probably not Latin */
public static boolean noLatin(String s) {
return(s.indexOf('h')>0 || s.indexOf('j')>0 || s.indexOf('k')>0 ||
s.indexOf('w')>0 || s.indexOf('y')>0 || s.indexOf('z')>0 ||
s.indexOf("ou")>0 || s.indexOf("sh")>0 || s.indexOf("ch")>0 ||
s.endsWith("aus"));
}
/** Returns true if a word is probably Greek */
private static boolean greek(String s) {
return(s.indexOf("ph")>0 || s.indexOf('y')>0 && s.endsWith("nges"));
}
/** Stems an English noun */
public static String stem(String s) {
String stem = s;
// Handle irregular ones
String irreg=irregular.get(s);
if(irreg!=null) return(stem=irreg);
// -on to -a
if(categoryON_A.contains(s)) return(stem=cut(s,"a")+"on");
// -um to -a
if(categoryUM_A.contains(s)) return(stem=cut(s,"a")+"um");
// -x to -ices
if(categoryIX_ICES.contains(s)) return(stem=cut(s,"ices")+"ix");
// -o to -i
if(categoryO_I.contains(s)) return(stem=cut(s,"i")+"o");
// -se to ses
if(categorySE_SES.contains(s)) return(stem=cut(s,"s"));
// -is to -es
if(categoryIS_ES.contains(s) || s.endsWith("theses")) return(stem=cut(s,"es")+"is");
// -us to -i
if(categoryUS_I.contains(s)) return(stem=cut(s,"i")+"us");
//Wrong plural
if(s.endsWith("uses") && (categoryUS_I.contains(cut(s,"uses")+"i") ||
s.equals("genuses") || s.equals("corpuses"))) return(stem=cut(s,"es"));
// -ex to -ices
if(categoryEX_ICES.contains(s)) return(stem=cut(s,"ices")+"ex");
// Words that do not inflect in the plural
if(s.endsWith("ois") || s.endsWith("itis") || category00.contains(s) || categoryICS.contains(s)) return(stem=s);
// -en to -ina
// No other common words end in -ina
if(s.endsWith("ina")) return(stem=cut(s,"en"));
// -a to -ae
// No other common words end in -ae
if(s.endsWith("ae")) return(stem=cut(s,"e"));
// -a to -ata
// No other common words end in -ata
if(s.endsWith("ata")) return(stem=cut(s,"ta"));
// trix to -trices
// No common word ends with -trice(s)
if(s.endsWith("trices")) return(stem=cut(s,"trices")+"trix");
// -us to -us
//No other common word ends in -us, except for false plurals of French words
//Catch words that are not latin or known to end in -u
if(s.endsWith("us") && !s.endsWith("eaus") && !s.endsWith("ieus") && !noLatin(s)
&& !categoryU_US.contains(s)) return(stem=s);
// -tooth to -teeth
// -goose to -geese
// -foot to -feet
// -zoon to -zoa
//No other common words end with the indicated suffixes
if(s.endsWith("teeth")) return(stem=cut(s,"teeth")+"tooth");
if(s.endsWith("geese")) return(stem=cut(s,"geese")+"goose");
if(s.endsWith("feet")) return(stem=cut(s,"feet")+"foot");
if(s.endsWith("zoa")) return(stem=cut(s,"zoa")+"zoon");
// -eau to -eaux
//No other common words end in eaux
if(s.endsWith("eaux")) return(stem=cut(s,"x"));
// -ieu to -ieux
//No other common words end in ieux
if(s.endsWith("ieux")) return(stem=cut(s,"x"));
// -nx to -nges
// Pay attention not to kill words ending in -nge with plural -nges
// Take only Greek words (works fine, only a handfull of exceptions)
if(s.endsWith("nges") && greek(s)) return(stem=cut(s,"nges")+"nx");
// -[sc]h to -[sc]hes
//No other common word ends with "shes", "ches" or "she(s)"
//Quite a lot end with "che(s)", filter them out
if(s.endsWith("shes") || s.endsWith("ches") && !categoryCHE_CHES.contains(s)) return(stem=cut(s,"es"));
// -ss to -sses
// No other common singular word ends with "sses"
// Filter out those ending in "sse(s)"
if(s.endsWith("sses") && !categorySSE_SSES.contains(s) && !s.endsWith("mousses")) return(stem=cut(s,"es"));
// -x to -xes
// No other common word ends with "xe(s)" except for "axe"
if(s.endsWith("xes") && !s.equals("axes")) return(stem=cut(s,"es"));
// -[nlw]ife to -[nlw]ives
//No other common word ends with "[nlw]ive(s)" except for olive
if(s.endsWith("nives") || s.endsWith("lives") && !s.endsWith("olives") ||
s.endsWith("wives")) return(stem=cut(s,"ves")+"fe");
// -[aeo]lf to -ves exceptions: valve, solve
// -[^d]eaf to -ves exceptions: heave, weave
// -arf to -ves no exception
if(s.endsWith("alves") && !s.endsWith("valves") ||
s.endsWith("olves") && !s.endsWith("solves") ||
s.endsWith("eaves") && !s.endsWith("heaves") && !s.endsWith("weaves") ||
s.endsWith("arves") ) return(stem=cut(s,"ves")+"f");
// -y to -ies
// -ies is very uncommon as a singular suffix
// but -ie is quite common, filter them out
if(s.endsWith("ies") && !categoryIE_IES.contains(s)) return(stem=cut(s,"ies")+"y");
// -o to -oes
// Some words end with -oe, so don't kill the "e"
if(s.endsWith("oes") && !categoryOE_OES.contains(s)) return(stem=cut(s,"es"));
// -s to -ses
// -z to -zes
// no words end with "-ses" or "-zes" in singular
if(s.endsWith("ses") || s.endsWith("zes") ) return(stem=cut(s,"es"));
// - to -s
if(s.endsWith("s") && !s.endsWith("ss") && !s.endsWith("is")) return(stem=cut(s,"s"));
return stem;
}
/** Words that end in "-se" in their plural forms (like "nurse" etc.)*/
public static Set<String> categorySE_SES=new FinalSet<String>(
"nurses",
"cruises",
"premises",
"houses"
);
/** Words that do not have a distinct plural form (like "atlas" etc.)*/
public static Set<String> category00=new FinalSet<String>(
"alias",
"asbestos",
"atlas",
"barracks",
"bathos",
"bias",
"breeches",
"britches",
"canvas",
"chaos",
"clippers",
"contretemps",
"corps",
"cosmos",
"crossroads",
"diabetes",
"ethos",
"gallows",
"gas",
"graffiti",
"headquarters",
"herpes",
"high-jinks",
"innings",
"jackanapes",
"lens",
"means",
"measles",
"mews",
"mumps",
"news",
"pathos",
"pincers",
"pliers",
"proceedings",
"rabies",
"rhinoceros",
"sassafras",
"scissors",
"series",
"shears",
"species",
"tuna"
);
/** Words that change from "-um" to "-a" (like "curriculum" etc.), listed in their plural forms*/
public static Set<String> categoryUM_A=new FinalSet<String>(
"addenda",
"agenda",
"aquaria",
"bacteria",
"candelabra",
"compendia",
"consortia",
"crania",
"curricula",
"data",
"desiderata",
"dicta",
"emporia",
"enconia",
"errata",
"extrema",
"gymnasia",
"honoraria",
"interregna",
"lustra",
"maxima",
"media",
"memoranda",
"millenia",
"minima",
"momenta",
"optima",
"ova",
"phyla",
"quanta",
"rostra",
"spectra",
"specula",
"stadia",
"strata",
"symposia",
"trapezia",
"ultimata",
"vacua",
"vela"
);
/** Words that change from "-on" to "-a" (like "phenomenon" etc.), listed in their plural forms*/
public static Set<String> categoryON_A=new FinalSet<String>(
"aphelia",
"asyndeta",
"automata",
"criteria",
"hyperbata",
"noumena",
"organa",
"perihelia",
"phenomena",
"prolegomena"
);
/** Words that change from "-o" to "-i" (like "libretto" etc.), listed in their plural forms*/
public static Set<String> categoryO_I=new FinalSet<String>(
"alti",
"bassi",
"canti",
"contralti",
"crescendi",
"libretti",
"soli",
"soprani",
"tempi",
"virtuosi"
);
/** Words that change from "-us" to "-i" (like "fungus" etc.), listed in their plural forms*/
public static Set<String> categoryUS_I=new FinalSet<String>(
"alumni",
"bacilli",
"cacti",
"foci",
"fungi",
"genii",
"hippopotami",
"incubi",
"nimbi",
"nuclei",
"nucleoli",
"octopi",
"radii",
"stimuli",
"styli",
"succubi",
"syllabi",
"termini",
"tori",
"umbilici",
"uteri"
);
/** Words that change from "-ix" to "-ices" (like "appendix" etc.), listed in their plural forms*/
public static Set<String> categoryIX_ICES=new FinalSet<String>(
"appendices",
"cervices"
);
/** Words that change from "-is" to "-es" (like "axis" etc.), listed in their plural forms*/
public static Set<String> categoryIS_ES=new FinalSet<String>(
// plus everybody ending in theses
"analyses",
"axes",
"bases",
"crises",
"diagnoses",
"ellipses",
"emphases",
"neuroses",
"oases",
"paralyses",
"synopses"
);
/** Words that change from "-oe" to "-oes" (like "toe" etc.), listed in their plural forms*/
public static Set<String> categoryOE_OES=new FinalSet<String>(
"aloes",
"backhoes",
"beroes",
"canoes",
"chigoes",
"cohoes",
"does",
"felloes",
"floes",
"foes",
"gumshoes",
"hammertoes",
"hoes",
"hoopoes",
"horseshoes",
"leucothoes",
"mahoes",
"mistletoes",
"oboes",
"overshoes",
"pahoehoes",
"pekoes",
"roes",
"shoes",
"sloes",
"snowshoes",
"throes",
"tic-tac-toes",
"tick-tack-toes",
"ticktacktoes",
"tiptoes",
"tit-tat-toes",
"toes",
"toetoes",
"tuckahoes",
"woes"
);
/** Words that change from "-ex" to "-ices" (like "index" etc.), listed in their plural forms*/
public static Set<String> categoryEX_ICES=new FinalSet<String>(
"apices",
"codices",
"cortices",
"indices",
"latices",
"murices",
"pontifices",
"silices",
"simplices",
"vertices",
"vortices"
);
/** Words that change from "-u" to "-us" (like "emu" etc.), listed in their plural forms*/
public static Set<String> categoryU_US=new FinalSet<String>(
"apercus",
"barbus",
"cornus",
"ecrus",
"emus",
"fondus",
"gnus",
"iglus",
"mus",
"nandus",
"napus",
"poilus",
"quipus",
"snafus",
"tabus",
"tamandus",
"tatus",
"timucus",
"tiramisus",
"tofus",
"tutus"
);
/** Words that change from "-sse" to "-sses" (like "finesse" etc.), listed in their plural forms*/
public static Set<String> categorySSE_SSES=new FinalSet<String>(
//plus those ending in mousse
"bouillabaisses",
"coulisses",
"crevasses",
"crosses",
"cuisses",
"demitasses",
"ecrevisses",
"fesses",
"finesses",
"fosses",
"impasses",
"lacrosses",
"largesses",
"masses",
"noblesses",
"palliasses",
"pelisses",
"politesses",
"posses",
"tasses",
"wrasses"
);
/** Words that change from "-che" to "-ches" (like "brioche" etc.), listed in their plural forms*/
public static Set<String> categoryCHE_CHES=new FinalSet<String>(
"adrenarches",
"attaches",
"avalanches",
"barouches",
"brioches",
"caches",
"caleches",
"caroches",
"cartouches",
"cliches",
"cloches",
"creches",
"demarches",
"douches",
"gouaches",
"guilloches",
"headaches",
"heartaches",
"huaraches",
"menarches",
"microfiches",
"moustaches",
"mustaches",
"niches",
"panaches",
"panoches",
"pastiches",
"penuches",
"pinches",
"postiches",
"psyches",
"quiches",
"schottisches",
"seiches",
"soutaches",
"synecdoches",
"thelarches",
"troches"
);
/** Words that end with "-ics" and do not exist as nouns without the 's' (like "aerobics" etc.)*/
public static Set<String> categoryICS=new FinalSet<String>(
"aerobatics",
"aerobics",
"aerodynamics",
"aeromechanics",
"aeronautics",
"alphanumerics",
"animatronics",
"apologetics",
"architectonics",
"astrodynamics",
"astronautics",
"astrophysics",
"athletics",
"atmospherics",
"autogenics",
"avionics",
"ballistics",
"bibliotics",
"bioethics",
"biometrics",
"bionics",
"bionomics",
"biophysics",
"biosystematics",
"cacogenics",
"calisthenics",
"callisthenics",
"catoptrics",
"civics",
"cladistics",
"cryogenics",
"cryonics",
"cryptanalytics",
"cybernetics",
"cytoarchitectonics",
"cytogenetics",
"diagnostics",
"dietetics",
"dramatics",
"dysgenics",
"econometrics",
"economics",
"electromagnetics",
"electronics",
"electrostatics",
"endodontics",
"enterics",
"ergonomics",
"eugenics",
"eurhythmics",
"eurythmics",
"exodontics",
"fibreoptics",
"futuristics",
"genetics",
"genomics",
"geographics",
"geophysics",
"geopolitics",
"geriatrics",
"glyptics",
"graphics",
"gymnastics",
"hermeneutics",
"histrionics",
"homiletics",
"hydraulics",
"hydrodynamics",
"hydrokinetics",
"hydroponics",
"hydrostatics",
"hygienics",
"informatics",
"kinematics",
"kinesthetics",
"kinetics",
"lexicostatistics",
"linguistics",
"lithoglyptics",
"liturgics",
"logistics",
"macrobiotics",
"macroeconomics",
"magnetics",
"magnetohydrodynamics",
"mathematics",
"metamathematics",
"metaphysics",
"microeconomics",
"microelectronics",
"mnemonics",
"morphophonemics",
"neuroethics",
"neurolinguistics",
"nucleonics",
"numismatics",
"obstetrics",
"onomastics",
"orthodontics",
"orthopaedics",
"orthopedics",
"orthoptics",
"paediatrics",
"patristics",
"patristics",
"pedagogics",
"pediatrics",
"periodontics",
"pharmaceutics",
"pharmacogenetics",
"pharmacokinetics",
"phonemics",
"phonetics",
"phonics",
"photomechanics",
"physiatrics",
"pneumatics",
"poetics",
"politics",
"pragmatics",
"prosthetics",
"prosthodontics",
"proteomics",
"proxemics",
"psycholinguistics",
"psychometrics",
"psychonomics",
"psychophysics",
"psychotherapeutics",
"robotics",
"semantics",
"semiotics",
"semitropics",
"sociolinguistics",
"stemmatics",
"strategics",
"subtropics",
"systematics",
"tectonics",
"telerobotics",
"therapeutics",
"thermionics",
"thermodynamics",
"thermostatics"
);
/** Words that change from "-ie" to "-ies" (like "auntie" etc.), listed in their plural forms*/
public static Set<String> categoryIE_IES=new FinalSet<String>(
"aeries",
"anomies",
"aunties",
"baddies",
"beanies",
"birdies",
"boccies",
"bogies",
"bolshies",
"bombies",
"bonhomies",
"bonxies",
"booboisies",
"boogies",
"boogie-woogies",
"bookies",
"booties",
"bosies",
"bourgeoisies",
"brasseries",
"brassies",
"brownies",
"budgies",
"byrnies",
"caddies",
"calories",
"camaraderies",
"capercaillies",
"capercailzies",
"cassies",
"catties",
"causeries",
"charcuteries",
"chinoiseries",
"collies",
"commies",
"cookies",
"coolies",
"coonties",
"cooties",
"corries",
"coteries",
"cowpies",
"cowries",
"cozies",
"crappies",
"crossties",
"curies",
"dachsies",
"darkies",
"dassies",
"dearies",
"dickies",
"dies",
"dixies",
"doggies",
"dogies",
"dominies",
"dovekies",
"eyries",
"faeries",
"falsies",
"floozies",
"folies",
"foodies",
"freebies",
"gaucheries",
"gendarmeries",
"genies",
"ghillies",
"gillies",
"goalies",
"goonies",
"grannies",
"grotesqueries",
"groupies",
"hankies",
"hippies",
"hoagies",
"honkies",
"hymies",
"indies",
"junkies",
"kelpies",
"kilocalories",
"knobkerries",
"koppies",
"kylies",
"laddies",
"lassies",
"lies",
"lingeries",
"magpies",
"magpies",
"marqueteries",
"mashies",
"mealies",
"meanies",
"menageries",
"millicuries",
"mollies",
"facts1",
"moxies",
"neckties",
"newbies",
"nighties",
"nookies",
"oldies",
"organdies",
"panties",
"parqueteries",
"passementeries",
"patisseries",
"pies",
"pinkies",
"pixies",
"porkpies",
"potpies",
"prairies",
"preemies",
"premies",
"punkies",
"pyxies",
"quickies",
"ramies",
"reveries",
"rookies",
"rotisseries",
"scrapies",
"sharpies",
"smoothies",
"softies",
"stoolies",
"stymies",
"swaggies",
"sweeties",
"talkies",
"techies",
"ties",
"tooshies",
"toughies",
"townies",
"veggies",
"walkie-talkies",
"wedgies",
"weenies",
"weirdies",
"yardies",
"yuppies",
"zombies"
);
/** Maps irregular Germanic English plural nouns to their singular form */
public static Map<String,String> irregular=new FinalMap<String,String>(
"beefs","beef",
"beeves","beef",
"brethren","brother",
"busses","bus",
"cattle","cattlebeast",
"children","child",
"corpora","corpus",
"ephemerides","ephemeris",
"firemen","fireman",
"genera","genus",
"genies","genie",
"genii","genie",
"kine","cow",
"lice","louse",
"men","man",
"mice","mouse",
"mongooses","mongoose",
"monies","money",
"mythoi","mythos",
"octopodes","octopus",
"octopuses","octopus",
"oxen","ox",
"people","person",
"soliloquies","soliloquy",
"throes","throes",
"trilbys","trilby",
"women","woman"
);
/** Contains word forms that can either be plural or singular */
public static Set<String> singAndPlur=new FinalSet<String>(
"acoustics",
"aestetics",
"aquatics",
"basics",
"ceramics",
"classics",
"cosmetics",
"dermatoglyphics",
"dialectics",
"dynamics",
"esthetics",
"ethics",
"harmonics",
"heroics",
"isometrics",
"mechanics",
"metrics",
"statistics",
"optic",
"people",
"physics",
"polemics",
"premises",
"propaedeutics",
"pyrotechnics",
"quadratics",
"quarters",
"statistics",
"tactics",
"tropics"
);
}
| 24.633663 | 118 | 0.551268 |
7ef26593830b4a4127c700737b4ba8ffab6e9ade | 2,063 | package sword.chap4;
import java.util.HashMap;
import java.util.Map;
/**
* @author wenghengcong
* @className: StringPermutation
* @desc:
* @date 2019-07-2917:20
*/
/**
* 给定两个字符串,请设计一个方法来判定其中一个字符串是否为另一个字符串的置换。
* 置换的意思是,通过改变顺序可以使得两个字符串相等。
*
* 题目:https://www.lintcode.com/problem/string-permutation/
*
* */
public class StringPermutation {
/**
* (1)判断A,B两个字符串长度是否相同。不相同返回false.
* (2)用map记录A中每个字符的个数
* (3)遍历B中的每个字符,map中个数-1,为0移出map
* (4)判断map长度,如果长度为0,返回true,否则返回false.
* */
public static boolean stringPermutation(String A, String B) {
if (A.equals("") && B.equals("")) {
return true;
}
if (A.length() != B.length()) {
return false;
}
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < B.length(); i++) {
if (!map.containsKey(B.charAt(i))) {
map.put(B.charAt(i), 1);
} else {
map.put(B.charAt(i), map.get(B.charAt(i)) + 1);
}
}
for (int i = 0; i < A.length(); i++) {
if (map.containsKey(A.charAt(i))) {
if (map.get(A.charAt(i)) == 1) {
map.remove(A.charAt(i));
} else {
map.put(A.charAt(i), map.get(A.charAt(i)) - 1);
}
}
}
return map.size() == 0;
}
/**
* 建立一个数组,记录字母出现的次数
* */
public boolean stringPermutation2(String A, String B) {
if(A==null && B==null) {
return true;
}
if(A==null || B==null) {
return false;
}
if(A.length() !=B.length()) {
return false;
}
int[] cnt = new int[256];
for (int i = 0; i < A.length(); i++) {
cnt[(int) A.charAt(i)] += 1;
cnt[(int) B.charAt(i)] -= 1;
}
for (int i = 0; i < 256; ++i) {
if (cnt[i] != 0) {
return false;
}
}
return true;
}
}
| 23.988372 | 72 | 0.457101 |
5dac2ec824cbed0cbd3b8295c9e58e77fabf3496 | 2,275 | package com.google.zxing.encoding;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.activity.Callback;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.util.Hashtable;
public final class EncodeHandler {
/**
* 根据字符串生成二维码图片
*
* @param text 要生成的字符串
* @param length 生成的图片边长
*/
@SuppressLint("StaticFieldLeak")
public static void createQRCode(String text, int length, final Callback<Bitmap> callback) {
new AsyncTask<Object, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Object... params) {
String text = (String) params[0];
int length = (int) params[1];
try {
Hashtable<EncodeHintType, String> hints = new Hashtable<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix matrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, length, length, hints);
int[] pixels = new int[length * length];
for (int y = 0; y < length; y++) {
for (int x = 0; x < length; x++) {
if (matrix.get(x, y)) {
pixels[y * length + x] = Color.BLACK;
} else {
pixels[y * length + x] = Color.WHITE;
}
}
}
Bitmap bitmap = Bitmap.createBitmap(length, length, Bitmap.Config.RGB_565);
bitmap.setPixels(pixels, 0, length, 0, 0, length, length);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (callback != null) {
callback.onEvent(bitmap);
}
}
}.execute(text, length);
}
}
| 35 | 117 | 0.517802 |
23688e74241002b607757a1cfe5ecd63558d82e0 | 4,026 | package no.entra.bacnet.agent.commands.cov;
import no.entra.bacnet.json.bvlc.BvlcFunction;
import no.entra.bacnet.objects.ObjectId;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import static no.entra.bacnet.internal.objects.ObjectIdMapper.toHexString;
import static no.entra.bacnet.json.apdu.SDContextTag.*;
import static no.entra.bacnet.json.objects.PduType.ConfirmedRequest;
import static no.entra.bacnet.json.services.ConfirmedServiceChoice.SubscribeCov;
import static no.entra.bacnet.json.utils.HexUtils.octetFromInt;
import static org.slf4j.LoggerFactory.getLogger;
/*
Subscribe to a single parameter for Change of Value(COV)
*/
public class UnConfirmedSubscribeCovCommand extends SubscribeCovCommand {
private static final Logger log = getLogger(UnConfirmedSubscribeCovCommand.class);
public static final String UNCONFIRMED = "00";
public UnConfirmedSubscribeCovCommand(InetAddress sendToAddress, int subscriptionId, ObjectId subscribeToSensorId) throws IOException {
super(sendToAddress, subscriptionId, subscribeToSensorId);
}
public UnConfirmedSubscribeCovCommand(DatagramSocket socket, InetAddress sendToAddress, int subscriptionId, ObjectId subscribeToSensorId) throws IOException {
super(socket, sendToAddress, subscriptionId, subscribeToSensorId);
}
@Override
protected String buildHexString() {
ObjectId deviceSensorId = getSubscribeToSensorIds().get(0);
return buildUnConfirmedCovSingleRequest(deviceSensorId);
}
/**
* Create HexString for a Confirmed COV Request to local net, and a single sensor.
* @return hexString with bvlc, npdu and apdu
* @param deviceSensorId
*/
protected String buildUnConfirmedCovSingleRequest(ObjectId deviceSensorId) {
String hexString = null;
String objectIdHex = toHexString(deviceSensorId);
String confirmEveryNotification = UNCONFIRMED;
String lifetimeHex = octetFromInt(0).toString(); //indefinite
String pduTypeHex = ConfirmedRequest.getPduTypeChar() + "0";
String serviceChoiceHex = SubscribeCov.getServiceChoiceHex();
String invokeIdHex = getInvokeId().toString();
String maxApduLengthHex = "02"; //TODO need to be able to set this.;
//When a client have multiple processes subscribing to the server. Use this parameter to route notifications to the
//corresponding client process. - Not much in use in a Java implementation.
String subscriberProcessIdentifier = getSubscriptionIdHex().toString();
String apdu = pduTypeHex + maxApduLengthHex + invokeIdHex + serviceChoiceHex + TAG0LENGTH1 +
subscriberProcessIdentifier + TAG1LENGTH4 + objectIdHex + TAG2LENGTH1 +
confirmEveryNotification + TAG3LENGTH1 + lifetimeHex;
/*
00 = PDUType = 0
02 = Max APDU size = 206
0f = invoke id = 15 // Identify multiple messages/segments for the same request.
05 = Service Choice 5 - SubscribeCOV-Request
09 = SD Context Tag 0, Subscriber Process Identifier, Length = 1
12 = 18 integer
1c = SD context Tag 1, Monitored Object Identifier, Length = 4
00000000 = Analog Input, Instance 0
29 = SD context Tag 2, Issue Confirmed Notification, Length = 1
01 = True, 00 = false
39 = SD context Tag 3, Lifetime, Length = 1
00 = 0 integer == indefinite
*/
String npdu = "0120ffff00ff"; //TODO need to objectify this.
int numberOfOctets = (apdu.length() + npdu.length() + 8) / 2;
String messageLength = Integer.toHexString(numberOfOctets);
if (numberOfOctets <= 255) {
messageLength = "00" + messageLength;
}
String bvlc = "81" + BvlcFunction.OriginalUnicastNpdu.getBvlcFunctionHex() + messageLength;
hexString = bvlc + npdu + apdu;
log.debug("Hex to send: {}", hexString);
return hexString;
}
}
| 46.275862 | 162 | 0.712618 |
b3d4f05e4c8580656b16c78186e338d524c2a44a | 1,234 | package com.sy.spring.cloud.alibaba.generator.message;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author sy
* @date Created in 2020.4.26 15:03
* @description 启动类
*/
@EnableSwagger2
@SpringBootApplication
@EnableDiscoveryClient
@EnableAsync
@MapperScan(basePackages = "com.sy.spring.cloud.alibaba.generator.message")
@ComponentScan(basePackages = {"com.sy.spring.cloud.alibaba.generator.message", "com.sy.spring.cloud.alibaba.provider.basic"})
@EnableCaching
@EnableBinding({Source.class})
public class BusRocketMQApplication {
public static void main(String[] args) {
SpringApplication.run(BusRocketMQApplication.class, args);
}
}
| 37.393939 | 126 | 0.822528 |
3d42307d7da9df303b69b21a5ee44f88bedfd548 | 11,619 | /*
* Copyright (c) 2019 Bixbit - Krzysztof Benedyczak. All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.saml.sp.web.authnEditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;
import pl.edu.icm.unity.Constants;
import pl.edu.icm.unity.engine.api.msg.UnityMessageSource;
import pl.edu.icm.unity.engine.api.translation.TranslationProfileGenerator;
import pl.edu.icm.unity.exceptions.InternalException;
import pl.edu.icm.unity.saml.SamlProperties;
import pl.edu.icm.unity.saml.SamlProperties.Binding;
import pl.edu.icm.unity.saml.sp.SAMLSPProperties;
import pl.edu.icm.unity.types.I18nString;
import pl.edu.icm.unity.types.translation.TranslationProfile;
import pl.edu.icm.unity.webui.authn.CommonWebAuthnProperties;
/**
* SAML Individual trusted idp configuration
* @author P.Piernik
*
*/
public class IndividualTrustedSamlIdpConfiguration
{
private String name;
private TranslationProfile translationProfile;
private String id;
private I18nString displayedName;
private String logo;
private String address;
private Binding binding;
private List<String> certificates;
private String registrationForm;
private boolean accountAssociation;
private boolean signRequest;
private List<String> requestedNameFormats;
private String postLogoutEndpoint;
private String postLogoutResponseEndpoint;
private String redirectLogoutEndpoint;
private String redirectLogoutResponseEndpoint;
private String soapLogoutEndpoint;
public IndividualTrustedSamlIdpConfiguration()
{
setBinding(SAMLSPProperties.DEFAULT_IDP_BINDING);
setTranslationProfile(TranslationProfileGenerator.generateEmptyInputProfile());
}
public void fromProperties(UnityMessageSource msg, SAMLSPProperties source, String name)
{
setName(name);
String prefix = SAMLSPProperties.IDP_PREFIX + name + ".";
setId(source.getValue(prefix + SAMLSPProperties.IDP_ID));
setDisplayedName(source.getLocalizedString(msg, prefix + SAMLSPProperties.IDP_NAME));
setLogo(source.getValue(prefix + SAMLSPProperties.IDP_LOGO));
if (source.isSet(prefix + SAMLSPProperties.IDP_BINDING))
{
setBinding(source.getEnumValue(prefix + SAMLSPProperties.IDP_BINDING, Binding.class));
}
setAddress(source.getValue(prefix + SAMLSPProperties.IDP_ADDRESS));
certificates = new ArrayList<>();
if (source.isSet(prefix + SAMLSPProperties.IDP_CERTIFICATE))
{
certificates.add(source.getValue(prefix + SAMLSPProperties.IDP_CERTIFICATE));
}
List<String> certs = source.getListOfValues(prefix + SAMLSPProperties.IDP_CERTIFICATES);
certs.forEach(
c -> {
certificates.add(c);
});
setRegistrationForm(source.getValue(prefix + CommonWebAuthnProperties.REGISTRATION_FORM));
if (source.isSet(prefix + CommonWebAuthnProperties.ENABLE_ASSOCIATION))
{
setAccountAssociation(
source.getBooleanValue(prefix + CommonWebAuthnProperties.ENABLE_ASSOCIATION));
}
if (source.isSet(prefix + SAMLSPProperties.IDP_SIGN_REQUEST))
{
setSignRequest(source.getBooleanValue(prefix + SAMLSPProperties.IDP_SIGN_REQUEST));
}
String reqNameFormat = source.getValue(prefix + SAMLSPProperties.IDP_REQUESTED_NAME_FORMAT);
setRequestedNameFormats(reqNameFormat != null ? Arrays.asList(reqNameFormat) : null);
setPostLogoutEndpoint(source.getValue(prefix + SamlProperties.POST_LOGOUT_URL));
setPostLogoutResponseEndpoint(source.getValue(prefix + SamlProperties.POST_LOGOUT_RET_URL));
setRedirectLogoutEndpoint(source.getValue(prefix + SamlProperties.REDIRECT_LOGOUT_URL));
setRedirectLogoutResponseEndpoint(source.getValue(prefix + SamlProperties.REDIRECT_LOGOUT_RET_URL));
setSoapLogoutEndpoint(source.getValue(prefix + SamlProperties.SOAP_LOGOUT_URL));
if (source.isSet(prefix + CommonWebAuthnProperties.EMBEDDED_TRANSLATION_PROFILE))
{
setTranslationProfile(TranslationProfileGenerator.getProfileFromString(source
.getValue(prefix + CommonWebAuthnProperties.EMBEDDED_TRANSLATION_PROFILE)));
} else if (source.isSet(prefix + CommonWebAuthnProperties.TRANSLATION_PROFILE))
{
setTranslationProfile(TranslationProfileGenerator.generateIncludeInputProfile(
source.getValue(prefix + CommonWebAuthnProperties.TRANSLATION_PROFILE)));
}
}
public void toProperties(Properties raw)
{
String prefix = SAMLSPProperties.P + SAMLSPProperties.IDP_PREFIX + getName() + ".";
raw.put(prefix + SAMLSPProperties.IDP_ID, getId());
if (getDisplayedName() != null)
{
getDisplayedName().toProperties(raw, prefix + SAMLSPProperties.IDP_NAME + ".");
}
if (getLogo() != null)
{
raw.put(prefix + SAMLSPProperties.IDP_LOGO, getLogo());
}
if (getBinding() != null)
{
raw.put(prefix + SAMLSPProperties.IDP_BINDING, getBinding().toString());
}
if (getAddress() != null)
{
raw.put(prefix + SAMLSPProperties.IDP_ADDRESS, getAddress());
}
if (requestedNameFormats != null)
{
requestedNameFormats.stream()
.forEach(f -> raw.put(prefix + SAMLSPProperties.IDP_REQUESTED_NAME_FORMAT, f));
}
if (certificates != null && !certificates.isEmpty())
{
certificates.forEach(c -> raw.put(
prefix + SAMLSPProperties.IDP_CERTIFICATES + (certificates.indexOf(c) + 1), c));
}
if (getRegistrationForm() != null)
{
raw.put(prefix + CommonWebAuthnProperties.REGISTRATION_FORM, getRegistrationForm());
}
raw.put(prefix + CommonWebAuthnProperties.ENABLE_ASSOCIATION, String.valueOf(isAccountAssociation()));
raw.put(prefix + SAMLSPProperties.IDP_SIGN_REQUEST, String.valueOf(isSignRequest()));
if (getPostLogoutEndpoint() != null)
{
raw.put(prefix + SamlProperties.POST_LOGOUT_URL, getPostLogoutEndpoint());
}
if (getPostLogoutResponseEndpoint() != null)
{
raw.put(prefix + SamlProperties.POST_LOGOUT_RET_URL, getPostLogoutResponseEndpoint());
}
if (getRedirectLogoutEndpoint() != null)
{
raw.put(prefix + SamlProperties.REDIRECT_LOGOUT_URL, getRedirectLogoutEndpoint());
}
if (getRedirectLogoutResponseEndpoint() != null)
{
raw.put(prefix + SamlProperties.REDIRECT_LOGOUT_RET_URL, getRedirectLogoutResponseEndpoint());
}
if (getSoapLogoutEndpoint() != null)
{
raw.put(prefix + SamlProperties.SOAP_LOGOUT_URL, getSoapLogoutEndpoint());
}
try
{
raw.put(prefix + SAMLSPProperties.IDPMETA_EMBEDDED_TRANSLATION_PROFILE,
Constants.MAPPER.writeValueAsString(getTranslationProfile().toJsonObject()));
} catch (Exception e)
{
throw new InternalException("Can't serialize provider's translation profile to JSON", e);
}
}
public IndividualTrustedSamlIdpConfiguration clone()
{
IndividualTrustedSamlIdpConfiguration clone = new IndividualTrustedSamlIdpConfiguration();
clone.setName(this.getName());
clone.setId(new String(this.getId()));
clone.setLogo(this.getLogo() != null ? new String(this.getLogo()) : null);
clone.setBinding(this.getBinding() != null ? Binding.valueOf(this.getBinding().toString()) : null);
clone.setTranslationProfile(
this.getTranslationProfile() != null ? this.getTranslationProfile().clone() : null);
clone.setDisplayedName(this.getDisplayedName() != null ? this.getDisplayedName().clone() : null);
clone.setAddress(this.getAddress() != null ? new String(this.getAddress()) : null);
clone.setCertificates(this.getCertificates() != null
? this.getCertificates().stream().map(s -> new String(s)).collect(Collectors.toList())
: null);
clone.setAccountAssociation(new Boolean(this.isAccountAssociation()));
clone.setSignRequest(new Boolean(this.isSignRequest()));
clone.setRegistrationForm(
this.getRegistrationForm() != null ? new String(this.getRegistrationForm()) : null);
clone.setRequestedNameFormats(
this.getRequestedNameFormats() != null
? this.getRequestedNameFormats().stream().map(f -> new String(f))
.collect(Collectors.toList())
: null);
clone.setPostLogoutEndpoint(
this.getPostLogoutEndpoint() != null ? new String(this.getPostLogoutEndpoint()) : null);
clone.setPostLogoutResponseEndpoint(this.getPostLogoutResponseEndpoint() != null
? new String(this.getPostLogoutResponseEndpoint())
: null);
clone.setRedirectLogoutEndpoint(
this.getRedirectLogoutEndpoint() != null ? new String(this.getRedirectLogoutEndpoint())
: null);
clone.setRedirectLogoutResponseEndpoint(this.getRedirectLogoutResponseEndpoint() != null
? new String(this.getRedirectLogoutResponseEndpoint())
: null);
clone.setSoapLogoutEndpoint(
this.getSoapLogoutEndpoint() != null ? new String(this.getSoapLogoutEndpoint()) : null);
return clone;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public TranslationProfile getTranslationProfile()
{
return translationProfile;
}
public void setTranslationProfile(TranslationProfile translationProfile)
{
this.translationProfile = translationProfile;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public I18nString getDisplayedName()
{
return displayedName;
}
public void setDisplayedName(I18nString displayedName)
{
this.displayedName = displayedName;
}
public String getLogo()
{
return logo;
}
public void setLogo(String logo)
{
this.logo = logo;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public Binding getBinding()
{
return binding;
}
public void setBinding(Binding binding)
{
this.binding = binding;
}
public List<String> getCertificates()
{
return certificates;
}
public void setCertificates(List<String> certificates)
{
this.certificates = certificates;
}
public String getRegistrationForm()
{
return registrationForm;
}
public void setRegistrationForm(String registrationForm)
{
this.registrationForm = registrationForm;
}
public boolean isAccountAssociation()
{
return accountAssociation;
}
public void setAccountAssociation(boolean accountAssociation)
{
this.accountAssociation = accountAssociation;
}
public boolean isSignRequest()
{
return signRequest;
}
public void setSignRequest(boolean signRequest)
{
this.signRequest = signRequest;
}
public List<String> getRequestedNameFormats()
{
return requestedNameFormats;
}
public void setRequestedNameFormats(List<String> requestedNameFormats)
{
this.requestedNameFormats = requestedNameFormats;
}
public String getPostLogoutEndpoint()
{
return postLogoutEndpoint;
}
public void setPostLogoutEndpoint(String postLogoutEndpoint)
{
this.postLogoutEndpoint = postLogoutEndpoint;
}
public String getPostLogoutResponseEndpoint()
{
return postLogoutResponseEndpoint;
}
public void setPostLogoutResponseEndpoint(String postLogoutResponseEndpoint)
{
this.postLogoutResponseEndpoint = postLogoutResponseEndpoint;
}
public String getRedirectLogoutEndpoint()
{
return redirectLogoutEndpoint;
}
public void setRedirectLogoutEndpoint(String redirectLogoutEndpoint)
{
this.redirectLogoutEndpoint = redirectLogoutEndpoint;
}
public String getRedirectLogoutResponseEndpoint()
{
return redirectLogoutResponseEndpoint;
}
public void setRedirectLogoutResponseEndpoint(String redirectLogoutResponseEndpoint)
{
this.redirectLogoutResponseEndpoint = redirectLogoutResponseEndpoint;
}
public String getSoapLogoutEndpoint()
{
return soapLogoutEndpoint;
}
public void setSoapLogoutEndpoint(String soapLogoutEndpoint)
{
this.soapLogoutEndpoint = soapLogoutEndpoint;
}
}
| 28.759901 | 104 | 0.766417 |
368fe8589a42c2aac58d135508bb6b48c285c987 | 4,410 | package org.yaoqiang.bpmn.editor.dialog.jsonpanels;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.naming.directory.Attributes;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import org.json.JSONException;
import org.json.JSONObject;
import org.yaoqiang.bpmn.editor.BPMNEditor;
import org.yaoqiang.bpmn.editor.dialog.JSONComboPanel;
import org.yaoqiang.bpmn.editor.dialog.JSONPanel;
import org.yaoqiang.bpmn.editor.dialog.JSONTextPanel;
import org.yaoqiang.bpmn.editor.dialog.PanelContainer;
import org.yaoqiang.bpmn.editor.dialog.ldaptree.LdapTreeNode;
import org.yaoqiang.bpmn.editor.util.LdapUtils;
import com.mxgraph.util.mxResources;
/**
* SearchLdapPanel
*
* @author Shi Yaoqiang([email protected])
*/
public class SearchLdapPanel extends JSONPanel {
private static final long serialVersionUID = 1L;
protected JSONObject con = BPMNEditor.getInstance().getCurrentLdapConnection();
protected JSONTextPanel connectionPanel;
protected JSONTextPanel urlPanel;
protected JSONTextPanel baseDNPanel;
protected JSONComboPanel scopePanel;
protected JSONTextPanel timelimitPanel;
protected JSONTextPanel countlimitPanel;
protected JSONTextPanel filterPanel;
public SearchLdapPanel(final PanelContainer pc, final BPMNEditor owner) {
super(pc, owner);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
String baseDN = owner.getLdapSelectedEntry();
if (baseDN.length() == 0) {
baseDN = con.optString("baseDN");
}
JPanel ldapPanel = new JPanel();
ldapPanel.setLayout(new BoxLayout(ldapPanel, BoxLayout.Y_AXIS));
ldapPanel.setBorder(BorderFactory.createTitledBorder(mxResources.get("ldapServer")));
connectionPanel = new JSONTextPanel(pc, null, "connection", false, null, con.optString("name"), 180, 26, false);
urlPanel = new JSONTextPanel(pc, null, "URL", false, null, con.optString("url"), 180, 26, false);
JPanel a1Panel = new JPanel();
a1Panel.setLayout(new BoxLayout(a1Panel, BoxLayout.X_AXIS));
a1Panel.add(connectionPanel);
a1Panel.add(urlPanel);
ldapPanel.add(a1Panel);
baseDNPanel = new JSONTextPanel(pc, null, "baseDN", false, baseDN);
ldapPanel.add(baseDNPanel);
this.add(ldapPanel);
JPanel searchPanel = new JPanel();
searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.Y_AXIS));
searchPanel.setBorder(BorderFactory.createTitledBorder(mxResources.get("searchOptions")));
List<String> choices = new ArrayList<String>();
choices.add("Subtree");
choices.add("One level");
choices.add("Base");
scopePanel = new JSONComboPanel(pc, owner, "scope", choices, false, false, true);
timelimitPanel = new JSONTextPanel(pc, null, "timeout", false, 20, 26, "0");
countlimitPanel = new JSONTextPanel(pc, null, "countlimit", false, 20, 26, "0");
JPanel a3Panel = new JPanel();
a3Panel.setLayout(new BoxLayout(a3Panel, BoxLayout.X_AXIS));
a3Panel.add(scopePanel);
a3Panel.add(timelimitPanel);
a3Panel.add(countlimitPanel);
searchPanel.add(a3Panel);
filterPanel = new JSONTextPanel(pc, null, "filter", false, "(objectClass=*)");
searchPanel.add(filterPanel);
this.add(searchPanel);
}
public void saveObjects() {
if (con == null) {
return;
}
Map<String, Attributes> results = LdapUtils.searchLdap(con.optString("protocol").substring(6), urlPanel.getText(), baseDNPanel.getText(), scopePanel
.getSelectedItem().toString(), filterPanel.getText(), Long.parseLong(countlimitPanel.getText()),
Integer.parseInt(timelimitPanel.getText()) * 1000, !con.optBoolean("useSecurityCredentials"), con.optString("userDN"), con
.optString("password"));
if (!results.isEmpty()) {
try {
con.put("scope", scopePanel.getSelectedItem().toString());
con.put("filter", filterPanel.getText());
con.put("countlimit", countlimitPanel.getText());
con.put("timelimit", timelimitPanel.getText());
} catch (JSONException e) {
e.printStackTrace();
}
BPMNEditor.getInstance().setCurrentLdapConnection(con);
BPMNEditor.getInstance().getLdapConnectionTextPanel().setText(con.optString("name"));
Map<String, LdapTreeNode> nodes = LdapUtils.buildLdapTreeNodes(baseDNPanel.getText(), results);
BPMNEditor.getInstance().resetLdapTree(new LdapTreeNode[] { nodes.get(baseDNPanel.getText()), nodes.get(baseDNPanel.getText()) });
BPMNEditor.setLdapEntries(results);
}
}
}
| 33.923077 | 150 | 0.75102 |
fc1da7cb82c5cc5e73ec70a2e93e1a90e8b18462 | 3,183 | /*
* Java Information Dynamics Toolkit (JIDT)
* Copyright (C) 2012, Joseph T. Lizier
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package infodynamics.demos;
import infodynamics.utils.RandomGenerator;
import infodynamics.measures.continuous.kraskov.TransferEntropyCalculatorKraskov;
/**
*
* = Example 7 - Ensemble method with transfer entropy on continuous data using Kraskov estimators =
*
* Calculation of transfer entropy (TE) by supplying an ensemble of
* samples from multiple time series.
* We use continuous-valued data using the Kraskov-estimator TE calculator
* here.
*
* @author Joseph Lizier
*
*/
public class Example7EnsembleMethodTeContinuousDataKraskov {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// Prepare to generate some random normalised data.
int numObservations = 1000;
double covariance = 0.4;
RandomGenerator rg = new RandomGenerator();
// Create a TE calculator and run it:
TransferEntropyCalculatorKraskov teCalc =
new TransferEntropyCalculatorKraskov();
teCalc.setProperty("k", "4"); // Use Kraskov parameter K=4 for 4 nearest neighbours
teCalc.initialise(1); // Use history length 1 (Schreiber k=1)
teCalc.startAddObservations();
for (int trial = 0; trial < 10; trial++) {
// Create a new trial, with destArray correlated to
// previous value of sourceArray:
double[] sourceArray = rg.generateNormalData(numObservations, 0, 1);
double[] destArray = rg.generateNormalData(numObservations, 0, 1-covariance);
for (int t = 1; t < numObservations; t++) {
destArray[t] += covariance * sourceArray[t-1];
}
// Add observations for this trial:
System.out.printf("Adding samples from trial %d ...\n", trial);
teCalc.addObservations(sourceArray, destArray);
}
// We've finished adding trials:
System.out.println("Finished adding trials");
teCalc.finaliseAddObservations();
// Compute the result:
System.out.println("Computing TE ...");
double result = teCalc.computeAverageLocalOfObservations();
// Note that the calculation is a random variable (because the generated
// data is a set of random variables) - the result will be of the order
// of what we expect, but not exactly equal to it; in fact, there will
// be some variance around it (smaller than example 4 since we have more samples).
System.out.printf("TE result %.4f nats; expected to be close to " +
"%.4f nats for these correlated Gaussians\n",
result, Math.log(1.0/(1-Math.pow(covariance,2))));
}
}
| 37.011628 | 100 | 0.717876 |
02f72a283965c67ed697e21756d15dc7f1a83ce3 | 7,461 | /*
* $Id$
* Copyright (C) 2006 Klaus Reimer <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package de.ailis.wlandsuite.huffman;
/**
* A Node in the Huffman tree.
*
* @author Klaus Reimer ([email protected])
* @version $Revision$
*/
public class HuffmanNode implements Comparable<HuffmanNode>
{
/** The left sub node */
private HuffmanNode left;
/** The right sub node */
private HuffmanNode right;
/** The parent node */
private HuffmanNode parent;
/** The node key (false = left, true = right) */
private boolean key;
/** The full node key */
private boolean[] fullKey;
/** The payload */
private final int payload;
/** The propability */
private int probability;
/** The id generator */
private static int nextId = 0;
/** The serial id */
private final int id = nextId++;
/**
* Constructor
*
* @param left
* The left sub node
* @param right
* The right sub node
*/
public HuffmanNode(final HuffmanNode left, final HuffmanNode right)
{
this.left = left;
if (this.left != null)
{
this.left.parent = this;
this.left.key = false;
}
this.right = right;
if (this.right != null)
{
this.right.parent = this;
this.right.key = true;
}
this.payload = -1;
this.probability = this.left.probability + this.right.probability;
}
/**
* Constructor
*
* @param payload
* The payload
*/
public HuffmanNode(final int payload)
{
this.payload = payload;
}
/**
* Constructor
*
* @param payload
* The payload
* @param probability
* The probability
*/
public HuffmanNode(final int payload, final int probability)
{
this.payload = payload;
this.probability = probability;
}
/**
* Returns the left.
*
* @return The left
*/
public HuffmanNode getLeft()
{
return this.left;
}
/**
* Returns the payload.
*
* @return The payload
*/
public int getPayload()
{
return this.payload;
}
/**
* Returns the right sub node.
*
* @return The right sub node
*/
public HuffmanNode getRight()
{
return this.right;
}
/**
* Returns the node key.
*
* @return The node key
*/
public boolean getKey()
{
return this.key;
}
/**
* Returns the parent node.
*
* @return The parent node
*/
public HuffmanNode getParent()
{
return this.parent;
}
/**
* Returns the full key of this node (Beginning from the root).
*
* @return The full key
*/
public boolean[] getFullKey()
{
HuffmanNode current;
int count;
int index;
// If there is already a cached full key then use it
if (this.fullKey == null)
{
// Find out how many key bits are needed for the full key
count = 0;
current = this;
while (current.parent != null)
{
count++;
current = current.parent;
}
// Build the full key
this.fullKey = new boolean[count];
current = this;
index = 0;
while (current.parent != null)
{
this.fullKey[index] = current.key;
current = current.parent;
index++;
}
}
return this.fullKey;
}
/**
* Returns the string representation of the node key. For the root node
* "ROOT" is returned
*
* @return The node key as a string
*/
public String getFullKeyName()
{
boolean[] fullKey;
StringBuilder builder;
if (this.parent == null)
{
return "ROOT";
}
fullKey = getFullKey();
builder = new StringBuilder(fullKey.length);
for (int i = fullKey.length - 1; i >= 0; i--)
{
builder.append(fullKey[i] ? '1' : '0');
}
return builder.toString();
}
/**
* Returns the probability.
*
* @return The probability
*/
public int getProbability()
{
return this.probability;
}
/**
* Compares to Huffman Nodes.
*
* @param other
* The other Huffman Node.
* @return The compare result
*/
@Override
public int compareTo(final HuffmanNode other)
{
if (this.probability < other.probability)
{
return 1;
}
else if (this.probability > other.probability)
{
return -1;
}
else
{
return (Integer.valueOf(this.id).compareTo(Integer
.valueOf(other.id)));
}
}
/**
* Dumps the current node into the given string builder. Output is indented
* by level*2 space characters. This method is used by toString() to
* recursively build a nice tree output.
*
* @param builder
* The string builder
* @param level
* The indent level
*/
private void dumpNode(final StringBuilder builder, final int level)
{
char[] indent;
indent = new char[level * 2];
for (int i = 0; i < level * 2; i++)
{
indent[i] = ' ';
}
builder.append(getFullKeyName());
if (this.payload == -1)
{
builder.append(":\n");
builder.append(indent);
builder.append(" Left -> ");
this.left.dumpNode(builder, level + 1);
builder.append('\n');
builder.append(indent);
builder.append(" Right -> ");
this.right.dumpNode(builder, level + 1);
}
else
{
builder.append(" = ");
builder.append(this.payload);
}
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
StringBuilder builder;
builder = new StringBuilder();
dumpNode(builder, 0);
return builder.toString();
}
}
| 21.944118 | 79 | 0.536925 |
082fcd5ad0fdb189b3e04cc25b4b193e8e61f298 | 710 | import java.util.HashMap;
//基本数据结构专题-LeetCode560.和为K的子数组
public class test005 {
/*
给定一个整数数组和一个整数 k,你需要找到该数组中和为 k 的连续的子数组的个数。
示例:
输入:nums = [1,1,1], k = 2
输出: 2 , [1,1] 与 [1,1] 为两种不同的情况。
注意,问题要求是连续的,所以输出的意思为 结果1:a[0],a[1]; 结果2:a[1],a[2]
*/
public int subarraySum(int[] nums, int k) {
HashMap<Integer, Integer> preSum = new HashMap<>();
int sum = 0, ans = 0;
preSum.put(0, 1);
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (preSum.containsKey(sum - k)) {
ans += preSum.get(sum - k);
}
preSum.put(sum, preSum.getOrDefault(sum, 0) + 1);
}
return ans;
}
}
| 26.296296 | 61 | 0.511268 |
f124f0ea017129310a9737a461af3be32bc0d47f | 1,856 | /***************************************************************************
* Copyright (C) 2018 iObserve Project (https://www.iobserve-devops.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
***************************************************************************/
package org.iobserve.model;
import java.util.Map;
import org.iobserve.model.privacy.EDataProtectionLevel;
/**
* @author Reiner Jung
*
*/
public class OperationSignatureDataProtection {
private final EDataProtectionLevel returnTypePrivacy;
private final Map<String, EDataProtectionLevel> parameterPrivacy;
/**
* Create a new operation signature privacy object.
*
* @param returnTypePrivacy
* privacy value for the return type
* @param parameterPrivacy
* privacy values for parameter types
*/
public OperationSignatureDataProtection(final EDataProtectionLevel returnTypePrivacy,
final Map<String, EDataProtectionLevel> parameterPrivacy) {
this.returnTypePrivacy = returnTypePrivacy;
this.parameterPrivacy = parameterPrivacy;
}
public final EDataProtectionLevel getReturnTypePrivacy() {
return this.returnTypePrivacy;
}
public final Map<String, EDataProtectionLevel> getParameterPrivacy() {
return this.parameterPrivacy;
}
}
| 34.37037 | 89 | 0.664332 |
2ea306afae9f0d96ec8205df79c2cfda3127e01d | 986 | package ooga.engine.physics.physicsCalculator;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AccelerationCalculatorTest {
private AccelerationCalculator ac=new AccelerationCalculator();
@Test
void getAX() {
// double initialXAcceleration, Double fx
double fx=10;
double initialXAcceleration=5;
assertEquals(15,ac.getAX(initialXAcceleration, fx));
assertEquals(5, ac.getAX(-initialXAcceleration, fx));
assertEquals(-15, ac.getAX(-initialXAcceleration, -fx));
assertEquals(-5, ac.getAX(initialXAcceleration, -fx));
}
@Test
void getAY() {
double fy=10;
double initialYAcceleration=5;
assertEquals(15,ac.getAY(initialYAcceleration, fy));
assertEquals(5, ac.getAY(-initialYAcceleration, fy));
assertEquals(-15, ac.getAY(-initialYAcceleration, -fy));
assertEquals(-5, ac.getAY(initialYAcceleration, -fy));
}
} | 30.8125 | 67 | 0.679513 |
d37ab27755182a19afbbb2353920b0aca6f702cb | 1,077 | package com.acme.test.vlingo.infrastructure.persistence;
import io.vlingo.xoom.annotation.persistence.Persistence;
import io.vlingo.xoom.annotation.persistence.Persistence.StorageType;
import io.vlingo.xoom.annotation.persistence.Projections;
import io.vlingo.xoom.annotation.persistence.Projection;
import io.vlingo.xoom.annotation.persistence.Adapters;
import io.vlingo.xoom.annotation.persistence.EnableQueries;
import io.vlingo.xoom.annotation.persistence.QueriesEntry;
import com.acme.test.vlingo.model.project.ProjectRenamed;
import com.acme.test.vlingo.model.project.ProjectDefined;
import com.acme.test.vlingo.model.project.ProjectState;
@Persistence(basePackage = "com.acme.test.vlingo", storageType = StorageType.JOURNAL, cqrs = true)
@Projections({
@Projection(actor = ProjectProjectionActor.class, becauseOf = {ProjectDefined.class, ProjectRenamed.class})
})
@Adapters({
ProjectRenamed.class,
ProjectDefined.class
})
@EnableQueries({
@QueriesEntry(protocol = ProjectQueries.class, actor = ProjectQueriesActor.class),
})
public class PersistenceSetup {
} | 38.464286 | 109 | 0.820799 |
e8d609226d4cea9adc7af9f3e1696f1cb5e1e407 | 18,056 | /*
* 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.axis2.description;
import edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axis2.AxisFault;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.i18n.Messages;
import org.apache.axis2.modules.Module;
import org.apache.axis2.util.JavaUtils;
import org.apache.axis2.util.Utils;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.axis2.wsdl.WSDLUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.neethi.Assertion;
import org.apache.neethi.Policy;
import javax.xml.stream.XMLStreamException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public abstract class AxisDescription implements ParameterInclude,
DescriptionConstants {
protected AxisDescription parent = null;
private ParameterInclude parameterInclude;
private PolicyInclude policyInclude = null;
private PolicySubject policySubject = null;
private Map children;
protected Map engagedModules;
/** List of ParameterObservers who want to be notified of changes */
protected List parameterObservers = null;
private OMFactory omFactory = OMAbstractFactory.getOMFactory();
// Holds the documentation details for each element
private OMNode documentation;
// creating a logger instance
private static Log log = LogFactory.getLog(AxisDescription.class);
public AxisDescription() {
parameterInclude = new ParameterIncludeImpl();
children = new ConcurrentHashMap();
policySubject = new PolicySubject();
}
public void addParameterObserver(ParameterObserver observer) {
if (parameterObservers == null)
parameterObservers = new ArrayList();
parameterObservers.add(observer);
}
public void removeParameterObserver(ParameterObserver observer) {
if (parameterObservers != null) {
parameterObservers.remove(observer);
}
}
public void addParameter(Parameter param) throws AxisFault {
if (param == null) {
return;
}
if (isParameterLocked(param.getName())) {
throw new AxisFault(Messages.getMessage("paramterlockedbyparent",
param.getName()));
}
parameterInclude.addParameter(param);
// Tell anyone who wants to know
if (parameterObservers != null) {
for (Iterator i = parameterObservers.iterator(); i.hasNext();) {
ParameterObserver observer = (ParameterObserver) i.next();
observer.parameterChanged(param.getName(), param.getValue());
}
}
}
public void addParameter(String name, Object value) throws AxisFault {
addParameter(new Parameter(name, value));
}
public void removeParameter(Parameter param) throws AxisFault {
parameterInclude.removeParameter(param);
}
public void deserializeParameters(OMElement parameterElement)
throws AxisFault {
parameterInclude.deserializeParameters(parameterElement);
}
/**
* If the parameter found in the current decription then the paremeter will
* be writable else it will be read only
*
* @param name
* @return
*/
public Parameter getParameter(String name) {
Parameter parameter = parameterInclude.getParameter(name);
if (parameter != null) {
parameter.setEditable(true);
return parameter;
}
if (parent != null) {
parameter = parent.getParameter(name);
if (parameter != null) {
parameter.setEditable(false);
}
return parameter;
}
return null;
}
public Object getParameterValue(String name) {
Parameter param = getParameter(name);
if (param == null) {
return null;
}
return param.getValue();
}
public boolean isParameterTrue(String name) {
Parameter param = getParameter(name);
return param != null && JavaUtils.isTrue(param.getValue());
}
public ArrayList getParameters() {
return parameterInclude.getParameters();
}
public boolean isParameterLocked(String parameterName) {
if (this.parent != null && this.parent.isParameterLocked(parameterName)) {
return true;
}
Parameter parameter = getParameter(parameterName);
return parameter != null && parameter.isLocked();
}
public String getDocumentation() {
if (documentation != null) {
if (documentation.getType() == OMNode.TEXT_NODE) {
return ((OMText) documentation).getText();
} else {
StringWriter writer = new StringWriter();
documentation.build();
try {
documentation.serialize(writer);
} catch (XMLStreamException e) {
log.error(e);
}
writer.flush();
return writer.toString();
}
}
return null;
}
public OMNode getDocumentationNode() {
return documentation;
}
public void setDocumentation(OMNode documentation) {
this.documentation = documentation;
}
public void setDocumentation(String documentation) {
if (!"".equals(documentation)) {
this.documentation = omFactory.createOMText(documentation);
}
}
public void setParent(AxisDescription parent) {
this.parent = parent;
}
public AxisDescription getParent() {
return parent;
}
/**
* @see org.apache.axis2.description.AxisDescription#setPolicyInclude(PolicyInclude)
* @deprecated As of release 1.4, if you want to access the policy cache of
* a particular AxisDescription object use
* {@line #getPolicySubject()} instead.
*
* @param policyInclude
*/
public void setPolicyInclude(PolicyInclude policyInclude) {
this.policyInclude = policyInclude;
}
/**
* @see org.apache.axis2.description.AxisDescription#getPolicySubject()
* @deprecated As of release 1.4, replaced by {@link #getPolicySubject()}
*/
public PolicyInclude getPolicyInclude() {
if (policyInclude == null) {
policyInclude = new PolicyInclude(this);
}
return policyInclude;
}
// NOTE - These are NOT typesafe!
public void addChild(AxisDescription child) {
if (child.getKey() == null) {
// FIXME: Several classes that extend AxisDescription pass null in their getKey method.
// throw new IllegalArgumentException("Please specify a key in the child");
} else {
children.put(child.getKey(), child);
}
}
public void addChild(Object key, AxisDescription child) {
children.put(key, child);
}
public Iterator getChildren() {
return children.values().iterator();
}
public AxisDescription getChild(Object key) {
if(key == null) {
// FIXME: Why are folks sending in null?
return null;
}
return (AxisDescription) children.get(key);
}
public void removeChild(Object key) {
children.remove(key);
}
/**
* This method sets the policy as the default of this AxisDescription
* instance. Further more this method does the followings. <p/> (1) Engage
* whatever modules necessary to execute new the effective policy of this
* AxisDescription instance. (2) Disengage whatever modules that are not
* necessary to execute the new effective policy of this AxisDescription
* instance. (3) Check whether each module can execute the new effective
* policy of this AxisDescription instance. (4) If not throw an AxisFault to
* notify the user. (5) Else notify each module about the new effective
* policy.
*
* @param policy
* the new policy of this AxisDescription instance. The effective
* policy is the merge of this argument with effective policy of
* parent of this AxisDescription.
* @throws AxisFault
* if any module is unable to execute the effective policy of
* this AxisDescription instance successfully or no module to
* execute some portion (one or more PrimtiveAssertions ) of
* that effective policy.
*/
public void applyPolicy(Policy policy) throws AxisFault {
// sets AxisDescription policy
getPolicySubject().clear();
getPolicySubject().attachPolicy(policy);
/*
* now we try to engage appropriate modules based on the merged policy
* of axis description object and the corresponding axis binding
* description object.
*/
applyPolicy();
}
/**
* Applies the policies on the Description Hierarchy recursively.
*
* @throws AxisFault
* an error occurred applying the policy
*/
public void applyPolicy() throws AxisFault {
AxisConfiguration configuration = getAxisConfiguration();
if (configuration == null) {
return;
}
Policy applicablePolicy = getApplicablePolicy(this);
if (applicablePolicy != null) {
engageModulesForPolicy(this, applicablePolicy, configuration);
}
for (Iterator children = getChildren(); children.hasNext();) {
AxisDescription child = (AxisDescription) children.next();
child.applyPolicy();
}
}
private boolean canSupportAssertion(Assertion assertion, List moduleList) {
AxisModule axisModule;
Module module;
for (Iterator iterator = moduleList.iterator(); iterator.hasNext();) {
axisModule = (AxisModule) iterator.next();
// FIXME is this step really needed ??
// Shouldn't axisMoudle.getModule always return not-null value ??
module = axisModule.getModule();
if (!(module == null || module.canSupportAssertion(assertion))) {
log.debug(axisModule.getName() + " says it can't support "
+ assertion.getName());
return false;
}
}
return true;
}
private void engageModulesForPolicy(AxisDescription axisDescription,
Policy policy, AxisConfiguration axisConfiguration)
throws AxisFault {
/*
* for the moment we consider policies with only one alternative. If the
* policy contains multiple alternatives only the first alternative will
* be considered.
*/
Iterator iterator = policy.getAlternatives();
if (!iterator.hasNext()) {
throw new AxisFault(
"Policy doesn't contain any policy alternatives");
}
List assertionList = (List) iterator.next();
Assertion assertion;
String namespaceURI;
List moduleList;
List namespaceList = new ArrayList();
List modulesToEngage = new ArrayList();
for (Iterator assertions = assertionList.iterator(); assertions
.hasNext();) {
assertion = (Assertion) assertions.next();
namespaceURI = assertion.getName().getNamespaceURI();
moduleList = axisConfiguration
.getModulesForPolicyNamesapce(namespaceURI);
if (moduleList == null) {
log.debug("can't find any module to process "
+ assertion.getName() + " type assertions");
continue;
}
if (!canSupportAssertion(assertion, moduleList)) {
throw new AxisFault("atleast one module can't support "
+ assertion.getName());
}
if (!namespaceList.contains(namespaceURI)) {
namespaceList.add(namespaceURI);
modulesToEngage.addAll(moduleList);
}
}
engageModulesToAxisDescription(modulesToEngage, this);
}
private void engageModulesToAxisDescription(List moduleList,
AxisDescription description) throws AxisFault {
AxisModule axisModule;
Module module;
for (Iterator iterator = moduleList.iterator(); iterator.hasNext();) {
axisModule = (AxisModule) iterator.next();
// FIXME is this step really needed ??
// Shouldn't axisMoudle.getModule always return not-null value ??
module = axisModule.getModule();
if (!(module == null || description.isEngaged(axisModule.getName()))) {
// engages the module to AxisDescription
description.engageModule(axisModule);
// notifies the module about the engagement
axisModule.getModule().engageNotify(description);
}
}
}
public AxisConfiguration getAxisConfiguration() {
if (this instanceof AxisConfiguration) {
return (AxisConfiguration) this;
}
if (this.parent != null) {
return this.parent.getAxisConfiguration();
}
return null;
}
public abstract Object getKey();
/**
* Engage a Module at this level
*
* @param axisModule
* the Module to engage
* @throws AxisFault
* if there's a problem engaging
*/
public void engageModule(AxisModule axisModule) throws AxisFault {
engageModule(axisModule, this);
}
/**
* Engage a Module at this level, keeping track of which level the engage was originally
* called from. This is meant for internal use only.
*
* @param axisModule module to engage
* @param source the AxisDescription which originally called engageModule()
* @throws AxisFault if there's a problem engaging
*/
public void engageModule(AxisModule axisModule, AxisDescription source) throws AxisFault {
if (engagedModules == null) engagedModules = new ConcurrentHashMap();
String moduleName = axisModule.getName();
for (Iterator iterator = engagedModules.values().iterator(); iterator.hasNext();) {
AxisModule tempAxisModule = ((AxisModule) iterator.next());
String tempModuleName = tempAxisModule.getName();
if (moduleName.equals(tempModuleName)) {
String existing = tempAxisModule.getVersion();
if (!Utils.checkVersion(axisModule.getVersion(), existing)) {
throw new AxisFault(Messages.getMessage("mismatchedModuleVersions",
getClass().getName(),
moduleName,
existing));
}
}
}
// Let the Module know it's being engaged. If it's not happy about it, it can throw.
Module module = axisModule.getModule();
if (module != null) {
module.engageNotify(this);
}
// If we have anything specific to do, let that happen
onEngage(axisModule, source);
engagedModules.put(Utils.getModuleName(axisModule.getName(), axisModule.getVersion()),
axisModule);
}
protected void onEngage(AxisModule module, AxisDescription engager)
throws AxisFault {
// Default version does nothing, feel free to override
}
static Collection NULL_MODULES = new ArrayList(0);
public Collection getEngagedModules() {
return engagedModules == null ? NULL_MODULES : engagedModules.values();
}
/**
* Check if a given module is engaged at this level.
*
* @param moduleName
* module to investigate.
* @return true if engaged, false if not. TODO: Handle versions?
* isEngaged("addressing") should be true even for versioned
* modulename...
*/
public boolean isEngaged(String moduleName) {
return engagedModules != null
&& engagedModules.keySet().contains(moduleName);
}
public boolean isEngaged(AxisModule axisModule) {
String id = Utils.getModuleName(axisModule.getName(), axisModule
.getVersion());
return engagedModules != null && engagedModules.keySet().contains(id);
}
public void disengageModule(AxisModule module) throws AxisFault {
if (module == null || engagedModules == null)
return;
// String id = Utils.getModuleName(module.getName(),
// module.getVersion());
if (isEngaged(module)) {
onDisengage(module);
engagedModules.remove(Utils.getModuleName(module.getName(), module
.getVersion()));
}
}
protected void onDisengage(AxisModule module) throws AxisFault {
// Base version does nothing
}
private Policy getApplicablePolicy(AxisDescription axisDescription) {
if (axisDescription instanceof AxisMessage) {
AxisMessage axisMessage = (AxisMessage) axisDescription;
AxisOperation axisOperation = axisMessage.getAxisOperation();
if (axisOperation != null) {
AxisService axisService = (AxisService) axisOperation
.getAxisService();
if (axisService != null) {
if (axisService.getEndpointName() != null) {
AxisEndpoint axisEndpoint = axisService
.getEndpoint(axisService.getEndpointName());
if (axisEndpoint != null) {
AxisBinding axisBinding = axisEndpoint.getBinding();
AxisBindingOperation axisBindingOperation = (AxisBindingOperation) axisBinding
.getChild(axisOperation.getName());
String direction = axisMessage.getDirection();
AxisBindingMessage axisBindingMessage = null;
if (WSDLConstants.WSDL_MESSAGE_DIRECTION_IN
.equals(direction)
&& WSDLUtil
.isInputPresentForMEP(axisOperation
.getMessageExchangePattern())) {
axisBindingMessage = (AxisBindingMessage) axisBindingOperation
.getChild(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
return axisBindingMessage.getEffectivePolicy();
} else if (WSDLConstants.WSDL_MESSAGE_DIRECTION_OUT
.equals(direction)
&& WSDLUtil
.isOutputPresentForMEP(axisOperation
.getMessageExchangePattern())) {
axisBindingMessage = (AxisBindingMessage) axisBindingOperation
.getChild(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
return axisBindingMessage.getEffectivePolicy();
}
}
}
}
}
return ((AxisMessage) axisDescription).getEffectivePolicy();
}
return null;
}
public PolicySubject getPolicySubject() {
return policySubject;
}
}
| 30.448567 | 99 | 0.701817 |
6be4a652e6e15d150d9bb5309cf9ff16e5db59e0 | 221 | package example.service;
import example.repo.Customer240Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer240Service {
public Customer240Service(Customer240Repository repo) {}
}
| 20.090909 | 57 | 0.837104 |
809196ede0983237efee08ddae122dab13d4db01 | 692 | package lab09_while_dowhile;
// A+ Computer Science - www.apluscompsci.com
//Name -
//Date -
//Class -
//Lab -
public class LetterRemoverRunner {
public static void main(String args[]) {
//add test cases
String[] testStrings = {"I am Sam I am", "ssssssssxssssesssssesss", "qwertyqwertyqwerty", "abababababa","abaababababa"};
char[] testChars = {'a', 's', 'a', 'b', 'x'};
LetterRemover tester = new LetterRemover(" ", ' ');
int index = 0;
for (String i : testStrings){
tester.setRemover(i, testChars[index]);
tester.removeLetters();
System.out.println(tester);
index++;
}
}
} | 28.833333 | 128 | 0.575145 |
0b8f535f78b0953405602a431a89db9c2ad9cc74 | 5,039 | package org.elastos.wallet.ela.rxjavahelp;
import android.app.Dialog;
import org.elastos.wallet.ela.utils.Log;
import android.widget.Toast;
import org.elastos.wallet.ela.ElaWallet.MyWallet;
import org.elastos.wallet.ela.base.BaseActivity;
import org.elastos.wallet.ela.base.BaseFragment;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
public class NewPresenterAbstract extends PresenterAbstract {
protected Observer<BaseEntity> createObserver(BaseFragment baseFragment, String methodName) {
//初始化参数
return createObserver(baseFragment, methodName, true, null);
}
protected Observer<BaseEntity> createObserver(BaseActivity baseActivity, String methodName) {
//初始化参数
return createObserver(baseActivity, methodName, true, null);
}
protected Observer<BaseEntity> createObserver(BaseFragment baseFragment, String methodName, boolean isShowDialog) {
//初始化参数
return createObserver(baseFragment, methodName, isShowDialog, null);
}
protected Observer<BaseEntity> createObserver(BaseActivity baseActivity, String methodName, boolean isShowDialog) {
//初始化参数
return createObserver(baseActivity, methodName, isShowDialog, null);
}
protected Observer<BaseEntity> createObserver(BaseFragment baseFragment, String methodName, Object o) {
//初始化参数
return createObserver(baseFragment, methodName, true, o);
}
protected Observer<BaseEntity> createObserver(BaseActivity baseActivity, String methodName, Object o) {
//初始化参数
return createObserver(baseActivity, methodName, true, o);
}
protected Observer<BaseEntity> createObserver(BaseFragment baseFragment, String methodName, boolean isShowDialog, Object o) {
//初始化参数
this.context = baseFragment.getBaseActivity();
Dialog dialog;
if (isShowDialog) {
dialog = initProgressDialog(context);
} else {
dialog = null;
}
//创建 Observer
return new Observer<BaseEntity>() {
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
Log.e(TAG, "onSubscribe");
}
@Override
public void onNext(BaseEntity value) {
if (isShowDialog) {
dismissProgessDialog(dialog);
}
if (MyWallet.SUCCESSCODE.equals(value.getCode()) || "0".equals(value.getCode())
||MyWallet.errorCodeDoInMeathed.equals(value.getCode())) {
((NewBaseViewData) baseFragment).onGetData(methodName, value, o);
} else {
showTips(value);
}
Log.e(TAG, methodName+" onNext:" + value);
}
@Override
public void onError(Throwable e) {
if (isShowDialog) {
dismissProgessDialog(dialog);
}
Log.e(TAG, "onError=" + e.getMessage());
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete()");
finish();
}
};
}
protected Observer<BaseEntity> createObserver(BaseActivity baseActivity, String methodName, boolean isShowDialog, Object o) {
//初始化参数
this.context = baseActivity;
Dialog dialog;
if (isShowDialog) {
dialog = initProgressDialog(context);
} else {
dialog = null;
}
//创建 Observer
return new Observer<BaseEntity>() {
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
Log.e(TAG, "onSubscribe");
}
@Override
public void onNext(BaseEntity value) {
if (isShowDialog) {
dismissProgessDialog(dialog);
}
if (MyWallet.SUCCESSCODE.equals(value.getCode()) || "0".equals(value.getCode())
||MyWallet.errorCodeDoInMeathed.equals(value.getCode())) {
((NewBaseViewData) baseActivity).onGetData(methodName, value, o);
} else {
showTips(value);
}
Log.e(TAG, methodName+" onNext:" + value);
}
@Override
public void onError(Throwable e) {
Log.e(TAG, "onError=" + e.getMessage());
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
if (isShowDialog) {
dismissProgessDialog(dialog);
}
finish();
}
@Override
public void onComplete() {
Log.e(TAG, "onComplete()");
finish();
}
};
}
}
| 32.509677 | 129 | 0.566382 |
5ebec2b44801f62370d09132e34dcd71aa80b9d8 | 1,116 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.annotation;
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;
/**
* Place it on classes which you want to be beans created conditionally based on
* OpenMRS version and/or started modules.
*
* @since 1.10, 1.9.8, 1.8.5, 1.7.5
*/
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OpenmrsProfile {
/**
* @since 1.11.3, 1.10.2, 1.9.9
*/
public String openmrsPlatformVersion() default "";
public String[] modules() default {};
}
| 31 | 80 | 0.734767 |
cc48f987e547bba37dd5d7572efc801757795d31 | 824 | package com.swingfrog.summer.client;
import com.google.common.collect.Lists;
import com.swingfrog.summer.util.PollingUtil;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class ClientGroup {
private final AtomicInteger next;
private final List<Client> clientList;
public ClientGroup() {
next = new AtomicInteger();
clientList = Lists.newArrayList();
}
public void addClient(Client client) {
clientList.add(client);
}
public Client getClientWithNext() {
return PollingUtil.getNext(next, clientList, client -> true);
}
public List<Client> listClients() {
return clientList;
}
public boolean hasAnyActive() {
for (Client client : clientList) {
if (client.isActive() && client.getClientContext().isChannelActive())
return true;
}
return true;
}
}
| 20.6 | 72 | 0.73301 |
f37961f38ecf505aba93d671987dc3881927d29c | 4,354 | package com.cqx.leetcode;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* Created by cqx on 2018/3/26.
*/
public class DAY3 {
/**
* '?' Matches any single character.
* '*' Matches any sequence of characters (including the empty sequence).
* <p>
* The matching should cover the entire input string (not partial).
* <p>
* The function prototype should be:
* bool isMatch(const char *s, const char *p)
* <p>
* Some examples:
* isMatch("aa","a") → false
* isMatch("aa","aa") → true
* isMatch("aaa","aa") → false
* isMatch("aa", "*") → true
* isMatch("aa", "a*") → true
* isMatch("ab", "?*") → true
* isMatch("aab", "c*a*b") → false
*
* @param s
* @param p
* @return
*/
public boolean isMatch(String s, String p) {
if (s.equals(p)) {
return true;
}
int targetIndex = 0;
char[] chars = new char[1024];
char[] pArray = p.toCharArray();
for (int i = 0; i < pArray.length; i++) {
if (pArray[i] == '?') {
char[] r1 = "([\\w\\W])".toCharArray();
System.arraycopy(r1, 0, chars, targetIndex, r1.length);
targetIndex += 8;
continue;
}
if (pArray[i] == '*') {
char[] r1 = "([\\w\\W]*)".toCharArray();
System.arraycopy(r1, 0, chars, targetIndex, r1.length);
targetIndex += 9;
continue;
}
chars[targetIndex++] = pArray[i];
}
Pattern pattern = Pattern.compile(new String(Arrays.copyOf(chars, targetIndex)));
return pattern.matcher(s).find();
}
/**
* https://leetcode.com/problems/replace-words/description/
* trie tree https://blog.csdn.net/jijianshuai/article/details/72455736
* @param dict
* @param sentence
* @return
*/
public String replaceWords(List<String> dict, String sentence) {
String[] tokens = sentence.split(" ");
TrieNode trie = buildTrie(dict);
return replaceWords(tokens, trie);
}
private String replaceWords(String[] tokens, TrieNode root) {
StringBuilder stringBuilder = new StringBuilder();
for (String token : tokens) {
stringBuilder.append(getShortestReplacement(token, root));
stringBuilder.append(" ");
}
return stringBuilder.substring(0, stringBuilder.length()-1);
}
private String getShortestReplacement(String token, final TrieNode root) {
TrieNode temp = root;
StringBuilder stringBuilder = new StringBuilder();
for (char c : token.toCharArray()) {
stringBuilder.append(c);
if (temp.children[c - 'a'] != null) {
if (temp.children[c - 'a'].isWord) {
return stringBuilder.toString();
}
temp = temp.children[c - 'a'];
} else {
return token;
}
}
return token;
}
private TrieNode buildTrie(List<String> dict) {
TrieNode root = new TrieNode(' ');
for (String word : dict) {
TrieNode temp = root;
for (char c : word.toCharArray()) {
if (temp.children[c - 'a'] == null) {
temp.children[c - 'a'] = new TrieNode(c);
}
temp = temp.children[c - 'a'];
}
temp.isWord = true;
}
return root;
}
public class TrieNode {
char val;
TrieNode[] children;
boolean isWord;
public TrieNode(char val) {
this.val = val;
this.children = new TrieNode[26];
this.isWord = false;
}
}
@Test
public void test1() {
System.out.println(isMatch("aaa", "a*"));
Pattern matcher = Pattern.compile("a([\\w\\W]*)");
boolean a = matcher.matcher("aaa").find();
System.out.println(a);
}
@Test
public void test2() {
String[] strings = new String[]{"cat", "bat", "rat"};
String result = replaceWords(Arrays.asList(strings), "the cattle was rattled by the battery");
System.out.println(result);
}
}
| 30.236111 | 102 | 0.519752 |
8e2867a393a94f282f1491549d0fe5bcf746953d | 17,485 | /*
Copyright 2012 Christian Dadswell
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 uk.co.chrisdadswell.browsecast;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Activity_Dashboard extends ListActivity implements SearchView.OnQueryTextListener, SearchView.OnCloseListener {
final static String APP_TAG = "browsecast";
final static String ACT_TAG = "Dashboard: ";
final static Date todayDate = new Date();
static String todayDay = null;
static String fileDay = null;
private MenuItem refresh;
@Override
public void onBackPressed() {
finish();//go back to the previous Activity
overridePendingTransition(R.anim.fadeout, R.anim.push_down);
}
@Override
public void onStart() {
super.onStart();
Log.d(APP_TAG, ACT_TAG + "... OnStart ...");
}
@Override
public void onPause() {
super.onPause();
Log.d(APP_TAG, ACT_TAG + "... OnPause ...");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(APP_TAG, ACT_TAG + "... OnDestroy ...");
clearDashList();
Log.d(APP_TAG, ACT_TAG + "ONDESTROY: Clearing Dashlist");
}
// CREATE
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.dashboard);
Context dashboard = this;
createAppDirectory();
Init();
populateDashList();
Log.d(APP_TAG, ACT_TAG + "ONCREATE: Showing Dashboard");
SimpleAdapter dashAdapter = new SimpleAdapter(dashboard,dash_list,R.layout.dash_rows, new String[] {"option", "desc"},new int[] {R.id.text1, R.id.text2});
setListAdapter(dashAdapter);
}
// END OF ONCREATE
// MENUS
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dashboard, menu);
// Set NAVIGATION up
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(false);
//actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.));
actionBar.setStackedBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar_underline)));
refresh = menu.findItem(R.id.menu_refresh);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(this, Activity_Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.menu_about:
Intent aboutActivity = new Intent(Activity_Dashboard.this, Activity_About.class);
startActivity(aboutActivity);
return true;
case R.id.menu_refresh:
downloadNewListingsDialog(this.getResources().getString(R.string.download_listings_dialog_title), this.getResources().getString(R.string.download_listings_dialog_body));
refresh.setActionView(R.layout.actionbar_indeterminate_progress);
return true;
case R.id.menu_blog:
Intent blogURL_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlBlog));
startActivity(blogURL_intent);
return true;
case R.id.menu_gplus:
Intent gplusURL_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlGooglePlus));
startActivity(gplusURL_intent);
return true;
case R.id.menu_rss:
Intent rssURL_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlRss));
startActivity(rssURL_intent);
return true;
case R.id.menu_twitter:
Intent twitter_intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse(Constants.urlTwitter));
startActivity(twitter_intent);
return true;
}
return false;
}
private void BrowseCastToast(String toast_text) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.browsecast_toast,(ViewGroup) findViewById(R.id.custom_toast_layout_id));
// set a message
ImageView image = (ImageView) layout.findViewById(R.id.toast_image);
image.setImageResource(R.drawable.browsecast_toast);
TextView text = (TextView) layout.findViewById(R.id.toast_text);
text.setText(toast_text);
// Toast...
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
// INITIALISATION
public boolean Init() {
Log.d(APP_TAG, ACT_TAG + "METHOD: Init()");
// CHECK IF XML HAS BEEN ALREADY DOWNLOADED
if(!Func_FileIO.FileOrDirectoryExists(Constants.mainxml)) {
Log.d(APP_TAG, ACT_TAG + "INIT: XML doesn't exist");
if(isInternetOn()) {
Log.d(APP_TAG, ACT_TAG + "INIT: Internet available, downloading file");
DownloadListings();
return true;
}else{
Log.d(APP_TAG, ACT_TAG + "INIT: No internet, denied!");
noInternetNoQuitDialog("No Internet Connection", "Unable to download Podcast listings.\n\nThere appears to be no internet connection.\n\nPlease connect to the internet\nand relaunch BrowseCast.");
return false;
}
}else{
// XML EXISTS
Log.d(APP_TAG, ACT_TAG + "INIT: XML exists, checking date stamp");
if (getFileDay().equals(getTodayDay())){
Log.d(APP_TAG, ACT_TAG + "INIT: XML has already been downloaded today");
if(getFileSize() != 0) { // DOWNLOADED TODAY ALREADY AND NOT 0 BYTES START ACTIVITY_BYSTATION
Log.d(APP_TAG, ACT_TAG + "INIT: XML downloaded and not 0 bytes, display dashboard");
return true;
}else{ // FILE AVAILABLE. BUT IS 0 BYTES. NEED TO CHECK INTERNET AND DOWNLOAD
Log.d(APP_TAG, ACT_TAG + "INIT: XML exists, but is 0 bytes, attempt re-download if internet available");
if(isInternetOn()) {
Log.d(APP_TAG, ACT_TAG + "INIT: Internet available, downloading ...");
DownloadListings();
return true;
}else{ // NO INTERNET, RAISE AN ALERT AND FORCE USER TO QUIT
Log.d(APP_TAG, ACT_TAG + "INIT: No internet, display no internet dialog and quit");
noInternetDialog("No internet connection", "A new Podcast listings file needs to be downloaded, but there appears to be no internet connection.\n\nPlease connect to the internet\nand relaunch BrowseCast.");
}
}
}else{ // OUT OF DATE XML, ADVISE USER AN UPDATE IS AVAILABLE
Log.d(APP_TAG, ACT_TAG + "INIT: XML is a day old, show the toast");
BrowseCastToast(this.getResources().getString(R.string.toast_listings_outofdate));
return true;
}
}
return false;
}
private void DownloadListings() {
String url = "http://www.bbc.co.uk/podcasts.xml";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("BBC Podcast listings");
request.setTitle("BBC Podcasts.xml");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
}
request.setDestinationInExternalPublicDir(Constants.xmldir, "podcasts.xml");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
Log.d(APP_TAG, ACT_TAG + "RUN: Starting download of Podcasts.xml file ...");
BrowseCastToast(this.getResources().getString(R.string.toast_download_listings));
//refresh.setActionView(null);
}
ArrayList<HashMap<String,String>> dash_list = new ArrayList<HashMap<String,String>>();
private void populateDashList() {
Log.d(APP_TAG, ACT_TAG + "DASHBOARD: Adding options to dashboard");
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("option", getString(R.string.dashboard_menu_bystation));
temp.put("desc", getString(R.string.dashboard_menu_bystation_subtitle));
dash_list.add(temp);
HashMap<String,String> temp1 = new HashMap<String,String>();
temp1.put("option","5Live Podcasts");
temp1.put("desc", "5Live Podcasts Website");
dash_list.add(temp1);
HashMap<String,String> temp3 = new HashMap<String,String>();
temp3.put("option","Radio Schedules");
temp3.put("desc", "View BBC Radio scheduling information");
dash_list.add(temp3);
HashMap<String,String> temp4 = new HashMap<String,String>();
temp4.put("option","Radio iPlayer by Station");
temp4.put("desc", "View iPlayer content by Station (BBC Media Player and BBC iPlayer required)");
dash_list.add(temp4);
// HashMap<String,String> temp5 = new HashMap<String,String>();
// temp5.put("option","Podcast Help and Assistance");
// temp5.put("desc", "What are Podcasts? What apps are good for Podcasting?");
// dash_list.add(temp5);
}
@Override
protected void onListItemClick(ListView listView, View view, int position, long id) {
super.onListItemClick(listView, view, position, id);
if(id == 0) {
Intent intentStation = new Intent(Activity_Dashboard.this, Activity_ByStation.class);
Activity_Dashboard.this.startActivity(intentStation);
overridePendingTransition(R.anim.fadeout,R.anim.push_left);
}else if(id == 1){
Intent fivelive_intent = new Intent(Intent.ACTION_VIEW);
fivelive_intent.setData(Uri.parse("http://www.bbc.co.uk/podcasts/5live.mp"));
startActivity(fivelive_intent);
overridePendingTransition(R.anim.fadeout,R.anim.push_left);
}else if(id == 2){
Intent intentSchedules = new Intent(Activity_Dashboard.this, Activity_Schedules.class);
Activity_Dashboard.this.startActivity(intentSchedules);
overridePendingTransition(R.anim.fadeout,R.anim.push_left);
}else if(id == 3){
Intent intentiPlayer = new Intent(Activity_Dashboard.this, Activity_iPlayer.class);
Activity_Dashboard.this.startActivity(intentiPlayer);
overridePendingTransition(R.anim.fadeout,R.anim.push_left);
}else if(id == 4){
Intent intentHelp = new Intent(Activity_Dashboard.this, Activity_Help.class);
Activity_Dashboard.this.startActivity(intentHelp);
overridePendingTransition(R.anim.fadeout,R.anim.push_left);
}
}
// CHECK INTERNET METHOD
public final boolean isInternetOn() {
Log.d(APP_TAG, ACT_TAG + "ISINTERNETON: Checking connectivity ...");
ConnectivityManager connec = null;
connec = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if ( connec != null){
NetworkInfo result = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (result != null && result.isConnectedOrConnecting());
return true;
}
return false;
}
// DIALOGS
protected void noInternetDialog(String title, String message) {
Log.d(APP_TAG, ACT_TAG + "NOINTERNETDIALOG: No internet");
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message)
.setTitle(title)
.setCancelable(true)
.setIcon(R.drawable.ic_alert_thumbsdown)
.setNeutralButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
finish();
}
});
alertbox.show();
}
protected void noInternetNoQuitDialog(String title, String message) {
Log.d(APP_TAG, ACT_TAG + "NOINTERNETNOQUITDIALOG: No InternetNoQuit");
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message)
.setTitle(title)
.setCancelable(true)
.setIcon(R.drawable.ic_alert_thumbsdown)
.setPositiveButton("Dashboard", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
Log.d(APP_TAG, ACT_TAG + "NOINTERNETNOQUITDIALOG: Using existing XML file");
dialog.dismiss();
}
})
.setNeutralButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
Log.d(APP_TAG, ACT_TAG + "DIALOG: Quitting BrowseCast");
finish();
}
});
alertbox.show();
}
protected void downloadNewListingsDialog(String title, String message) {
Log.d(APP_TAG, ACT_TAG + "DOWNLOADNEWLISTINGSDIALOG: Download new file or not");
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage(message)
.setTitle(title)
.setCancelable(true)
.setIcon(R.drawable.ic_action_about)
.setPositiveButton("Download new listings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
Log.d(APP_TAG, ACT_TAG + "DOWNLOADNEWLISTINGSDIALOG: Download new file");
if(isInternetOn()) {
Log.d(APP_TAG, ACT_TAG + "INIT: We have internet, go get it!");
// delete current podcasts.xml
Func_FileIO.DeleteFile(Constants.mainxml);
// clear stationnamearraylist
resetData();
// download new listings
DownloadListings();
}else{
Log.d(APP_TAG, ACT_TAG + "INIT: No internet, display no internet dialog and quit");
noInternetDialog("No internet connection", "A new Podcast listings file needs to be downloaded, but there appears to be no internet connection.\n\nPlease connect to the internet\nand relaunch BrowseCast.");
}
}
})
.setNeutralButton("Use current listings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
Log.d(APP_TAG, ACT_TAG + "DOWNLOADNEWLISTINGSDIALOG: Resuming with current file");
dialog.dismiss();
}
});
alertbox.show();
}
private void createAppDirectory() {
Log.d(APP_TAG, ACT_TAG + "CREATEAPPDIRECTORY: Create application directories");
Func_FileIO.CreateDirectory(Constants.appdir);
Func_FileIO.CreateDirectory(Constants.xmldir);
Func_FileIO.CreateDirectory(Constants.imagesdir);
}
private long getFileSize() {
long fileSize = Func_FileIO.FileSize(Constants.mainxml);
return fileSize;
}
private String getFileDay() {
Date fileDate = Func_FileIO.FileLastModified(Constants.mainxml); // GET DAY OF THE WEEK FOR LAST FILE DOWNLOAD
fileDay = Func_Date.GetDayofTheDate(fileDate);
return fileDay;
}
private String getTodayDay() {
String todayDay = Func_Date.GetDayofTheDate(todayDate);
return todayDay;
}
private void clearDashList() {
dash_list.clear();
}
private final void resetData() {
Log.d(APP_TAG, ACT_TAG + "RESETDATA: Clearing ArrayLists");
Activity_ByStation.ARRAYLIST_STATUS = false;
Activity_ByStation.stationNameArrayList.clear();
}
public boolean onClose() {
return false;
}
public boolean onQueryTextChange(String arg0) {
return false;
}
public boolean onQueryTextSubmit(String arg0) {
return false;
}
} // END OF ACTIVITY CLASS | 39.558824 | 218 | 0.692079 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.