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
|
---|---|---|---|---|---|
91dae54f9c1298eb32ddc97772dc153d8bf6f0e8
| 4,165 |
package com.player.melophile;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class AlbumDetailsAdapter extends RecyclerView.Adapter<AlbumDetailsAdapter.MyHolder> {
private Context mContext;
static ArrayList<MusicFiles> albumFiles;
View view;
private static String siz;
public AlbumDetailsAdapter(Context mContext, ArrayList<MusicFiles> albumFiles) {
this.mContext = mContext;
this.albumFiles = albumFiles;
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
view = LayoutInflater.from(mContext).inflate(R.layout.music_items,parent,false);
return new MyHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
holder.album_name.setText(albumFiles.get(position).getTitle());
size(albumFiles.get(position).getSize());
holder.album_name.setHorizontallyScrolling(true);
holder.album_name.setSelected(true);
int durationTotal = Integer.parseInt(albumFiles.get(position).getDuration()) / 1000;
holder.album_size.setText(siz+", "+formatedTime(durationTotal)+" Mins");
byte[] image = getAlbumArt(albumFiles.get(position).getPath());
if(image != null){
Glide.with(mContext).asBitmap().load(image).into(holder.album_image);
}
else{
Glide.with(mContext).load(R.drawable.splashscreen).into(holder.album_image);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mContext,PlayerActivity.class);
intent.putExtra("sender","albumDetails");
intent.putExtra("position",position);
mContext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return albumFiles.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
ImageView album_image;
TextView album_name,album_size;
public MyHolder(@NonNull View itemView) {
super(itemView);
album_image = itemView.findViewById(R.id.music_img);
album_name = itemView.findViewById(R.id.music_file_name);
album_size = itemView.findViewById(R.id.music_size);
}
}
private byte[] getAlbumArt(String uri){
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(uri);
byte[] art = retriever.getEmbeddedPicture();
retriever.release();
return art;
}
public static String size(int size) {
String modifiedFileSize = null;
double fileSize = 0.0;
fileSize = (double) size;//in Bytes
if (fileSize < 1000) {
modifiedFileSize = String.valueOf(fileSize).concat(" B");
} else if (fileSize > 1024 && fileSize < (1000 * 1000)) {
modifiedFileSize = String.valueOf(Math.round((fileSize / 1000 * 100.0)) / 100.0).concat(" KB");
} else {
modifiedFileSize = String.valueOf(Math.round((fileSize / (1000 * 1000) * 100.0)) / 100.0).concat(" MB");
}
siz = modifiedFileSize;
return modifiedFileSize;
}
private String formatedTime(int mCurrentPosition) {
String totalOut = "";
String totalNew = "";
String seconds = String.valueOf(mCurrentPosition % 60);
String minutes = String.valueOf(mCurrentPosition / 60);
totalOut = minutes + ":" + seconds;
totalNew = minutes + ":" + "0" + seconds;
if (seconds.length() == 1) {
return totalNew;
} else {
return totalOut;
}
}
}
| 34.421488 | 116 | 0.646579 |
6b2af0d5dafdf873603453a427bc65cd68e9ba6f
| 3,095 |
/*
* #%L
* Wisdom-Framework
* %%
* Copyright (C) 2013 - 2014 Wisdom Framework
* %%
* 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.wisdom.engine.server;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import java.security.KeyStoreException;
import javax.net.ssl.SSLEngine;
import org.wisdom.engine.ssl.SSLServerContext;
/**
* Initializes the pipeline.
*/
public class WisdomServerInitializer extends ChannelInitializer<SocketChannel> {
private final ServiceAccessor accessor;
private final boolean secure;
public WisdomServerInitializer(final ServiceAccessor accessor, final boolean secure) throws KeyStoreException {
this.accessor = accessor;
this.secure = secure;
}
@Override
public void initChannel(final SocketChannel ch) throws Exception {
// Create a default pipeline implementation.
final ChannelPipeline pipeline = ch.pipeline();
if (secure) {
final SSLEngine engine = SSLServerContext
.getInstance(accessor).serverContext().createSSLEngine();
engine.setUseClientMode(false);
setClientAuthenticationMode(engine);
pipeline.addLast("ssl", new SslHandler(engine));
}
pipeline.addLast("decoder", new HttpRequestDecoder());
// Uncomment the following line if you don't want to handle HttpChunks.
//p.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
// The wisdom handler.
pipeline.addLast("handler", new WisdomHandler(accessor));
}
private void setClientAuthenticationMode(final SSLEngine engine) {
final String clientCertificate = accessor.getConfiguration().get("https.clientCertificate");
if (clientCertificate != null)
{
switch (clientCertificate.toLowerCase())
{
case "needs":
engine.setNeedClientAuth(true);
break;
case "wants":
engine.setWantClientAuth(true);
break;
default:
break;
}
}
}
}
| 33.27957 | 115 | 0.672375 |
badf573847730d63f49b3e8f5a3680935ed6d3ea
| 1,145 |
package com.lzk.moushimouke.Model;
import com.lzk.moushimouke.Model.Bean.MyUser;
import com.lzk.moushimouke.Model.Bean.Post;
import com.lzk.moushimouke.Presenter.EditTextPresenter;
import com.lzk.moushimouke.View.Interface.IUploadTextModel;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
/**
* Created by huqun on 2018/5/14.
*/
public class UploadTextModel implements IUploadTextModel{
@Override
public void requestUploadText(String text) {
MyUser user= BmobUser.getCurrentUser(MyUser.class);
Post post=new Post();
post.setUser(user);
post.setDescription(text);
post.setForward(0);
post.setLike(0);
post.setComment(0);
post.setType(1);
post.save(new SaveListener<String>() {
@Override
public void done(String s, BmobException e) {
if (e==null){
EditTextPresenter.showUploadTextResult(true);
}else {
EditTextPresenter.showUploadTextResult(false);
}
}
});
}
}
| 29.358974 | 66 | 0.638428 |
44fe676c7e5375d2d962585f71d93cc2db6c7602
| 2,205 |
package com.marverenic.music.utils;
import android.content.Context;
import android.graphics.BitmapFactory;
import androidx.core.app.NotificationCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import com.marverenic.music.R;
/**
* Helper APIs for constructing MediaStyle notifications
*
* Modified from https://gist.github.com/ianhanniballake/47617ec3488e0257325c
* @author Ian Lake
*/
public class MediaStyleHelper {
/**
* Build a notification using the information from the given media session.
* @param context Context used to construct the notification.
* @param mediaSession Media session to get information.
* @return A pre-built notification with information from the given media session.
*/
public static NotificationCompat.Builder from(Context context,
MediaSessionCompat mediaSession,
String channel) {
MediaControllerCompat controller = mediaSession.getController();
MediaMetadataCompat mediaMetadata = controller.getMetadata();
MediaDescriptionCompat description = mediaMetadata.getDescription();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel);
builder
.setContentTitle(description.getTitle())
.setContentText(description.getSubtitle())
.setSubText(description.getDescription())
.setContentIntent(controller.getSessionActivity())
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setWhen(0)
.setShowWhen(false);
if (description.getIconBitmap() == null || description.getIconBitmap().isRecycled()) {
builder.setLargeIcon(
BitmapFactory.decodeResource(context.getResources(), R.drawable.art_default));
} else {
builder.setLargeIcon(description.getIconBitmap());
}
return builder;
}
}
| 40.090909 | 98 | 0.684354 |
595e0a070c28dc70b43afd3da4a56217089fe164
| 1,997 |
import java.util.Scanner;
import java.io.*;
class MainPage
{
static BufferedReader brline = new BufferedReader(new InputStreamReader(System.in));
public static void mainpage()
{
System.out.println("\f\t\t\t\tWelcome To Domestic AirServices");
System.out.println("Please choose one of the following: ");
System.out.println("1. To book a new flight");
System.out.println("2. To see our network of flights");
System.out.println("3. To check a previous booking");
System.out.println("4. To read our 'About us' page");
System.out.println("5. To quit");
choicemainpage();
}
static int c;
private static void choicemainpage()
{
Scanner sc = new Scanner(System.in);
System.out.print("Please enter your choice: ");
try
{
c = Integer.parseInt(brline.readLine());
}
catch(Exception e)
{
System.out.println("Wrong choice. Please enter an integer.");
choicemainpage();
}
switch(c)
{
case 1:
FlightBooking.mainpage();
break;
case 2:
OurNetwork.mainpage();
break;
case 3:
System.out.print("\f");
PreviousBooking.mainpage();
break;
case 4:
Aboutus.mainpage();
mainpage();
break;
case 5:
quit();
break;
default:
System.out.println("Wrong choice. Please enter again.");
choicemainpage();
break;
}
}
private static void quit()
{
System.out.println("\f\t\t\t\t\t\t\t Thank You for using our Services!!");
System.out.println("\t\t\t\t\t Use our official services to book tickets at unbelievable prices!!");
System.out.println("\t\t\t\t\t\t\t We wish you a great day ahead!!");
System.exit(0);
}
}
| 30.723077 | 108 | 0.535804 |
476a3fa37cea56e6161a351f5dbb458704be2c17
| 9,955 |
package mekanism.common.tile;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import mekanism.api.Coord4D;
import mekanism.api.NBTConstants;
import mekanism.api.inventory.IInventorySlot;
import mekanism.api.providers.IBlockProvider;
import mekanism.common.Mekanism;
import mekanism.common.multiblock.IMultiblock;
import mekanism.common.multiblock.IStructuralMultiblock;
import mekanism.common.multiblock.MultiblockCache;
import mekanism.common.multiblock.MultiblockManager;
import mekanism.common.multiblock.SynchronizedData;
import mekanism.common.multiblock.UpdateProtocol;
import mekanism.common.tile.base.TileEntityMekanism;
import mekanism.common.util.EnumUtils;
import mekanism.common.util.MekanismUtils;
import mekanism.common.util.NBTUtils;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.common.util.Constants.NBT;
public abstract class TileEntityMultiblock<T extends SynchronizedData<T>> extends TileEntityMekanism implements IMultiblock<T> {
/**
* The multiblock data for this structure.
*/
@Nullable
public T structure;
/**
* This multiblock's previous "has structure" state.
*/
private boolean prevStructure;
/**
* Whether or not this multiblock has it's structure, for the client side mechanics.
*/
public boolean clientHasStructure;
/**
* Whether or not this multiblock segment is rendering the structure.
*/
public boolean isRendering;
/**
* This multiblock segment's cached data
*/
public MultiblockCache<T> cachedData = getNewCache();
/**
* This multiblock segment's cached inventory ID
*/
@Nullable
public String cachedID = null;
public TileEntityMultiblock(IBlockProvider blockProvider) {
super(blockProvider);
}
@Override
protected void onUpdateClient() {
super.onUpdateClient();
if (!clientHasStructure && !playersUsing.isEmpty()) {
for (PlayerEntity player : new ObjectOpenHashSet<>(playersUsing)) {
player.closeScreen();
}
}
}
@Override
protected void onUpdateServer() {
super.onUpdateServer();
if (structure == null) {
if (!playersUsing.isEmpty()) {
for (PlayerEntity player : new ObjectOpenHashSet<>(playersUsing)) {
player.closeScreen();
}
}
isRendering = false;
if (cachedID != null) {
getManager().updateCache(this);
}
if (ticker == 5) {
doUpdate();
}
if (prevStructure) {
structureChanged();
prevStructure = false;
}
} else {
if (!prevStructure) {
structureChanged();
prevStructure = true;
}
structure.didTick = false;
if (structure.inventoryID != null) {
cachedData.sync(structure);
cachedID = structure.inventoryID;
getManager().updateCache(this);
}
}
}
private void structureChanged() {
if (structure != null && !structure.hasRenderer) {
structure.hasRenderer = true;
isRendering = true;
}
Coord4D thisCoord = Coord4D.get(this);
for (Direction side : EnumUtils.DIRECTIONS) {
Coord4D obj = thisCoord.offset(side);
if (structure == null || (!structure.locations.contains(obj) && !structure.internalLocations.contains(obj))) {
BlockPos pos = obj.getPos();
TileEntity tile = MekanismUtils.getTileEntity(world, pos);
if (!world.isAirBlock(pos) && (tile == null || tile.getClass() != getClass()) && !(tile instanceof IStructuralMultiblock || tile instanceof IMultiblock)) {
MekanismUtils.notifyNeighborofChange(world, pos, getPos());
}
}
}
sendUpdatePacket();
}
@Override
public void doUpdate() {
if (!isRemote() && (structure == null || !structure.didTick)) {
getProtocol().doUpdate();
if (structure != null) {
structure.didTick = true;
}
}
}
@Nonnull
protected abstract T getNewStructure();
public abstract MultiblockCache<T> getNewCache();
protected abstract UpdateProtocol<T> getProtocol();
public abstract MultiblockManager<T> getManager();
@Nonnull
@Override
public CompoundNBT getUpdateTag() {
CompoundNBT updateTag = super.getUpdateTag();
updateTag.putBoolean(NBTConstants.RENDERING, isRendering);
updateTag.putBoolean(NBTConstants.HAS_STRUCTURE, structure != null);
if (structure != null && isRendering) {
updateTag.putInt(NBTConstants.HEIGHT, structure.volHeight);
updateTag.putInt(NBTConstants.WIDTH, structure.volWidth);
updateTag.putInt(NBTConstants.LENGTH, structure.volLength);
if (structure.renderLocation != null) {
updateTag.put(NBTConstants.RENDER_LOCATION, structure.renderLocation.write(new CompoundNBT()));
}
if (structure.inventoryID != null) {
updateTag.putString(NBTConstants.INVENTORY_ID, structure.inventoryID);
}
}
return updateTag;
}
@Override
public void handleUpdateTag(@Nonnull CompoundNBT tag) {
super.handleUpdateTag(tag);
if (structure == null) {
structure = getNewStructure();
}
NBTUtils.setBooleanIfPresent(tag, NBTConstants.RENDERING, value -> isRendering = value);
NBTUtils.setBooleanIfPresent(tag, NBTConstants.HAS_STRUCTURE, value -> clientHasStructure = value);
if (isRendering) {
if (clientHasStructure) {
NBTUtils.setIntIfPresent(tag, NBTConstants.HEIGHT, value -> structure.volHeight = value);
NBTUtils.setIntIfPresent(tag, NBTConstants.WIDTH, value -> structure.volWidth = value);
NBTUtils.setIntIfPresent(tag, NBTConstants.LENGTH, value -> structure.volLength = value);
NBTUtils.setCoord4DIfPresent(tag, NBTConstants.RENDER_LOCATION, value -> structure.renderLocation = value);
if (tag.contains(NBTConstants.INVENTORY_ID, NBT.TAG_STRING)) {
structure.inventoryID = tag.getString(NBTConstants.INVENTORY_ID);
} else {
structure.inventoryID = null;
}
//TODO: Test sparkle
if (structure.renderLocation != null && !prevStructure) {
Mekanism.proxy.doMultiblockSparkle(this, structure.renderLocation.getPos(), structure.volLength, structure.volWidth, structure.volHeight,
tile -> MultiblockManager.areEqual(this, tile));
}
}
prevStructure = clientHasStructure;
}
}
@Override
public void read(CompoundNBT nbtTags) {
super.read(nbtTags);
if (structure == null) {
if (nbtTags.contains(NBTConstants.INVENTORY_ID, NBT.TAG_STRING)) {
cachedID = nbtTags.getString(NBTConstants.INVENTORY_ID);
cachedData.load(nbtTags);
}
}
}
@Nonnull
@Override
public CompoundNBT write(CompoundNBT nbtTags) {
super.write(nbtTags);
if (cachedID != null) {
nbtTags.putString(NBTConstants.INVENTORY_ID, cachedID);
cachedData.save(nbtTags);
}
return nbtTags;
}
@Nonnull
@Override
public AxisAlignedBB getRenderBoundingBox() {
if (clientHasStructure && structure != null && isRendering && structure.renderLocation != null) {
//TODO: Eventually we may want to look into caching this
BlockPos corner1 = structure.renderLocation.getPos();
//height - 2 up, but then we go up one further to take into account that block
BlockPos corner2 = corner1.east(structure.volLength + 1).south(structure.volWidth + 1).up(structure.volHeight - 1);
//Note: We do basically the full dimensions as it still is a lot smaller than always rendering it, and makes sure no matter
// how the specific multiblock wants to render, that it is being viewed
return new AxisAlignedBB(corner1, corner2);
}
return super.getRenderBoundingBox();
}
@Override
public boolean persistInventory() {
return false;
}
@Override
public T getSynchronizedData() {
return structure;
}
@Nonnull
@Override
public List<IInventorySlot> getInventorySlots(@Nullable Direction side) {
//TODO: Check we may have to still be disabling the item handler cap for some blocks like the boundaries
if (!hasInventory() || structure == null) {
//TODO: Previously we had a check like !isRemote() ? structure == null : !clientHasStructure
// Do we still need this if we ever actually needed it?
//If we don't have a structure then return that we have no slots accessible
return Collections.emptyList();
}
//Otherwise we get the inventory slots for our structure.
// NOTE: Currently we have nothing that "cares" about facing/can give different output to different sides
// so we are just returning the list directly instead of dealing with the side
return structure.getInventorySlots(side);
}
}
| 37.996183 | 171 | 0.630738 |
04fae26f549b644d1c27d35e54bc72d3fbc18993
| 26,613 |
package jet.opengl.demos.intel.antialiasing;
import com.nvidia.developer.opengl.models.GLVAO;
import com.nvidia.developer.opengl.models.ModelGenerator;
import org.lwjgl.util.vector.Readable;
import org.lwjgl.util.vector.Vector4f;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.StringTokenizer;
import jet.opengl.postprocessing.buffer.BufferGL;
import jet.opengl.postprocessing.common.Disposeable;
import jet.opengl.postprocessing.common.GLFuncProvider;
import jet.opengl.postprocessing.common.GLFuncProviderFactory;
import jet.opengl.postprocessing.common.GLenum;
import jet.opengl.postprocessing.shader.GLSLProgram;
import jet.opengl.postprocessing.shader.Macro;
import jet.opengl.postprocessing.texture.RenderTargets;
import jet.opengl.postprocessing.texture.Texture2D;
import jet.opengl.postprocessing.texture.Texture2DDesc;
import jet.opengl.postprocessing.texture.TextureDataDesc;
import jet.opengl.postprocessing.texture.TextureGL;
import jet.opengl.postprocessing.texture.TextureUtils;
import jet.opengl.postprocessing.util.CacheBuffer;
import jet.opengl.postprocessing.util.CommonUtil;
import jet.opengl.postprocessing.util.FileUtils;
/**
* Created by mazhen'gui on 2017/9/23.
*/
final class SMAAEffect implements Disposeable{
static final int AREATEX_WIDTH = 160;
static final int AREATEX_HEIGHT = 560;
static final int AREATEX_PITCH = (AREATEX_WIDTH * 2);
static final int AREATEX_SIZE = (AREATEX_HEIGHT * AREATEX_PITCH);
static final int SEARCHTEX_WIDTH = 64;
static final int SEARCHTEX_HEIGHT = 16;
static final int SEARCHTEX_PITCH = SEARCHTEX_WIDTH;
static final int SEARCHTEX_SIZE = (SEARCHTEX_HEIGHT * SEARCHTEX_PITCH);
private float m_ScreenWidth;
private float m_ScreenHeight;
private GLSLProgram m_SMAAEdgeDetectionProgram;
private GLSLProgram m_SMAABlendingWeightCalculationProgram;
private GLSLProgram m_SMAANeighborhoodBlendingProgram;
private BufferGL m_constantsBuffer;
private Texture2D m_depthStencilTex;
private Texture2D m_workingColorTexture;
private Texture2D m_edgesTex;
private Texture2D m_blendTex;
//ID3D11Texture2D* m_areaTex;
private Texture2D m_areaTexSRV;
//ID3D11Texture2D* m_searchTex;
private Texture2D m_searchTexSRV;
// ID3D11SamplerState* m_samplerState;
// class SMAAEffect_Quad * m_quad;
private GLVAO m_quad;
private GLFuncProvider gl;
private final SMAAConstants m_constants = new SMAAConstants();
private RenderTargets m_renderTargets;
private boolean m_prinOnce = false;
void OnCreate(int width, int height){
final Macro[] macros = {
new Macro("SMAA_RT_METRICS", "float4(1.0 / " + width + ", 1.0 / " + height + ", " + width + ", " + height + ")"),
new Macro("SMAA_PRESET_HIGH", 1),
// new Macro("SMAA_PREDICATION", 1)
};
// HRESULT hr = S_OK;
// CPUTResult result;
// cString FullPath, FinalPath;
// ID3DBlob *pPSBlob = NULL;
m_renderTargets = new RenderTargets();
gl = GLFuncProviderFactory.getGLFuncProvider();
m_areaTexSRV = CreateTextureFromRAWMemory( AREATEX_WIDTH, AREATEX_HEIGHT, AREATEX_PITCH, AREATEX_SIZE, GLenum.GL_RG8, "shader_libs/AntiAliasing/AreaTex.dat" );
m_searchTexSRV = CreateTextureFromRAWMemory( SEARCHTEX_WIDTH, SEARCHTEX_HEIGHT, SEARCHTEX_PITCH, SEARCHTEX_SIZE, GLenum.GL_R8, "shader_libs/AntiAliasing/SearchTex.dat" );
// Create constant buffer
/*D3D11_BUFFER_DESC BufferDesc;
ZeroMemory(&BufferDesc, sizeof(BufferDesc));
BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
BufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
BufferDesc.ByteWidth = sizeof( SMAAConstants );
hr = pD3DDevice->CreateBuffer( &BufferDesc, NULL, &m_constantsBuffer );*/
m_constantsBuffer = new BufferGL();
m_constantsBuffer.initlize(GLenum.GL_UNIFORM_BUFFER, SMAAConstants.SIZE, null, GLenum.GL_DYNAMIC_COPY);
m_constantsBuffer.unbind();
/*CPUTAssetLibraryDX11 *pAssetLibrary = (CPUTAssetLibraryDX11*)CPUTAssetLibrary::GetAssetLibrary();
cString OriginalAssetLibraryDirectory = pAssetLibrary->GetShaderDirectoryName();*/
// vertex shaders
{
/*FullPath = OriginalAssetLibraryDirectory + L"SMAA.fx";
CPUTFileSystem::ResolveAbsolutePathAndFilename(FullPath, &FinalPath);*/
/*result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAAEdgeDetectionVS", L"vs_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Vertex shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreateVertexShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAAEdgeDetectionVS);*/
m_SMAAEdgeDetectionProgram = createProgram("EdgeDetection", macros);
/*m_quad = new SMAAEffect_Quad( pD3DDevice, pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize() );
SAFE_RELEASE( pPSBlob );*/
m_quad = ModelGenerator.genRect(-1,-1,+1,+1, true).genVAO();
/*result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAABlendingWeightCalculationVS", L"vs_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Vertex shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreateVertexShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAABlendingWeightCalculationVS);
SAFE_RELEASE( pPSBlob );*/
m_SMAABlendingWeightCalculationProgram = createProgram("BlendingWeightCalculation", macros);
/*result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAANeighborhoodBlendingVS", L"vs_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Vertex shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreateVertexShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAANeighborhoodBlendingVS);
SAFE_RELEASE( pPSBlob );*/
m_SMAANeighborhoodBlendingProgram = createProgram("NeighborhoodBlending", macros);
}
// pixel shaders
{
/*result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAAEdgeDetectionPS", L"ps_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Pixel shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAAEdgeDetectionPS);
SAFE_RELEASE( pPSBlob );
result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAABlendingWeightCalculationPS", L"ps_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Pixel shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAABlendingWeightCalculationPS);
SAFE_RELEASE( pPSBlob );
result = pAssetLibrary->CompileShaderFromFile(FinalPath, L"DX11_SMAANeighborhoodBlendingPS", L"ps_5_0", &pPSBlob, NULL );
ASSERT( CPUTSUCCESS(result), _L("Error compiling Pixel shader:\n\n") );
UNREFERENCED_PARAMETER(result);
hr = pD3DDevice->CreatePixelShader( pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(),NULL, &m_SMAANeighborhoodBlendingPS);
SAFE_RELEASE( pPSBlob );*/
}
}
static Texture2D CreateTextureFromRAWMemory(int width, int height, int pitch, int size, int format, String filename){
try {
byte[] data = FileUtils.loadBytes(filename);
if(size != data.length)
throw new IllegalArgumentException();
Texture2DDesc desc = new Texture2DDesc(width,height, format);
TextureDataDesc dataDesc = new TextureDataDesc(TextureUtils.measureFormat(format), TextureUtils.measureDataType(format), data);
return TextureUtils.createTexture2D(desc, dataDesc);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static GLSLProgram createProgram(String shaderName, Macro... macros){
try {
GLSLProgram program = GLSLProgram.createFromFiles(
String.format("shader_libs/AntiAliasing/PostProcessingSMAA_%sVS.vert", shaderName),
String.format("shader_libs/AntiAliasing/PostProcessingSMAA_%sPS.frag", shaderName),
macros);
program.setName(shaderName);
return program;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
void OnSize(/*ID3D11Device* pD3DDevice,*/ int width, int height){
m_ScreenHeight = (float)height;
m_ScreenWidth = (float)width;
CommonUtil.safeRelease( m_workingColorTexture );
CommonUtil.safeRelease( m_edgesTex );
CommonUtil.safeRelease( m_blendTex );
CommonUtil.safeRelease( m_depthStencilTex );
// Create working textures
/*D3D11_TEXTURE2D_DESC td;
DXGI_SAMPLE_DESC SampleDesc;
SampleDesc.Count = 1;
SampleDesc.Quality = 0;
memset(&td, 0, sizeof(td));
td.ArraySize = 1;
td.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
td.Height = (UINT)m_ScreenHeight;
td.Width = (UINT)m_ScreenWidth;
td.CPUAccessFlags = 0;
td.MipLevels = 1;
td.MiscFlags = 0;
td.SampleDesc = SampleDesc;
td.Usage = D3D11_USAGE_DEFAULT;
assert( td.SampleDesc.Count == 1 ); // other not supported yet
td.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
hr = pD3DDevice->CreateTexture2D( &td, NULL, &m_workingColorTexture ) ;*/
m_workingColorTexture =
TextureUtils.createTexture2D(new Texture2DDesc(width, height, GLenum.GL_RGBA8), null);
/*{
CD3D11_SHADER_RESOURCE_VIEW_DESC srvd( m_workingColorTexture, D3D11_SRV_DIMENSION_TEXTURE2D, td.Format );
CD3D11_RENDER_TARGET_VIEW_DESC dsvDesc( m_workingColorTexture, D3D11_RTV_DIMENSION_TEXTURE2D, td.Format );
hr = pD3DDevice->CreateShaderResourceView( m_workingColorTexture, &srvd, &m_workingColorTextureSRV );
hr = pD3DDevice->CreateRenderTargetView( m_workingColorTexture, &dsvDesc, &m_workingColorTextureRTV );
}*/
/*td.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
hr = pD3DDevice->CreateTexture2D( &td, NULL, &m_edgesTex );
{
CD3D11_SHADER_RESOURCE_VIEW_DESC srvd( m_edgesTex, D3D11_SRV_DIMENSION_TEXTURE2D, td.Format );
CD3D11_RENDER_TARGET_VIEW_DESC dsvDesc( m_edgesTex, D3D11_RTV_DIMENSION_TEXTURE2D, td.Format );
hr = ( pD3DDevice->CreateShaderResourceView( m_edgesTex, &srvd, &m_edgesTexSRV ) );
hr = ( pD3DDevice->CreateRenderTargetView( m_edgesTex, &dsvDesc, &m_edgesTexRTV ) );
}*/
m_edgesTex = TextureUtils.createTexture2D(new Texture2DDesc(width, height, GLenum.GL_RG8), null);
/*hr = ( pD3DDevice->CreateTexture2D( &td, NULL, &m_blendTex ) );
{
CD3D11_SHADER_RESOURCE_VIEW_DESC srvd( m_blendTex, D3D11_SRV_DIMENSION_TEXTURE2D, td.Format );
CD3D11_RENDER_TARGET_VIEW_DESC dsvDesc( m_blendTex, D3D11_RTV_DIMENSION_TEXTURE2D, td.Format );
hr = ( pD3DDevice->CreateShaderResourceView( m_blendTex, &srvd, &m_blendTexSRV ) );
hr = ( pD3DDevice->CreateRenderTargetView( m_blendTex, &dsvDesc, &m_blendTexRTV ) );
}*/
m_blendTex = TextureUtils.createTexture2D(new Texture2DDesc(width, height, GLenum.GL_RGBA8), null);
/*td.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
td.BindFlags = D3D11_BIND_DEPTH_STENCIL;
hr = ( pD3DDevice->CreateTexture2D( &td, NULL, &m_depthStencilTex ) );
{
CD3D11_DEPTH_STENCIL_VIEW_DESC dsvd( m_depthStencilTex, D3D11_DSV_DIMENSION_TEXTURE2D, td.Format );
hr = ( pD3DDevice->CreateDepthStencilView( m_depthStencilTex, &dsvd, &m_depthStencilTexDSV ) );
}*/
m_depthStencilTex = TextureUtils.createTexture2D(new Texture2DDesc(width, height, GLenum.GL_DEPTH24_STENCIL8), null);
}
void Draw(/*ID3D11DeviceContext* pD3DImmediateContext,*/ float PPAADEMO_gEdgeDetectionThreshold, Texture2D sourceColorSRV_SRGB,
Texture2D sourceColorSRV_UNORM, boolean showEdges ){
/*ID3D11ShaderResourceView * nullSRVs[4] = { NULL };
// Backup current render/stencil
ID3D11RenderTargetView * oldRenderTargetViews[4] = { NULL };
ID3D11DepthStencilView * oldDepthStencilView = NULL;
context->OMGetRenderTargets( _countof(oldRenderTargetViews), oldRenderTargetViews, &oldDepthStencilView );*/
gl.glBindFramebuffer(GLenum.GL_FRAMEBUFFER, 0);
// update consts
{
/*HRESULT hr;
D3D11_MAPPED_SUBRESOURCE MappedResource;
hr = context->Map( m_constantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &MappedResource );
SMAAConstants *pCB = (SMAAConstants *) MappedResource.pData;*/
SMAAConstants pCB = m_constants;
pCB.c_PixelSize[ 0 ] = 1.0f / m_ScreenWidth;
pCB.c_PixelSize[ 1 ] = 1.0f / m_ScreenHeight;
pCB.c_Dummy[0] = 0;
pCB.c_Dummy[1] = 0;
pCB.c_SubsampleIndices[0] = 0;
pCB.c_SubsampleIndices[1] = 0;
pCB.c_SubsampleIndices[2] = 0;
pCB.c_SubsampleIndices[3] = 0;
/*context->Unmap( m_constantsBuffer, 0 );
context->VSSetConstantBuffers( 0, 1, &m_constantsBuffer );
context->PSSetConstantBuffers( 0, 1, &m_constantsBuffer );
context->CSSetConstantBuffers( 0, 1, &m_constantsBuffer );*/
ByteBuffer bytes = CacheBuffer.getCachedByteBuffer(SMAAConstants.SIZE);
pCB.store(bytes).flip();
m_constantsBuffer.update(0, bytes);
gl.glBindBufferBase(GLenum.GL_UNIFORM_BUFFER, 0, m_constantsBuffer.getBuffer());
}
{
// Setup the viewport to match the backbuffer
/*D3D11_VIEWPORT vp;
vp.Width = (float)m_ScreenWidth;
vp.Height = (float)m_ScreenHeight;
vp.MinDepth = 0;
vp.MaxDepth = 1;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
context->RSSetViewports( 1, &vp );*/
gl.glViewport(0,0, (int)m_ScreenWidth, (int)m_ScreenHeight);
}
/*float f4zero[4] = { 0, 0, 0, 0 };
context->ClearRenderTargetView( m_edgesTexRTV, f4zero );
context->ClearRenderTargetView( m_blendTexRTV, f4zero );
context->ClearDepthStencilView( m_depthStencilTexDSV, D3D11_CLEAR_STENCIL, 0.0f, 0 );*/
gl.glClearTexImage(m_edgesTex.getTexture(), 0, TextureUtils.measureFormat(m_edgesTex.getFormat()), TextureUtils.measureDataType(m_edgesTex.getFormat()), null);
gl.glClearTexImage(m_blendTex.getTexture(), 0, TextureUtils.measureFormat(m_blendTex.getFormat()), TextureUtils.measureDataType(m_blendTex.getFormat()), null);
gl.glDisable(GLenum.GL_BLEND);
gl.glDisable(GLenum.GL_CULL_FACE);
// m_quad->setInputLayout( context );
// common textures
/*context->PSSetShaderResources( 4, 1, &m_areaTexSRV );
context->PSSetShaderResources( 5, 1, &m_searchTexSRV ); TODO*/
// common samplers
/*ID3D11SamplerState * samplerStates[2] = { MySample::GetSS_LinearClamp(), MySample::GetSS_PointClamp() };
context->PSSetSamplers( 0, 2, samplerStates );TODO*/
// Detect edges
{
/*context->VSSetShader( m_SMAAEdgeDetectionVS, NULL, 0 );
context->PSSetShader( m_SMAAEdgeDetectionPS, NULL, 0 );*/
m_SMAAEdgeDetectionProgram.enable();
/*context->OMSetRenderTargets( 1, &m_edgesTexRTV, m_depthStencilTexDSV );*/
m_renderTargets.bind();
m_renderTargets.setRenderTextures(new TextureGL[]{m_edgesTex, m_depthStencilTex}, null);
gl.glClearBufferfi(GLenum.GL_DEPTH_STENCIL, 0, 1.0f, 0);
/*context->PSSetShaderResources( 0, 1, &sourceColorSRV_SRGB );
context->PSSetShaderResources( 1, 1, &sourceColorSRV_UNORM );*/
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(sourceColorSRV_SRGB.getTarget(), sourceColorSRV_SRGB.getTexture());
gl.glActiveTexture(GLenum.GL_TEXTURE1);
gl.glBindTexture(sourceColorSRV_UNORM.getTarget(), sourceColorSRV_UNORM.getTexture());
/*context->OMSetDepthStencilState( MySample::GetDSS_DepthDisabled_ReplaceStencil(), 1 );
context->OMSetBlendState( MySample::GetBS_Opaque(), f4zero, 0xFFFFFFFF );*/
gl.glDisable(GLenum.GL_DEPTH_TEST);
gl.glEnable(GLenum.GL_STENCIL_TEST);
gl.glStencilOp(GLenum.GL_KEEP, GLenum.GL_KEEP, GLenum.GL_REPLACE);
gl.glStencilFunc(GLenum.GL_ALWAYS, 1, 1);
// m_quad->draw( context );
drawQuad();
// this doesn't work unfortunately, there's some kind of mismatch - please don't change without confirming that before/after screen shots are pixel identical
//MySample::FullscreenPassDraw( context, m_SMAAEdgeDetectionPS, m_SMAAEdgeDetectionVS, MySample::GetBS_Opaque(), MySample::GetDSS_DepthDisabled_ReplaceStencil(), 1, 0.0f );
// context->PSSetShaderResources( 0, 2, nullSRVs );
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(sourceColorSRV_SRGB.getTarget(), 0);
gl.glActiveTexture(GLenum.GL_TEXTURE1);
gl.glBindTexture(sourceColorSRV_UNORM.getTarget(), 0);
if(!m_prinOnce){
m_SMAAEdgeDetectionProgram.printPrograminfo();
}
}
// Blending weight calculation
{
/*context->VSSetShader( m_SMAABlendingWeightCalculationVS, NULL, 0 );
context->PSSetShader( m_SMAABlendingWeightCalculationPS, NULL, 0 );*/
m_SMAABlendingWeightCalculationProgram.enable();
/*context->OMSetRenderTargets( 1, &m_blendTexRTV, m_depthStencilTexDSV );
context->PSSetShaderResources( 2, 1, &m_edgesTexSRV );*/
m_renderTargets.setRenderTextures(new TextureGL[]{m_blendTex, m_depthStencilTex}, null);
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(m_edgesTex.getTarget(), m_edgesTex.getTexture());
gl.glActiveTexture(GLenum.GL_TEXTURE1);
gl.glBindTexture(m_areaTexSRV.getTarget(), m_areaTexSRV.getTexture());
gl.glActiveTexture(GLenum.GL_TEXTURE2);
gl.glBindTexture(m_searchTexSRV.getTarget(), m_searchTexSRV.getTexture());
/*context->OMSetDepthStencilState( MySample::GetDSS_DepthDisabled_UseStencil(), 1 ); TODO
context->OMSetBlendState( MySample::GetBS_Opaque(), f4zero, 0xFFFFFFFF );*/
gl.glDisable(GLenum.GL_DEPTH_TEST);
gl.glEnable(GLenum.GL_STENCIL_TEST);
gl.glStencilOp(GLenum.GL_KEEP, GLenum.GL_KEEP, GLenum.GL_REPLACE);
gl.glStencilFunc(GLenum.GL_EQUAL, 1, 1);
// m_quad->draw( context );
drawQuad();
if(!m_prinOnce){
m_SMAABlendingWeightCalculationProgram.printPrograminfo();
}
// this doesn't work unfortunately, there's some kind of mismatch - please don't change without confirming that before/after screen shots are pixel identical
//MySample::FullscreenPassDraw( context, m_SMAABlendingWeightCalculationPS, m_SMAABlendingWeightCalculationVS, MySample::GetBS_Opaque(), MySample::GetDSS_DepthDisabled_UseStencil(), 1, 0.0f );
}
// Neighborhood blending (apply)
{
/*context->VSSetShader( m_SMAANeighborhoodBlendingVS, NULL, 0 );
context->PSSetShader( m_SMAANeighborhoodBlendingPS, NULL, 0 );*/
m_SMAANeighborhoodBlendingProgram.enable();
/*context->OMSetRenderTargets( 1, oldRenderTargetViews, m_depthStencilTexDSV );
context->PSSetShaderResources( 0, 1, &sourceColorSRV_SRGB );
context->PSSetShaderResources( 1, 1, &sourceColorSRV_UNORM );
context->PSSetShaderResources( 3, 1, &m_blendTexSRV );*/
gl.glBindFramebuffer(GLenum.GL_FRAMEBUFFER, 0);
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(sourceColorSRV_UNORM.getTarget(), sourceColorSRV_UNORM.getTexture());
gl.glActiveTexture(GLenum.GL_TEXTURE1);
gl.glBindTexture(m_blendTex.getTarget(), m_blendTex.getTexture());
/*context->OMSetDepthStencilState( MySample::GetDSS_DepthDisabled_NoDepthWrite(), 1 ); TODO
context->OMSetBlendState( MySample::GetBS_Opaque(), f4zero, 0xFFFFFFFF );*/
gl.glDisable(GLenum.GL_DEPTH_TEST);
gl.glDisable(GLenum.GL_STENCIL_TEST);
gl.glDepthMask(false);
// m_quad->draw( context );
drawQuad();
gl.glDepthMask(true);
if(!m_prinOnce){
m_SMAANeighborhoodBlendingProgram.printPrograminfo();
}
// this doesn't work unfortunately, there's some kind of mismatch - please don't change without confirming that before/after screen shots are pixel identical
//MySample::FullscreenPassDraw( context, m_SMAANeighborhoodBlendingPS, m_SMAANeighborhoodBlendingVS, MySample::GetBS_Opaque(), MySample::GetDSS_DepthDisabled_NoDepthWrite(), 1, 0.0f );
}
/*ID3D11ShaderResourceView * nullSRV[8] = { NULL };
context->PSSetShaderResources( 0, _countof(nullSRV), nullSRV );*/
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(sourceColorSRV_SRGB.getTarget(), 0);
gl.glActiveTexture(GLenum.GL_TEXTURE1);
gl.glBindTexture(sourceColorSRV_UNORM.getTarget(), 0);
gl.glActiveTexture(GLenum.GL_TEXTURE2);
gl.glBindTexture(m_blendTex.getTarget(), 0);
gl.glBindBufferBase(GLenum.GL_UNIFORM_BUFFER, 0,0);
// Restore old stencil/depth
/*context->OMSetRenderTargets( _countof(oldRenderTargetViews), oldRenderTargetViews, oldDepthStencilView );
for( int i = 0; i < _countof(oldRenderTargetViews); i++ )
SAFE_RELEASE( oldRenderTargetViews[i] );
SAFE_RELEASE( oldDepthStencilView );*/
m_prinOnce = true;
}
private void drawQuad(){
gl.glDrawArrays(GLenum.GL_TRIANGLES, 0, 3);
// m_quad.bind();
// m_quad.draw(GLenum.GL_TRIANGLE_STRIP);
// m_quad.unbind();
}
@Override
public void dispose() {
CommonUtil.safeRelease( m_SMAAEdgeDetectionProgram );
CommonUtil.safeRelease( m_SMAABlendingWeightCalculationProgram );
CommonUtil.safeRelease( m_SMAANeighborhoodBlendingProgram );
CommonUtil.safeRelease( m_constantsBuffer );
//SAFE_RELEASE( m_areaTex );
CommonUtil.safeRelease( m_areaTexSRV );
//SAFE_RELEASE( m_searchTex );
CommonUtil.safeRelease( m_searchTexSRV );
CommonUtil.safeRelease( m_workingColorTexture );
CommonUtil.safeRelease( m_edgesTex );
CommonUtil.safeRelease( m_blendTex );
CommonUtil.safeRelease( m_depthStencilTex );
}
public static class SMAAConstants implements Readable{
static final int SIZE = Vector4f.SIZE * 2;
final float[] c_PixelSize = new float[2];
final float[] c_Dummy = new float[2];
// This is only required for temporal modes (SMAA T2x).
float[] c_SubsampleIndices = new float[4];
@Override
public ByteBuffer store(ByteBuffer buf) {
CacheBuffer.put(buf, c_PixelSize);
CacheBuffer.put(buf, c_Dummy);
CacheBuffer.put(buf, c_SubsampleIndices);
return buf;
}
//float threshld;
//float maxSearchSteps;
//float maxSearchStepsDiag;
//float cornerRounding;
}
public static void main(String[] args){
convertFiles("E:\\SDK\\smaa\\Textures\\AreaTex.h");
convertFiles("E:\\SDK\\smaa\\Textures\\SearchTex.h");
}
private static void convertFiles(String filename){
int dot = filename.lastIndexOf('.');
String _filename = dot > 0 ? filename.substring(0, dot) : filename;
File file = new File(filename);
File outFile = new File(_filename + ".dat");
int lineNumber = 0;
String token = "";
try {
BufferedReader in = new BufferedReader(new FileReader(file));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
String line;
boolean inArrayBlock = false;
Tag: while((line = in.readLine()) != null){
if(inArrayBlock){
StringTokenizer tokenizer = new StringTokenizer(line, " \t\f,");
while (tokenizer.hasMoreElements()){
token = tokenizer.nextToken().trim();
if(token.equals("") || token.equals("};"))
break Tag;
int value = Integer.parseInt(token.substring(2), 16);
out.write(value);
}
}else if(line.startsWith("static const unsigned char")){
inArrayBlock = true;
}
lineNumber ++;
}
in.close();
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NumberFormatException e){
System.out.println("Error occored in the number: " + lineNumber + ", in the file: " + filename + ", the token is: " + token);
e.printStackTrace();
}
}
}
| 48.211957 | 204 | 0.658588 |
b77b8a1de4f742261085231a102584798a5f9b22
| 8,625 |
package org.testobject.kernel.ocr.tesseract;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.TessAPI.TessPageIteratorLevel;
import org.junit.Test;
import org.testobject.commons.math.algebra.Rectangle;
import org.testobject.commons.util.distances.StringDistances;
import org.testobject.commons.util.distances.StringDistances.Distance;
import org.testobject.kernel.imaging.segmentation.Group;
import org.testobject.kernel.imaging.segmentation.GroupBuilder;
import org.testobject.kernel.imaging.segmentation.HasBoundingBox;
import org.testobject.kernel.ocr.OCR;
import org.testobject.kernel.ocr.OCR.Result;
import org.testobject.kernel.ocr.OCR.TextPosition;
import org.testobject.kernel.ocr.tesseract.TesseractCopyRectOCR.Tess;
import com.google.common.base.Stopwatch;
public class TesseractCopyRectOCRTest {
private static final String QUERY_STRING = "Tap below to select seats";
private static final int THREADS = 2;
private static final double SCALE = 1;
private static final String FILE = "/home/aluedeke/Desktop/before.png";
private static final String FILE_TEXTS = "/home/aluedeke/Desktop/before.texts.png";
private static final String FILE_BOXES = "/home/aluedeke/Desktop/before.boxes.png";
private final ExecutorService executor = Executors.newFixedThreadPool(THREADS);
Stopwatch w = new Stopwatch();
@Test
public void test() throws IOException, InterruptedException, ExecutionException {
TesseractCopyRectOCR.Tess ocr = new TesseractCopyRectOCR.Tess();
w.start();
Stopwatch w6 = new Stopwatch().start();
BufferedImage image = ImageIO.read(new File(FILE));
final BufferedImage scaledImage = scale(image, SCALE);
// final BufferedImage scaledImage = ImageUtil.scale(image, (int) (image.getWidth() * SCALE), (int) (image.getHeight() * SCALE));
System.out.println("timing scaling: " + w6.stop().elapsedMillis());
Stopwatch w5 = new Stopwatch().start();
ocr.setImage(scaledImage, new Rectangle.Int(scaledImage.getWidth(), scaledImage.getHeight()));
List<OCR.TextPosition> textPositions = ocr.getTextPositions();
System.out.println("timing getTextPositions: " + w5.stop().elapsedMillis());
Stopwatch w4 = new Stopwatch().start();
GroupBuilder<OCR.TextPosition> groupBuilder = new GroupBuilder<>();
List<Group<OCR.TextPosition>> groups = groupBuilder.buildGroups(textPositions, new Insets(10, 10, 10, 10));
System.out.println("timing grouping: " + w4.stop().elapsedMillis());
Set<OCR.TextPosition> mergedTextPositions = new HashSet<>(textPositions);
for (Group<OCR.TextPosition> group : groups) {
mergedTextPositions.add(new OCR.TextGroup(group));
}
Stopwatch w3 = new Stopwatch().start();
final ConcurrentLinkedQueue<Tess> tessQueue = new ConcurrentLinkedQueue<TesseractCopyRectOCR.Tess>();
for (int i = 0; i < THREADS; i++) {
executor.submit(new Runnable() {
@Override
public void run() {
try {
TesseractCopyRectOCR.Tess tess = new TesseractCopyRectOCR.Tess();
tess.setImage(scaledImage, null);
tessQueue.add(tess);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
System.out.println("timing setup tess: " + w3.stop().elapsedMillis());
System.out.println("merge textpositions: " + mergedTextPositions.size() + " testpositions: " + textPositions.size() + " groups: "
+ groups.size());
Stopwatch w2 = new Stopwatch().start();
Map<OCR.TextPosition, Future<List<Result>>> textFutures = new HashMap<>();
for (final TextPosition textPosition : mergedTextPositions) {
if (textPosition.getBoundingBox().w < 10 || textPosition.getBoundingBox().h < 10) {
continue;
}
Future<List<Result>> future = executor.submit(new Callable<List<Result>>() {
@Override
public List<Result> call() throws Exception {
Tess tess = tessQueue.poll();
try {
tess.setRectangle(textPosition.getBoundingBox());
tess.recognize();
return tess.parseResults(TessPageIteratorLevel.RIL_WORD);
} finally {
tessQueue.add(tess);
}
}
});
textFutures.put(textPosition, future);
}
System.out.println("timing queuing: " + w2.stop().elapsedMillis());
Stopwatch w1 = new Stopwatch().start();
OCR.Result bestResult = new OCR.Result("", 0f, null);
for (Entry<TextPosition, Future<List<Result>>> textFuture : textFutures.entrySet()) {
{
List<Result> results = textFuture.getValue().get();
Result result = toResult(results, QUERY_STRING.length());
if (result != null && result.getProbability() > bestResult.getProbability()) {
bestResult = result;
}
}
if (textFuture instanceof OCR.TextGroup) {
OCR.TextGroup textGroup = (OCR.TextGroup) textFuture;
List<Result> results = toResults(textGroup.getTextElements(), textFutures);
Result result = toResult(results, QUERY_STRING.length());
if (result != null && result.getProbability() > bestResult.getProbability()) {
bestResult = result;
}
}
}
System.out.println("timing results: " + w1.stop().elapsedMillis());
System.out.println("BestResult: " + bestResult);
w.stop();
render(textPositions, FILE_TEXTS);
render(groups, FILE_BOXES);
System.out.println(w.elapsedTime(TimeUnit.MILLISECONDS));
}
private List<Result> toResults(List<TextPosition> textElements, Map<TextPosition, Future<List<Result>>> textFutures)
throws InterruptedException, ExecutionException {
List<Result> results = new LinkedList<OCR.Result>();
for (TextPosition textElement : textElements) {
results.addAll(textFutures.get(textElement).get());
}
return results;
}
private void render(List<? extends HasBoundingBox> textPositions, String file) throws IOException {
BufferedImage image = scale(ImageIO.read(new File(FILE)), SCALE);
Graphics g = image.getGraphics();
g.setColor(Color.RED);
for (HasBoundingBox hasBoundingBox : textPositions) {
Rectangle.Int bbox = hasBoundingBox.getBoundingBox();
g.drawRect(bbox.x, bbox.y, bbox.w, bbox.h);
}
ImageIO.write(image, "PNG", new File(file));
}
private BufferedImage scale(BufferedImage image, double scale) {
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
return new AffineTransformOp(at, AffineTransformOp.TYPE_BICUBIC).filter(image, null);
}
private static String toString(Iterable<OCR.Result> group) {
String resultString = "";
for (OCR.Result result : group) {
if (result.getText().trim().isEmpty()) {
continue;
}
resultString += result.getText() + " ";
}
return resultString.isEmpty() ? resultString : resultString.substring(0, resultString.length() - 1);
}
private OCR.Result toResult(List<Result> results, int length) {
String text = toString(results);
Result[] resultMap = toResultMap(results, text);
Distance distance = StringDistances.getSubstringNormalizedDistance(QUERY_STRING, text);
if (distance.propability == 0 || distance.position == -1) {
return null;
}
Set<OCR.Result> resultSet = new LinkedHashSet<OCR.Result>();
for (int i = distance.position; i < distance.position + length; i++) {
resultSet.add(resultMap[i]);
}
Rectangle.Int bbox = resultSet.iterator().next().getBoundingBox();
for (OCR.Result result : resultSet) {
bbox = bbox.union(result.getBoundingBox());
}
String matchingText = toString(resultSet);
return new OCR.Result(matchingText, distance.propability, bbox);
}
private static OCR.Result[] toResultMap(Iterable<OCR.Result> group, String grouptext) {
OCR.Result[] resultMap = new OCR.Result[grouptext.length() + 1];
int position = 0;
for (OCR.Result result : group) {
if (result.getText().trim().isEmpty()) {
continue;
}
int fromIndex = position;
int toIndex = position + result.getText().length() + 1;
Arrays.fill(resultMap, fromIndex, toIndex, result);
position = toIndex;
}
return resultMap;
}
}
| 34.5 | 131 | 0.728116 |
fc88207a70df39327beb2556cf066c92183a0d77
| 5,611 |
/*
* 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.flink.runtime.memory;
import org.apache.flink.core.memory.MemorySegment;
import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable;
import org.apache.flink.runtime.memorymanager.DefaultMemoryManager;
import org.apache.flink.runtime.memorymanager.MemoryAllocationException;
import org.apache.flink.runtime.operators.testutils.DummyInvokable;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static org.junit.Assert.fail;
/**
* Tests for the memory manager, in the mode where it pre-allocates all memory.
*/
public class MemoryManagerLazyAllocationTest {
private static final long RANDOM_SEED = 643196033469871L;
private static final int MEMORY_SIZE = 1024 * 1024 * 72; // 72 MiBytes
private static final int PAGE_SIZE = 1024 * 32; // 32 KiBytes
private static final int NUM_PAGES = MEMORY_SIZE / PAGE_SIZE;
private DefaultMemoryManager memoryManager;
private Random random;
@Before
public void setUp() {
this.memoryManager = new DefaultMemoryManager(MEMORY_SIZE, 1, PAGE_SIZE, false);
this.random = new Random(RANDOM_SEED);
}
@After
public void tearDown() {
if (!this.memoryManager.verifyEmpty()) {
fail("Memory manager is not complete empty and valid at the end of the test.");
}
this.memoryManager = null;
this.random = null;
}
@Test
public void allocateAllSingle() {
try {
final AbstractInvokable mockInvoke = new DummyInvokable();
List<MemorySegment> segments = new ArrayList<MemorySegment>();
try {
for (int i = 0; i < NUM_PAGES; i++) {
segments.add(this.memoryManager.allocatePages(mockInvoke, 1).get(0));
}
}
catch (MemoryAllocationException e) {
fail("Unable to allocate memory");
}
for (MemorySegment seg : segments) {
this.memoryManager.release(seg);
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void allocateAllMulti() {
try {
final AbstractInvokable mockInvoke = new DummyInvokable();
final List<MemorySegment> segments = new ArrayList<MemorySegment>();
try {
for(int i = 0; i < NUM_PAGES / 2; i++) {
segments.addAll(this.memoryManager.allocatePages(mockInvoke, 2));
}
} catch (MemoryAllocationException e) {
Assert.fail("Unable to allocate memory");
}
this.memoryManager.release(segments);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void allocateMultipleOwners() {
final int NUM_OWNERS = 17;
try {
AbstractInvokable[] owners = new AbstractInvokable[NUM_OWNERS];
@SuppressWarnings("unchecked")
List<MemorySegment>[] mems = (List<MemorySegment>[]) new List<?>[NUM_OWNERS];
for (int i = 0; i < NUM_OWNERS; i++) {
owners[i] = new DummyInvokable();
mems[i] = new ArrayList<MemorySegment>(64);
}
// allocate all memory to the different owners
for (int i = 0; i < NUM_PAGES; i++) {
final int owner = this.random.nextInt(NUM_OWNERS);
mems[owner].addAll(this.memoryManager.allocatePages(owners[owner], 1));
}
// free one owner at a time
for (int i = 0; i < NUM_OWNERS; i++) {
this.memoryManager.releaseAll(owners[i]);
owners[i] = null;
Assert.assertTrue("Released memory segments have not been destroyed.", allMemorySegmentsFreed(mems[i]));
mems[i] = null;
// check that the owner owners were not affected
for (int k = i+1; k < NUM_OWNERS; k++) {
Assert.assertTrue("Non-released memory segments are accidentaly destroyed.", allMemorySegmentsValid(mems[k]));
}
}
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
@Test
public void allocateTooMuch() {
try {
final AbstractInvokable mockInvoke = new DummyInvokable();
List<MemorySegment> segs = this.memoryManager.allocatePages(mockInvoke, NUM_PAGES);
try {
this.memoryManager.allocatePages(mockInvoke, 1);
Assert.fail("Expected MemoryAllocationException.");
} catch (MemoryAllocationException maex) {
// expected
}
Assert.assertTrue("The previously allocated segments were not valid any more.",
allMemorySegmentsValid(segs));
this.memoryManager.releaseAll(mockInvoke);
}
catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
private boolean allMemorySegmentsValid(List<MemorySegment> memSegs) {
for (MemorySegment seg : memSegs) {
if (seg.isFreed()) {
return false;
}
}
return true;
}
private boolean allMemorySegmentsFreed(List<MemorySegment> memSegs) {
for (MemorySegment seg : memSegs) {
if (!seg.isFreed()) {
return false;
}
}
return true;
}
}
| 27.915423 | 115 | 0.699697 |
34909759679389fbc743e570dc7100019746dde8
| 8,238 |
package org.fisco.bcos;
import static org.junit.Assert.assertTrue;
import java.math.BigInteger;
import org.apache.tools.ant.taskdefs.SQLExec.Transaction;
import org.fisco.bcos.constants.GasConstants;
import org.fisco.bcos.temp.HelloWorld;
import org.fisco.bcos.temp.SupplyChain;
import org.fisco.bcos.web3j.crypto.Credentials;
import org.fisco.bcos.web3j.crypto.gm.GenCredential;
import org.fisco.bcos.web3j.protocol.Web3j;
import org.fisco.bcos.web3j.protocol.core.methods.response.TransactionReceipt;
import org.fisco.bcos.web3j.tx.gas.StaticGasProvider;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class ContractTest extends BaseTest {
@Autowired private Web3j web3j;
@Autowired private Credentials credentials;
@Test
public void deployAndCallHelloWorld() throws Exception {
// deploy contract
HelloWorld helloWorld =
HelloWorld.deploy(
web3j,
credentials,
new StaticGasProvider(
GasConstants.GAS_PRICE, GasConstants.GAS_LIMIT))
.send();
if (helloWorld != null) {
System.out.println("HelloWorld address is: " + helloWorld.getContractAddress());
// call set function
helloWorld.set("Hello, World!").send();
// call get function
String result = helloWorld.get().send();
System.out.println(result);
assertTrue("Hello, World!".equals(result));
}
}
@Test
public void deployANdCallSupplyChain() throws Exception {
Credentials bank_account = GenCredential.create();
String bank_account_address = bank_account.getAddress();
String bank_account_private_key = bank_account.getEcKeyPair().getPrivateKey().toString(16);
System.out.println("root privatekey*****"+bank_account_private_key+"*****");
System.out.println("original address: "+bank_account_address);
System.out.println("reget address: "+GenCredential.create(bank_account_private_key).getAddress());
Credentials user1_account = GenCredential.create();
String user1_account_address = user1_account.getAddress();
Credentials user2_account = GenCredential.create();
String user2_account_address = user2_account.getAddress();
Credentials user3_account = GenCredential.create();
String user3_account_address = user3_account.getAddress();
SupplyChain sc = SupplyChain.deploy(
web3j,
bank_account,
new StaticGasProvider(
GasConstants.GAS_PRICE,
GasConstants.GAS_LIMIT)).send();
if (sc != null) {
//////////////////// deploy test done
System.out.println("SupplyChain address is: *****" + sc.getContractAddress() + "*****");
//////////////////// init test done
//////////////////// user1 init: 20000000
//////////////////// user2 init: 19981023
//////////////////// user3 init: 995000000
// TransactionReceipt temp1 = sc.init(user1_account_address, BigInteger.valueOf(20000000)).send();
// TransactionReceipt temp2 = sc.init(user2_account_address, BigInteger.valueOf(19981023)).send();
// TransactionReceipt temp3 = sc.init(user3_account_address, BigInteger.valueOf(995000000)).send();
// System.out.println("*****first contract call receipt: \n\ttemp1: " + temp1.toString() + "\n\ttemp2: " + temp2.toString() + "\n\ttemp3: " + temp3.toString());
}
// SupplyChain scu1 = SupplyChain.load(sc.getContractAddress(), web3j, user1_account, new StaticGasProvider(GasConstants.GAS_PRICE, GasConstants.GAS_LIMIT));
// if (scu1 != null) {
// System.out.println("\n\t*****user1 balance after init: " + scu1.getBalances().send());
// }
// SupplyChain scu2 = SupplyChain.load(sc.getContractAddress(), web3j, user2_account, new StaticGasProvider(GasConstants.GAS_PRICE, GasConstants.GAS_LIMIT));
// if (scu2 != null) {
// System.out.println("\n\t*****user2 balance after init: " + scu2.getBalances().send());
// TransactionReceipt temp = scu2.transferMoney(user1_account_address, BigInteger.valueOf(1023)).send();
// // System.out.println("*****transfer money receipt: " + temp.toString());
// //////////////////// transfer test done
// //////////////////// user2 transfer 1023 to user1
// System.out.println("\n\t*****user1 balance after transfer: " + scu1.getBalances().send());
// System.out.println("\n\t*****user2 balance after transfer: " + scu2.getBalances().send());
// //////////////////// loan test done
// //////////////////// user1 loan 20000000 to user2
// TransactionReceipt loan_tr = scu1.loan(user2_account_address, BigInteger.valueOf(20000000), BigInteger.valueOf(10)).send();
// // System.out.println("*****loan receipt: " + loan_tr.toString());
// System.out.println("\n\t*****user1 balance after loan: " + scu1.getBalances().send());
// System.out.println("\n\t*****user2 balance after loan: " + scu2.getBalances().send());
// //////////////////// get loans test done
// //////////////////// param1 user_account_address, param2 index
// System.out.println("\t**********check loans: " + sc.loans(user1_account_address, BigInteger.valueOf(0)).send().toString());
// //////////////////// **********check loans: Tuple6{value1=1576050328445, value2=true, value3=0x101be9d9fa84c90a4c4ee9e6f65e82bc8ab31080, value4=20000000, value5=87976050328445, value6=false}
// //////////////////// payLoan test done
// //////////////////// user2 payloan 10000000 back to user1
// TransactionReceipt pay_tr = scu2.payLoan(BigInteger.valueOf(0), BigInteger.valueOf(10000000)).send();
// // System.out.println("*****payloan receipt: " + pay_tr.toString());
// System.out.println("\n\t*****user1 balance after loan: " + scu1.getBalances().send());
// System.out.println("\n\t*****user2 balance after loan: " + scu2.getBalances().send());
// System.out.println("\t**********check loans after pay: " + sc.loans(user1_account_address, BigInteger.valueOf(0)).send().toString());
// }
// SupplyChain scu3 = SupplyChain.load(sc.getContractAddress(), web3j, user3_account, new StaticGasProvider(GasConstants.GAS_PRICE, GasConstants.GAS_LIMIT));
// if (scu3 != null) {
// //////////////////// transferLoan test done
// //////////////////// user1 transferLoan 5000000 to user3
// System.out.println("\n\t*****user3 balance after init: " + scu3.getBalances().send());
// TransactionReceipt temp = scu1.transferLoan(BigInteger.valueOf(0), user3_account_address, BigInteger.valueOf(5000000)).send();
// // System.out.println("*****transfer loan receipt: " + temp.toString());
// System.out.println("\t**********check loans after transferloan: \n\t\tuser1:" + sc.loans(user1_account_address, BigInteger.valueOf(0)).send().toString() + "\n\t\tuser3:" + sc.loans(user3_account_address, BigInteger.valueOf(0)).send().toString());
// System.out.println("\n\t*****user3 balance after transfer loan: " + scu3.getBalances().send());
// //////////////////// financing test done
// //////////////////// user3 ask for financing to get 5000000
// TransactionReceipt f_rt = scu3.finacing(BigInteger.valueOf(1000000), BigInteger.valueOf(365)).send();
// // System.out.println("*****transfer loan receipt: " + f_rt.toString());
// System.out.println("\n\t*****user3 balance after financing: " + scu3.getBalances().send());
// System.out.println("\t**********check loans after financing: \n\t\tuser3 loans 1:" + sc.loans(user3_account_address, BigInteger.valueOf(1)).send().toString());
// }
}
}
| 58.425532 | 261 | 0.602573 |
34fc26aaacfc2622a79e0d842809f828e1fb3b9d
| 315 |
package study.nestpath;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NestPathStudy {
public static void main(final String[] args) {
SpringApplication.run(NestPathStudy.class, args);
}
}
| 26.25 | 68 | 0.790476 |
9bef72cbe9769b6204eb8c63a92a9dac6e59c821
| 3,203 |
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.propertychain.models;
import com.aliyun.tea.*;
public class UpdateWarehouseRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 地址(传原值,不可修改此项)
@NameInMap("address")
@Validation(required = true)
public String address;
// 平面图
@NameInMap("blueprint_id")
public String blueprintId;
// 所在国家(传原值,不可修改此项)
@NameInMap("country")
@Validation(required = true)
public String country;
// 其他信息
@NameInMap("extra_info")
public String extraInfo;
// 仓库面积
@NameInMap("warehouse_area")
@Validation(required = true)
public String warehouseArea;
// 仓库id
@NameInMap("warehouse_id")
@Validation(required = true)
public String warehouseId;
// 仓库名称(传原值,不可修改此项)
@NameInMap("warehouse_name")
@Validation(required = true)
public String warehouseName;
public static UpdateWarehouseRequest build(java.util.Map<String, ?> map) throws Exception {
UpdateWarehouseRequest self = new UpdateWarehouseRequest();
return TeaModel.build(map, self);
}
public UpdateWarehouseRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public UpdateWarehouseRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public UpdateWarehouseRequest setAddress(String address) {
this.address = address;
return this;
}
public String getAddress() {
return this.address;
}
public UpdateWarehouseRequest setBlueprintId(String blueprintId) {
this.blueprintId = blueprintId;
return this;
}
public String getBlueprintId() {
return this.blueprintId;
}
public UpdateWarehouseRequest setCountry(String country) {
this.country = country;
return this;
}
public String getCountry() {
return this.country;
}
public UpdateWarehouseRequest setExtraInfo(String extraInfo) {
this.extraInfo = extraInfo;
return this;
}
public String getExtraInfo() {
return this.extraInfo;
}
public UpdateWarehouseRequest setWarehouseArea(String warehouseArea) {
this.warehouseArea = warehouseArea;
return this;
}
public String getWarehouseArea() {
return this.warehouseArea;
}
public UpdateWarehouseRequest setWarehouseId(String warehouseId) {
this.warehouseId = warehouseId;
return this;
}
public String getWarehouseId() {
return this.warehouseId;
}
public UpdateWarehouseRequest setWarehouseName(String warehouseName) {
this.warehouseName = warehouseName;
return this;
}
public String getWarehouseName() {
return this.warehouseName;
}
}
| 25.624 | 95 | 0.66906 |
c7eb0660ef0bcaa95a7f875e5046c3060f214712
| 218 |
package ru.stqa.pft.sandbox;
class HelloWorld {
public static void main(String[] args) {
System.out.println("1\"\"");
System.out.println("2");
System.out.println("3");
System.out.println("4");
}
}
| 19.818182 | 42 | 0.623853 |
f0f7032b852998cbb867f11e9b9a94f392c2194b
| 869 |
package aula07.exercicio2;
public class Testes {
// Testes Ex2
public static void main(String[] args) {
//Crio Jogadores
JogadorDeCampo jogador1 = new JogadorDeCampo(7, "Ronaldo");
GuardaRedes guardaRedes1 = new GuardaRedes(1, "Rui Patricio");
JogadorDeCampo jogador2 = new JogadorDeCampo(5, "Pepe");
// Atribuir valores ao guarda redes
guardaRedes1.setGolosSofridos(3);
guardaRedes1.setNumGolos(2);
//Atribuir valores ao jogador
jogador1.setNumGolos(6);
jogador1.setPassesFeitos(4);
jogador1.setPassesRecebidos(5);
// Testes dos atributos com toString
System.out.println("Jogadores Criados: ");
System.out.println(jogador1.toString());
System.out.println(guardaRedes1.toString());
System.out.println(jogador2.toString());
}
}
| 34.76 | 70 | 0.654776 |
0a33386dda625e4b2799a038acae923b321d04a5
| 15,097 |
/*
* Copyright 2017 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License"). See License in the project root for license information.
*/
package com.linkedin.kafka.cruisecontrol.monitor.sampling.aggregator;
import com.linkedin.cruisecontrol.exception.NotEnoughValidWindowsException;
import com.linkedin.cruisecontrol.monitor.sampling.aggregator.AggregationOptions;
import com.linkedin.cruisecontrol.monitor.sampling.aggregator.MetricSampleAggregationResult;
import com.linkedin.cruisecontrol.monitor.sampling.aggregator.MetricSampleCompleteness;
import com.linkedin.cruisecontrol.monitor.sampling.aggregator.MetricSampleAggregator;
import com.linkedin.kafka.cruisecontrol.async.progress.OperationProgress;
import com.linkedin.kafka.cruisecontrol.async.progress.RetrievingMetrics;
import com.linkedin.kafka.cruisecontrol.common.MetadataClient;
import com.linkedin.kafka.cruisecontrol.config.KafkaCruiseControlConfig;
import com.linkedin.kafka.cruisecontrol.monitor.ModelCompletenessRequirements;
import com.linkedin.kafka.cruisecontrol.monitor.metricdefinition.KafkaMetricDef;
import com.linkedin.kafka.cruisecontrol.monitor.sampling.PartitionEntity;
import com.linkedin.kafka.cruisecontrol.monitor.sampling.PartitionMetricSample;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.kafka.clients.Metadata;
import org.apache.kafka.common.Cluster;
import org.apache.kafka.common.Node;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class aggregates the partition metric samples generated by the MetricFetcher.
* <p>
* The partition metric sample aggregator performs the sanity check on the samples and aggregate the samples into the
* corresponding window. we assume the sample we get are only from the leaders, and we are going to derive the
* follower metrics based on the leader metrics.
* </p>
* @see MetricSampleAggregator
*/
public class KafkaPartitionMetricSampleAggregator extends MetricSampleAggregator<String, PartitionEntity> {
private static final Logger LOG = LoggerFactory.getLogger(KafkaPartitionMetricSampleAggregator.class);
private final int _maxAllowedExtrapolationsPerPartition;
private final Metadata _metadata;
/**
* Construct the metric sample aggregator.
*
* @param config The load monitor configurations.
* @param metadata The metadata of the cluster.
*/
public KafkaPartitionMetricSampleAggregator(KafkaCruiseControlConfig config,
Metadata metadata) {
super(config.getInt(KafkaCruiseControlConfig.NUM_PARTITION_METRICS_WINDOWS_CONFIG),
config.getLong(KafkaCruiseControlConfig.PARTITION_METRICS_WINDOW_MS_CONFIG),
config.getInt(KafkaCruiseControlConfig.MIN_SAMPLES_PER_PARTITION_METRICS_WINDOW_CONFIG).byteValue(),
config.getInt(KafkaCruiseControlConfig.PARTITION_METRIC_SAMPLE_AGGREGATOR_COMPLETENESS_CACHE_SIZE_CONFIG),
KafkaMetricDef.commonMetricDef());
_metadata = metadata;
_maxAllowedExtrapolationsPerPartition =
config.getInt(KafkaCruiseControlConfig.MAX_ALLOWED_EXTRAPOLATIONS_PER_PARTITION_CONFIG);
_sampleType = SampleType.PARTITION;
}
/**
* Add a sample to the metric aggregator. This method is thread safe.
*
* @param sample The metric sample to add.
*/
public boolean addSample(PartitionMetricSample sample) {
return addSample(sample, true);
}
/**
* Add a sample to the metric aggregator. This method is thread safe.
*
* @param sample The metric sample to add.
* @param leaderValidation whether perform the leader validation or not.
*
* @return true if the sample is accepted, false if the sample is ignored.
*/
public boolean addSample(PartitionMetricSample sample, boolean leaderValidation) {
// Sanity check the sample
return isValidSample(sample, leaderValidation) && super.addSample(sample);
}
/**
* Collect the aggregated metrics for all the topic partitions.
* <p>
* If a topic has at least one window that does not have enough samples, that topic will be excluded from the
* returned aggregated metrics. This is because:
* <ol>
* <li>
* We assume that only new topics would have insufficient data. So we only balance the existing topics and
* allow more time to collect enough utilization data for the new topics.
* </li>
* <li>
* If we don't have enough data to make a replica movement decision, it is better not to take any action.
* </li>
* </ol>
*
* @param clusterAndGeneration The current cluster information.
* @param now the current time.
* @param operationProgress to report the async operation progress.
* @return The {@link MetricSampleAggregationResult} for all the partitions.
*/
public MetricSampleAggregationResult<String, PartitionEntity> aggregate(MetadataClient.ClusterAndGeneration clusterAndGeneration,
long now,
OperationProgress operationProgress)
throws NotEnoughValidWindowsException {
ModelCompletenessRequirements requirements = new ModelCompletenessRequirements(1, 0.0, false);
return aggregate(clusterAndGeneration, -1L, now, requirements, operationProgress);
}
/**
* Collect the aggregated metrics for all the topic partitions for a time window.
* <p>
* If a topic has at least one window that does not have enough samples, that topic will be excluded from the
* returned aggregated metrics. This is because:
* <ol>
* <li>
* We assume that only new topics would have insufficient data. So we only balance the existing topics and
* allow more time to collect enough utilization data for the new topics.
* </li>
* <li>
* If we don't have enough data to make a replica movement decision, it is better not to take any action.
* </li>
* </ol>
*
* @param clusterAndGeneration The current cluster information.
* @param from the start of the time window
* @param to the end of the time window
* @param requirements the {@link ModelCompletenessRequirements} for the aggregation result.
* @param operationProgress to report the operation progress.
* @return The {@link MetricSampleAggregationResult} for all the partitions.
*/
public MetricSampleAggregationResult<String, PartitionEntity> aggregate(MetadataClient.ClusterAndGeneration clusterAndGeneration,
long from,
long to,
ModelCompletenessRequirements requirements,
OperationProgress operationProgress)
throws NotEnoughValidWindowsException {
RetrievingMetrics step = new RetrievingMetrics();
try {
operationProgress.addStep(step);
return aggregate(from, to, toAggregationOptions(clusterAndGeneration.cluster(), requirements));
} finally {
step.done();
}
}
/**
* Get the metric sample completeness for a given period.
*
* @param cluster the current cluster topology
* @param from the start of the period
* @param to the end of the period
* @param requirements the model completeness requirements.
* @return The metric sample completeness based on the completeness requirements.
*/
public MetricSampleCompleteness<String, PartitionEntity> completeness(Cluster cluster,
long from,
long to,
ModelCompletenessRequirements requirements) {
return completeness(from, to, toAggregationOptions(cluster, requirements));
}
/**
* Get a sorted set of valid windows in the aggregator. A valid window is a window with
* {@link KafkaCruiseControlConfig#MIN_VALID_PARTITION_RATIO_CONFIG enough valid partitions}
* being monitored. A valid partition must be valid in all the windows in the returned set.
*
* @param clusterAndGeneration The current cluster and generation.
* @param minMonitoredPartitionsPercentage the minimum required monitored partitions percentage.
* @return a sorted set of valid windows in the aggregator.
*/
public SortedSet<Long> validWindows(MetadataClient.ClusterAndGeneration clusterAndGeneration,
double minMonitoredPartitionsPercentage) {
AggregationOptions<String, PartitionEntity> options =
new AggregationOptions<>(minMonitoredPartitionsPercentage,
0.0,
1,
_maxAllowedExtrapolationsPerPartition,
allPartitions(clusterAndGeneration.cluster()),
AggregationOptions.Granularity.ENTITY_GROUP,
true);
MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options);
return windowIndicesToWindows(completeness.validWindowIndices(), _windowMs);
}
/**
* Get the valid partitions percentage across all the windows.
*
* @param clusterAndGeneration the current cluster and generation.
* @return The percentage of valid partitions across all the windows.
*/
public double monitoredPercentage(MetadataClient.ClusterAndGeneration clusterAndGeneration) {
AggregationOptions<String, PartitionEntity> options =
new AggregationOptions<>(0.0,
0.0,
1,
_maxAllowedExtrapolationsPerPartition,
allPartitions(clusterAndGeneration.cluster()),
AggregationOptions.Granularity.ENTITY_GROUP,
true);
MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options);
return completeness.validEntityRatio();
}
/**
* Get the monitored partition percentage in each window.
* @param clusterAndGeneration the current cluster and generation.
* @return A mapping from window to the monitored partitions percentage.
*/
public SortedMap<Long, Float> validPartitionRatioByWindows(MetadataClient.ClusterAndGeneration clusterAndGeneration) {
AggregationOptions<String, PartitionEntity> options =
new AggregationOptions<>(0.0,
0.0,
1,
_maxAllowedExtrapolationsPerPartition,
allPartitions(clusterAndGeneration.cluster()),
AggregationOptions.Granularity.ENTITY_GROUP,
true);
MetricSampleCompleteness<String, PartitionEntity> completeness = completeness(-1, Long.MAX_VALUE, options);
return windowIndicesToWindows(completeness.validEntityRatioWithGroupGranularityByWindowIndex(), _windowMs);
}
private Set<PartitionEntity> allPartitions(Cluster cluster) {
Set<PartitionEntity> allPartitions = new HashSet<>();
for (String topic : cluster.topics()) {
for (PartitionInfo partitionInfo : cluster.partitionsForTopic(topic)) {
TopicPartition tp = new TopicPartition(partitionInfo.topic(), partitionInfo.partition());
PartitionEntity partitionEntity = new PartitionEntity(tp);
allPartitions.add(_identityEntityMap.computeIfAbsent(partitionEntity, k -> partitionEntity));
}
}
return allPartitions;
}
private SortedSet<Long> windowIndicesToWindows(SortedSet<Long> original, long windowMs) {
SortedSet<Long> result = new TreeSet<>(Collections.reverseOrder());
original.forEach(idx -> result.add(idx * windowMs));
return result;
}
private <T> SortedMap<Long, T> windowIndicesToWindows(SortedMap<Long, T> original, long windowMs) {
SortedMap<Long, T> result = new TreeMap<>(Collections.reverseOrder());
original.forEach((key, value) -> result.put(key * windowMs, value));
return result;
}
/**
* This is a simple sanity check on the sample data. We only verify that
* <p>
* 1. the broker of the sampled data is from the broker who holds the leader replica. If it is not, we simply
* discard the data because leader migration may have occurred so the metrics on the old data might not be
* accurate anymore.
* <p>
* 2. The sample contains metric for all the resources.
*
* @param sample the sample to do the sanity check.
* @param leaderValidation whether do the leader validation or not.
* @return <tt>true</tt> if the sample is valid.
*/
private boolean isValidSample(PartitionMetricSample sample, boolean leaderValidation) {
boolean validLeader = true;
if (leaderValidation) {
Node leader = _metadata.fetch().leaderFor(sample.entity().tp());
validLeader = (leader != null) && (sample.brokerId() == leader.id());
if (!validLeader) {
LOG.warn("The metric sample is discarded due to invalid leader. Current leader {}, Sample: {}", leader, sample);
}
}
// TODO: We do not have the replication bytes rate at this point. Use the default validation after they are available.
boolean completeMetrics = sample.isValid(_metricDef) || (sample.allMetricValues().size() == _metricDef.size() - 2
&& sample.allMetricValues().containsKey(_metricDef.metricInfo(KafkaMetricDef.REPLICATION_BYTES_IN_RATE.name()).id())
&& sample.allMetricValues().containsKey(_metricDef.metricInfo(KafkaMetricDef.REPLICATION_BYTES_OUT_RATE.name()).id()));
if (!completeMetrics) {
LOG.warn("The metric sample is discarded due to missing metrics. Sample: {}", sample);
}
return validLeader && completeMetrics;
}
private AggregationOptions<String, PartitionEntity> toAggregationOptions(Cluster cluster,
ModelCompletenessRequirements requirements) {
Set<PartitionEntity> allPartitions = allPartitions(cluster);
return new AggregationOptions<>(requirements.minMonitoredPartitionsPercentage(),
0.0,
requirements.minRequiredNumWindows(),
_maxAllowedExtrapolationsPerPartition,
allPartitions,
AggregationOptions.Granularity.ENTITY_GROUP,
requirements.includeAllTopics());
}
}
| 49.661184 | 146 | 0.68199 |
f68e9558300dc5075c34abbb77b7a0a657254168
| 1,856 |
package com.annarestech.alert911.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Call {
private static final String LATLON_TEMPLATE = "http://maps.googleapis.com/maps/api/geocode/json?latlng=";
private String latlong;
private int zipCode;
private String details;
private int callerID;
private Location loc;
Call(CityDepartment c, float lat, float longitude, String hundredBlock) {
latlong = LATLON_TEMPLATE + lat + "," + longitude;
details = hundredBlock;
String rawString = "";
BufferedReader contentURL;
try {
URL u = new URL(latlong);
contentURL = new BufferedReader(new InputStreamReader(u.openStream()));
String curr;
while ((curr = contentURL.readLine()) != null) {
rawString += curr;
}
} catch (IOException e) {
e.printStackTrace();
}
JsonParser parse = new JsonParser();
JsonElement elem = parse.parse(rawString);
//JsonArray searchArray = elem.getAsJsonArray();
JsonObject searchResults = elem.getAsJsonObject();
JsonArray searchArray = (JsonArray) (searchResults.get("results"));
JsonObject addressObject = (JsonObject) searchArray.get(0);
JsonArray addressArray = (JsonArray) addressObject.get("address_components");
for(int i = 0; i < addressArray.size(); i++) {
if(((JsonElement) ((JsonObject) addressArray.get(i)).get("types")).toString().equals("[\"postal_code\"]")) {
zipCode = Integer.parseInt(((JsonElement) ((JsonObject) addressArray.get(i)).get("short_name")).toString().substring(1, 6));
}
loc = c.getLocT().get(Integer.toString(zipCode));
for(int j = 0; j < loc.uBase.uBase.size(); i++) {
}
}
}
}
| 30.933333 | 128 | 0.706358 |
eef0191b06c0ce4956d1fbbd8eb6dc318324620c
| 15,612 |
package com.direwolf20.buildinggadgets.client.renders;
import com.direwolf20.buildinggadgets.client.renderer.DireBufferBuilder;
import com.direwolf20.buildinggadgets.client.renderer.DireVertexBuffer;
import com.direwolf20.buildinggadgets.client.renderer.OurRenderTypes;
import com.direwolf20.buildinggadgets.common.BuildingGadgets;
import com.direwolf20.buildinggadgets.common.tainted.building.PlacementTarget;
import com.direwolf20.buildinggadgets.common.tainted.building.Region;
import com.direwolf20.buildinggadgets.common.tainted.building.view.IBuildView;
import com.direwolf20.buildinggadgets.common.tainted.building.view.BuildContext;
import com.direwolf20.buildinggadgets.common.capability.CapabilityTemplate;
import com.direwolf20.buildinggadgets.common.items.GadgetCopyPaste;
import com.direwolf20.buildinggadgets.common.world.MockDelegationWorld;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.mojang.blaze3d.matrix.MatrixStack;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRenderType;
import net.minecraft.block.BlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BlockRendererDispatcher;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.renderer.model.IBakedModel;
import net.minecraft.client.renderer.vertex.VertexFormat;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Matrix4f;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.client.model.data.EmptyModelData;
import java.io.Closeable;
import java.util.*;
import java.util.function.Consumer;
import static com.direwolf20.buildinggadgets.client.renderer.MyRenderMethods.renderModelBrightnessColorQuads;
public class CopyPasteRender extends BaseRenderer {
private MultiVBORenderer renderBuffer;
private int tickTrack = 0;
@Override
public void render(RenderWorldLastEvent evt, PlayerEntity player, ItemStack heldItem) {
// We can completely trust that heldItem isn't empty and that it's a copy paste gadget.
super.render(evt, player, heldItem);
// Provide this as both renders require the data.
Vector3d cameraView = getMc().gameRenderer.getActiveRenderInfo().getProjectedView();
// translate the matric to the projected view
MatrixStack stack = evt.getMatrixStack(); //Get current matrix position from the evt call
stack.push(); //Save the render position from RenderWorldLast
stack.translate(-cameraView.getX(), -cameraView.getY(), -cameraView.getZ()); //Sets render position to 0,0,0
if (GadgetCopyPaste.getToolMode(heldItem) == GadgetCopyPaste.ToolMode.COPY) {
GadgetCopyPaste.getSelectedRegion(heldItem).ifPresent(region ->
renderCopy(stack, region));
} else
renderPaste(stack, cameraView, player, heldItem);
stack.pop();
}
private void renderCopy(MatrixStack matrix, Region region) {
BlockPos startPos = region.getMin();
BlockPos endPos = region.getMax();
BlockPos blankPos = new BlockPos(0, 0, 0);
if (startPos.equals(blankPos) || endPos.equals(blankPos))
return;
//We want to draw from the starting position to the (ending position)+1
int x = Math.min(startPos.getX(), endPos.getX()), y = Math.min(startPos.getY(), endPos.getY()), z = Math.min(startPos.getZ(), endPos.getZ());
int dx = (startPos.getX() > endPos.getX()) ? startPos.getX() + 1 : endPos.getX() + 1;
int dy = (startPos.getY() > endPos.getY()) ? startPos.getY() + 1 : endPos.getY() + 1;
int dz = (startPos.getZ() > endPos.getZ()) ? startPos.getZ() + 1 : endPos.getZ() + 1;
int R = 255, G = 223, B = 127;
IRenderTypeBuffer.Impl buffer = Minecraft.getInstance().getRenderTypeBuffers().getBufferSource();
IVertexBuilder builder = buffer.getBuffer(OurRenderTypes.CopyGadgetLines);
Matrix4f matrix4f = matrix.getLast().getMatrix();
builder.pos(matrix4f, x, y, z).color(G, G, G, 0.0F).endVertex();
builder.pos(matrix4f, x, y, z).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, y, z).color(G, B, B, R).endVertex();
builder.pos(matrix4f, dx, y, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, y, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, y, z).color(B, B, G, R).endVertex();
builder.pos(matrix4f, x, dy, z).color(B, G, B, R).endVertex();
builder.pos(matrix4f, dx, dy, z).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, dy, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, dy, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, dy, z).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, dy, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, x, y, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, y, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, dy, dz).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, dy, z).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, y, z).color(G, G, G, R).endVertex();
builder.pos(matrix4f, dx, y, z).color(G, G, G, 0.0F).endVertex();
buffer.finish(); // @mcp: draw = finish
}
private void renderPaste(MatrixStack matrices, Vector3d cameraView, PlayerEntity player, ItemStack heldItem) {
World world = player.world;
// Check the template cap from the world
// Fetch the template key (because for some reason this is it's own cap)
world.getCapability(CapabilityTemplate.TEMPLATE_PROVIDER_CAPABILITY).ifPresent(provider -> heldItem.getCapability(CapabilityTemplate.TEMPLATE_KEY_CAPABILITY).ifPresent(key -> {
// Finally get the data from the render.
GadgetCopyPaste.getActivePos(player, heldItem).ifPresent(startPos -> {
MockDelegationWorld fakeWorld = new MockDelegationWorld(world);
BuildContext context = BuildContext.builder().player(player).stack(heldItem).build(fakeWorld);
// Get the template and move it to the start pos (player.pick())
IBuildView view = provider.getTemplateForKey(key).createViewInContext(context);
// Sort the render
List<PlacementTarget> targets = new ArrayList<>(view.estimateSize());
for (PlacementTarget target : view) {
if (target.placeIn(context)) {
targets.add(target);
}
}
renderTargets(matrices, cameraView, context, targets, startPos);
});
}));
}
private void renderTargets(MatrixStack matrix, Vector3d projectedView, BuildContext context, List<PlacementTarget> targets, BlockPos startPos) {
tickTrack++;
if (renderBuffer != null && tickTrack < 300) {
if (tickTrack % 30 == 0) {
try {
Vector3d projectedView2 = projectedView;
Vector3d startPosView = new Vector3d(startPos.getX(), startPos.getY(), startPos.getZ());
projectedView2 = projectedView2.subtract(startPosView);
renderBuffer.sort((float) projectedView2.getX(), (float) projectedView2.getY(), (float) projectedView2.getZ());
} catch (Exception ignored) {
}
}
matrix.translate(startPos.getX(), startPos.getY(), startPos.getZ());
renderBuffer.render(matrix.getLast().getMatrix()); //Actually draw whats in the buffer
return;
}
// List<BlockPos> blockPosList = sorter.getSortedTargets().stream().map(PlacementTarget::getPos).collect(Collectors.toList());
tickTrack = 0;
// System.out.println("Creating cache");
if (renderBuffer != null) //Reset Render Buffer before rebuilding
renderBuffer.close();
renderBuffer = MultiVBORenderer.of((buffer) -> {
// System.out.println("Building again");
IVertexBuilder builder = buffer.getBuffer(OurRenderTypes.RenderBlock);
IVertexBuilder noDepthbuilder = buffer.getBuffer(OurRenderTypes.CopyPasteRenderBlock);
BlockRendererDispatcher dispatcher = getMc().getBlockRendererDispatcher();
MatrixStack stack = new MatrixStack(); //Create a new matrix stack for use in the buffer building process
stack.push(); //Save position
for (PlacementTarget target : targets) {
BlockPos targetPos = target.getPos();
BlockState state = context.getWorld().getBlockState(target.getPos());
stack.push(); //Save position again
//matrix.translate(-startPos.getX(), -startPos.getY(), -startPos.getZ());
stack.translate(targetPos.getX(), targetPos.getY(), targetPos.getZ());
IBakedModel ibakedmodel = dispatcher.getModelForState(state);
BlockColors blockColors = Minecraft.getInstance().getBlockColors();
int color = blockColors.getColor(state, context.getWorld(), targetPos, 0);
float f = (float) (color >> 16 & 255) / 255.0F;
float f1 = (float) (color >> 8 & 255) / 255.0F;
float f2 = (float) (color & 255) / 255.0F;
try {
if (state.getRenderType() == BlockRenderType.MODEL) {
for (Direction direction : Direction.values()) {
if (Block.shouldSideBeRendered(state, context.getWorld(), targetPos, direction) && !(context.getWorld().getBlockState(targetPos.offset(direction)).getBlock().equals(state.getBlock()))) {
if (state.getMaterial().isOpaque()) {
renderModelBrightnessColorQuads(stack.getLast(), builder, f, f1, f2, 0.7f, ibakedmodel.getQuads(state, direction, new Random(MathHelper.getPositionRandom(targetPos)), EmptyModelData.INSTANCE), 15728640, 655360);
} else {
renderModelBrightnessColorQuads(stack.getLast(), noDepthbuilder, f, f1, f2, 0.7f, ibakedmodel.getQuads(state, direction, new Random(MathHelper.getPositionRandom(targetPos)), EmptyModelData.INSTANCE), 15728640, 655360);
}
}
}
if (state.getMaterial().isOpaque())
renderModelBrightnessColorQuads(stack.getLast(), builder, f, f1, f2, 0.7f, ibakedmodel.getQuads(state, null, new Random(MathHelper.getPositionRandom(targetPos)), EmptyModelData.INSTANCE), 15728640, 655360);
else
renderModelBrightnessColorQuads(stack.getLast(), noDepthbuilder, f, f1, f2, 0.7f, ibakedmodel.getQuads(state, null, new Random(MathHelper.getPositionRandom(targetPos)), EmptyModelData.INSTANCE), 15728640, 655360);
}
} catch (Exception e) {
BuildingGadgets.LOG.trace("Caught exception whilst rendering {}.", state, e);
}
stack.pop(); // Load the position we saved earlier
}
stack.pop(); //Load after loop
});
// try {
Vector3d projectedView2 = getMc().gameRenderer.getActiveRenderInfo().getProjectedView();
Vector3d startPosView = new Vector3d(startPos.getX(), startPos.getY(), startPos.getZ());
projectedView2 = projectedView2.subtract(startPosView);
renderBuffer.sort((float) projectedView2.getX(), (float) projectedView2.getY(), (float) projectedView2.getZ());
// } catch (Exception ignored) {
// }
matrix.translate(startPos.getX(), startPos.getY(), startPos.getZ());
renderBuffer.render(matrix.getLast().getMatrix()); //Actually draw whats in the buffer
}
@Override
public boolean isLinkable() {
return true;
}
/**
* Vertex Buffer Object for caching the render. Pretty similar to how the chunk caching works
*/
public static class MultiVBORenderer implements Closeable {
private static final int BUFFER_SIZE = 2 * 1024 * 1024 * 3;
public static MultiVBORenderer of(Consumer<IRenderTypeBuffer> vertexProducer) {
final Map<RenderType, DireBufferBuilder> builders = Maps.newHashMap();
vertexProducer.accept(rt -> builders.computeIfAbsent(rt, (_rt) -> {
DireBufferBuilder builder = new DireBufferBuilder(BUFFER_SIZE);
builder.begin(_rt.getDrawMode(), _rt.getVertexFormat());
return builder;
}));
Map<RenderType, DireBufferBuilder.State> sortCaches = Maps.newHashMap();
Map<RenderType, DireVertexBuffer> buffers = Maps.transformEntries(builders, (rt, builder) -> {
Objects.requireNonNull(rt);
Objects.requireNonNull(builder);
sortCaches.put(rt, builder.getVertexState());
builder.finishDrawing();
VertexFormat fmt = rt.getVertexFormat();
DireVertexBuffer vbo = new DireVertexBuffer(fmt);
vbo.upload(builder);
return vbo;
});
return new MultiVBORenderer(buffers, sortCaches);
}
private final ImmutableMap<RenderType, DireVertexBuffer> buffers;
private final ImmutableMap<RenderType, DireBufferBuilder.State> sortCaches;
protected MultiVBORenderer(Map<RenderType, DireVertexBuffer> buffers, Map<RenderType, DireBufferBuilder.State> sortCaches) {
this.buffers = ImmutableMap.copyOf(buffers);
this.sortCaches = ImmutableMap.copyOf(sortCaches);
}
public void sort(float x, float y, float z) {
for (Map.Entry<RenderType, DireBufferBuilder.State> kv : sortCaches.entrySet()) {
RenderType rt = kv.getKey();
DireBufferBuilder.State state = kv.getValue();
DireBufferBuilder builder = new DireBufferBuilder(BUFFER_SIZE);
builder.begin(rt.getDrawMode(), rt.getVertexFormat());
builder.setVertexState(state);
builder.sortVertexData(x, y, z);
builder.finishDrawing();
DireVertexBuffer vbo = buffers.get(rt);
vbo.upload(builder);
}
}
public void render(Matrix4f matrix) {
buffers.forEach((rt, vbo) -> {
VertexFormat fmt = rt.getVertexFormat();
rt.setupRenderState();
vbo.bindBuffer();
fmt.setupBufferState(0L);
vbo.draw(matrix, rt.getDrawMode());
DireVertexBuffer.unbindBuffer();
fmt.clearBufferState();
rt.clearRenderState();
});
}
public void close() {
buffers.values().forEach(DireVertexBuffer::close);
}
}
}
| 50.524272 | 254 | 0.640085 |
1fd7f05a28711b9f9173adf1c77a3aa1e170d01e
| 544 |
/******************************************************************************
Copyright (c) 2013, Mandar Chitre
This file is part of fjage which is released under Simplified BSD License.
See file LICENSE.txt or go to http://www.opensource.org/licenses/BSD-3-Clause
for full license details.
******************************************************************************/
package org.arl.fjage.shell;
/**
* Represents the type of output string to display.
*/
enum OutputType {
INPUT,
OUTPUT,
NOTIFY,
ERROR,
RECEIVED,
SENT
}
| 22.666667 | 79 | 0.514706 |
dd37b543656d3fb0f5eb8a6b9714710de977ad1b
| 667 |
package camelinaction;
import java.util.Map;
import org.apache.camel.Headers;
import org.apache.camel.language.XPath;
public class OrderToSqlBean {
public String toSql(@XPath("order/@name") String name,
@XPath("order/@amount") int amount,
@XPath("order/@customer") String customer,
@Headers Map<String, Object> outHeaders) {
outHeaders.put("partName", name);
outHeaders.put("quantity", amount);
outHeaders.put("customer", customer);
return "insert into incoming_orders (part_name, quantity, customer) values (:?partName, :?quantity, :?customer)";
}
}
| 33.35 | 121 | 0.628186 |
238463bc224f1c5c700f947dc09cfe25b63ecd50
| 266 |
package org.codehaus.xfire.spring;
/**
* @author <a href="mailto:tsztelak@gmail.com">Tomasz Sztelak</a>
*
*/
public class TestServiceImpl
implements TestService
{
public String returnEcho(String value)
{
return value;
}
}
| 14 | 65 | 0.62782 |
51db57bc8e3efe134907e6460edee38212458809
| 909 |
package net.dumbcode.hwkengine.display;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.*;
public enum DisplayManager
{
INSTANCE;
public void createDisplay(String title, int width, int height)
{
ContextAttribs attribs = new ContextAttribs(3,2)
.withForwardCompatible(true)
.withProfileCore(true);
try
{
Display.setDisplayMode(new DisplayMode(width, height));
Display.create(new PixelFormat(), attribs);
Display.setTitle(title);
} catch (LWJGLException e)
{
e.printStackTrace();
}
GL11.glViewport(0,0, width, height); // Use the whole display to render.
}
public void destroyDisplay()
{
Display.destroy();
}
public void updateDisplay(int fpsCap)
{
Display.sync(fpsCap);
Display.update();
}
}
| 21.642857 | 80 | 0.59516 |
73396c2c05062ea3e6217adf5a5327a65afb23ab
| 3,301 |
package application;
import models.CheckBoxes;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
public class HelperElements extends HelperBase {
public HelperElements(WebDriver wd) {
super(wd);
}
public void openListOfElements() {
click(By.xpath("//*[@class='card mt-4 top-card'][1]"));//???????????????
}
public void openTextBoxPage() {
click(By.xpath("//*[.='Text Box']"));
}
public void fillFullNameTextBox(String fullName) {
type(By.xpath("//*[@*='Full Name']"), fullName);
}
public void fillEmailTextBox(String email) {
type(By.xpath("//*[@*='name@example.com']"), email);
}
public void fillCurrentAddressTextBox(String address) {
type(By.xpath("//*[@*='Current Address']"), address);
}
public void fillPermanentAddressTextBox(String address) {
type(By.xpath("//*[@*='permanentAddress']"), address);
}
public void clickubmitButton() {
click(By.cssSelector("button#submit"));
}
public String resultText() {
String s = "";
List<WebElement> list = getElements(By.cssSelector(".border.col-md-12.col-sm-12 p"));
for(WebElement el : list){
s += el.getText().split(":", 2)[1];
}
return s;
}
public void openCheckBoxPage() {
click(By.xpath("//*[.='Check Box']"));
}
public void openAllCheckBoxes() {
JavascriptExecutor js = (JavascriptExecutor)wd;
js.executeScript("document.querySelector('footer').style.display='none'");
click(By.xpath("//*[@title='Expand all']"));
}
public CheckBoxes chooseCheckBoxes() {
CheckBoxes ch = CheckBoxes.builder()
.veu(true)
.commands(true)
.notes(true)
.build();
HashMap<String, Boolean> checkBoxes = ch.getMap();
for(String key : checkBoxes.keySet()){
if(checkBoxes.get(key)){
click(By.xpath("//span[@class='rct-title'][.='" + key + "']"));
}
}
return ch;
}
public String actualResult() {
String result = "";
if(isElementPresent(By.cssSelector("div#result span"))) {
List<WebElement> l = getElements(By.cssSelector("div#result span"));
for (int i = 1; i < l.size(); i++) {
result += l.get(i).getText();
}
}
return result;
}
public String expectedResult(CheckBoxes ch) {
String result = "";
LinkedHashMap<String, Boolean> map = ch.getMapRes();
for(String key : map.keySet()){
System.out.println("================================");
System.out.println(map.get(key));
if(map.get(key)){
if(key.equals("Word File.doc")){
result += "wordFile";
}else if(key.equals("Excel File.doc")) {
result += "excelFile";
} else {
result += key.toLowerCase();
}
}
}
return result;
}
}
| 29.473214 | 93 | 0.539836 |
a3aad92543b5291e25cd382dc5e7bdd963f69c2a
| 831 |
// Demonstration of arrays in Java as pointers
public class ArrayParam {
public static void main(String[] args) {
int[] years = new int[3];
years[0] = 1987;
years[1] = 1989;
years[2] = 1994;
changeArray(years);
for (int i = 0; i < years.length; i++) {
System.out.println(years[i]);
}
}
public static void changeArray(int[] numbers){
numbers[0]++;
}
}
/******************************************************
Main function returns:
1988
1989
1994
and NOT:
1987
1989
1994
Because the changeArray(); function gets passed a
pointer to the array (in memory) instead of a copy of the array,
so it is changing the values in the memory location itself.
********************************************************/
| 24.441176 | 65 | 0.509025 |
78fa5b2ca565615269192926f80988548dbc21af
| 678 |
package com.cloud.hello.rabbit.header;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @author ys
* @topic
* @date 2020/2/28 22:00
*/
@Component
public class ApiCreditReceive {
@RabbitListener(queues = "credit.bank")
@RabbitHandler
public void creditBank(String msg){
System.out.println("credit.bank receive message"+msg);
}
@RabbitListener(queues = "credit.finance")
@RabbitHandler
public void creditFinance(String msg){
System.out.println("credit.finance receive message"+msg);
}
}
| 25.111111 | 65 | 0.727139 |
e330d0af65b798b2bf51fee35e436f6b3349d292
| 2,036 |
package edu.virginia.engine.display;
import java.util.ArrayList;
import edu.virginia.engine.util.GameClock;
public class PhysicsSprite extends AnimatedSprite{
private double vx = 0;
private double vy = 0;
private double ax = 0;
private double ay = 0;
private double g = 0.001;
private double dt = 0;
private GameClock clock = new GameClock();
/*
* ********************* Constructors *********************************
*/
public PhysicsSprite(String id) {
super(id);
}
public PhysicsSprite(String id, String fileName, int numFrames,String path) {
super(id, fileName, numFrames,path);
}
public PhysicsSprite(String id, String fileNames) {
super(id, fileNames);
}
/*
* ********************* Getters and Setters **************************
*/
public double getVx() {
return vx;
}
public void setVx(double vx) {
this.vx = vx;
}
public double getVy() {
return vy;
}
public void setVy(double vy) {
this.vy = vy;
}
public double getAx() {
return ax;
}
public void setAx(double ax) {
this.ax = ax;
}
public double getAy() {
return ay;
}
public void setAy(double ay) {
this.ay = ay;
}
public double getGravity() {
return g;
}
public void setGravity(double gravity) {
this.g = gravity;
}
public double getDt() {
return dt;
}
public void setDt(double dt) {
this.dt = dt;
}
public GameClock getClock() {
return clock;
}
public void calculateX() {
this.setPositionX((int)(this.getPositionX() + vx*dt + ax*dt*dt/2));
vx = vx + dt * ax;
}
public void calculateY() {
this.setPositionY((int)(this.getPositionY() + vy*dt + (ay+g)*dt*dt/2));
vy = vy + dt * (ay + g);
}
/*
* ****************************Update and Draw Loop ******************************
*/
public void update(ArrayList<Integer> pressedKeys) {
super.update(pressedKeys);
dt = clock.getElapsedTime();
clock.resetGameClock();;
}
}
| 17.704348 | 84 | 0.558939 |
0fb766fbec05641371a974fe267641cfca88a56b
| 2,846 |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. 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. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.internal.shared.Version;
/**
* Used to fetch a record's raw bytes and user bits.
* The actual data length in byte array may be less than
* the size of the byte array itself. An integer field contains
* the valid length. This class is used exclusively by the Oplog Compactor
* for rolling the entries. The reason for this class is to reuse the
* underlying byte array for rolling multiple entries there by
* reducing the garbage.
* @author Asif
* @since 5.5
*/
public class BytesAndBitsForCompactor {
private byte[] data;
private byte userBits=0;
// length of the data present in the byte array
private int validLength;
private static final byte[] INIT_FOR_WRAPPER = new byte[0];
// boolean indicating if the object can be reused.
// Typically if the data stores the reference of a value byte [] directly
// from the RegionEntry than this byte array cannot be reused for
//storing another entry's data
private boolean isReusable;
private transient Version version;
public BytesAndBitsForCompactor() {
this.data = INIT_FOR_WRAPPER;
//this.userBits = userBits;
this.validLength = INIT_FOR_WRAPPER.length;
this.isReusable = true;
}
public final byte[] getBytes() {
return this.data;
}
public final byte getBits() {
return this.userBits;
}
public final int getValidLength() {
return this.validLength;
}
public boolean isReusable() {
return this.isReusable;
}
/**
*
* @param data byte array storing the data
* @param userBits byte with appropriate bits set
* @param validLength The number of bytes representing the data , starting from 0 as offset
* @param isReusable true if this object is safe for reuse as a data holder
*/
public void setData(byte[] data, byte userBits, int validLength, boolean isReusable) {
this.data = data;
this.userBits = userBits;
this.validLength = validLength;
this.isReusable = isReusable;
}
public Version getVersion() {
return version;
}
public void setVersion(Version version) {
this.version = version;
}
}
| 31.622222 | 94 | 0.717147 |
94351d63b3a5660188960b16d427580de82a6b91
| 378 |
package dao;
import models.BarberShop;
import models.HairStyle;
import java.util.List;
public interface HairstyleDao {
List<HairStyle> getAll();
List<HairStyle> getAllHairStyleByBarbershop(int barbershopId);
void add(HairStyle hairstyle);
void addHairStyleToBarberShop(HairStyle hairstyle, BarberShop barbershop);
void deleteById(int id);
void clearAll();
}
| 18 | 76 | 0.777778 |
1abefa7ad1ca181d25146dca531caf820d04cd13
| 138 |
package com.cymonevo.aurora.vent.handler;
public interface ClickEventHandler {
void onClickEvent(int requestCode, int resultCode);
}
| 23 | 55 | 0.797101 |
2b5ab5d9fbeefecaf98b6f1604355b79339fcbe8
| 7,380 |
/**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo 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 the following location:
*
* 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.apereo.portal.groups.pags.dao.jpa;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupDefinition;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestDefinition;
import org.apereo.portal.groups.pags.dao.IPersonAttributesGroupTestGroupDefinition;
import org.apereo.portal.rest.PagsRESTController;
import org.apereo.portal.url.IPortalRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Supports serialization and deserialization of PAGS definitions in various
* ways. The {@link JsonSerializer} and {@link JsonDeserializer} classes
* themselves are nested types on this class, which is stereotyped as a Spring
* Component. This approach allows the outer type to access Spring-managed
* dependencies and make them (privately, statically) available to the nested
* types.
*
* @author drewwills
*/
@Component
public final class PagsDefinitionJsonUtils {
private static final Map<Class<?>, Object> beans = new HashMap<>();
@Autowired
private IPortalRequestUtils portalRequestUtils;
/**
* Makes some beans from the Spring app context available to nested types.
*/
@PostConstruct
public void setUp() {
beans.clear();
beans.put(IPortalRequestUtils.class, portalRequestUtils);
}
/*
* Nested Types
*/
/**
* We only want name, description, and a URL that would return the whole
* object (in JSON) when we serialize the <code>members</code> attribute of
* a PAGS definition.
*/
public static final class DefinitionLinkJsonSerializer extends JsonSerializer<Set<IPersonAttributesGroupDefinition>> {
@Override
public void serialize(Set<IPersonAttributesGroupDefinition> members,
JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws JsonGenerationException, IOException {
jsonGenerator.writeStartArray();
for (IPersonAttributesGroupDefinition groupDef : members) {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", groupDef.getName());
jsonGenerator.writeStringField("description", groupDef.getDescription());
IPortalRequestUtils portalRequestUtils = (IPortalRequestUtils) beans.get(IPortalRequestUtils.class);
HttpServletRequest req = portalRequestUtils.getCurrentPortalRequest();
StringBuilder url = new StringBuilder();
url.append(req.getContextPath()).append(String.format(
PagsRESTController.URL_FORMAT_STRING,
URLEncoder.encode(groupDef.getName(), "UTF-8")));
jsonGenerator.writeStringField("url", url.toString());
jsonGenerator.writeEndObject();
}
jsonGenerator.writeEndArray();
}
}
/**
* This deserializer will (when it's implemented) translate JSON references
* to PAGS definitions into full PAGS definitions.
*/
public static final class DefinitionLinkJsonDeserializer extends JsonDeserializer<Set<IPersonAttributesGroupDefinition>> {
@Override
public Set<IPersonAttributesGroupDefinition> deserialize(JsonParser jsonParser,
DeserializationContext ctx) throws JsonProcessingException, IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
// For now, we'll only support deserializing PAGS definitions WITHOUT members...
if (node.elements().hasNext()) {
throw new UnsupportedOperationException("Members not yet supported");
}
return Collections.emptySet();
}
}
public static final class TestGroupJsonDeserializer extends JsonDeserializer<Set<IPersonAttributesGroupTestGroupDefinition>> {
@Override
public Set<IPersonAttributesGroupTestGroupDefinition> deserialize(JsonParser jsonParser, DeserializationContext ctx) throws JsonProcessingException, IOException {
Set<IPersonAttributesGroupTestGroupDefinition> rslt = new HashSet<>();
ObjectCodec oc = jsonParser.getCodec();
JsonNode json = oc.readTree(jsonParser);
for (Iterator<JsonNode> testGroupNodes = json.elements(); testGroupNodes.hasNext();) {
JsonNode testGroupNode = testGroupNodes.next();
IPersonAttributesGroupTestGroupDefinition testGroupDef = new PersonAttributesGroupTestGroupDefinitionImpl();
Set<IPersonAttributesGroupTestDefinition> testDefs = new HashSet<>();
for (Iterator<JsonNode> testNodes = testGroupNode.get("tests").elements(); testNodes.hasNext();) {
JsonNode testNode = testNodes.next();
IPersonAttributesGroupTestDefinition testDef = new PersonAttributesGroupTestDefinitionImpl();
testDef.setAttributeName(testNode.get("attributeName").asText());
testDef.setTesterClassName(testNode.get("testerClassName").asText());
testDef.setTestValue(testNode.get("testValue").asText());
testDefs.add(testDef);
// NOTE: We are also obligated to establish the backlink
// testDef --> testGroupDef; arguably this backlink serves
// little purpose and could be removed.
testDef.setTestGroup(testGroupDef);
}
testGroupDef.setTests(testDefs);
rslt.add(testGroupDef);
}
return rslt;
}
}
}
| 43.928571 | 170 | 0.703794 |
e2af0c177ddd92b6ec9f6a9effa8556fd6cf5325
| 1,925 |
package com.deevvi.device.detector.engine.parser.device;
import com.deevvi.device.detector.engine.loader.MapLoader;
import com.deevvi.device.detector.engine.parser.Parser;
import com.deevvi.device.detector.model.Model;
import com.deevvi.device.detector.model.device.Device;
import com.deevvi.device.detector.model.device.Notebook;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
import static com.deevvi.device.detector.engine.parser.device.DeviceType.DESKTOP;
public final class NotebookParser extends DeviceParser implements Parser, MapLoader<Notebook> {
/**
* List with notebooks models loaded from file.
*/
private final List<Notebook> notebooks = streamToList();
/**
* {@inheritDoc}
*/
@Override
protected List<? extends Device> getDevices() {
return notebooks;
}
/**
* {@inheritDoc}
*/
@Override
protected String getDeviceType() {
return DESKTOP.getDeviceName();
}
/**
* {@inheritDoc}
*/
@Override
public Notebook toObject(String key, Object value) {
Map map = (Map) value;
List<Model> models = Lists.newArrayList();
if (map.containsKey(MODELS)) {
((List) map.get(MODELS)).forEach(obj -> {
Map modelEntry = (Map) obj;
models.add(new Model(((String) modelEntry.get(REGEX)), (String) modelEntry.get(MODEL)));
});
}
return new Notebook.Builder()
.withDevice((String) map.get(DEVICE))
.withBrand(key)
.withRawRegex((String) map.get(REGEX))
.withModel((String) map.getOrDefault(MODEL, EMPTY_STRING))
.withModels(models)
.build();
}
/**
* {@inheritDoc}
*/
@Override
public String getFilePath() {
return "/regexes/device/notebooks.yml";
}
}
| 27.898551 | 104 | 0.619221 |
1c5a3bf23db0a4cd98351cc6ce0426ba53a6605c
| 5,351 |
/*
* 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.lucene.search.suggest.analyzing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.Transition;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.Util;
// TODO: move to core? nobody else uses it yet though...
/**
* Exposes a utility method to enumerate all paths intersecting an {@link Automaton} with an {@link
* FST}.
*/
public class FSTUtil {
private FSTUtil() {}
/** Holds a pair (automaton, fst) of states and accumulated output in the intersected machine. */
public static final class Path<T> {
/** Node in the automaton where path ends: */
public final int state;
/** Node in the FST where path ends: */
public final FST.Arc<T> fstNode;
/** Output of the path so far: */
public final T output;
/** Input of the path so far: */
public final IntsRefBuilder input;
/** Sole constructor. */
public Path(int state, FST.Arc<T> fstNode, T output, IntsRefBuilder input) {
this.state = state;
this.fstNode = fstNode;
this.output = output;
this.input = input;
}
}
/**
* Enumerates all minimal prefix paths in the automaton that also intersect the FST, accumulating
* the FST end node and output for each path.
*/
public static <T> List<Path<T>> intersectPrefixPaths(Automaton a, FST<T> fst) throws IOException {
assert a.isDeterministic();
final List<Path<T>> queue = new ArrayList<>();
final List<Path<T>> endNodes = new ArrayList<>();
if (a.getNumStates() == 0) {
return endNodes;
}
queue.add(
new Path<>(
0, fst.getFirstArc(new FST.Arc<T>()), fst.outputs.getNoOutput(), new IntsRefBuilder()));
final FST.Arc<T> scratchArc = new FST.Arc<>();
final FST.BytesReader fstReader = fst.getBytesReader();
Transition t = new Transition();
while (queue.size() != 0) {
final Path<T> path = queue.remove(queue.size() - 1);
if (a.isAccept(path.state)) {
endNodes.add(path);
// we can stop here if we accept this path,
// we accept all further paths too
continue;
}
IntsRefBuilder currentInput = path.input;
int count = a.initTransition(path.state, t);
for (int i = 0; i < count; i++) {
a.getNextTransition(t);
final int min = t.min;
final int max = t.max;
if (min == max) {
final FST.Arc<T> nextArc = fst.findTargetArc(t.min, path.fstNode, scratchArc, fstReader);
if (nextArc != null) {
final IntsRefBuilder newInput = new IntsRefBuilder();
newInput.copyInts(currentInput.get());
newInput.append(t.min);
queue.add(
new Path<>(
t.dest,
new FST.Arc<T>().copyFrom(nextArc),
fst.outputs.add(path.output, nextArc.output()),
newInput));
}
} else {
// TODO: if this transition's TO state is accepting, and
// it accepts the entire range possible in the FST (ie. 0 to 255),
// we can simply use the prefix as the accepted state instead of
// looking up all the ranges and terminate early
// here. This just shifts the work from one queue
// (this one) to another (the completion search
// done in AnalyzingSuggester).
FST.Arc<T> nextArc = Util.readCeilArc(min, fst, path.fstNode, scratchArc, fstReader);
while (nextArc != null && nextArc.label() <= max) {
assert nextArc.label() <= max;
assert nextArc.label() >= min : nextArc.label() + " " + min;
final IntsRefBuilder newInput = new IntsRefBuilder();
newInput.copyInts(currentInput.get());
newInput.append(nextArc.label());
queue.add(
new Path<>(
t.dest,
new FST.Arc<T>().copyFrom(nextArc),
fst.outputs.add(path.output, nextArc.output()),
newInput));
final int label = nextArc.label(); // used in assert
nextArc = nextArc.isLast() ? null : fst.readNextRealArc(nextArc, fstReader);
assert nextArc == null || label < nextArc.label()
: "last: " + label + " next: " + nextArc.label();
}
}
}
}
return endNodes;
}
}
| 37.41958 | 100 | 0.617268 |
f4c64c698d59ad799da819ea6f65ecc9f74b4223
| 1,553 |
package com.xmasworking.project01.controller;
/**
* Created by IntelliJ IDEA.
*
* @author XmasPiano
* @date 2018/8/30 - 上午10:23
* Created by IntelliJ IDEA.
*/
import com.xmasworking.project01.entity.ShowUserInfo;
import com.xmasworking.project01.service.ShowUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
@RequestMapping("/show")
public class ShowController {
@Autowired
ShowUserInfoService showUserInfoService;
@RequestMapping("")
public ModelAndView index(){
List<ShowUserInfo> showUserInfos = showUserInfoService.findAll();
ModelAndView modelAndView = new ModelAndView("show");
modelAndView.addObject("showUserInfos", showUserInfos);
return modelAndView;
}
@RequestMapping("/user")
public ModelAndView getShowUser(@RequestParam("id")Long id){
ShowUserInfo showUserInfo = showUserInfoService.findById(id);
ModelAndView modelAndView = new ModelAndView("show");
modelAndView.addObject("showUserInfo",showUserInfo);
return modelAndView;
}
@ResponseBody
@RequestMapping("/showuser")
public List<ShowUserInfo> getAllUser(){
return showUserInfoService.findAll();
}
}
| 30.45098 | 73 | 0.749517 |
12b1f2a6afa6228f67b0c5fd54e0eb10971cc58d
| 747 |
package com.yishuifengxiao.common.crawler.link.filter.impl;
import org.apache.commons.lang3.StringUtils;
import com.yishuifengxiao.common.crawler.domain.constant.RuleConstant;
import com.yishuifengxiao.common.crawler.link.filter.BaseLinkFilter;
/**
* 哈希链接过滤器<br/>
* 当抓取出来的链接为相对地址,且地址的开头为 # 时,该地址可能是哈希地址,不对其进行处理<br/>
* 该过滤器最好作用在相对链接过滤器的前面
*
* @author yishui
* @date 2019年12月27日
* @version 1.0.0
*/
public class HashLinkFilter extends BaseLinkFilter {
public HashLinkFilter(BaseLinkFilter next) {
super(next);
}
@Override
protected String doFilter(BaseLinkFilter next, String path, String url) {
if (StringUtils.startsWith(url, RuleConstant.HASH_ADDR)) {
// 哈希地址
return null;
}
return next.doFilter(path, url);
}
}
| 22.636364 | 74 | 0.753681 |
8b936c736a1b3d251f8a67a61ba03d16e5584f22
| 1,075 |
/**
* Test the Cylinder class to make sure it functions properly
*
* @author Andrew
* @version 2019
*/
public class CylinderTester
{
public static void main (String[] args) {
Cylinder cylinder1 = new Cylinder(1, 1);
Cylinder cylinder2 = new Cylinder(2, 2);
System.out.println("Expected volume Cylinder 1 (Approximately): 3.14159265");
System.out.println("Observed volume Cylinder 1 (Approximately): " + cylinder1.getVolume());
System.out.println("Expected volume Cylinder 2 (Approximately): 25.13274");
System.out.println("Observed volume Cylinder 2 (Approximately): " + cylinder2.getVolume());
System.out.println("Expected surface area Cylinder 1 (Approximately): 12.56637");
System.out.println("Observed surface area Cylinder 1 (Approximately): " + cylinder1.getSurfArea());
System.out.println("Expected surface area Cylinder 2 (Approximately): 50.26548");
System.out.println("Observed surface area Cylinder 2 (Approximately): " + cylinder2.getSurfArea());
}
}
| 43 | 107 | 0.67814 |
1c93bcb0cb125a22f15e38aeb7d7fc94ef96393f
| 642 |
package uk.ac.ebi.pride.toolsuite.gui.task.impl;
import uk.ac.ebi.pride.toolsuite.gui.task.Task;
import uk.ac.ebi.pride.toolsuite.gui.task.TaskUtil;
/**
* @author Rui Wang
* @version $Id$
*/
public class OpenMyAssayTask extends OpenMyProjectTask {
public OpenMyAssayTask(String accession, String username, char[] password) {
super(accession, username, password);
}
@Override
protected void getFileMetadata(String un, char[] pwd, String accession) {
Task task = new GetMyAssayFilesMetadataTask(un, pwd, accession);
task.addTaskListener(this);
TaskUtil.startBackgroundTask(task);
}
}
| 26.75 | 80 | 0.708723 |
1d82cd69e808b7ea2b24a1ed1e24037f576b3203
| 1,688 |
package mlp.dataset;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
/**
*
* @author rodolpho
*/
public class Sample {
private final double[] input;
private final double[] output;
private final String textRepresentation;
public Sample(double[] input, double[] output) {
this.input = new double[input.length];
this.output = new double[output.length];
System.arraycopy(input, 0, this.input, 0, input.length);
System.arraycopy(output, 0, this.output, 0, output.length);
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < input.length; i++) {
if (i > 0) {
stringBuilder.append(";");
}
stringBuilder.append(String.valueOf(input[i]));
}
stringBuilder.append("|");
for (int i = 0; i < output.length; i++) {
if (i > 0) {
stringBuilder.append(";");
}
stringBuilder.append(String.valueOf(output[i]));
}
this.textRepresentation = stringBuilder.toString();
}
public int inputSize() {
return this.input.length;
}
public double[] getInput() {
return this.input;
}
public int outputSize() {
return this.output.length;
}
public double[] getOutput() {
return this.output;
}
@Override
public String toString() {
return this.textRepresentation;
}
public void write(OutputStream outputStream) throws UnsupportedEncodingException, IOException {
outputStream.write(textRepresentation.getBytes("UTF-8"));
}
}
| 25.19403 | 99 | 0.597749 |
4e6589225f30af147ecffed8f8264c69b26f4a04
| 1,478 |
package org.mjd.util;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* The Class TestEntitiesBuilder.
*
* @author Luis Eduardo Ferro Diez
*/
public class TestEntitiesBuilder {
/**
* Gets the test jar files.
*
* @return the test jar files
*/
public static List<Path> getTestDefaultJarFiles(){
List<Path> testJars = new ArrayList<>();
testJars.add(Paths.get("adf-controller-api.jar"));
testJars.add(Paths.get("adf-controller-rt-common.jar"));
testJars.add(Paths.get("adf-controller.jar"));
testJars.add(Paths.get("adf-desktop-integration.jar"));
testJars.add(Paths.get("adf-desktop-integration-model-api.jar"));
testJars.add(Paths.get("javax.mail.jar"));
testJars.add(Paths.get("groovy-all-1.6.3.jar"));
return testJars;
}
/**
* Gets the test default maven jar files.
*
* @return the test default maven jar files
*/
public static List<Path> getTestDefaultMavenJarFiles(){
List<Path> testJars = new ArrayList<>();
testJars.add(Paths.get("adf-controller-api-11.1.1.jar"));
testJars.add(Paths.get("adf-controller-rt-common-11.1.1.jar"));
testJars.add(Paths.get("adf-controller-11.1.1.jar"));
testJars.add(Paths.get("adf-desktop-integration-11.1.1.jar"));
testJars.add(Paths.get("adf-desktop-integration-model-api-11.1.1.jar"));
testJars.add(Paths.get("javax.mail-11.1.1.7.0.jar"));
testJars.add(Paths.get("groovy-all-1.6.3.jar"));
return testJars;
}
}
| 29.56 | 74 | 0.701624 |
fce63ac9684d9b9b4ba059ff3d5dad1be50f20b5
| 1,080 |
package com.fishercoder;
import com.fishercoder.common.utils.TreeUtils;
import com.fishercoder.solutions._617;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Arrays;
import static junit.framework.TestCase.assertEquals;
public class _617Test {
private static _617.Solution1 solution1;
private static _617.Solution2 solution2;
@BeforeClass
public static void setup() {
solution1 = new _617.Solution1();
solution2 = new _617.Solution2();
}
@Test
public void test1() {
assertEquals(TreeUtils.constructBinaryTree(Arrays.asList(3, 4, 5, 5, 4, null, 7)), solution1.mergeTrees(TreeUtils.constructBinaryTree(Arrays.asList(1, 3, 2, 5)), TreeUtils.constructBinaryTree(Arrays.asList(2, 1, 3, null, 4, null, 7))));
}
@Test
public void test2() {
assertEquals(TreeUtils.constructBinaryTree(Arrays.asList(3, 4, 5, 5, 4, null, 7)), solution2.mergeTrees(TreeUtils.constructBinaryTree(Arrays.asList(1, 3, 2, 5)), TreeUtils.constructBinaryTree(Arrays.asList(2, 1, 3, null, 4, null, 7))));
}
}
| 32.727273 | 244 | 0.711111 |
b990eee6b90b02e5777e99e568789955ac016aa6
| 1,719 |
package org.nglr.astar.twodim;
import org.nglr.astar.AStar;
import org.nglr.astar.Grid;
/**
* AStar class that works under a 2D "world" plane using Node2D as points
* in the "world" plane and by default uses a {@link Grid2D}
*
* @author J
* @see AStar
* @see Node2D
* @see Grid2DNoDiagonal
* @see Grid2D
*/
public class AStar2D extends AStar {
/**
* Create a new AStar2D instance with a "world" with a size of 20x20
*/
public AStar2D() {
super( new Grid2D(20, 20) );
}
/**
* Instance a new AStar2D object with a size of the given width x the given
* height
*
* @param width "world" width
* @param height "world" height
*/
public AStar2D(int width, int height) {
super( new Grid2D(width, height) );
}
/**
* Create a duplicate instance of an AStar2D instance
*
* @param aStar AStar2D instance to duplicate
*/
public AStar2D(AStar2D aStar) {
super(aStar.instanceGridCopy());
}
/**
* Instance an AStar2D using the given two-dimension
* representational grid
*
* @param grid2D 2D Grid to use in the A*
*/
public AStar2D(BaseGrid2D grid2D) {
super(grid2D);
}
/**
* @return A copy of the Grid instance the AStar class is using
*/
public Grid instanceGridCopy() {
if (getGrid().getMap()[0].usesDiagonals()) {
return new Grid2DNoDiagonal( (Grid2DNoDiagonal) getGrid());
} else {
return new Grid2D( (Grid2D) getGrid());
}
}
public static AStar2D createNoDiagonals(int width, int height) {
return new AStar2D(new Grid2DNoDiagonal(width, height));
}
}
| 24.211268 | 79 | 0.602094 |
2643a04fc683d7cf63d023a9917807c9d8486343
| 179 |
package org.github.yassine.samples.domain.event.company;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class CompanyCreatedEvent {
private String name;
}
| 16.272727 | 56 | 0.798883 |
496d3f293889daa2508e2d6834e037ea1c6a65e8
| 1,408 |
package com.springboottry.springbootdemo.Controller;
import com.springboottry.springbootdemo.Entity.Department;
import com.springboottry.springbootdemo.Service.DepartmentService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import static org.junit.jupiter.api.Assertions.*;
@WebMvcTest(DepartmentController.class)
class DepartmentControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private DepartmentService departmentService;
private Department deparment;
@BeforeEach
void setUp() {
deparment = Department.builder().address("Philly").code("CCi1").name("CCI").id(1L).build();
}
@Test
void saveDepartment() {
Department input = Department.builder().address("Philly").code("CCi1").name("CCI").id(1L).build();
Mockito.when(departmentService.saveDepartment(input)).thenReturn(deparment);
}
@Test
void getDepartment() {
}
}
| 32.744186 | 106 | 0.771307 |
dd78a4e7e4edfe57f80dab11085cf39028e033d3
| 3,403 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twitter.distributedlog.impl;
import com.twitter.distributedlog.DistributedLogConfiguration;
import com.twitter.distributedlog.exceptions.InvalidStreamNameException;
import java.net.URI;
/**
* Utils for bookkeeper based distributedlog implementation
*/
public class BKDLUtils {
/**
* Is it a reserved stream name in bkdl namespace?
*
* @param name
* stream name
* @return true if it is reserved name, otherwise false.
*/
public static boolean isReservedStreamName(String name) {
return name.startsWith(".");
}
/**
* Validate the configuration and uri.
*
* @param conf
* distributedlog configuration
* @param uri
* distributedlog uri
* @throws IllegalArgumentException
*/
public static void validateConfAndURI(DistributedLogConfiguration conf, URI uri)
throws IllegalArgumentException {
if (null == conf) {
throw new IllegalArgumentException("Incorrect Configuration");
} else {
conf.validate();
}
if ((null == uri) || (null == uri.getAuthority()) || (null == uri.getPath())) {
throw new IllegalArgumentException("Incorrect ZK URI");
}
}
/**
* Validate the stream name.
*
* @param nameOfStream
* name of stream
* @throws InvalidStreamNameException
*/
public static void validateName(String nameOfStream)
throws InvalidStreamNameException {
String reason = null;
char chars[] = nameOfStream.toCharArray();
char c;
// validate the stream to see if meet zookeeper path's requirement
for (int i = 0; i < chars.length; i++) {
c = chars[i];
if (c == 0) {
reason = "null character not allowed @" + i;
break;
} else if (c == '/') {
reason = "'/' not allowed @" + i;
break;
} else if (c > '\u0000' && c < '\u001f'
|| c > '\u007f' && c < '\u009F'
|| c > '\ud800' && c < '\uf8ff'
|| c > '\ufff0' && c < '\uffff') {
reason = "invalid charater @" + i;
break;
}
}
if (null != reason) {
throw new InvalidStreamNameException(nameOfStream, reason);
}
if (isReservedStreamName(nameOfStream)) {
throw new InvalidStreamNameException(nameOfStream,
"Stream Name is reserved");
}
}
}
| 33.693069 | 87 | 0.592712 |
85b39d881b3aaa91062055cb63914e1161196359
| 3,372 |
import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
// 물통의 현재 상태와 물을 붓는 행위를 관리하는 구조체
class State{
int[] X;
State(int[] _X){
X = new int[3];
for (int i=0;i<3;i++) X[i] = _X[i];
}
State move(int from,int to,int[] Limit){
// from 물통에서 to 물통으로 물을 옮긴다.
int[] nX = new int[]{X[0], X[1], X[2]};
if (X[from] + X[to] <= Limit[to]){ // 만약 from 을 전부 부을 수 있다면
nX[to] = nX[from] + nX[to];
nX[from] = 0;
}else{ // from 의 일부만 옮길 수 있는 경우
nX[from] -= Limit[to] - nX[to];
nX[to] = Limit[to];
}
return new State(nX);
}
};
public class Main {
static FastReader scan = new FastReader();
static StringBuilder sb = new StringBuilder();
static int[] Limit;
static boolean[] possible;
static boolean[][][] visit;
static void input() {
Limit = new int[3];
for (int i=0;i<3;i++) Limit[i] = scan.nextInt();
visit = new boolean[205][205][205];
possible = new boolean[205];
}
// 물통 탐색 시작~
static void bfs(int x1, int x2, int x3) {
Queue<State> Q = new LinkedList<>();
visit[x1][x2][x3] = true;
Q.add(new State(new int[]{x1, x2, x3}));
// BFS 과정 시작
while (!Q.isEmpty()) {
State st = Q.poll();
if (st.X[0] == 0) possible[st.X[2]] = true;
for (int from = 0; from < 3; from++) {
for (int to = 0; to < 3; to++) {
if (from == to) continue;
// i 번 물통에서 j 번 물통으로 물을 옮긴다.
State nxt = st.move(from, to, Limit);
// 만약 바뀐 상태를 탐색한 적이 없다면
if (!visit[nxt.X[0]][nxt.X[1]][nxt.X[2]]) {
visit[nxt.X[0]][nxt.X[1]][nxt.X[2]] = true;
Q.add(nxt);
}
}
}
}
}
static void pro() {
bfs(0, 0, Limit[2]);
for (int i=0;i<=200;i++){
if (possible[i]) sb.append(i).append(' ');
}
System.out.println(sb);
}
public static void main(String[] args) {
input();
pro();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| 26.551181 | 70 | 0.44306 |
0106a82369d7533c456c6178db5b457a213540c4
| 4,496 |
package com.devonfw.module.cxf.common.impl.client.ws;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.message.Message;
import org.apache.cxf.transport.Conduit;
import org.apache.cxf.transport.http.HTTPConduit;
import com.devonfw.module.cxf.common.impl.client.SyncServiceClientFactoryCxf;
import com.devonfw.module.service.common.api.client.context.ServiceContext;
import com.devonfw.module.service.common.api.client.sync.SyncServiceClientFactory;
import com.devonfw.module.service.common.api.config.ServiceConfig;
import com.devonfw.module.service.common.api.constants.ServiceConstants;
/**
* Implementation of {@link SyncServiceClientFactory} for JAX-WS SOAP service clients using Apache CXF.
*
* @since 3.0.0
*/
public class SyncServiceClientFactoryCxfWs extends SyncServiceClientFactoryCxf {
private static final String WSDL_SUFFIX = "?wsdl";
@Override
protected <S> S createService(ServiceContext<S> context, String url) {
Class<S> api = context.getApi();
WebService webService = api.getAnnotation(WebService.class);
QName qname = new QName(getNamespace(api, webService), getLocalName(api, webService));
boolean downloadWsdl = context.getConfig().getChild(ServiceConfig.KEY_SEGMENT_WSDL)
.getChild(ServiceConfig.KEY_SEGMENT_DISABLE_DOWNLOAD).getValueAsBoolean();
URL wsdlUrl = null;
if (downloadWsdl) {
try {
wsdlUrl = new URL(url);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Illegal URL: " + url, e);
}
}
S serviceClient = Service.create(wsdlUrl, qname).getPort(api);
if (!downloadWsdl) {
BindingProvider bindingProvider = (BindingProvider) serviceClient;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);
}
return serviceClient;
}
@Override
protected <S> void applyAspects(ServiceContext<S> context, S serviceClient) {
Client cxfClient = ClientProxy.getClient(serviceClient);
applyInterceptors(context, cxfClient);
Conduit conduit = cxfClient.getConduit();
if (conduit instanceof HTTPConduit) {
HTTPConduit httpConduit = (HTTPConduit) conduit;
applyClientPolicy(context, httpConduit);
}
applyHeaders(context, cxfClient);
}
@Override
protected String getServiceTypeFolderName() {
return ServiceConstants.URL_FOLDER_WEB_SERVICE;
}
@Override
protected String getUrl(ServiceContext<?> context) {
String url = super.getUrl(context);
if (!url.endsWith(WSDL_SUFFIX)) {
String serviceName = context.getApi().getSimpleName();
if (!url.endsWith(serviceName)) {
if (!url.endsWith("/")) {
url = url + "/";
}
url = url + serviceName;
}
url = url + WSDL_SUFFIX;
}
return url;
}
private String getLocalName(Class<?> api, WebService webService) {
String portName = webService.portName();
if (portName.isEmpty()) {
return api.getSimpleName();
}
return portName;
}
private String getNamespace(Class<?> api, WebService webService) {
String targetNamespace = webService.targetNamespace();
if (targetNamespace.isEmpty()) {
return api.getPackage().getName();
}
return targetNamespace;
}
@Override
protected void applyHeaders(ServiceContext<?> context, Object client) {
Collection<String> headerNames = context.getHeaderNames();
if (!headerNames.isEmpty()) {
Map<String, List<String>> headers = new HashMap<>();
for (String headerName : headerNames) {
headers.put(headerName, Arrays.asList(context.getHeader(headerName)));
}
((Client) client).getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
}
}
/**
* @param context the {@link ServiceContext}.
* @return {@code true} if this implementation is responsibe for creating a service client corresponding to the given
* {@link ServiceContext}, {@code false} otherwise.
*/
@Override
protected boolean isResponsibleForService(ServiceContext<?> context) {
return context.getApi().isAnnotationPresent(WebService.class);
}
}
| 32.114286 | 119 | 0.719973 |
120aa2e39a79039e174823852dbb0e72255fc7c2
| 1,876 |
package br.com.centralit.citcorpore.quartz.job;
import java.util.Collection;
import net.htmlparser.jericho.Source;
import org.apache.commons.lang.StringUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import br.com.centralit.citcorpore.bean.SolicitacaoServicoDTO;
import br.com.centralit.citcorpore.negocio.SolicitacaoServicoService;
import br.com.citframework.excecao.ServiceException;
import br.com.citframework.service.ServiceLocator;
public class EventoPopulaDescricaoSolicitacao implements Job {
@Override
public void execute(final JobExecutionContext arg0) throws JobExecutionException {
try {
final Collection<SolicitacaoServicoDTO> lista = this.getService().list();
for (final SolicitacaoServicoDTO solicitacaoServicoDTO : lista) {
if (solicitacaoServicoDTO.getDescricao() != null && !StringUtils.isBlank(solicitacaoServicoDTO.getDescricao())) {
final Source source = new Source(solicitacaoServicoDTO.getDescricao());
solicitacaoServicoDTO.setDescricaoSemFormatacao(source.getTextExtractor().toString());
}
if (solicitacaoServicoDTO.getDescricaoSemFormatacao() != null && !StringUtils.isBlank(solicitacaoServicoDTO.getDescricaoSemFormatacao())) {
this.getService().updateNotNull(solicitacaoServicoDTO);
}
}
} catch (final Exception e) {
e.printStackTrace();
}
}
private SolicitacaoServicoService service;
private SolicitacaoServicoService getService() throws ServiceException {
if (service == null) {
service = (SolicitacaoServicoService) ServiceLocator.getInstance().getService(SolicitacaoServicoService.class, null);
}
return service;
}
}
| 39.083333 | 155 | 0.712154 |
f728b1588d26d433578f33a99c5d0e1b2caf4934
| 10,643 |
package org.apache.geronimo.samples.daytrader;
import javax.xml.bind.annotation.XmlRegistry;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.apache.geronimo.samples.daytrader package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.apache.geronimo.samples.daytrader
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link GetMarketSummary }
*
*/
public GetMarketSummary createGetMarketSummary() {
return new GetMarketSummary();
}
/**
* Create an instance of {@link GetMarketSummaryResponse }
*
*/
public GetMarketSummaryResponse createGetMarketSummaryResponse() {
return new GetMarketSummaryResponse();
}
/**
* Create an instance of {@link MarketSummaryDataBeanWS }
*
*/
public MarketSummaryDataBeanWS createMarketSummaryDataBeanWS() {
return new MarketSummaryDataBeanWS();
}
/**
* Create an instance of {@link Buy }
*
*/
public Buy createBuy() {
return new Buy();
}
/**
* Create an instance of {@link BuyResponse }
*
*/
public BuyResponse createBuyResponse() {
return new BuyResponse();
}
/**
* Create an instance of {@link OrderDataBean }
*
*/
public OrderDataBean createOrderDataBean() {
return new OrderDataBean();
}
/**
* Create an instance of {@link Sell }
*
*/
public Sell createSell() {
return new Sell();
}
/**
* Create an instance of {@link SellResponse }
*
*/
public SellResponse createSellResponse() {
return new SellResponse();
}
/**
* Create an instance of {@link QueueOrder }
*
*/
public QueueOrder createQueueOrder() {
return new QueueOrder();
}
/**
* Create an instance of {@link QueueOrderResponse }
*
*/
public QueueOrderResponse createQueueOrderResponse() {
return new QueueOrderResponse();
}
/**
* Create an instance of {@link CompleteOrder }
*
*/
public CompleteOrder createCompleteOrder() {
return new CompleteOrder();
}
/**
* Create an instance of {@link CompleteOrderResponse }
*
*/
public CompleteOrderResponse createCompleteOrderResponse() {
return new CompleteOrderResponse();
}
/**
* Create an instance of {@link CancelOrder }
*
*/
public CancelOrder createCancelOrder() {
return new CancelOrder();
}
/**
* Create an instance of {@link CancelOrderResponse }
*
*/
public CancelOrderResponse createCancelOrderResponse() {
return new CancelOrderResponse();
}
/**
* Create an instance of {@link OrderCompleted }
*
*/
public OrderCompleted createOrderCompleted() {
return new OrderCompleted();
}
/**
* Create an instance of {@link OrderCompletedResponse }
*
*/
public OrderCompletedResponse createOrderCompletedResponse() {
return new OrderCompletedResponse();
}
/**
* Create an instance of {@link GetOrders }
*
*/
public GetOrders createGetOrders() {
return new GetOrders();
}
/**
* Create an instance of {@link GetOrdersResponse }
*
*/
public GetOrdersResponse createGetOrdersResponse() {
return new GetOrdersResponse();
}
/**
* Create an instance of {@link ArrayOfOrderDataBean }
*
*/
public ArrayOfOrderDataBean createArrayOfOrderDataBean() {
return new ArrayOfOrderDataBean();
}
/**
* Create an instance of {@link GetClosedOrders }
*
*/
public GetClosedOrders createGetClosedOrders() {
return new GetClosedOrders();
}
/**
* Create an instance of {@link GetClosedOrdersResponse }
*
*/
public GetClosedOrdersResponse createGetClosedOrdersResponse() {
return new GetClosedOrdersResponse();
}
/**
* Create an instance of {@link CreateQuote }
*
*/
public CreateQuote createCreateQuote() {
return new CreateQuote();
}
/**
* Create an instance of {@link CreateQuoteResponse }
*
*/
public CreateQuoteResponse createCreateQuoteResponse() {
return new CreateQuoteResponse();
}
/**
* Create an instance of {@link QuoteDataBean }
*
*/
public QuoteDataBean createQuoteDataBean() {
return new QuoteDataBean();
}
/**
* Create an instance of {@link GetQuote }
*
*/
public GetQuote createGetQuote() {
return new GetQuote();
}
/**
* Create an instance of {@link GetQuoteResponse }
*
*/
public GetQuoteResponse createGetQuoteResponse() {
return new GetQuoteResponse();
}
/**
* Create an instance of {@link GetAllQuotes }
*
*/
public GetAllQuotes createGetAllQuotes() {
return new GetAllQuotes();
}
/**
* Create an instance of {@link GetAllQuotesResponse }
*
*/
public GetAllQuotesResponse createGetAllQuotesResponse() {
return new GetAllQuotesResponse();
}
/**
* Create an instance of {@link ArrayOfQuoteDataBean }
*
*/
public ArrayOfQuoteDataBean createArrayOfQuoteDataBean() {
return new ArrayOfQuoteDataBean();
}
/**
* Create an instance of {@link UpdateQuotePriceVolume }
*
*/
public UpdateQuotePriceVolume createUpdateQuotePriceVolume() {
return new UpdateQuotePriceVolume();
}
/**
* Create an instance of {@link UpdateQuotePriceVolumeResponse }
*
*/
public UpdateQuotePriceVolumeResponse createUpdateQuotePriceVolumeResponse() {
return new UpdateQuotePriceVolumeResponse();
}
/**
* Create an instance of {@link GetHoldings }
*
*/
public GetHoldings createGetHoldings() {
return new GetHoldings();
}
/**
* Create an instance of {@link GetHoldingsResponse }
*
*/
public GetHoldingsResponse createGetHoldingsResponse() {
return new GetHoldingsResponse();
}
/**
* Create an instance of {@link ArrayOfHoldingDataBean }
*
*/
public ArrayOfHoldingDataBean createArrayOfHoldingDataBean() {
return new ArrayOfHoldingDataBean();
}
/**
* Create an instance of {@link GetHolding }
*
*/
public GetHolding createGetHolding() {
return new GetHolding();
}
/**
* Create an instance of {@link GetHoldingResponse }
*
*/
public GetHoldingResponse createGetHoldingResponse() {
return new GetHoldingResponse();
}
/**
* Create an instance of {@link HoldingDataBean }
*
*/
public HoldingDataBean createHoldingDataBean() {
return new HoldingDataBean();
}
/**
* Create an instance of {@link GetAccountData }
*
*/
public GetAccountData createGetAccountData() {
return new GetAccountData();
}
/**
* Create an instance of {@link GetAccountDataResponse }
*
*/
public GetAccountDataResponse createGetAccountDataResponse() {
return new GetAccountDataResponse();
}
/**
* Create an instance of {@link AccountDataBean }
*
*/
public AccountDataBean createAccountDataBean() {
return new AccountDataBean();
}
/**
* Create an instance of {@link GetAccountProfileData }
*
*/
public GetAccountProfileData createGetAccountProfileData() {
return new GetAccountProfileData();
}
/**
* Create an instance of {@link GetAccountProfileDataResponse }
*
*/
public GetAccountProfileDataResponse createGetAccountProfileDataResponse() {
return new GetAccountProfileDataResponse();
}
/**
* Create an instance of {@link AccountProfileDataBean }
*
*/
public AccountProfileDataBean createAccountProfileDataBean() {
return new AccountProfileDataBean();
}
/**
* Create an instance of {@link UpdateAccountProfile }
*
*/
public UpdateAccountProfile createUpdateAccountProfile() {
return new UpdateAccountProfile();
}
/**
* Create an instance of {@link UpdateAccountProfileResponse }
*
*/
public UpdateAccountProfileResponse createUpdateAccountProfileResponse() {
return new UpdateAccountProfileResponse();
}
/**
* Create an instance of {@link Login }
*
*/
public Login createLogin() {
return new Login();
}
/**
* Create an instance of {@link LoginResponse }
*
*/
public LoginResponse createLoginResponse() {
return new LoginResponse();
}
/**
* Create an instance of {@link Logout }
*
*/
public Logout createLogout() {
return new Logout();
}
/**
* Create an instance of {@link LogoutResponse }
*
*/
public LogoutResponse createLogoutResponse() {
return new LogoutResponse();
}
/**
* Create an instance of {@link Register }
*
*/
public Register createRegister() {
return new Register();
}
/**
* Create an instance of {@link RegisterResponse }
*
*/
public RegisterResponse createRegisterResponse() {
return new RegisterResponse();
}
/**
* Create an instance of {@link ResetTrade }
*
*/
public ResetTrade createResetTrade() {
return new ResetTrade();
}
/**
* Create an instance of {@link ResetTradeResponse }
*
*/
public ResetTradeResponse createResetTradeResponse() {
return new ResetTradeResponse();
}
/**
* Create an instance of {@link RunStatsDataBean }
*
*/
public RunStatsDataBean createRunStatsDataBean() {
return new RunStatsDataBean();
}
}
| 22.888172 | 151 | 0.607066 |
f416e08c14c8d956cc90a6f68c7c16a6c3d057c3
| 2,693 |
package com.example.coffeeshop.ui;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.coffeeshop.R;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class FindUserFragment extends AppCompatActivity {
RecyclerView mrecview;
//myadapter adapter;
FirebaseDatabase mfirebaseDatabase;
DatabaseReference mRef;
private NoteAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_find_user);
FloatingActionButton buttonAddNote = findViewById(R.id.button_add_note);
buttonAddNote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(FindUserFragment.this, RegisterActivity.class));
}
});
setUpRecyclerView();
}
private void setUpRecyclerView() {
FirebaseRecyclerOptions<User> options =
new FirebaseRecyclerOptions.Builder<User>()
.setQuery(FirebaseDatabase.getInstance().getReference().child("User"), User.class)
.build();
adapter = new NoteAdapter(options);
RecyclerView recyclerView = findViewById(R.id.recview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
adapter.deleteItem(viewHolder.getAdapterPosition());
}
}).attachToRecyclerView(recyclerView);
}
@Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
}
| 39.602941 | 130 | 0.695878 |
d2e3cd74a6f57bd6cbc9fe49dce62b68b971d3f1
| 691 |
package ru.job4j.design.srp.presenters;
import ru.job4j.design.srp.model.Employer;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
/**
* Presenter interface.
*/
public interface Presenter {
/**
* @param data - employers for present
* @param fieldsSet - fields and fields format
* @return String - report
* @throws NoSuchMethodException - exception
* @throws InvocationTargetException - exception
* @throws IllegalAccessException - exception
*/
String execute(List<Employer> data, Map<String, String> fieldsSet) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException;
}
| 30.043478 | 151 | 0.740955 |
024b2f364d3119bc89b59671b0be4963319759ba
| 945 |
package org.mariapresso.impd.bean.entity;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* Created by ez2sarang on 15. 4. 9..
*/
@Entity
public @Data
class InOutHistory implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private boolean logType;
private boolean valid;
private String sessionToken;
private Date createDateTime;
public InOutHistory() {
}
public InOutHistory(boolean logType, String sessionToken) {
this.logType = logType;
this.sessionToken = sessionToken;
this.createDateTime = new Date();
}
public void addSessionToken(String sessionToken) {
if(null == this.sessionToken) {
this.sessionToken = sessionToken;
} else {
this.sessionToken = String.format("%s|%s", this.sessionToken, sessionToken);
}
}
}
| 24.230769 | 88 | 0.669841 |
b66eead1b14c870cc6e06204f509ac5055640116
| 1,011 |
package com.airbnb.lottie;
import android.graphics.PointF;
class z
{
private final PointF a;
private final PointF b;
private final PointF c;
z()
{
this.a = new PointF();
this.b = new PointF();
this.c = new PointF();
}
z(PointF paramPointF1, PointF paramPointF2, PointF paramPointF3)
{
this.a = paramPointF1;
this.b = paramPointF2;
this.c = paramPointF3;
}
PointF a()
{
return this.a;
}
void a(float paramFloat1, float paramFloat2)
{
this.a.set(paramFloat1, paramFloat2);
}
PointF b()
{
return this.b;
}
void b(float paramFloat1, float paramFloat2)
{
this.b.set(paramFloat1, paramFloat2);
}
PointF c()
{
return this.c;
}
void c(float paramFloat1, float paramFloat2)
{
this.c.set(paramFloat1, paramFloat2);
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/com/airbnb/lottie/z.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
| 16.85 | 101 | 0.6182 |
d4d4929c34badfa202fd6ca04e92260f24ad9a59
| 5,695 |
/*
* Copyright (c) 2004-2021, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.trackedentity;
import android.database.Cursor;
import androidx.annotation.Nullable;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.gabrielittner.auto.value.cursor.ColumnAdapter;
import com.google.auto.value.AutoValue;
import org.hisp.dhis.android.core.arch.db.adapters.custom.internal.FilterPeriodColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.enums.internal.EnrollmentStatusColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.identifiable.internal.ObjectWithUidColumnAdapter;
import org.hisp.dhis.android.core.arch.db.adapters.ignore.internal.IgnoreTrackedEntityInstanceEventFilterListColumnAdapter;
import org.hisp.dhis.android.core.common.BaseIdentifiableObject;
import org.hisp.dhis.android.core.common.CoreObject;
import org.hisp.dhis.android.core.common.FilterPeriod;
import org.hisp.dhis.android.core.common.ObjectStyle;
import org.hisp.dhis.android.core.common.ObjectWithStyle;
import org.hisp.dhis.android.core.common.ObjectWithUid;
import org.hisp.dhis.android.core.enrollment.EnrollmentStatus;
import org.hisp.dhis.android.core.trackedentity.internal.TrackedEntityInstanceFilterFields;
import java.util.List;
@AutoValue
@JsonDeserialize(builder = $$AutoValue_TrackedEntityInstanceFilter.Builder.class)
public abstract class TrackedEntityInstanceFilter extends BaseIdentifiableObject implements CoreObject,
ObjectWithStyle<TrackedEntityInstanceFilter, TrackedEntityInstanceFilter.Builder> {
@Nullable
@JsonProperty()
@ColumnAdapter(ObjectWithUidColumnAdapter.class)
public abstract ObjectWithUid program();
@Nullable
@JsonProperty()
public abstract String description();
@Nullable
@JsonProperty()
public abstract Integer sortOrder();
@Nullable
@JsonProperty()
@ColumnAdapter(EnrollmentStatusColumnAdapter.class)
public abstract EnrollmentStatus enrollmentStatus();
@Nullable
@JsonProperty(TrackedEntityInstanceFilterFields.FOLLOW_UP)
public abstract Boolean followUp();
@Nullable
@JsonProperty()
@ColumnAdapter(FilterPeriodColumnAdapter.class)
public abstract FilterPeriod enrollmentCreatedPeriod();
@Nullable
@JsonProperty()
@ColumnAdapter(IgnoreTrackedEntityInstanceEventFilterListColumnAdapter.class)
public abstract List<TrackedEntityInstanceEventFilter> eventFilters();
public static Builder builder() {
return new $$AutoValue_TrackedEntityInstanceFilter.Builder();
}
public static TrackedEntityInstanceFilter create(Cursor cursor) {
return $AutoValue_TrackedEntityInstanceFilter.createFromCursor(cursor);
}
public abstract Builder toBuilder();
@AutoValue.Builder
@JsonPOJOBuilder(withPrefix = "")
public static abstract class Builder extends BaseIdentifiableObject.Builder<Builder>
implements ObjectWithStyle.Builder<TrackedEntityInstanceFilter, Builder> {
public abstract Builder id(Long id);
public abstract Builder program(ObjectWithUid program);
public abstract Builder description(String description);
public abstract Builder sortOrder(Integer sortOrder);
public abstract Builder enrollmentStatus(EnrollmentStatus enrollmentStatus);
@JsonProperty(TrackedEntityInstanceFilterFields.FOLLOW_UP)
public abstract Builder followUp(Boolean followUp);
public abstract Builder enrollmentCreatedPeriod(FilterPeriod enrollmentCreatedPeriod);
public abstract Builder eventFilters(List<TrackedEntityInstanceEventFilter> eventFilters);
abstract TrackedEntityInstanceFilter autoBuild();
// Auxiliary fields
abstract ObjectStyle style();
public TrackedEntityInstanceFilter build() {
try {
style();
} catch (IllegalStateException e) {
style(ObjectStyle.builder().build());
}
return autoBuild();
}
}
}
| 40.678571 | 123 | 0.772081 |
1fe254004fa78b9cafb033da6398b8e744ac97eb
| 2,063 |
package com.clevercloud.biscuit.crypto;
import cafe.cryptography.curve25519.Constants;
import cafe.cryptography.curve25519.RistrettoElement;
import cafe.cryptography.curve25519.Scalar;
import java.security.SecureRandom;
/**
* Private and public key
*/
public final class KeyPair {
public final Scalar private_key;
public final RistrettoElement public_key;
public KeyPair(final SecureRandom rng) {
byte[] b = new byte[64];
rng.nextBytes(b);
this.private_key = Scalar.fromBytesModOrderWide(b);
this.public_key = Constants.RISTRETTO_GENERATOR.multiply(this.private_key);
}
public byte[] toBytes() {
return this.private_key.toByteArray();
}
public KeyPair(byte[] b) {
this.private_key = Scalar.fromBytesModOrderWide(b);
this.public_key = Constants.RISTRETTO_GENERATOR.multiply(this.private_key);
}
public String toHex() {
return byteArrayToHexString(this.toBytes());
}
public KeyPair(String hex) {
byte[] b = hexStringToByteArray(hex);
this.private_key = Scalar.fromBytesModOrder(b);
this.public_key = Constants.RISTRETTO_GENERATOR.multiply(this.private_key);
}
public PublicKey public_key() {
return new PublicKey(this.public_key);
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
static String byteArrayToHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l/2];
for (int i = 0; i < l; i += 2) {
data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i+1), 16));
}
return data;
}
}
| 30.338235 | 83 | 0.627727 |
c91f2db66028599b99856060bc8fcbedb3ccac72
| 4,074 |
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.models.ApplicationModeHelper;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.UIConstants;
public class EditHostModel extends HostModel {
public EditHostModel() {
getExternalHostProviderEnabled().setIsAvailable(ApplicationModeHelper.getUiMode() != ApplicationMode.GlusterOnly);
}
@Override
protected boolean showInstallationProperties() {
return false;
}
@Override
protected void updateModelDataCenterFromVds(List<StoragePool> dataCenters, VDS vds) {
if (dataCenters != null) {
getDataCenter().setItems(dataCenters);
getDataCenter().setSelectedItem(Linq.firstOrNull(dataCenters,
new Linq.IdPredicate<>(vds.getStoragePoolId())));
if (getDataCenter().getSelectedItem() == null) {
getDataCenter().setSelectedItem(Linq.firstOrNull(dataCenters));
}
}
}
@Override
protected void setAllowChangeHost(VDS vds) {
if (vds.getStatus() != VDSStatus.InstallFailed) {
getHost().setIsChangeable(false);
getAuthSshPort().setIsChangeable(false);
} else {
getHost().setIsChangeable(true);
getAuthSshPort().setIsChangeable(true);
}
}
@Override
protected void setAllowChangeHostPlacementPropertiesWhenNotInMaintenance() {
UIConstants constants = ConstantsManager.getInstance().getConstants();
getDataCenter().setChangeProhibitionReason(constants.dcCanOnlyBeChangedWhenHostInMaintMode());
getDataCenter().setIsChangeable(false);
getCluster().setChangeProhibitionReason(constants.clusterCanOnlyBeChangedWhenHostInMaintMode());
getCluster().setIsChangeable(false);
}
@Override
protected void updateProvisionedHosts() {
}
@Override
public boolean showExternalProviderPanel() {
return true;
}
@Override
public boolean externalProvisionEnabled() {
return false;
}
@Override
protected void setPort(VDS vds) {
getPort().setEntity(vds.getPort());
}
@Override
protected void updateModelClusterFromVds(ArrayList<Cluster> clusters, VDS vds) {
if (clusters != null) {
getCluster().setSelectedItem(Linq.firstOrNull(clusters,
new Linq.IdPredicate<>(vds.getClusterId())));
}
}
@Override
public boolean showNetworkProviderTab() {
return false;
}
@Override
protected boolean editTransportProperties(VDS vds) {
if (VDSStatus.Maintenance.equals(vds.getStatus())) {
return true;
}
return false;
}
public void setSelectedCluster(VDS host) {
ArrayList<Cluster> clusters;
if (getCluster().getItems() == null) {
Cluster tempVar = new Cluster();
tempVar.setName(host.getClusterName());
tempVar.setId(host.getClusterId());
tempVar.setCompatibilityVersion(host.getClusterCompatibilityVersion());
getCluster()
.setItems(new ArrayList<>(Arrays.asList(new Cluster[]{tempVar})));
}
clusters = (ArrayList<Cluster>) getCluster().getItems();
updateModelClusterFromVds(clusters, host);
if (getCluster().getSelectedItem() == null) {
getCluster().setSelectedItem(Linq.firstOrNull(clusters));
}
}
@Override
protected void cpuVendorChanged() {
updateKernelCmdlineCheckboxesChangeability();
}
}
| 33.393443 | 122 | 0.672558 |
455132b83815631d88287364272d754d2fb18bbd
| 1,537 |
/**
* 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.geronimo.management.geronimo;
import java.util.Map;
import org.apache.geronimo.management.J2EEManagedObject;
/**
* Management interface for admin objects
*
* @version $Rev$ $Date$
*/
public interface JCAAdminObject extends J2EEManagedObject {
public String getAdminObjectClass();
public String getAdminObjectInterface();
/**
* Gets the config properties in the form of a map where the key is the
* property name and the value is property type (as a String not a Class).
*/
public Map getConfigProperties();
public void setConfigProperty(String property, Object value) throws Exception;
public Object getConfigProperty(String property) throws Exception;
}
| 36.595238 | 82 | 0.744958 |
27212bb7974bb23331937e8d69bde1c9db1f4469
| 3,884 |
package ar.com.system.afip.wsfe.business.api;
import java.util.List;
import ar.com.system.afip.wsfe.service.api.CbteTipo;
import ar.com.system.afip.wsfe.service.api.ConceptoTipo;
import ar.com.system.afip.wsfe.service.api.Cotizacion;
import ar.com.system.afip.wsfe.service.api.DocTipo;
import ar.com.system.afip.wsfe.service.api.FECAEAGet;
import ar.com.system.afip.wsfe.service.api.FECAEARequest;
import ar.com.system.afip.wsfe.service.api.FECAEAResponse;
import ar.com.system.afip.wsfe.service.api.FECAEASinMov;
import ar.com.system.afip.wsfe.service.api.FECAEASinMovResponse;
import ar.com.system.afip.wsfe.service.api.FECAERequest;
import ar.com.system.afip.wsfe.service.api.FECAEResponse;
import ar.com.system.afip.wsfe.service.api.FECompConsResponse;
import ar.com.system.afip.wsfe.service.api.FECompConsultaReq;
import ar.com.system.afip.wsfe.service.api.IvaTipo;
import ar.com.system.afip.wsfe.service.api.Moneda;
import ar.com.system.afip.wsfe.service.api.OpcionalTipo;
import ar.com.system.afip.wsfe.service.api.PaisTipo;
import ar.com.system.afip.wsfe.service.api.PtoVenta;
import ar.com.system.afip.wsfe.service.api.TributoTipo;
public interface WsfeManager {
/**
* Solicitud de Codigo de Autorizacion Electronico (CAE)
*/
FECAEResponse fecaeSolicitar(FECAERequest feCAEReq);
/**
* Retorna la cantidad maxima de registros que puede tener una invocacion al
* metodo FECAESolicitar / FECAEARegInformativo
*/
int feCompTotXRequest();
/**
* Retorna el ultimo comprobante autorizado para el tipo de comprobante /
* cuit / punto de venta ingresado / Tipo de Emision
*/
int feCompUltimoAutorizado(int ptoVta, int cbteTipo);
/**
* Consulta Comprobante emitido y su codigo.
*/
FECompConsResponse feCompConsultar(FECompConsultaReq feCompConsReq);
/**
* Rendicion de comprobantes asociados a un CAEA.
*/
FECAEAResponse fecaeaRegInformativo(FECAEARequest feCAEARegInfReq);
/**
* Solicitud de Codigo de Autorizacion Electronico Anticipado (CAEA)
*/
FECAEAGet fecaeaSolicitar(int periodo, short orden);
/**
* Consulta CAEA informado como sin movimientos.
*/
List<FECAEASinMov> fecaeaSinMovimientoConsultar(String caea, int ptoVta);
/**
* Informa CAEA sin movimientos.
*/
FECAEASinMovResponse fecaeaSinMovimientoInformar(int ptoVta, String caea);
/**
* Consultar CAEA emitidos.
*/
FECAEAGet fecaeaConsultar(int periodo, short orden);
/**
* Recupera la cotizacion de la moneda consultada y su fecha
*/
Cotizacion feParamGetCotizacion(String monId);
/**
* Recupera el listado de los diferente tributos que pueden ser utilizados
* en el servicio de autorizacion
*
* @return returns prueba.ws.wsfe.FETributoResponse
*/
List<TributoTipo> feParamGetTiposTributos();
/**
* Recupera el listado de monedas utilizables en servicio de autorizacion
*/
List<Moneda> feParamGetTiposMonedas();
/**
* Recupera el listado de Tipos de Iva utilizables en servicio de
* autorizacion.
*/
List<IvaTipo> feParamGetTiposIva();
/**
* Recupera el listado de identificadores para los campos Opcionales
*
* @return returns prueba.ws.wsfe.OpcionalTipoResponse
*/
List<OpcionalTipo> feParamGetTiposOpcional();
/**
* Recupera el listado de identificadores para el campo Concepto.
*/
List<ConceptoTipo> feParamGetTiposConcepto();
/**
* Recupera el listado de puntos de venta registrados y su estado
*/
List<PtoVenta> feParamGetPtosVenta();
/**
* Recupera el listado de Tipos de Comprobantes utilizables en servicio de
* autorizacion.
*/
List<CbteTipo> feParamGetTiposCbte();
/**
* Recupera el listado de Tipos de Documentos utilizables en servicio de
* autorizacion.
*/
List<DocTipo> feParamGetTiposDoc();
/**
* Recupera el listado de los diferente paises que pueden ser utilizados en
* el servicio de autorizacion
*/
List<PaisTipo> feParamGetTiposPaises();
}
| 29.424242 | 77 | 0.761071 |
9d877e78d049de4b5ded5d04ddfe6e057ab65944
| 5,018 |
package org.jahia.se.modules.edp.dam.widen;
import org.jahia.services.content.JCRNodeWrapper;
import org.jahia.services.content.JCRTemplate;
import org.jahia.services.content.decorator.JCRMountPointNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.RepositoryException;
import java.util.Locale;
public class MountPoint {
private static final Logger LOGGER = LoggerFactory.getLogger(MountPoint.class);
public static final String NODETYPE = "wdennt:mountPoint";
public static final String PROPERTY_PREFIX = "wden:";
private static final String NODETYPE_PROPERTY_PROTOCOL = PROPERTY_PREFIX+"apiProtocol";
public static final String NODETYPE_PROPERTY_ENDPOINT = PROPERTY_PREFIX+"apiEndPoint";
private static final String NODETYPE_PROPERTY_SITE = PROPERTY_PREFIX+"apiSite";
private static final String NODETYPE_PROPERTY_TOKEN = PROPERTY_PREFIX+"apiToken";
private static final String NODETYPE_PROPERTY_VERSION = PROPERTY_PREFIX+"apiVersion";
private static final String NODETYPE_PROPERTY_LAZYLOAD = PROPERTY_PREFIX+"lazyLoad";
private static final String NODETYPE_PROPERTY_RESULT_PER_PAGE = PROPERTY_PREFIX+"resultPerPage";
private static final boolean LAZYLOAD = false;
private static final int RESULT_PER_PAGE = 50;
private String id;
private String systemname;
private String protocol;
private String endpoint;
private String site;
private String token;
private String version;
private boolean lazyLoad;
private int resultPerPage;
private String mountPath;
public MountPoint() {
// default constructor for ObjectMapper
}
public MountPoint(JCRNodeWrapper mountNode) {
systemname = mountNode.getName();
try {
id = mountNode.getIdentifier();
mountPath = mountNode.getProperty(JCRMountPointNode.MOUNT_POINT_PROPERTY_NAME).getNode().getPath();
} catch (RepositoryException e) {
id = null;
mountPath = mountNode.getPath();
}
try {
lazyLoad = mountNode.getProperty(NODETYPE_PROPERTY_LAZYLOAD).getBoolean();
} catch (RepositoryException e) {
LOGGER.info("Set Default Lazyload {}", LAZYLOAD, e);
}
try {
resultPerPage = (int) mountNode.getProperty(NODETYPE_PROPERTY_RESULT_PER_PAGE).getLong();
} catch (RepositoryException e) {
LOGGER.info("Set Default Result per page {}", RESULT_PER_PAGE, e);
}
protocol = mountNode.getPropertyAsString(NODETYPE_PROPERTY_PROTOCOL);
endpoint = mountNode.getPropertyAsString(NODETYPE_PROPERTY_ENDPOINT);
site = mountNode.getPropertyAsString(NODETYPE_PROPERTY_SITE);
token = mountNode.getPropertyAsString(NODETYPE_PROPERTY_TOKEN);
version = mountNode.getPropertyAsString(NODETYPE_PROPERTY_VERSION);
}
public String getId() {
return id;
}
public String getSystemname() {
return systemname;
}
public String getProtocol () { return protocol;}
public String getEndpoint () { return endpoint;}
public String getSite () { return site;}
public String getToken () { return token;}
public String getVersion () { return version;}
public boolean getLazyLoad () { return lazyLoad;}
public int getResultPerPage () { return resultPerPage;}
public String getMountPath () { return mountPath;}
public static JCRNodeWrapper getOrCreateMountPoint(MountPoint mountPoint) throws RepositoryException {
return JCRTemplate.getInstance().doExecuteWithSystemSession(session -> {
String systemMountPath = "/mounts";
JCRNodeWrapper wdenMountPointNode;
if (session.nodeExists(systemMountPath.concat("/").concat(mountPoint.getSystemname()))) {
wdenMountPointNode = session.getNode(systemMountPath.concat("/").concat(mountPoint.getSystemname()));
} else {
wdenMountPointNode = session.getNode(systemMountPath).addNode(mountPoint.getSystemname(), MountPoint.NODETYPE);
}
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_PROTOCOL, mountPoint.getProtocol());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_ENDPOINT, mountPoint.getEndpoint());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_SITE, mountPoint.getSite());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_TOKEN, mountPoint.getToken());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_VERSION, mountPoint.getVersion());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_LAZYLOAD, mountPoint.getLazyLoad());
wdenMountPointNode.setProperty(NODETYPE_PROPERTY_RESULT_PER_PAGE, mountPoint.getResultPerPage());
wdenMountPointNode.setProperty(JCRMountPointNode.MOUNT_POINT_PROPERTY_NAME, session.getNode(mountPoint.getMountPath()));
wdenMountPointNode.saveSession();
return wdenMountPointNode;
});
}
}
| 46.036697 | 132 | 0.720008 |
2cdfccaed2fb938f2b24df92a765cda4355aa967
| 5,488 |
/**
* Copyright 2016 Netflix, 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 rx.internal.operators;
import java.util.concurrent.atomic.AtomicInteger;
import rx.*;
/**
* Base class for Subscribers that consume the entire upstream and signal
* zero or one element (or an error) in a backpressure honoring fashion.
* <p>
* Store any temporary value in {@link #value} and indicate there is
* a value available when completing by setting {@link #hasValue}.
* <p.
* Use {@link #subscribeTo(Observable)} to properly setup the link between this and the downstream
* subscriber.
*
* @param <T> the source value type
* @param <R> the result value type
*/
public abstract class DeferredScalarSubscriber<T, R> extends Subscriber<T> {
/** The downstream subscriber. */
protected final Subscriber<? super R> actual;
/** Indicates there is a value available in value. */
protected boolean hasValue;
/** The holder of the single value. */
protected R value;
/** The state, see the constants below. */
final AtomicInteger state;
/** Initial state. */
static final int NO_REQUEST_NO_VALUE = 0;
/** Request came first. */
static final int HAS_REQUEST_NO_VALUE = 1;
/** Value came first. */
static final int NO_REQUEST_HAS_VALUE = 2;
/** Value will be emitted. */
static final int HAS_REQUEST_HAS_VALUE = 3;
public DeferredScalarSubscriber(Subscriber<? super R> actual) {
this.actual = actual;
this.state = new AtomicInteger();
}
@Override
public void onError(Throwable ex) {
value = null;
actual.onError(ex);
}
@Override
public void onCompleted() {
if (hasValue) {
complete(value);
} else {
complete();
}
}
/**
* Signals onCompleted() to the downstream subscriber.
*/
protected final void complete() {
actual.onCompleted();
}
/**
* Atomically switches to the terminal state and emits the value if
* there is a request for it or stores it for retrieval by {@code downstreamRequest(long)}.
* @param value the value to complete with
*/
protected final void complete(R value) {
Subscriber<? super R> a = actual;
for (;;) {
int s = state.get();
if (s == NO_REQUEST_HAS_VALUE || s == HAS_REQUEST_HAS_VALUE || a.isUnsubscribed()) {
return;
}
if (s == HAS_REQUEST_NO_VALUE) {
a.onNext(value);
if (!a.isUnsubscribed()) {
a.onCompleted();
}
state.lazySet(HAS_REQUEST_HAS_VALUE);
return;
}
this.value = value;
if (state.compareAndSet(NO_REQUEST_NO_VALUE, NO_REQUEST_HAS_VALUE)) {
return;
}
}
}
final void downstreamRequest(long n) {
if (n < 0L) {
throw new IllegalArgumentException("n >= 0 required but it was " + n);
}
if (n != 0L) {
Subscriber<? super R> a = actual;
for (;;) {
int s = state.get();
if (s == HAS_REQUEST_NO_VALUE || s == HAS_REQUEST_HAS_VALUE || a.isUnsubscribed()) {
return;
}
if (s == NO_REQUEST_HAS_VALUE) {
if (state.compareAndSet(NO_REQUEST_HAS_VALUE, HAS_REQUEST_HAS_VALUE)) {
a.onNext(value);
if (!a.isUnsubscribed()) {
a.onCompleted();
}
}
return;
}
if (state.compareAndSet(NO_REQUEST_NO_VALUE, HAS_REQUEST_NO_VALUE)) {
return;
}
}
}
}
@Override
public final void setProducer(Producer p) {
p.request(Long.MAX_VALUE);
}
/**
* Links up with the downstream Subscriber (cancellation, backpressure) and
* subscribes to the source Observable.
* @param source the source Observable
*/
public final void subscribeTo(Observable<? extends T> source) {
setupDownstream();
source.unsafeSubscribe(this);
}
/* test */ final void setupDownstream() {
Subscriber<? super R> a = actual;
a.add(this);
a.setProducer(new InnerProducer(this));
}
/**
* Redirects the downstream request amount bach to the DeferredScalarSubscriber.
*/
static final class InnerProducer implements Producer {
final DeferredScalarSubscriber<?, ?> parent;
public InnerProducer(DeferredScalarSubscriber<?, ?> parent) {
this.parent = parent;
}
@Override
public void request(long n) {
parent.downstreamRequest(n);
}
}
}
| 30.831461 | 100 | 0.573615 |
5952d37ec286fdb1724a3c375eb684344b12ec26
| 461 |
package org.honton.chas.dogstatd.model;
/**
* A Gauge records a value of a metric at a particular time.
*/
public class Gauge extends Metric<Number> {
/**
* Create an Gauge value to be sent to DogStatD.
*
* @param name The name of the gauge.
* @param value The value of the gauge.
* @param tags Any additional data about the value.
*/
public Gauge(String name, Number value, String... tags) {
super(name, value, 'g', tags);
}
}
| 24.263158 | 60 | 0.657267 |
639574f82a17cea9ea2370eaa4703dd9aab047c3
| 3,172 |
/*
* (c) Copyright 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
* All rights reserved.
* [See end of file]
*/
package arq.cmdline;
public class ModGeneral extends ModBase
{
private CallbackHelp helpCallback = null ;
public ModGeneral(CallbackHelp callback) { this.helpCallback = callback ; }
// Could be turned into a module but these are convenient as inherited flags
private final ArgDecl argDeclHelp = new ArgDecl(false, "help", "h");
private final ArgDecl argDeclVerbose = new ArgDecl(false, "v", "verbose");
private final ArgDecl argDeclQuiet = new ArgDecl(false, "q", "quiet");
private final ArgDecl argDeclDebug = new ArgDecl(false, "debug");
protected boolean verbose = false ;
protected boolean quiet = false ;
protected boolean debug = false ;
protected boolean help = false ;
public void registerWith(CmdGeneral cmdLine)
{
cmdLine.getUsage().startCategory("General") ;
cmdLine.add(argDeclVerbose, "-v --verbose", "Verbose") ;
cmdLine.add(argDeclQuiet, "-q --quiet", "Run with minimal output") ;
cmdLine.add(argDeclDebug, "--debug", "Output information for debugging") ;
cmdLine.add(argDeclHelp, "--help", null) ;
}
public void processArgs(CmdArgModule cmdLine)
{
verbose = cmdLine.contains(argDeclVerbose) ;
quiet = cmdLine.contains(argDeclQuiet) ;
debug = cmdLine.contains(argDeclDebug) ;
if ( debug )
verbose = true ;
help = cmdLine.contains(argDeclHelp) ;
if ( help )
helpCallback.doHelp() ;
}
}
/*
* (c) Copyright 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
| 43.452055 | 82 | 0.702081 |
ac23532077f1fc54c34cd83c616fd752aadf677d
| 5,878 |
package no.ks.kryptering;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.JRE;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.UUID;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
class KSKeyStoreLoaderTest {
private static final String PKCS12_KEYSTORE_PATH = "keystore.p12";
private static final String PKCS12_KEYSTORE_PASSWORD = "test1234";
private static final String JCEKS_KEYSTORE_PATH = "keystore.jks";
private static final String JCEKS_KEYSTORE_PASSWORD = "test1234";
@Test
@DisplayName("Det skal være mulig å laste en PKCS12 keystore som en fil")
void testLoadPKCS12Keystore() {
new KSKeyStoreLoader(getClass().getClassLoader().getResource(JCEKS_KEYSTORE_PATH).getFile(), JCEKS_KEYSTORE_PASSWORD.toCharArray());
}
@Test
@DisplayName("Det skal være mulig å laste en JCEKS keystore som en fil uten å spesifisere type")
void testLoadKeystore() {
new KSKeyStoreLoader(getClass().getClassLoader().getResource(PKCS12_KEYSTORE_PATH).getFile(), PKCS12_KEYSTORE_PASSWORD.toCharArray(), "PKCS12");
}
@Test
@DisplayName("Det skal være mulig å laste en JCEKS keystore som en resource uten å spesifisere type")
void testLoadKeystoreFraRessurs() {
new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
}
@Test
@DisplayName("Det skal være mulig å laste en PKCS12 keystore som en resource")
void testLoadPKCS12KeystoreFraRessurs() {
new KSKeyStoreLoader(PKCS12_KEYSTORE_PATH, PKCS12_KEYSTORE_PASSWORD.toCharArray(), "PKCS12");
}
@Test
@DisplayName("Dersom feil passord er oppgitt ved lasting av keystore skal en exception kastes")
void testLoadKeystoreFeilPassord() {
RuntimeException exception = assertThrows(RuntimeException.class, () ->
new KSKeyStoreLoader(getClass().getClassLoader().getResource(JCEKS_KEYSTORE_PATH).getFile(), UUID.randomUUID().toString().toCharArray()));
assertThat(exception.getMessage(), containsString("Keystore was tampered with, or password was incorrect"));
}
@Test
@EnabledOnJre(JRE.JAVA_8)
@DisplayName("Dersom feil type er oppgitt ved lasting av keystore skal en exception kastes")
void testLoadKeystoreFeilType() {
RuntimeException exception = assertThrows(RuntimeException.class, () ->
new KSKeyStoreLoader(getClass().getClassLoader().getResource(JCEKS_KEYSTORE_PATH).getFile(), JCEKS_KEYSTORE_PASSWORD.toCharArray(), "PKCS12"));
assertThat(exception.getMessage(), containsString("DerInputStream.getLength(): lengthTag=109, too big"));
}
@Test
@DisplayName("Dersom keystore ikke finnes som fil eller resource skal en exception kastes")
void testLoadIkkeEksisterendeKeystore() {
String path = UUID.randomUUID().toString();
RuntimeException exception = assertThrows(RuntimeException.class, () ->
new KSKeyStoreLoader(path, UUID.randomUUID().toString().toCharArray()));
assertThat(exception.getMessage(), is(String.format("Klarte ikke å laste keystore fra \"%s\"", path)));
}
@Test
@DisplayName("Det skal være mulig å hente ut public key med alias fra en keystore")
void testGetPublicKey() {
KSKeyStoreLoader keyStoreLoader = new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
X509Certificate publicKey = keyStoreLoader.getPublicKey("kryptering");
assertThat(publicKey, notNullValue());
}
@Test
@DisplayName("Dersom man forsøker å hente ut en public key for et alias som ikke finnes skal en exception kastes")
void testGetPublicKeyIkkeEksisterende() {
KSKeyStoreLoader keyStoreLoader = new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
RuntimeException exception = assertThrows(RuntimeException.class, () -> keyStoreLoader.getPublicKey("ukjent"));
assertThat(exception.getMessage(), is("Fant ingen public key for alias \"ukjent\""));
}
@Test
@DisplayName("Det skal være mulig å hente ut private key med alias fra en keystore")
void testGetPrivateKey() {
KSKeyStoreLoader keyStoreLoader = new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
PrivateKey privateKey = keyStoreLoader.getPrivateKey("kryptering", JCEKS_KEYSTORE_PASSWORD.toCharArray());
assertThat(privateKey, notNullValue());
}
@Test
@DisplayName("Dersom man forsøker å hente ut en private key for et alias som ikke finnes skal en exception kastes")
void testGetPrivateKeyIkkeEksisterende() {
KSKeyStoreLoader keyStoreLoader = new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
RuntimeException exception = assertThrows(RuntimeException.class, () ->
keyStoreLoader.getPrivateKey("ukjent", UUID.randomUUID().toString().toCharArray()));
assertThat(exception.getMessage(), is("Fant ingen private key for alias \"ukjent\""));
}
@Test
@DisplayName("Dersom man forsøker å hente ut en eksisterende private key med feil passord skal en exception kastes")
void testGetPrivateKeyFeilPassord() {
KSKeyStoreLoader keyStoreLoader = new KSKeyStoreLoader(JCEKS_KEYSTORE_PATH, JCEKS_KEYSTORE_PASSWORD.toCharArray());
RuntimeException exception = assertThrows(RuntimeException.class, () ->
keyStoreLoader.getPrivateKey("kryptering", UUID.randomUUID().toString().toCharArray()));
assertThat(exception.getMessage(), containsString("Cannot recover key"));
}
}
| 47.788618 | 159 | 0.737496 |
08424a8576e87f744c741c81b6bcfa7b720b5c9c
| 1,237 |
/*
* Copyright 2012 Decebal Suiu
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with
* the License. You may obtain a copy of the License in the LICENSE file, or 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 ro.fortsoft.wicket.dashboard.web;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.IModel;
import ro.fortsoft.wicket.dashboard.Widget;
/**
* @author Decebal Suiu
*/
public class WidgetView extends GenericPanel<Widget> {
private static final long serialVersionUID = 1L;
public WidgetView(String id, IModel<Widget> model) {
super(id, model);
setOutputMarkupPlaceholderTag(true);
}
public Widget getWidget() {
return getModelObject();
}
@Override
protected void onConfigure() {
super.onConfigure();
setVisible(!getWidget().isCollapsed());
}
}
| 27.488889 | 118 | 0.742118 |
ac3788f968b2404321caa8311755f6a288570857
| 815 |
package Homework.Seventh;
import java.util.Scanner;
class Fibonacci {
int first, second, res, target;
Scanner scan = new Scanner(System.in);
public void setRes() {
System.out.print("몇 번째 항까지 구할까요 ? ");
target = scan.nextInt();
}
public void Print() {
first = 1;
second = 1;
System.out.printf("%d번째 항까지의 피보나치 수열 : %d %d", target, first, second);
for (int i = 2; i < target; i++) {
res = first + second;
first = second;
second = res;
System.out.printf(" %d", res);
}
}
}
public class Homework6 {
public static void main(String[] args) {
// 6) 피보나치 수열을 배열 없이 만들어서 출력해 보도록 만든다.
Fibonacci fib = new Fibonacci();
fib.setRes();
fib.Print();
}
}
| 20.897436 | 78 | 0.522699 |
96f723b1bcc9579326ca759c041ba278dbd1838c
| 3,824 |
/**
*
*/
package com.gojek.application.metrics;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.MetricRegistryListener;
import com.codahale.metrics.MetricSet;
import com.codahale.metrics.Timer;
/**
* @author ganeshs
*
*/
public class EnhancedMetricRegistry extends MetricRegistry {
private MetricRegistry metricRegistry;
private Map<String, Counter> counters = new HashMap<>();
/**
* @param metricRegistry
*/
public EnhancedMetricRegistry(MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
/**
* Overrides the counter method and converts it to a guage
*/
@Override
public Counter counter(String name) {
Counter counter = counters.get(name);
if (counter == null) {
counter = new Counter();
counters.put(name, counter);
registerGuage(name, counter);
}
return counter;
}
/**
* @param name
* @param counter
*/
protected void registerGuage(String name, Counter counter) {
if (getNames().contains(name)) {
return;
}
Gauge<Integer> gauge = () -> {
Long count = counter.getCount();
counter.dec(count);
return count.intValue();
};
register(name, gauge);
}
public int hashCode() {
return metricRegistry.hashCode();
}
public <T extends Metric> T register(String name, T metric) throws IllegalArgumentException {
return metricRegistry.register(name, metric);
}
public void registerAll(MetricSet metrics) throws IllegalArgumentException {
metricRegistry.registerAll(metrics);
}
public boolean equals(Object obj) {
return metricRegistry.equals(obj);
}
public Histogram histogram(String name) {
return metricRegistry.histogram(name);
}
public Meter meter(String name) {
return metricRegistry.meter(name);
}
public Timer timer(String name) {
return metricRegistry.timer(name);
}
public boolean remove(String name) {
return metricRegistry.remove(name);
}
public void removeMatching(MetricFilter filter) {
metricRegistry.removeMatching(filter);
}
public void addListener(MetricRegistryListener listener) {
metricRegistry.addListener(listener);
}
public void removeListener(MetricRegistryListener listener) {
metricRegistry.removeListener(listener);
}
public SortedSet<String> getNames() {
return metricRegistry.getNames();
}
public SortedMap<String, Gauge> getGauges() {
return metricRegistry.getGauges();
}
public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
return metricRegistry.getGauges(filter);
}
public SortedMap<String, Counter> getCounters() {
return metricRegistry.getCounters();
}
public SortedMap<String, Counter> getCounters(MetricFilter filter) {
return metricRegistry.getCounters(filter);
}
public SortedMap<String, Histogram> getHistograms() {
return metricRegistry.getHistograms();
}
public SortedMap<String, Histogram> getHistograms(MetricFilter filter) {
return metricRegistry.getHistograms(filter);
}
public SortedMap<String, Meter> getMeters() {
return metricRegistry.getMeters();
}
public SortedMap<String, Meter> getMeters(MetricFilter filter) {
return metricRegistry.getMeters(filter);
}
public String toString() {
return metricRegistry.toString();
}
public SortedMap<String, Timer> getTimers() {
return metricRegistry.getTimers();
}
public SortedMap<String, Timer> getTimers(MetricFilter filter) {
return metricRegistry.getTimers(filter);
}
public Map<String, Metric> getMetrics() {
return metricRegistry.getMetrics();
}
}
| 23.036145 | 94 | 0.747123 |
3927a3a3c3aaff0548924a63f89d64af727f37f5
| 553 |
package analyzer;
import lexical.LexicalAnalyzer;
import syntactic.SyntaticAnalyzer;
public class Analyzer2M {
private static LexicalAnalyzer lexicalAnalyzer;
private static SyntaticAnalyzer syntaticAnalyzer;
private static String filePath = "files/input/fibonacci.2m";
public Analyzer2M() {
}
public static void main(String[] args) {
lexicalAnalyzer = new LexicalAnalyzer(filePath);
lexicalAnalyzer.readFile();
syntaticAnalyzer = new SyntaticAnalyzer(lexicalAnalyzer);
syntaticAnalyzer.analyze();
}
}
| 21.269231 | 62 | 0.748644 |
a8602c86d58cda90c89aa50c6227b4302dc8741e
| 12,497 |
package io.github.zebalu.aoc2021;
import java.text.StringCharacterIterator;
import java.util.List;
import java.util.Optional;
public class Day18 {
public static void main(String[] args) {
var nums = INPUT.lines().map(Day18::read).toList();
firstPart(nums);
secondPart(nums);
}
private static void firstPart(List<SnailNum> nums) {
System.out.println(nums.stream().reduce((l, r) -> add(l, r)).orElseThrow().magnitude());
}
private static void secondPart(List<SnailNum> nums) {
System.out.println(nums.stream().mapToLong(l -> maxMagnitude(nums, l)).max().orElseThrow());
}
private static long maxMagnitude(List<SnailNum> nums, SnailNum left) {
return nums.stream().filter(n -> n != left).mapToLong(r -> add(left, r).magnitude()).max().orElseThrow();
}
private static SnailNum add(SnailNum left, SnailNum right) {
var added = new PairNum(left.clone(), right.clone(), null);
while (added.reduce()) {
}
return added;
}
private static SnailNum read(String line) {
return read(new StringCharacterIterator(line));
}
private static SnailNum read(StringCharacterIterator siterator) {
if ('[' == siterator.current()) {
siterator.next();
SnailNum left = read(siterator);
SnailNum right = read(siterator);
siterator.next();
return new PairNum(left, right, null);
}
if (',' == siterator.current()) {
siterator.next();
return read(siterator);
} else {
StringBuilder sb = new StringBuilder();
while (siterator.current() != ']' && siterator.current() != ','
&& siterator.getIndex() != siterator.getEndIndex()) {
sb.append(siterator.current());
siterator.next();
}
return new SimpleNum(Long.parseLong(sb.toString()), null);
}
}
private static abstract sealed class SnailNum implements Cloneable permits PairNum,SimpleNum {
protected SnailNum parent;
abstract long magnitude();
int depth() {
return parent == null ? 1 : parent.depth() + 1;
}
abstract boolean reduce();
abstract void add(long value, boolean left);
abstract boolean shouldReduce();
abstract boolean canExplode();
abstract Optional<PairNum> getExploding();
@Override
protected SnailNum clone() {
try {
SnailNum clone = (SnailNum) super.clone();
return clone;
} catch (CloneNotSupportedException e) {
throw new IllegalStateException(e);
}
}
}
private static final class PairNum extends SnailNum {
SnailNum left;
SnailNum right;
PairNum(SnailNum left, SnailNum right, SnailNum parent) {
this.parent = parent;
this.left = left;
this.right = right;
if (left.parent == null) {
left.parent = this;
}
if (right.parent == null) {
right.parent = this;
}
}
@Override
boolean reduce() {
var exploding = getExploding();
if(exploding.isPresent()) {
exploding.get().explode();
return true;
}
if (!left.reduce()) {
return right.reduce();
}
return true;
}
@Override
long magnitude() {
return 3 * left.magnitude() + 2 * right.magnitude();
}
private void explode() {
if (depth() > 4) {
addTo(((SimpleNum) left).value, true);
addTo(((SimpleNum) right).value, false);
unlinkMe((PairNum) parent);
}
}
private void addTo(long value, boolean left) {
findFirstNotMe(left).ifPresent(found -> found.add(value, !left));
}
private void unlinkMe(PairNum currParent) {
if (currParent.left == this) {
currParent.left = new SimpleNum(0, currParent);
} else {
currParent.right = new SimpleNum(0, currParent);
}
}
Optional<SnailNum> findFirstNotMe(boolean left) {
var currParent = (PairNum) parent;
var curr = this;
while (currParent != null) {
if (left && currParent.right == curr) {
return Optional.of(currParent.left);
} else if (!left && currParent.left == curr) {
return Optional.of(currParent.right);
}
curr = currParent;
currParent = (PairNum) currParent.parent;
}
return Optional.empty();
}
@Override
void add(long value, boolean left) {
if (left) {
this.left.add(value, left);
} else {
right.add(value, left);
}
}
@Override
boolean shouldReduce() {
return depth() > 4;
}
@Override
boolean canExplode() {
return depth() > 4 && left instanceof SimpleNum && right instanceof SimpleNum;
}
@Override
Optional<PairNum> getExploding() {
return left.getExploding().or(()-> canExplode() ? Optional.of(this) : right.getExploding());
}
@Override
public String toString() {
return (depth() > 4 ? "![" : "[") + left + "," + right + "]";
}
@Override
protected PairNum clone() {
PairNum clone = (PairNum) super.clone();
clone.left = clone.left.clone();
clone.right = clone.right.clone();
clone.left.parent = clone;
clone.right.parent = clone;
return clone;
}
}
private static final class SimpleNum extends SnailNum {
long value;
SimpleNum(long value, SnailNum parent) {
this.parent = parent;
this.value = value;
}
@Override
long magnitude() {
return value;
}
@Override
boolean reduce() {
if (shouldReduce()) {
long left = value / 2;
long right = value % 2 == 1 ? (value + 1) / 2 : value / 2;
var replacement = new PairNum(new SimpleNum(left, null), new SimpleNum(right, null), parent);
PairNum p = (PairNum) parent;
if (p.left == this) {
p.left = replacement;
} else {
p.right = replacement;
}
return true;
}
return false;
}
@Override
void add(long value, boolean left) {
this.value += value;
}
@Override
boolean shouldReduce() {
return value >= 10;
}
@Override
public String toString() {
return Long.toString(value);
}
@Override
boolean canExplode() {
return false;
}
@Override
Optional<PairNum> getExploding() {
return Optional.empty();
}
@Override
protected SimpleNum clone() {
return (SimpleNum) super.clone();
}
}
private static final String INPUT = """
[6,[[6,3],[[1,4],[8,4]]]]
[5,[[[0,8],[1,0]],8]]
[[[6,[7,7]],[2,[6,4]]],[2,6]]
[[[[7,4],[2,7]],[4,[1,5]]],[[[0,5],5],[[2,1],[8,2]]]]
[[[[5,9],[7,2]],[0,[9,9]]],[[[5,3],[7,9]],[3,[9,1]]]]
[5,[[3,0],[[8,2],5]]]
[[2,[[0,8],7]],[4,[7,7]]]
[[[[3,4],6],[5,[4,2]]],[[9,[9,5]],2]]
[[7,[0,5]],[[1,3],[7,[4,0]]]]
[[[6,2],3],[[[2,0],9],[5,[7,2]]]]
[[4,[8,6]],8]
[[[9,8],[[7,3],[4,6]]],[5,3]]
[[[0,[8,4]],8],[[5,[4,7]],[5,9]]]
[[[[0,8],[3,7]],[5,1]],[[5,6],2]]
[[[[5,8],0],[[3,0],3]],[[6,5],[[8,0],[3,9]]]]
[[[8,[5,6]],[6,4]],[8,0]]
[7,[[5,[3,8]],3]]
[[[4,[2,0]],2],[[[8,1],[5,8]],5]]
[9,[[[6,6],[8,1]],[[7,9],9]]]
[[[6,0],[[7,2],9]],[[[7,3],[1,1]],0]]
[[[[7,8],[0,3]],[5,9]],[[2,[4,3]],7]]
[[[3,1],[3,[6,3]]],[[6,[8,9]],7]]
[[[[1,1],[0,5]],[8,1]],[0,[8,[1,4]]]]
[[[6,[8,6]],[7,8]],[[7,3],[3,[5,8]]]]
[[[2,5],[[6,8],[4,5]]],[[2,[8,2]],[2,[3,2]]]]
[[[[9,2],0],5],0]
[[7,[[3,7],[0,9]]],[6,[1,[6,9]]]]
[[[[4,5],5],5],4]
[[[6,[6,9]],[8,3]],9]
[[[[2,7],[8,6]],0],[2,[4,9]]]
[[[4,[9,8]],[7,6]],[7,[[2,7],[2,7]]]]
[[[0,8],[4,[5,9]]],[[4,[1,0]],[6,8]]]
[[[2,4],9],[[[7,9],5],[0,5]]]
[[[3,[8,6]],6],[[8,[6,7]],[[6,1],[2,1]]]]
[[[0,[0,5]],[[0,5],4]],9]
[[[[0,0],7],8],[[8,[4,6]],9]]
[[[1,[1,1]],[3,[2,5]]],[6,6]]
[[[[3,7],[6,1]],[5,4]],[[0,[2,6]],[0,1]]]
[[1,1],[3,4]]
[9,[[4,[7,8]],[3,4]]]
[[[[5,3],[5,9]],9],[[[2,4],[2,7]],[[6,3],[1,8]]]]
[[[2,[2,2]],[[8,7],9]],[[[4,6],[5,3]],[[2,6],9]]]
[[[3,8],[[5,7],7]],[[[0,9],3],1]]
[[[6,[1,9]],[2,1]],[[[7,0],[2,1]],8]]
[[[8,[9,9]],1],[[4,1],[[2,8],1]]]
[[[2,[3,7]],[[2,4],[3,5]]],[[3,[1,9]],[[1,3],[1,7]]]]
[[[[4,3],8],3],[[6,[1,7]],[[4,2],9]]]
[[[[1,9],1],[[0,7],[9,4]]],[[[7,2],[0,1]],8]]
[9,5]
[[[[6,4],4],[[3,4],0]],[[9,[7,6]],[[3,4],[7,1]]]]
[[0,2],[[[4,9],[3,4]],[2,[3,9]]]]
[[[[8,9],9],[[6,4],[2,9]]],[[4,5],[[1,8],2]]]
[[[6,[9,5]],[4,[1,0]]],[[[4,1],[3,5]],[3,3]]]
[[[7,1],[[5,4],8]],[[0,[9,4]],7]]
[[[4,[0,3]],[[0,2],8]],[[0,[9,6]],[[6,3],[3,2]]]]
[[[[5,5],8],[[4,5],3]],[3,[[0,2],0]]]
[[[[9,5],[1,0]],[[9,1],[0,9]]],[[1,[9,1]],[1,3]]]
[[9,[[5,7],8]],[[9,[9,3]],[3,[0,1]]]]
[[[5,6],[9,8]],[2,9]]
[[[9,[3,8]],[9,0]],[[8,[6,2]],1]]
[3,[4,[1,[0,4]]]]
[[9,[[8,5],[8,0]]],[[1,6],[8,4]]]
[[7,[[6,8],5]],[[9,[1,3]],[[6,5],[0,8]]]]
[[[6,0],[9,[3,5]]],[8,6]]
[[[1,[2,3]],[[5,2],4]],[1,[[7,3],2]]]
[[[2,[1,1]],3],[[8,[5,5]],[[7,5],[8,9]]]]
[[[4,0],[8,6]],[[[7,1],7],0]]
[2,6]
[[[[5,4],[9,7]],4],[0,6]]
[[4,[0,5]],[1,[[1,6],[6,2]]]]
[[[7,8],[0,6]],[0,[[2,9],[1,5]]]]
[1,[[[4,4],1],[[3,2],[2,5]]]]
[[[[9,8],[2,4]],[1,2]],[[[5,1],9],[[0,8],[5,2]]]]
[[8,[[2,6],[4,6]]],[[0,[2,9]],[[2,2],[7,2]]]]
[[[7,[8,1]],[[8,8],7]],[3,[7,[7,9]]]]
[[6,[[3,1],[3,6]]],[[[5,8],[9,8]],[2,[7,4]]]]
[[[4,[2,0]],[3,[3,3]]],[[6,[8,5]],5]]
[[[3,2],3],[[8,2],8]]
[[7,[[8,7],[5,8]]],[[2,0],[7,7]]]
[[[[3,3],1],[[5,1],4]],[[4,3],[[4,9],8]]]
[[[0,[5,8]],7],[4,9]]
[[0,[[7,7],[1,1]]],[[0,[5,0]],[4,5]]]
[[[[2,8],[1,6]],[[7,3],9]],[[2,8],[6,2]]]
[[1,[4,7]],[8,0]]
[3,[[[6,1],9],[[1,1],5]]]
[[[[3,0],[9,8]],[6,[8,3]]],3]
[4,[[1,[8,1]],[[6,0],2]]]
[[4,[4,[0,3]]],[[[7,5],[0,2]],[[9,7],[6,5]]]]
[[0,[4,[6,1]]],[[[1,9],[6,0]],9]]
[[[[0,2],[8,4]],[2,3]],[[9,[8,4]],1]]
[[[[1,2],[7,7]],[[3,8],3]],[[[1,1],[7,5]],6]]
[[[[1,8],[8,4]],[[4,0],1]],[0,[1,[9,4]]]]
[[[3,1],[9,5]],[[[9,5],4],[[8,7],4]]]
[[[6,[3,0]],0],[[[6,9],7],[[6,1],[6,6]]]]
[[[[9,6],[4,4]],5],9]
[[5,[[6,0],0]],1]
[3,[0,[4,[9,0]]]]
[[[5,[2,2]],3],5]
[[2,3],[9,[6,7]]]
[[[[6,8],[7,9]],[4,7]],[[1,2],[0,1]]]""";
}
| 34.522099 | 114 | 0.377691 |
e47ef28b7d42ea523912532b3eff7ac027901aba
| 4,063 |
package net.renfei.config;
import net.renfei.security.filter.JwtTokenFilter;
import net.renfei.security.handler.AccessDeniedHandlerImpl;
import net.renfei.security.handler.AuthenticationEntryPointImpl;
import net.renfei.security.interceptor.AccessDecisionManagerImpl;
import net.renfei.security.interceptor.FilterInvocationSecurityMetadataSourceImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* Spring Security 的安全配置
*
* @author renfei
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtTokenFilter jwtTokenFilter;
private final AccessDecisionManagerImpl accessDecisionManager;
private final FilterInvocationSecurityMetadataSourceImpl filterInvocationSecurityMetadataSource;
public SecurityConfig(JwtTokenFilter jwtTokenFilter,
AccessDecisionManagerImpl accessDecisionManager,
FilterInvocationSecurityMetadataSourceImpl filterInvocationSecurityMetadataSource) {
this.jwtTokenFilter = jwtTokenFilter;
this.accessDecisionManager = accessDecisionManager;
this.filterInvocationSecurityMetadataSource = filterInvocationSecurityMetadataSource;
}
/**
* anyRequest | 匹配所有请求路径
* access | SpringEl表达式结果为true时可以访问
* anonymous | 匿名可以访问
* denyAll | 用户不能访问
* fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
* hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
* hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
* hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
* hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
* hasRole | 如果有参数,参数表示角色,则其角色可以访问
* permitAll | 用户可以任意访问
* rememberMe | 允许通过remember-me登录的用户访问
* authenticated | 用户登录后可访问
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// rest 接口不用 CSRF
http.csrf().disable();
http.headers()
.frameOptions().sameOrigin()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.antMatchers("/api/**").authenticated()
.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
@Override
public <O extends FilterSecurityInterceptor> O postProcess(O o) {
o.setSecurityMetadataSource(filterInvocationSecurityMetadataSource);
o.setAccessDecisionManager(accessDecisionManager);
return o;
}
})
.anyRequest().permitAll()
.and().exceptionHandling()
.accessDeniedHandler(new AccessDeniedHandlerImpl())
.authenticationEntryPoint(new AuthenticationEntryPointImpl());
http.addFilterBefore(
jwtTokenFilter,
UsernamePasswordAuthenticationFilter.class
);
}
}
| 47.8 | 110 | 0.699237 |
0fdfe4688a05a9c6703fdfd25c1ef311dcd5c3db
| 311 |
package de.hftstuttgart.projectindoorweb.persistence.repositories;
import de.hftstuttgart.projectindoorweb.persistence.entities.Building;
import org.springframework.data.repository.CrudRepository;
public interface BuildingRepository extends CrudRepository<Building, Long> {
Building findOne(Long id);
}
| 28.272727 | 76 | 0.842444 |
8efe85125038ac63ef67375c001d5b60c0e34f55
| 749 |
package chapter07.section01.thread_7_1_3.pro_1_stateTest3;
/**
* Project Name:java-multi-thread-programming <br/>
* Package Name:chapter07.section01.thread_7_1_3.pro_1_stateTest3 <br/>
* Date:2019/12/1 22:49 <br/>
*
* @author <a href="turodog@foxmail.com">chenzy</a><br/>
*/
public class Run {
// NEW,
// RUNNABLE,
// TERMINATED,
// BLOCKED,
// WAITING,
// TIMED_WAITING,
public static void main(String[] args) throws InterruptedException {
MyThread1 t1 = new MyThread1();
t1.setName("a");
t1.start();
MyThread2 t2 = new MyThread2();
t2.setName("b");
t2.start();
//Thread.sleep(1000);
System.out.println("main方法中的t2状态:" + t2.getState());
}
}
| 23.40625 | 72 | 0.608812 |
2cc91949f0f28b11e8b8193a01b549072eb0ece4
| 1,388 |
package pt.it.av.tnav.utils.structures.point;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import pt.it.av.tnav.utils.csv.CSV;
public class Point2DTest {
@Test
public void test_csv_load() {
final String csv = "0,0\r\n1,1\r\n2,2";
List<Point2D> points = null;
try {
points = Point2D.csvLoad(CSV.read(new StringReader(csv)));
} catch (IOException e) {
e.printStackTrace();
}
List<Point2D> expected = new ArrayList<>();
expected.add(new Point2D(0, 0));
expected.add(new Point2D(1, 1));
expected.add(new Point2D(2, 2));
assertEquals(expected, points);
}
@Test
public void test_csv_dump() {
List<Point2D> points = new ArrayList<>();
points.add(new Point2D(0, 0));
points.add(new Point2D(1, 1));
points.add(new Point2D(2, 2));
CSV csv = new CSV();
csv.addLines(points);
StringWriter w = new StringWriter();
try {
csv.write(w);
} catch (IOException e) {
e.printStackTrace();
}
final String expected = "0.0,0.0\r\n1.0,1.0\r\n2.0,2.0";
assertEquals(expected, w.toString());
}
}
| 25.236364 | 70 | 0.589337 |
64bb716b81110384bc4b3f6cdd84f29d08fd65a3
| 1,528 |
package web.constants;
/**
*
* 邮件发送
* @author Administrator
*
*/
public class MailInfo {
//邮箱服务器 如smtp.163.com
private String host ;
//用户邮箱 如**@163
private String formName ;
//用户授权码 不是用户名密码 可以自行查看相关邮件服务器怎么查看
private String formPassword ;
//消息回复邮箱
private String replayAddress ;
//发送地址
private String toAddress ;
//发送主题
private String subject ;
//发送内容
private String content ;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getFormName() {
return formName;
}
public void setFormName(String formName) {
this.formName = formName;
}
public String getFormPassword() {
return formPassword;
}
public void setFormPassword(String formPassword) {
this.formPassword = formPassword;
}
public String getReplayAddress() {
return replayAddress;
}
public void setReplayAddress(String replayAddress) {
this.replayAddress = replayAddress;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| 23.151515 | 56 | 0.622382 |
e9a4f6d796f8c1e44b321471423c1e6575c2514f
| 811 |
package com.yboot.base.modules.activiti.entity;
import com.yboot.common.base.YbootBaseEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author 田培融
*/
@Data
@Entity
@Table(name = "t_act_model")
@TableName("t_act_model")
@ApiModel(value = "模型")
public class ActModel extends YbootBaseEntity {
private static final long serialVersionUID = 1L;
@ApiModelProperty(value = "模型名称")
private String name;
@ApiModelProperty(value = "标识")
private String modelKey;
@ApiModelProperty(value = "版本")
private Integer version;
@ApiModelProperty(value = "描述/备注")
private String description;
}
| 23.171429 | 53 | 0.748459 |
344d9936eb3683f83cffd84c1bfca307635710db
| 3,823 |
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.Session.InputCallback;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.io.IOException;
import java.util.*;
/*
Copyright 2004-2015 Bo Zimmerman
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.
*/
@SuppressWarnings("rawtypes")
public class Retire extends StdCommand
{
public Retire(){}
private final String[] access=I(new String[]{"RETIRE"});
@Override public String[] getAccessWords(){return access;}
@Override
public boolean execute(final MOB mob, Vector commands, int metaFlags)
throws java.io.IOException
{
final Session session=mob.session();
if(session==null)
return false;
final PlayerStats pstats=mob.playerStats();
if(pstats==null)
return false;
mob.tell(L("^HThis will delete your player from the system FOREVER!"));
session.prompt(new InputCallback(InputCallback.Type.PROMPT,"",120000)
{
@Override public void showPrompt()
{
session.promptPrint(L("If that's what you want, re-enter your password: "));
}
@Override public void timedOut() {}
@Override public void callBack()
{
if(input.trim().length()==0)
return;
if(!pstats.matchesPassword(input.trim()))
mob.tell(L("Password incorrect."));
else
{
if(CMSecurity.isDisabled(CMSecurity.DisFlag.RETIREREASON))
{
Log.sysOut("Retire","Retired: "+mob.Name());
CMLib.players().obliteratePlayer(mob,true,false);
session.logout(true);
}
else
session.prompt(new InputCallback(InputCallback.Type.PROMPT,"")
{
@Override public void showPrompt()
{
session.promptPrint(L("OK. Please leave us a short message as to why you are deleting this character. Your answers will be kept confidential, and are for administrative purposes only.\n\r: "));
}
@Override public void timedOut() {}
@Override public void callBack()
{
Log.sysOut("Retire","Retired: "+mob.Name()+": "+this.input);
CMLib.players().obliteratePlayer(mob,true,false);
session.logout(true);
}
});
}
}
});
return false;
}
@Override public double combatActionsCost(final MOB mob, final List<String> cmds){return CMProps.getCommandCombatActionCost(ID());}
@Override public double actionsCost(final MOB mob, final List<String> cmds){return CMProps.getCommandActionCost(ID());}
@Override public boolean canBeOrdered(){return false;}
}
| 37.116505 | 203 | 0.711745 |
301c5b7e89fc09d500ead7f64f317b59a3f4c831
| 2,212 |
/*
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.central.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.AbstractMessage;
import com.google.protobuf.Parser;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.glowroot.common.util.SizeLimitBypassingParser;
public class Messages {
private Messages() {}
public static ByteBuffer toByteBuffer(List<? extends AbstractMessage> messages)
throws IOException {
// TODO optimize byte copying
ByteArrayOutputStream output = new ByteArrayOutputStream();
for (AbstractMessage message : messages) {
message.writeDelimitedTo(output);
}
return ByteBuffer.wrap(output.toByteArray());
}
public static <T extends /*@NonNull*/ AbstractMessage> List<T> parseDelimitedFrom(
@Nullable ByteBuffer byteBuf, Parser<T> parser) throws IOException {
if (byteBuf == null) {
return ImmutableList.of();
}
SizeLimitBypassingParser<T> sizeLimitBypassingParser =
new SizeLimitBypassingParser<>(parser);
List<T> messages = new ArrayList<>();
try (InputStream input = new ByteBufferInputStream(byteBuf)) {
T message;
while ((message = sizeLimitBypassingParser.parseDelimitedFrom(input)) != null) {
messages.add(message);
}
}
return messages;
}
}
| 35.111111 | 92 | 0.699819 |
acd6349ad130184fc917e774bd4f74694f212aa1
| 3,042 |
/**********************************************************************
Copyright (c) 2014 HubSpot 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.hubspot.jinjava.lib.tag;
import java.util.Iterator;
import org.apache.commons.lang3.StringUtils;
import com.hubspot.jinjava.interpret.InterpretException;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import com.hubspot.jinjava.tree.Node;
import com.hubspot.jinjava.tree.TagNode;
import com.hubspot.jinjava.util.ObjectTruthValue;
/**
* {% if expr %}
* {% else %}
* {% endif %}
*
* {% if expr %}
* {% endif %}
*
* @author anysome
*/
public class IfTag implements Tag {
private static final String TAGNAME = "if";
private static final String ENDTAGNAME = "endif";
@Override
public String interpret(TagNode tagNode, JinjavaInterpreter interpreter) {
if(StringUtils.isBlank(tagNode.getHelpers())) {
throw new InterpretException("Tag 'if' expects expression", tagNode.getLineNumber());
}
Iterator<Node> nodeIterator = tagNode.getChildren().iterator();
TagNode nextIfElseTagNode = (TagNode) tagNode;
while(nextIfElseTagNode != null && !evaluateIfElseTagNode(nextIfElseTagNode, interpreter)) {
nextIfElseTagNode = findNextIfElseTagNode(nodeIterator);
}
StringBuilder sb = new StringBuilder();
if(nextIfElseTagNode != null) {
while(nodeIterator.hasNext()) {
Node n = nodeIterator.next();
if(n.getName().equals(ElseIfTag.ELSEIF) || n.getName().equals(ElseTag.ELSE)) {
break;
}
sb.append(n.render(interpreter));
}
}
return sb.toString();
}
private TagNode findNextIfElseTagNode(Iterator<Node> nodeIterator) {
while(nodeIterator.hasNext()) {
Node node = nodeIterator.next();
if(TagNode.class.isAssignableFrom(node.getClass())) {
TagNode tag = (TagNode) node;
if(tag.getName().equals(ElseIfTag.ELSEIF) || tag.getName().equals(ElseTag.ELSE)) {
return tag;
}
}
}
return null;
}
protected boolean evaluateIfElseTagNode(TagNode tagNode, JinjavaInterpreter interpreter) {
if(tagNode.getName().equals(ElseTag.ELSE)) {
return true;
}
return ObjectTruthValue.evaluate(interpreter.resolveELExpression(tagNode.getHelpers(), tagNode.getLineNumber()));
}
@Override
public String getEndTagName() {
return ENDTAGNAME;
}
@Override
public String getName() {
return TAGNAME;
}
}
| 29.533981 | 117 | 0.666667 |
d861706356d3c4cd6465024d2d1d8e5033aa8e75
| 1,319 |
/*
* Copyright 2018 Organizations participating in ISAAC, ISAAC's KOMET, and SOLOR development include the
US Veterans Health Administration, OSHERA, and the Health Services Platform Consortium..
*
* 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 sh.isaac.api.statement;
import java.util.Optional;
import sh.isaac.api.component.concept.ConceptChronology;
/**
* The Result measures the actual state of the
* clinical statement topic during the timing specified
* by the performance circumstance.
* @author kec
*/
public interface ObservationResult extends Result {
/**
*
* @return an indicator as to the possibility of an immediate
* health risk to the individual that may require immediate action.
*/
Optional<ConceptChronology> getHealthRisk();
}
| 35.648649 | 104 | 0.740713 |
1034ad01ce6a2c66b9a86ac9d661458e5e3f39f9
| 190 |
package com.elarian.model;
public class PaymentPurseCounterParty {
public String purseId;
public PaymentPurseCounterParty(String purseId) {
this.purseId = purseId;
}
}
| 19 | 53 | 0.721053 |
9cd64f79821652a7e2aa64ed8a7da1e9370278de
| 2,116 |
package com.abin.lee.march.svr.concurrent.complicating;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;
/**
* Created by abin on 2017/8/4 13:01.
* march-svr
* com.abin.lee.march.svr.concurrent.complicating
* FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。
* 然后通过Future来取得计算结果。但是,若开启了多个任务,我们无从知晓哪个任务最先结束。因此,若要实现“当某任务结束时,立刻做一些事情,例如记录日志”这一功能,就需要写一些额外的代码
* https://blog.csdn.net/zmx729618/article/details/51596414
*/
public class ForkJoinTaskComplicate extends RecursiveTask<Integer> {
private static final long serialVersionUID = -3611254198265061729L;
public static final int threshold = 2;
private int start;
private int end;
public ForkJoinTaskComplicate(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
int sum = 0;
//如果任务足够小就计算任务
boolean canCompute = (end - start) <= threshold;
if (canCompute) {
for (int i = start; i <= end; i++) {
sum += i;
}
} else {
// 如果任务大于阈值,就分裂成两个子任务计算
int middle = (start + end) / 2;
ForkJoinTaskComplicate leftTask = new ForkJoinTaskComplicate(start, middle);
ForkJoinTaskComplicate rightTask = new ForkJoinTaskComplicate(middle + 1, end);
// 执行子任务
leftTask.fork();
rightTask.fork();
//等待任务执行结束合并其结果
int leftResult = leftTask.join();
int rightResult = rightTask.join();
//合并子任务
sum = leftResult + rightResult;
}
return sum;
}
public static void main(String[] args) {
ForkJoinPool forkjoinPool = new ForkJoinPool();
//生成一个计算任务,计算1+2+3+4
ForkJoinTaskComplicate task = new ForkJoinTaskComplicate(1, 100);
//执行一个任务
Future<Integer> result = forkjoinPool.submit(task);
try {
System.out.println(result.get());
} catch (Exception e) {
System.out.println(e);
}
}
}
| 28.213333 | 96 | 0.614367 |
1a926529d6291c6e546db5a0ffa342749dbeee03
| 23,085 |
package com.android.quack.network;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;
public class NetworkUtils {
private static final String TAG = "NetworkUtils";
private static final int NET_TYPE_3GWAP = 2;
private static final int NET_TYPE_3GNET = 3;
private static final int NET_TYPE_2GWAP = 4;
private static final int NET_TYPE_2GNET = 5;
private static final int NETWORK_TYPE_EVDO_B = 12;
private static final int NETWORK_TYPE_LTE = 13;
private static final int NETWORK_TYPE_EHRPD = 14;
private static final int NETWORK_TYPE_HSPAP = 15;
private static final String CHINA_MOBILE_46000 = "46000";
private static final String CHINA_MOBILE_46002 = "46002";
private static final String CHINA_MOBILE_46007 = "46007";
public static int getNetType(Context context) {
int netType = -1;
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String extraInfo = info.getExtraInfo();
// LogUtil.d(TAG, "extraInfo=" + extraInfo);
int type = info.getType();
if (type == ConnectivityManager.TYPE_WIFI) {
netType = 1;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
int subType = info.getSubtype();
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_GPRS:
netType = get2GApnConfig(extraInfo);
break;
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_UMTS:
case NETWORK_TYPE_EVDO_B:
case NETWORK_TYPE_LTE:
case NETWORK_TYPE_EHRPD:
case NETWORK_TYPE_HSPAP:
netType = get3GApnConfig(extraInfo);
}
}
}
return netType;
}
private static int get2GApnConfig(String extraInfo) {
if (extraInfo != null) {
String info = extraInfo.toLowerCase();
if (info.contains("wap")) {
return NET_TYPE_2GWAP;
}
}
return NET_TYPE_2GNET;
}
private static int get3GApnConfig(String extraInfo) {
if (extraInfo != null) {
String info = extraInfo.toLowerCase();
if (info.contains("wap")) {
return NET_TYPE_3GWAP;
}
}
return NET_TYPE_3GNET;
}
public static boolean isMobileWap(Context context) {
int netType = getNetType(context);
return NET_TYPE_2GWAP == netType || NET_TYPE_3GWAP == netType;
}
/**
* 是否移动sim卡
*
* @param context
* @return
*/
public static boolean isMobileCMCC(Context context) {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String operator = telephonyManager.getSimOperator();
if (!TextUtils.isEmpty(operator)
&& (operator.equals(CHINA_MOBILE_46000) || operator.equals(CHINA_MOBILE_46002) || operator
.equals(CHINA_MOBILE_46007))) {
return true;
}
String subscribeId = telephonyManager.getSubscriberId();
return !TextUtils.isEmpty(subscribeId)
&& (subscribeId.startsWith(CHINA_MOBILE_46000)
|| subscribeId.startsWith(CHINA_MOBILE_46002)
|| subscribeId.startsWith(CHINA_MOBILE_46007));
}
public static boolean isConnectivityNetAvailable(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected() && info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
} catch (Exception e) {
return false;
}
return false;
}
public static boolean ping() {
Process process = null;
PingWorker worker = null;
try {
process = Runtime.getRuntime().exec("ping -c 3 -w 100 www.baidu.com");
worker = new PingWorker(process);
worker.start();
worker.join(1000 * 3);
if (worker.exit != null && worker.exit == 0) {
return true;
} else {
return false;
}
} catch (Exception ex) {
if (worker != null) {
worker.interrupt();
}
Thread.currentThread().interrupt();
return false;
} finally {
if (process != null) {
process.destroy();
}
}
}
static class PingWorker extends Thread {
private final Process process;
private Integer exit = -1;
public PingWorker(Process process) {
this.process = process;
}
@Override
public void run() {
try {
exit = process.waitFor();
} catch (InterruptedException e) {
return;
}
}
}
public interface ICouldSurfTheInternet {
void networkOK();
void networkError();
}
public static boolean isWifiEnable(Context context) {
// 取得WifiManager对象
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
}
/**
* Check whether WIFI is available.
*
* @param context Application context
* @return <code>true</code> if WIFI available, <code>false</code> otherwise
*/
public static boolean isWifiAvailable(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
}
NetworkInfo networkInfo = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network[] networks = connectivity.getAllNetworks();
if (networks == null) {
return false;
}
for (Network network : networks) {
networkInfo = connectivity.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
break;
} else {
networkInfo = null;
}
}
} else {
networkInfo = connectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return networkInfo != null && networkInfo.isConnected();
} catch (Throwable e) {
return false;
}
}
/**
* Check whether network is available.
*
* @param context Application context
* @return <code>true</code> if network available, <code>false</code> otherwise
*/
public static boolean isNetworkAvailableOld(Context context) {
try {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Network[] networks = connectivity.getAllNetworks();
if (networks == null) {
return false;
}
for (Network network : networks) {
if (connectivity.getNetworkInfo(network).isConnected()) {
return true;
}
}
} else {
NetworkInfo[] networkInfoArr = connectivity.getAllNetworkInfo();
if (networkInfoArr == null) {
return false;
}
for (NetworkInfo networkInfo : networkInfoArr) {
if (networkInfo.isConnected()) {
return true;
}
}
}
return false;
} catch (Throwable e) {
return false;
}
}
public static boolean isNetworkAvailable(Context context) {
if (context != null) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null) {
return false;
}
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
return networkInfo.isAvailable();
}
}
return false;
}
/**
* 获取当前连入的wifi的SSID
*/
public static String getConnectWifiSsid(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (isWifiAvailable(context)) {
return wifiInfo.getSSID();
} else {
return "";
}
}
/**
* 获取当前连入的wifi信息,返回的ssid没有""
*/
public static String getConnectWifiSsidFormat(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (isWifiAvailable(context)) {
return wifiInfo.getSSID().replace("\"", "");
} else {
return "";
}
}
/**
* 获取当前wifi列表
*/
public List<ScanResult> getWifiList(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
List<ScanResult> list = wifiManager.getScanResults();
for (ScanResult scanResult : list) {
if (!TextUtils.isEmpty(scanResult.SSID.trim())) {
list.add(scanResult);
}
}
return list;
}
public static boolean is5GHz(int freq) {
return freq > 4900 && freq < 5900;
}
public static int getChannelAccordingToFreq(int freq) {
int channel = -1;
switch (freq) {
case 2412:
channel = 1;
break;
case 2417:
channel = 2;
break;
case 2422:
channel = 3;
break;
case 2427:
channel = 4;
break;
case 2432:
channel = 5;
break;
case 2437:
channel = 6;
break;
case 2442:
channel = 7;
break;
case 2447:
channel = 8;
break;
case 2452:
channel = 9;
break;
case 2457:
channel = 10;
break;
case 2462:
channel = 11;
break;
case 2467:
channel = 12;
break;
case 2472:
channel = 13;
break;
case 2484:
channel = 14;
break;
case 5745:
channel = 149;
break;
case 5765:
channel = 153;
break;
case 5785:
channel = 157;
break;
case 5805:
channel = 161;
break;
case 5825:
channel = 165;
break;
default:
break;
}
return channel;
}
/**
* 常用wifi相关的工具管理类
*/
public static class WifiUtils {
// 定义WifiManager对象
private WifiManager mWifiManager;
// 扫描出的网络连接列表
private List<ScanResult> mWifiList;
// 网络连接列表
private List<WifiConfiguration> mWifiConfiguration;
// 定义一个WifiLock
private WifiManager.WifiLock mWifiLock;
// 构造器
public WifiUtils(Context context) {
// 取得WifiManager对象
mWifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
}
public boolean isWifiEnable() {
return mWifiManager.isWifiEnabled();
}
// 打开WIFI
public void openWifi() {
if (!mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(true);
}
}
// 关闭WIFI
public void closeWifi() {
if (mWifiManager.isWifiEnabled()) {
mWifiManager.setWifiEnabled(false);
}
}
// 检查当前WIFI状态
public int checkState() {
return mWifiManager.getWifiState();
}
// 锁定WifiLock
public void acquireWifiLock() {
mWifiLock.acquire();
}
// 解锁WifiLock
public void releaseWifiLock() {
// 判断时候锁定
if (mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
// 创建一个WifiLock
public void creatWifiLock() {
mWifiLock = mWifiManager.createWifiLock("Test");
}
// 得到配置好的网络
public List<WifiConfiguration> getConfigurationList() {
return mWifiConfiguration;
}
public boolean connectConfigurationByNetworkId(int id) {
return mWifiManager.enableNetwork(id,
true);
}
// 指定配置好的网络进行连接
public void connectConfiguration(int index) {
// 索引大于配置好的网络索引返回
if (index > mWifiConfiguration.size()) {
return;
}
// 连接配置好的指定ID的网络
mWifiManager.enableNetwork(mWifiConfiguration.get(index).networkId,
true);
}
public void startScan() {
mWifiManager.startScan();
// 得到扫描结果
mWifiList = mWifiManager.getScanResults();
// 得到配置好的网络连接
mWifiConfiguration = mWifiManager.getConfiguredNetworks();
}
// 得到网络列表
public List<ScanResult> getWifiList() {
return mWifiList;
}
// 查看扫描结果
public StringBuilder lookUpScan() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < mWifiList.size(); i++) {
stringBuilder.append("Index_").append(Integer.toString(i + 1)).append(":");
// 将ScanResult信息转换成一个字符串包
// 其中把包括:BSSID、SSID、capabilities、frequency、level
stringBuilder.append((mWifiList.get(i)).toString());
stringBuilder.append("/n");
}
return stringBuilder;
}
// 得到MAC地址
public String getMacAddress() {
return mWifiManager.getConnectionInfo().getMacAddress();
}
// 得到接入点的ssid
public String getSsid() {
return mWifiManager.getConnectionInfo().getSSID();
}
// 得到接入点的BSSID
public String getBSSID() {
return mWifiManager.getConnectionInfo().getBSSID();
}
// 得到IP地址
public int getIPAddress() {
return mWifiManager.getConnectionInfo().getIpAddress();
}
// 得到连接的ID
public int getNetworkId() {
return mWifiManager.getConnectionInfo().getNetworkId();
}
// 得到WifiInfo的所有信息包
public String getWifiInfo() {
return mWifiManager.getConnectionInfo().toString();
}
public boolean ping() {
return mWifiManager.pingSupplicant();
}
public WifiConfiguration getWifiConfig(String ssid) {
for (WifiConfiguration config : mWifiConfiguration) {
if (config.SSID.equals(ssid)) {
return config;
}
}
return null;
}
// 添加一个网络并连接
public boolean addNetwork(WifiConfiguration wcg) {
int wcgID = mWifiManager.addNetwork(wcg);
return mWifiManager.enableNetwork(wcgID, true);
}
// 断开指定ID的网络
public void disconnectWifi(int netId) {
mWifiManager.disableNetwork(netId);
mWifiManager.disconnect();
}
/**
* 获取相应的ssid的热点的配置信息(连接不上带密码的wifi,需进一步调试)
*
* @param type 分3种情况,1、无密码 2、wep方式 3、wpa方式
*/
public WifiConfiguration createWifiInfo(String SSID, String password, int type) {
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + SSID + "\"";
config.status = WifiConfiguration.Status.ENABLED;
removeNetwork(SSID);
if (type == 1) {//无密码方式
config.wepKeys[0] = "\"" + "\"";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 2) {//WEP方式
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + password + "\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
}
if (type == 3) {//WPA方式
config.hiddenSSID = true;
config.preSharedKey = "\"" + password + "\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
//config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
return config;
}
public void removeNetwork(String Ssid) {
WifiConfiguration tempConfig = this.isExists(Ssid);
if (tempConfig != null) {
mWifiManager.removeNetwork(tempConfig.networkId);
}
}
private WifiConfiguration isExists(String SSID) {
List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
if (existingConfigs != null) {
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
return existingConfig;
}
}
}
return null;
}
}
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());//得到IPV4地址
return ipAddress;
}
} else {
//当前无网络连接,请在设置中打开网络
}
return null;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
}
| 33.60262 | 128 | 0.545462 |
dac2f648ff06a22674f0ddbc35cac1bf832f673d
| 449 |
package com.example.story.wxapi;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import com.example.story.xiaoyao.R;
/**
*
* Created by story on 2017/4/27.
*/
public class WXEntryActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_activity);
}
}
| 21.380952 | 66 | 0.739421 |
6c9d40676381de3fe0b554e503ca4456b0e2e827
| 9,552 |
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|// Generated by the protocol buffer compiler. DO NOT EDIT!
end_comment
begin_comment
comment|// source: complexpb.proto
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|proto
operator|.
name|test
package|;
end_package
begin_class
specifier|public
specifier|final
class|class
name|Complexpb
block|{
specifier|private
name|Complexpb
parameter_list|()
block|{}
specifier|public
specifier|static
specifier|final
class|class
name|IntString
block|{
specifier|public
name|IntString
parameter_list|(
name|int
name|myInt
parameter_list|,
name|String
name|myString
parameter_list|,
name|int
name|underscoreInt
parameter_list|)
block|{
name|this
operator|.
name|myint_
operator|=
name|myInt
expr_stmt|;
name|this
operator|.
name|hasMyint
operator|=
literal|true
expr_stmt|;
name|this
operator|.
name|myString_
operator|=
name|myString
expr_stmt|;
name|this
operator|.
name|hasMyString
operator|=
literal|true
expr_stmt|;
name|this
operator|.
name|underscoreInt_
operator|=
name|underscoreInt
expr_stmt|;
name|this
operator|.
name|hasUnderscoreInt
operator|=
literal|true
expr_stmt|;
block|}
comment|// optional int32 myint = 1;
specifier|public
specifier|static
specifier|final
name|int
name|MYINT_FIELD_NUMBER
init|=
literal|1
decl_stmt|;
specifier|private
specifier|final
name|boolean
name|hasMyint
decl_stmt|;
specifier|private
name|int
name|myint_
init|=
literal|0
decl_stmt|;
specifier|public
name|boolean
name|hasMyint
parameter_list|()
block|{
return|return
name|hasMyint
return|;
block|}
specifier|public
name|int
name|getMyint
parameter_list|()
block|{
return|return
name|myint_
return|;
block|}
comment|// optional string myString = 2;
specifier|public
specifier|static
specifier|final
name|int
name|MYSTRING_FIELD_NUMBER
init|=
literal|2
decl_stmt|;
specifier|private
specifier|final
name|boolean
name|hasMyString
decl_stmt|;
specifier|private
name|java
operator|.
name|lang
operator|.
name|String
name|myString_
init|=
literal|""
decl_stmt|;
specifier|public
name|boolean
name|hasMyString
parameter_list|()
block|{
return|return
name|hasMyString
return|;
block|}
specifier|public
name|java
operator|.
name|lang
operator|.
name|String
name|getMyString
parameter_list|()
block|{
return|return
name|myString_
return|;
block|}
comment|// optional int32 underscore_int = 3;
specifier|public
specifier|static
specifier|final
name|int
name|UNDERSCORE_INT_FIELD_NUMBER
init|=
literal|3
decl_stmt|;
specifier|private
specifier|final
name|boolean
name|hasUnderscoreInt
decl_stmt|;
specifier|private
name|int
name|underscoreInt_
init|=
literal|0
decl_stmt|;
specifier|public
name|boolean
name|hasUnderscoreInt
parameter_list|()
block|{
return|return
name|hasUnderscoreInt
return|;
block|}
specifier|public
name|int
name|getUnderscoreInt
parameter_list|()
block|{
return|return
name|underscoreInt_
return|;
block|}
specifier|public
specifier|final
name|boolean
name|isInitialized
parameter_list|()
block|{
return|return
literal|true
return|;
block|}
block|}
specifier|public
specifier|static
specifier|final
class|class
name|Complex
block|{
comment|// Use Complex.newBuilder() to construct.
specifier|public
name|Complex
parameter_list|(
name|int
name|aint
parameter_list|,
name|String
name|aString
parameter_list|,
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|Integer
argument_list|>
name|lint
parameter_list|,
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|String
argument_list|>
name|lString
parameter_list|,
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|IntString
argument_list|>
name|lintString
parameter_list|)
block|{
name|this
operator|.
name|aint_
operator|=
name|aint
expr_stmt|;
name|this
operator|.
name|hasAint
operator|=
literal|true
expr_stmt|;
name|this
operator|.
name|aString_
operator|=
name|aString
expr_stmt|;
name|this
operator|.
name|hasAString
operator|=
literal|true
expr_stmt|;
name|this
operator|.
name|lint_
operator|=
name|lint
expr_stmt|;
name|this
operator|.
name|lString_
operator|=
name|lString
expr_stmt|;
name|this
operator|.
name|lintString_
operator|=
name|lintString
expr_stmt|;
block|}
comment|// optional int32 aint = 1;
specifier|public
specifier|static
specifier|final
name|int
name|AINT_FIELD_NUMBER
init|=
literal|1
decl_stmt|;
specifier|private
specifier|final
name|boolean
name|hasAint
decl_stmt|;
specifier|private
name|int
name|aint_
init|=
literal|0
decl_stmt|;
specifier|public
name|boolean
name|hasAint
parameter_list|()
block|{
return|return
name|hasAint
return|;
block|}
specifier|public
name|int
name|getAint
parameter_list|()
block|{
return|return
name|aint_
return|;
block|}
comment|// optional string aString = 2;
specifier|public
specifier|static
specifier|final
name|int
name|ASTRING_FIELD_NUMBER
init|=
literal|2
decl_stmt|;
specifier|private
specifier|final
name|boolean
name|hasAString
decl_stmt|;
specifier|private
name|java
operator|.
name|lang
operator|.
name|String
name|aString_
init|=
literal|""
decl_stmt|;
specifier|public
name|boolean
name|hasAString
parameter_list|()
block|{
return|return
name|hasAString
return|;
block|}
specifier|public
name|java
operator|.
name|lang
operator|.
name|String
name|getAString
parameter_list|()
block|{
return|return
name|aString_
return|;
block|}
comment|// repeated int32 lint = 3;
specifier|public
specifier|static
specifier|final
name|int
name|LINT_FIELD_NUMBER
init|=
literal|3
decl_stmt|;
specifier|private
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|java
operator|.
name|lang
operator|.
name|Integer
argument_list|>
name|lint_
init|=
name|java
operator|.
name|util
operator|.
name|Collections
operator|.
name|emptyList
argument_list|()
decl_stmt|;
specifier|public
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|java
operator|.
name|lang
operator|.
name|Integer
argument_list|>
name|getLintList
parameter_list|()
block|{
return|return
name|lint_
return|;
block|}
specifier|public
name|int
name|getLintCount
parameter_list|()
block|{
return|return
name|lint_
operator|.
name|size
argument_list|()
return|;
block|}
specifier|public
name|int
name|getLint
parameter_list|(
name|int
name|index
parameter_list|)
block|{
return|return
name|lint_
operator|.
name|get
argument_list|(
name|index
argument_list|)
return|;
block|}
comment|// repeated string lString = 4;
specifier|public
specifier|static
specifier|final
name|int
name|LSTRING_FIELD_NUMBER
init|=
literal|4
decl_stmt|;
specifier|private
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|java
operator|.
name|lang
operator|.
name|String
argument_list|>
name|lString_
init|=
name|java
operator|.
name|util
operator|.
name|Collections
operator|.
name|emptyList
argument_list|()
decl_stmt|;
specifier|public
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|java
operator|.
name|lang
operator|.
name|String
argument_list|>
name|getLStringList
parameter_list|()
block|{
return|return
name|lString_
return|;
block|}
specifier|public
name|int
name|getLStringCount
parameter_list|()
block|{
return|return
name|lString_
operator|.
name|size
argument_list|()
return|;
block|}
specifier|public
name|java
operator|.
name|lang
operator|.
name|String
name|getLString
parameter_list|(
name|int
name|index
parameter_list|)
block|{
return|return
name|lString_
operator|.
name|get
argument_list|(
name|index
argument_list|)
return|;
block|}
comment|// repeated .org.apache.hadoop.hive.serde2.proto.test.IntString lintString = 5;
specifier|public
specifier|static
specifier|final
name|int
name|LINTSTRING_FIELD_NUMBER
init|=
literal|5
decl_stmt|;
specifier|private
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|proto
operator|.
name|test
operator|.
name|Complexpb
operator|.
name|IntString
argument_list|>
name|lintString_
init|=
name|java
operator|.
name|util
operator|.
name|Collections
operator|.
name|emptyList
argument_list|()
decl_stmt|;
specifier|public
name|java
operator|.
name|util
operator|.
name|List
argument_list|<
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|proto
operator|.
name|test
operator|.
name|Complexpb
operator|.
name|IntString
argument_list|>
name|getLintStringList
parameter_list|()
block|{
return|return
name|lintString_
return|;
block|}
specifier|public
name|int
name|getLintStringCount
parameter_list|()
block|{
return|return
name|lintString_
operator|.
name|size
argument_list|()
return|;
block|}
specifier|public
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|serde2
operator|.
name|proto
operator|.
name|test
operator|.
name|Complexpb
operator|.
name|IntString
name|getLintString
parameter_list|(
name|int
name|index
parameter_list|)
block|{
return|return
name|lintString_
operator|.
name|get
argument_list|(
name|index
argument_list|)
return|;
block|}
specifier|private
name|void
name|initFields
parameter_list|()
block|{ }
specifier|public
specifier|final
name|boolean
name|isInitialized
parameter_list|()
block|{
return|return
literal|true
return|;
block|}
comment|// @@protoc_insertion_point(class_scope:org.apache.hadoop.hive.serde2.proto.test.Complex)
block|}
comment|// @@protoc_insertion_point(outer_class_scope)
block|}
end_class
end_unit
| 13.378151 | 97 | 0.802136 |
2a173275a9b8209961d6e096909f0fddcb1c2333
| 1,124 |
/**
* Copyright (c) 2000-2018 Liferay, Inc. All rights reserved.
*
* This library 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 2.1 of the License, or (at your option)
* any later version.
*
* This library 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.
*/
package com.liferay.faces.osgi.weaver.internal;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.util.CheckClassAdapter;
/**
* @author Kyle Stiemann
*/
public abstract class TestCheckClassAdapter extends CheckClassAdapter {
public TestCheckClassAdapter(ClassVisitor cv) {
super(cv);
}
public TestCheckClassAdapter(ClassVisitor cv, boolean checkDataFlow) {
super(cv, checkDataFlow);
}
public TestCheckClassAdapter(int api, ClassVisitor cv, boolean checkDataFlow) {
super(api, cv, checkDataFlow);
}
}
| 30.378378 | 80 | 0.762456 |
0c054e17f40df501ba45f95cd2e0090503fbec0a
| 2,440 |
package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("42")
class Record_1165 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 1165: FirstName is Ingrid")
void FirstNameOfRecord1165() {
assertEquals("Ingrid", customers.get(1164).getFirstName());
}
@Test
@DisplayName("Record 1165: LastName is Kordys")
void LastNameOfRecord1165() {
assertEquals("Kordys", customers.get(1164).getLastName());
}
@Test
@DisplayName("Record 1165: Company is Bach, Robert H Esq")
void CompanyOfRecord1165() {
assertEquals("Bach, Robert H Esq", customers.get(1164).getCompany());
}
@Test
@DisplayName("Record 1165: Address is 6776 Hamilton Blvd")
void AddressOfRecord1165() {
assertEquals("6776 Hamilton Blvd", customers.get(1164).getAddress());
}
@Test
@DisplayName("Record 1165: City is Allentown")
void CityOfRecord1165() {
assertEquals("Allentown", customers.get(1164).getCity());
}
@Test
@DisplayName("Record 1165: County is Lehigh")
void CountyOfRecord1165() {
assertEquals("Lehigh", customers.get(1164).getCounty());
}
@Test
@DisplayName("Record 1165: State is PA")
void StateOfRecord1165() {
assertEquals("PA", customers.get(1164).getState());
}
@Test
@DisplayName("Record 1165: ZIP is 18106")
void ZIPOfRecord1165() {
assertEquals("18106", customers.get(1164).getZIP());
}
@Test
@DisplayName("Record 1165: Phone is 610-398-8078")
void PhoneOfRecord1165() {
assertEquals("610-398-8078", customers.get(1164).getPhone());
}
@Test
@DisplayName("Record 1165: Fax is 610-398-7158")
void FaxOfRecord1165() {
assertEquals("610-398-7158", customers.get(1164).getFax());
}
@Test
@DisplayName("Record 1165: Email is ingrid@kordys.com")
void EmailOfRecord1165() {
assertEquals("ingrid@kordys.com", customers.get(1164).getEmail());
}
@Test
@DisplayName("Record 1165: Web is http://www.ingridkordys.com")
void WebOfRecord1165() {
assertEquals("http://www.ingridkordys.com", customers.get(1164).getWeb());
}
}
| 25.416667 | 76 | 0.731967 |
ecdb4ac500dd654afbc294d19b135fbe5232b57f
| 6,944 |
package com.example.wttech.basicrestapi.service;
import com.example.wttech.basicrestapi.model.Unit;
import com.example.wttech.basicrestapi.repo.UnitRepository;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Component
public class ExcelFieldMapperService {
// Repository
@Autowired
UnitRepository unitRepository;
/* Private */
private static void mapFieldsToList(List<String> fieldValues, int count, XSSFSheet sheet) {
Iterator rows = sheet.rowIterator();
XSSFRow row;
XSSFCell cell;
if(count == 1) {
rows.next();
while (rows.hasNext() && count == 1)
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
fieldValues.add(cell.getStringCellValue());
}
}
count++;
}
}
//print values
fieldValues.forEach(s -> System.out.println(s.toString()));
}
private static int mapHeaders(List<String> fieldNames, int count, XSSFSheet sheet) {
Iterator rows = sheet.rowIterator();
XSSFRow row;
XSSFCell cell;
while (rows.hasNext() && count== 0)
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext() && count == 0)
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
fieldNames.add(cell.getStringCellValue());
}
}
count++;
}
//print values
fieldNames.forEach(s -> System.out.println(s.toString()));
return count;
}
private static void printFields(List<String> fieldNames, List<String> fieldValuess) {
for(int i = 0 ; i < fieldNames.size(); i++){
System.out.print(fieldNames.get(i) + " ");
System.out.println(fieldValuess.get(i) + ";");
}
}
/* PUBLIC */
public static void readXLSXFile() throws IOException
{
ExcelFieldMapperService mapper = new ExcelFieldMapperService();
/*
* Create A new file input stream from your Excel sheet file.
* Feed that into a Workbook wrapper Object.
* */
InputStream ExcelFileToRead = new FileInputStream("src\\main\\resources\\Dutch.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
// Test creation of a dummy workbook for runtime crash protection
XSSFWorkbook test = new XSSFWorkbook();
// Create a worksheet object to read from, out of the data pulled from the workbook. ( A sheet from a book)
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
List<String> fieldNames = new ArrayList<>();
List<String> fieldValues = new ArrayList<>();
int count = 0;
// Iterate over the rows. Print their value as a string.
// TODO: Make this able to read the column headers so we can map values to Custom Object
//count = mapHeaders(fieldNames, count, sheet);
//mapHeaders(fieldNames, 0, sheet);
//mapFieldsToList(fieldValues, 1, sheet);
System.out.println(mapper.mapFieldsToUnit(sheet, 3));
}
public List<Unit> mapFieldsToUnit(XSSFSheet sheet, int count) {
Unit unit;
List<Unit> unitsList = new ArrayList<>();
Iterator rows = sheet.rowIterator();
XSSFRow row;
XSSFCell cell;
rows.next();
rows.next();
rows.next();
System.out.println(unitRepository);
while (rows.hasNext() && count >= 3) {
List<String> values = new ArrayList<>();
row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
values.add(cell.getStringCellValue());
}
if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
values.add(String.valueOf(cell.getNumericCellValue()));
}
}
count++;
if (!values.isEmpty()){
unit = new Unit(
values.get(0),
values.get(1),
values.get(2),
Double.parseDouble(values.get(3)),
Double.parseDouble(values.get(4)),
Double.parseDouble(values.get(5)),
Double.parseDouble(values.get(6)),
Double.parseDouble(values.get(7)),
Double.parseDouble(values.get(8)),
Double.parseDouble(values.get(9)),
Double.parseDouble(values.get(10)),
Double.parseDouble(values.get(11)),
Double.parseDouble(values.get(12)),
Double.parseDouble(values.get(13)),
Double.parseDouble(values.get(14)),
Double.parseDouble(values.get(15)),
Double.parseDouble(values.get(16)),
Double.parseDouble(values.get(17)),
Double.parseDouble(values.get(18)),
Double.parseDouble(values.get(19)),
Double.parseDouble(values.get(20)),
Double.parseDouble(values.get(21)),
Double.parseDouble(values.get(22)),
Double.parseDouble(values.get(23)),
Double.parseDouble(values.get(24)),
Double.parseDouble(values.get(25)),
Double.parseDouble(values.get(26)),
Double.parseDouble(values.get(27)),
Double.parseDouble(values.get(28)),
values.get(29));
unitsList.add(unit);
}
}
return unitsList;
}
public String mappedFields(String fieldsList){
return null;
}
}
| 34.039216 | 115 | 0.544355 |
7feadf3aab34eb5e740faaf351e7de7a89977c5d
| 3,101 |
package org.sagebionetworks.repo.manager.file.scanner;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Collections;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.sagebionetworks.repo.model.file.FileHandleAssociateType;
import com.google.common.collect.ImmutableSet;
@ExtendWith(MockitoExtension.class)
public class FileHandleScannerUtilsTest {
private FileHandleAssociateType associateType = FileHandleAssociateType.FileEntity;
@Test
public void testMapAssociationWithNullFileHandles() {
Instant timestamp = Instant.now();
Long objectId = 123L;
ScannedFileHandleAssociation scanned = new ScannedFileHandleAssociation(objectId);
Set<FileHandleAssociationRecord> expected = Collections.emptySet();
Set<FileHandleAssociationRecord> result = FileHandleScannerUtils.mapAssociation(associateType, scanned, timestamp.toEpochMilli());
assertEquals(expected, result);
}
@Test
public void testMapAssociationWithEmptyFileHandles() {
Instant timestamp = Instant.now();
Long objectId = 123L;
ScannedFileHandleAssociation scanned = new ScannedFileHandleAssociation(objectId).withFileHandleIds(Collections.emptySet());
Set<FileHandleAssociationRecord> expected = Collections.emptySet();
Set<FileHandleAssociationRecord> result = FileHandleScannerUtils.mapAssociation(associateType, scanned, timestamp.toEpochMilli());
assertEquals(expected, result);
}
@Test
public void testMapAssociationWithSingleFileHandle() {
Instant timestamp = Instant.now();
Long objectId = 123L;
Long fileHandleId = 456L;
ScannedFileHandleAssociation scanned = new ScannedFileHandleAssociation(objectId, fileHandleId);
Set<FileHandleAssociationRecord> expected = Collections.singleton(new FileHandleAssociationRecord().withAssociateType(associateType).withTimestamp(timestamp.toEpochMilli()).withAssociateId(objectId).withFileHandleId(fileHandleId));
Set<FileHandleAssociationRecord> result = FileHandleScannerUtils.mapAssociation(associateType, scanned, timestamp.toEpochMilli());
assertEquals(expected, result);
}
@Test
public void testMapAssociationWithMultipleFileHandles() {
Instant timestamp = Instant.now();
Long objectId = 123L;
ScannedFileHandleAssociation scanned = new ScannedFileHandleAssociation(objectId).withFileHandleIds(ImmutableSet.of(456L, 789L));
Set<FileHandleAssociationRecord> expected = ImmutableSet.of(
new FileHandleAssociationRecord().withAssociateType(associateType).withTimestamp(timestamp.toEpochMilli()).withAssociateId(objectId).withFileHandleId(456L),
new FileHandleAssociationRecord().withAssociateType(associateType).withTimestamp(timestamp.toEpochMilli()).withAssociateId(objectId).withFileHandleId(789L)
);
Set<FileHandleAssociationRecord> result = FileHandleScannerUtils.mapAssociation(associateType, scanned, timestamp.toEpochMilli());
assertEquals(expected, result);
}
}
| 35.643678 | 233 | 0.806514 |
86c0cd07451dfd221698f89199502991ea966dc0
| 2,845 |
package com.linkedin.datahub.graphql.resolvers.search;
import com.linkedin.datahub.graphql.types.SearchableEntityType;
import com.linkedin.datahub.graphql.exception.ValidationException;
import com.linkedin.datahub.graphql.generated.EntityType;
import com.linkedin.datahub.graphql.generated.SearchInput;
import com.linkedin.datahub.graphql.generated.SearchResults;
import com.linkedin.datahub.graphql.resolvers.ResolverUtils;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static com.linkedin.datahub.graphql.resolvers.ResolverUtils.bindArgument;
import static org.apache.commons.lang3.StringUtils.isBlank;
/**
* Resolver responsible for resolving the 'search' field of the Query type
*/
public class SearchResolver implements DataFetcher<CompletableFuture<SearchResults>> {
private static final int DEFAULT_START = 0;
private static final int DEFAULT_COUNT = 10;
private final Map<EntityType, SearchableEntityType<?>> _typeToEntity;
public SearchResolver(@Nonnull final List<SearchableEntityType<?>> searchableEntities) {
_typeToEntity = searchableEntities.stream().collect(Collectors.toMap(
SearchableEntityType::type,
entity -> entity
));
}
@Override
public CompletableFuture<SearchResults> get(DataFetchingEnvironment environment) {
final SearchInput input = bindArgument(environment.getArgument("input"), SearchInput.class);
// escape forward slash since it is a reserved character in Elasticsearch
final String sanitizedQuery = ResolverUtils.escapeForwardSlash(input.getQuery());
if (isBlank(sanitizedQuery)) {
throw new ValidationException("'query' parameter cannot be null or empty");
}
final int start = input.getStart() != null ? input.getStart() : DEFAULT_START;
final int count = input.getCount() != null ? input.getCount() : DEFAULT_COUNT;
return CompletableFuture.supplyAsync(() -> {
try {
return _typeToEntity.get(input.getType()).search(
sanitizedQuery,
input.getFilters(),
start,
count
);
} catch (Exception e) {
throw new RuntimeException("Failed to execute search: "
+ String.format("entity type %s, query %s, filters: %s, start: %s, count: %s",
input.getType(),
input.getQuery(),
input.getFilters(),
start,
count));
}
});
}
}
| 40.070423 | 100 | 0.662917 |
f7e46d82cce838d89bab3a897908ece6793e1df5
| 1,823 |
package io.extr.kafka.connect.logminer.sql;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.kafka.connect.util.ConnectorUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.extr.kafka.connect.logminer.LogMinerSourceConnector;
import io.extr.kafka.connect.logminer.model.Table;
public class TaskPartitionTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskPartitionTest.class);
private static List<Table> tables;
public TaskPartitionTest() {
}
@BeforeClass
public static void init() {
tables = new LinkedList<Table>();
tables.add(new Table("CON1", "OWN1", "TAB1", 15L));
tables.add(new Table("CON2", "OWN1", "TAB1", 33L));
tables.add(new Table("CON3", "OWN1", "TAB1", 0L));
tables.add(new Table("CON1", "OWN2", "TAB1", 204L));
tables.add(new Table("CON2", "OWN2", "TAB2", 234243L));
tables.add(new Table("CON3", "OWN2", "TAB3", 1L));
tables.add(new Table("CON1", "OWN3", "TAB1", 13L));
tables.add(new Table("CON2", "OWN3", "TAB2", 34343L));
tables.add(new Table("CON3", "OWN3", "TAB3", 333L));
}
@Test
public void testSimpleTaskPartition() throws Exception {
List<List<Table>> partitions = ConnectorUtils.groupPartitions(tables, 3);
for (List<Table> partition : partitions) {
Assert.assertTrue(partition.size() == 3);
LOGGER.debug(partition.toString());
}
}
@Test
public void testPerformanceTaskPartition() throws Exception {
List<List<Table>> partitions = LogMinerSourceConnector.groupTables(tables, 3);
for (List<Table> partition : partitions) {
Assert.assertTrue(partition.size() == 3);
LOGGER.debug(partition.toString());
}
}
}
| 30.898305 | 87 | 0.720241 |
91cad2c824bf4323cc08779c8e4d3a6b790619e4
| 1,151 |
/*
* Copyright (c) 2020 ForgeRock. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package org.forgerock.android.auth.ui.callback;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import org.forgerock.android.auth.callback.TextOutputCallback;
import org.forgerock.android.auth.ui.R;
/**
* UI representation for {@link org.forgerock.android.auth.callback.SuspendedTextOutputCallback}
*/
public class SuspendedTextOutputCallbackFragment extends CallbackFragment<TextOutputCallback> {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_text_output_callback, container, false);
TextView message = view.findViewById(R.id.message);
message.setText(callback.getMessage());
suspend();
return view;
}
}
| 29.512821 | 101 | 0.736751 |
cbfdc419e9e11564cdb5f6e914c8b6e02f83d6c9
| 374 |
package com.ibm.airlytics.retentiontracker.push;
import java.sql.SQLException;
import java.util.List;
public abstract class PushProtocol {
public abstract boolean notifyUser(String userID) throws ClassNotFoundException, SQLException;
public abstract boolean notifyUser(String token, String message);
public abstract boolean notifyUsers(List<String> tokens);
}
| 34 | 98 | 0.807487 |
317c7a211660361b70da7f2ec2e26da170f59c9b
| 1,636 |
package com.rho.battery;
import com.rho.emdk3.EMDK3Extension;
import com.rho.emdk3.IEmdkManagerListener;
import com.rhomobile.rhodes.Logger;
import com.rhomobile.rhodes.extmanager.IRhoExtension;
import com.rhomobile.rhodes.extmanager.RhoExtManager;
import com.symbol.emdk.EMDKManager;
public class EMDK3ExtensionListener implements IEmdkManagerListener{
private static final String TAG = "EMDK3ExtensionListener";
private EMDK3Extension emdkExtension = null;
private EMDKManager emdkManager;
public EMDK3ExtensionListener()
{
Logger.D(TAG, "+");
//this.mobilePaymentFactory = mobilePaymentFactory;
IRhoExtension emdkExtensionInterface = RhoExtManager.getImplementationInstance().getExtByName("EMDK3Manager");
if(emdkExtensionInterface != null)
{
Logger.D(TAG, "Emdk-manager extension found. This is an EMDK 3 device");
emdkExtension = (EMDK3Extension) emdkExtensionInterface;
emdkExtension.registerForEmdkManagerEvents(this);
}
else
{
Logger.D(TAG, "Cannot find EMDK-manager extension");
}
Logger.D(TAG, "-");
}
@Override
public void onOpened(EMDKManager emdkManager) {
Logger.D(TAG, "onOpened");
this.emdkManager = emdkManager;
}
@Override
public void onClosed() {
Logger.D(TAG, "onClosed+");
if(emdkManager != null) emdkManager.release();
this.emdkManager = null;
}
public EMDKManager getEMDKManager()
{
Logger.D(TAG, "getEMDKManager");
return emdkManager;
}
public void destroy()
{
Logger.D(TAG, "destroy");
if(emdkExtension != null)
{
emdkExtension.unregisterForEmdkManagerEvents(this);
emdkExtension = null;
}
onClosed();
}
}
| 23.710145 | 112 | 0.743888 |
6451238bcd86afee40488e7c3f65b59a61900eb7
| 4,598 |
/*
* 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.commons.jelly.expression;
import java.util.Collections;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.iterators.ArrayIterator;
import org.apache.commons.collections.iterators.EnumerationIterator;
import org.apache.commons.collections.iterators.SingletonIterator;
import org.apache.commons.jelly.JellyContext;
import org.apache.commons.jelly.JellyTagException;
import org.apache.commons.lang.StringUtils;
/** <p><code>ExpressionSupport</code>
* an abstract base class for Expression implementations
* which provides default implementations of some of the
* typesafe evaluation methods.</p>
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision$
*/
public abstract class ExpressionSupport implements Expression {
protected static final Iterator EMPTY_ITERATOR = Collections.EMPTY_LIST.iterator();
// inherit javadoc from interface
public String evaluateAsString(JellyContext context) {
Object value = evaluateRecurse(context);
// sometimes when Jelly is used inside Maven the value
// of an expression can actually be an expression.
// e.g. ${foo.bar} can lookup "foo.bar" in a Maven context
// which could actually be an expression
if ( value != null ) {
return value.toString();
}
return null;
}
// inherit javadoc from interface
public Object evaluateRecurse(JellyContext context) {
Object value = evaluate(context);
if (value instanceof Expression) {
Expression expression = (Expression) value;
return expression.evaluateRecurse(context);
}
return value;
}
// inherit javadoc from interface
public boolean evaluateAsBoolean(JellyContext context) {
Object value = evaluateRecurse(context);
if ( value instanceof Boolean ) {
Boolean b = (Boolean) value;
return b.booleanValue();
}
else if ( value instanceof String ) {
// return Boolean.getBoolean( (String) value );
String str = (String) value;
return ( str.equalsIgnoreCase( "on" )
||
str.equalsIgnoreCase( "yes" )
||
str.equals( "1" )
||
str.equalsIgnoreCase( "true" ) );
}
return false;
}
// inherit javadoc from interface
public Iterator evaluateAsIterator(JellyContext context) {
Object value = evaluateRecurse(context);
if ( value == null ) {
return EMPTY_ITERATOR;
} else if ( value instanceof Iterator ) {
return (Iterator) value;
} else if ( value instanceof List ) {
List list = (List) value;
return list.iterator();
} else if ( value instanceof Map ) {
Map map = (Map) value;
return map.entrySet().iterator();
} else if ( value.getClass().isArray() ) {
return new ArrayIterator( value );
} else if ( value instanceof Enumeration ) {
return new EnumerationIterator((Enumeration ) value);
} else if ( value instanceof Collection ) {
Collection collection = (Collection) value;
return collection.iterator();
} else if ( value instanceof String ) {
String[] array = StringUtils.split((String) value, "," );
array = StringUtils.stripAll( array );
return new ArrayIterator( array );
} else {
// XXX: should we return single iterator?
return new SingletonIterator( value );
}
}
}
| 37.080645 | 87 | 0.648325 |
75c7d527f2a73b34ced76dca825cecaae1052d08
| 4,546 |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* 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.drools.workbench.models.guided.scorecard.backend;
import org.dmg.pmml.pmml_4_2.descr.Attribute;
import org.dmg.pmml.pmml_4_2.descr.Characteristic;
import org.dmg.pmml.pmml_4_2.descr.Characteristics;
import org.dmg.pmml.pmml_4_2.descr.Extension;
import org.dmg.pmml.pmml_4_2.descr.False;
import org.dmg.pmml.pmml_4_2.descr.PMML;
import org.dmg.pmml.pmml_4_2.descr.Scorecard;
import org.dmg.pmml.pmml_4_2.descr.True;
import org.drools.compiler.compiler.GuidedScoreCardProvider;
import org.drools.core.util.IoUtils;
import org.drools.scorecards.ScorecardCompiler;
import org.drools.workbench.models.guided.scorecard.shared.ScoreCardModel;
import org.kie.api.KieBase;
import org.kie.api.io.ResourceType;
import org.kie.internal.utils.KieHelper;
import org.kie.pmml.pmml_4_2.PMML4Compiler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
public class GuidedScoreCardProviderImpl implements GuidedScoreCardProvider {
@Override
public String loadFromInputStream(InputStream is) throws IOException {
String xml = new String(IoUtils.readBytesFromInputStream(is), IoUtils.UTF8_CHARSET);
ScoreCardModel model = GuidedScoreCardXMLPersistence.getInstance().unmarshall(xml);
return GuidedScoreCardDRLPersistence.marshal(model);
}
@Override
public KieBase getKieBaseFromInputStream(InputStream is) throws IOException {
String pmmlString = getPMMLStringFromInputStream(is);
KieBase kbase = new KieHelper().addContent(pmmlString, ResourceType.PMML).build();
return kbase;
}
@Override
public String getPMMLStringFromInputStream(InputStream is) throws IOException {
String xml = new String(IoUtils.readBytesFromInputStream(is), IoUtils.UTF8_CHARSET);
ScoreCardModel model = GuidedScoreCardXMLPersistence.getInstance().unmarshall(xml);
PMML pmml = GuidedScoreCardDRLPersistence.createPMMLDocument(model);
checkCharacteristics(pmml);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PMML4Compiler compiler = new PMML4Compiler();
compiler.dumpModel(pmml, baos);
return new String(baos.toByteArray());
}
private void checkCharacteristics(PMML pmml) {
if (pmml != null
&& pmml.getAssociationModelsAndBaselineModelsAndClusteringModels() != null
&& !pmml.getAssociationModelsAndBaselineModelsAndClusteringModels().isEmpty()) {
for (Serializable s : pmml.getAssociationModelsAndBaselineModelsAndClusteringModels()) {
if (s instanceof Scorecard) {
Scorecard scard = (Scorecard) s;
if (scard.getExtensionsAndCharacteristicsAndMiningSchemas() != null
&& !scard.getExtensionsAndCharacteristicsAndMiningSchemas().isEmpty()) {
for (Serializable sz : scard.getExtensionsAndCharacteristicsAndMiningSchemas()) {
if (sz instanceof Characteristics) {
Characteristics characteristics = (Characteristics) sz;
if (characteristics.getCharacteristics() == null
|| characteristics.getCharacteristics().isEmpty()) {
Characteristic ch = new Characteristic();
ch.setBaselineScore(0.0);
ch.setName("placeholder");
Attribute attr = new Attribute();
attr.setFalse(new False());
ch.getAttributes().add(attr);
characteristics.getCharacteristics().add(ch);
}
}
}
}
}
}
}
}
}
| 45.46 | 105 | 0.657281 |
ca8667627c7754ff37e30a16d9e8b688edf65a07
| 2,003 |
package net.cabezudo.sofia.core.passwords;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import net.cabezudo.sofia.core.configuration.Configuration;
/**
* @author <a href="http://cabezudo.net">Esteban Cabezudo</a>
* @version 0.01.00, 2018.07.18
*/
public class Password {
public static final int MIN_LENGTH = 4;
public static final int MAX_LENGTH = 50;
private final String plainPassword;
private String base64Password;
private final byte[] bytePassword;
private enum Type {
PLAIN, BASE_64
}
public static Password createFromBase64(String base64Password) {
return new Password(base64Password, Type.BASE_64);
}
public static Password createFromPlain(String password) {
return new Password(password, Type.PLAIN);
}
private Password(String password, Type type) {
if (type == Type.PLAIN) {
this.plainPassword = password;
this.base64Password = Base64.getEncoder().encodeToString(password.getBytes());
} else {
byte[] decodedValue = Base64.getDecoder().decode(password);
this.plainPassword = new String(decodedValue, StandardCharsets.UTF_8);
this.base64Password = password;
}
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-512");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
md.update(plainPassword.getBytes(Configuration.getInstance().getEncoding()));
bytePassword = md.digest();
}
public String toBase64() {
return base64Password;
}
public byte[] getBytes() {
return bytePassword;
}
@Override
public String toString() {
return plainPassword + " : " + this.toBase64();
}
public boolean isEmpty() {
return plainPassword.isEmpty();
}
public int length() {
return plainPassword.length();
}
public boolean equals(Password p) {
return this.plainPassword.equals(p.plainPassword);
}
}
| 24.728395 | 84 | 0.704943 |
0246d6d80aee33c161cd2fc3a195a278265d5faf
| 1,710 |
package sirinleroyun;
/**
*
* @author Gökçe Yılmaz
*/
public class Gozluklu extends Oyuncu {
int altinmiktari;
int konum_x=0;
int konum_y=0;
public Gozluklu() {
}
public Gozluklu(int karakterID, String karakterAdi, String karakterTur) {
super(karakterID, karakterAdi, karakterTur);
}
@Override
public int getKarakterID() {
return super.getKarakterID(); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setKarakterID(int karakterID) {
super.setKarakterID(1); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getKarakterAd() {
return super.getKarakterAd(); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setKarakterAd(String karakterAd) {
super.setKarakterAd("gozluklu"); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String getKarakterTur() {
return super.getKarakterTur(); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void setKarakterTur(String karakterTur) {
super.setKarakterTur("oyuncu"); //To change body of generated methods, choose Tools | Templates.
}
public void setkonum(int konum_x,int konum_y)
{
this.konum_x=konum_x;
this.konum_y=konum_y;
}
public int getkonum_x()
{
return konum_x;
}
public int getkonum_y()
{
return konum_y;
}
@Override
public int PuaniGoster(int x) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| 23.75 | 135 | 0.683626 |
35d3bc6856059b0fce3141dc7448d80653ccf438
| 4,718 |
package com.universl.englandcalendar.ryan.data_reminder;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import com.universl.englandcalendar.ryan.R;
import com.universl.englandcalendar.ryan.data.AlarmReminderContract;
import com.universl.englandcalendar.ryan.sub_activity.RemindTaskActivity;
@SuppressLint("Registered")
public class ReminderAlarmService extends IntentService {
private static final String TAG = ReminderAlarmService.class.getSimpleName();
private static final int NOTIFICATION_ID = 42;
public static final String channelID = "com.universl.englandcalendar.ryan";
public static final String channelName = "ryan";
private NotificationManager manager;
Cursor cursor;
//This is a deep link intent, and needs the task stack
public static PendingIntent getReminderPendingIntent(Context context, Uri uri) {
Intent action = new Intent(context, ReminderAlarmService.class);
action.setData(uri);
return PendingIntent.getService(context, 0, action, PendingIntent.FLAG_UPDATE_CURRENT);
}
public ReminderAlarmService() {
super(TAG);
}
@TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID,channelName, NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(R.color.colorPrimary);
channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager(){
if (manager == null){
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return manager;
}
@Override
protected void onHandleIntent(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
createChannel();
}
Uri uri = intent.getData();
//Display a notification to view the task details
Intent action = new Intent(this, RemindTaskActivity.class);
action.setData(uri);
PendingIntent operation = TaskStackBuilder.create(this)
.addNextIntentWithParentStack(action)
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
//Grab the task description
if(uri != null){
cursor = getContentResolver().query(uri, null, null, null, null);
}
String description = "";
try {
if (cursor != null && cursor.moveToFirst()) {
description = AlarmReminderContract.getColumnString(cursor, AlarmReminderContract.AlarmReminderEntry.KEY_TITLE);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
/*Notification note = new NotificationCompat.Builder(this)
.setContentTitle("Sri Lanka Calendar 2019")
.setContentText(description)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSmallIcon(R.drawable.sl_calendar_logo)
.setContentIntent(operation)
.setAutoCancel(true)
.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(NOTIFICATION_ID, note);*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelID)
.setContentTitle("England Calendar 2020")
.setContentText(description)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setStyle(new NotificationCompat.BigTextStyle())
.setContentIntent(operation)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setSmallIcon(R.mipmap.ic_launcher_foreground)
.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
| 38.672131 | 128 | 0.69415 |
1c31a6ad20f865b62e9330d2fd1b2e2fa498c7a8
| 1,580 |
/*
* @Description:
*
* @Date: 2020-01-08 21:27:07
*
* @Author: duchangchun
*/
/**
* 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
*
* 示例 1:
*
* 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2:
*
* 输入: "cbbd" 输出: "bb"
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/longest-palindromic-substring
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) {
return s;
}
String res = s.substring(0, 1);
int maxLen = 1;
for (int i = 1; i < s.length(); i++) {
int low = i - 1;
int high = i + 1;
while (low > 0 && s.charAt(low) == s.charAt(i)) {
low--;
}
if (low < 0 || s.charAt(low) != s.charAt(i)) {
low++;
}
while (high < s.length() && s.charAt(high) == s.charAt(i)) {
high++;
}
if (high >= s.length() || s.charAt(high) != s.charAt(i)) {
high--;
}
while (low > 0 && high < s.length() && s.charAt(low) == s.charAt(high)) {
low--;
high++;
}
if (low < 0 || high >= s.length() || s.charAt(low) != s.charAt(high)) {
low++;
high--;
}
if (high - low + 1 > maxLen) {
maxLen = high - low + 1;
res = s.substring(low, high + 1);
}
}
return res;
}
}
| 23.235294 | 85 | 0.405696 |
d3c1158f3154abf907361ffeaf36e7aab506d7b4
| 5,233 |
// Copyright 2004, 2005 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.apache.hivemind.methodmatch;
import org.apache.hivemind.ApplicationRuntimeException;
/**
* Tests for {@link org.apache.hivemind.methodmatch.MethodPatternParser}.
*
* @author Howard Lewis Ship
*/
public class TestMethodPatternParser extends AbstractMethodTestCase
{
public void testCount()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*(1)");
assertEquals(false, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "toString")));
assertEquals(true, f.matchMethod(getMethodSignature(this, "equals")));
}
public void testExactName()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("hashCode");
assertEquals(true, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "toString")));
}
public void testInvalidName()
{
try
{
MethodPatternParser p = new MethodPatternParser();
p.parseMethodPattern("*foo*bar*()");
unreachable();
}
catch (ApplicationRuntimeException ex)
{
assertEquals(
"Method pattern '*foo*bar*()' contains an invalid method name pattern.",
ex.getMessage());
}
}
public void testInvalidParams()
{
try
{
MethodPatternParser p = new MethodPatternParser();
p.parseMethodPattern("*bar(");
unreachable();
}
catch (ApplicationRuntimeException ex)
{
assertEquals(
"Method pattern '*bar(' contains an invalid parameters pattern.",
ex.getMessage());
}
}
public void testInvalidParamCount()
{
try
{
MethodPatternParser p = new MethodPatternParser();
p.parseMethodPattern("*(1x)");
unreachable();
}
catch (ApplicationRuntimeException ex)
{
assertEquals(
"Method pattern '*(1x)' contains an invalid parameters pattern.",
ex.getMessage());
}
}
public void testMatchAll()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*");
assertEquals(true, f.matchMethod(null));
}
public void testNameMissing()
{
try
{
MethodPatternParser p = new MethodPatternParser();
p.parseMethodPattern("");
unreachable();
}
catch (ApplicationRuntimeException ex)
{
assertEquals("Method pattern '' does not contain a method name.", ex.getMessage());
}
}
public void testParameterTypes()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*(int,java.lang.String[])");
assertEquals(false, f.matchMethod(getMethodSignature(MethodSubject.class, "intArg")));
assertEquals(true, f.matchMethod(getMethodSignature(MethodSubject.class, "intStringArrayArgs")));
}
public void testPrefix()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("hash*");
assertEquals(true, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "toString")));
}
public void testSubstring()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*od*");
assertEquals(true, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "toString")));
}
public void testSuffix()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*Code");
assertEquals(true, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "toString")));
}
public void testEmpty()
{
MethodPatternParser p = new MethodPatternParser();
MethodFilter f = p.parseMethodPattern("*()");
assertEquals(true, f.matchMethod(getMethodSignature(this, "hashCode")));
assertEquals(true, f.matchMethod(getMethodSignature(this, "toString")));
assertEquals(false, f.matchMethod(getMethodSignature(this, "equals")));
}
}
| 32.302469 | 105 | 0.636537 |
ddc1eb02075144da6e5e86560791dc2269f45b92
| 1,796 |
package me.chanjar.weixin.qidian.api.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.locks.ReentrantLock;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.thoughtworks.xstream.XStream;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxRuntimeException;
import me.chanjar.weixin.common.util.xml.XStreamInitializer;
import me.chanjar.weixin.qidian.api.WxQidianService;
import me.chanjar.weixin.qidian.api.impl.WxQidianServiceHttpClientImpl;
import me.chanjar.weixin.qidian.config.WxQidianConfigStorage;
@Slf4j
public class ApiTestModule implements Module {
private static final String TEST_CONFIG_XML = "test-config.xml";
@Override
public void configure(Binder binder) {
try (InputStream inputStream = ClassLoader.getSystemResourceAsStream(TEST_CONFIG_XML)) {
if (inputStream == null) {
throw new WxRuntimeException("测试配置文件【" + TEST_CONFIG_XML + "】未找到,请参照test-config-sample.xml文件生成");
}
TestConfigStorage config = this.fromXml(TestConfigStorage.class, inputStream);
config.setAccessTokenLock(new ReentrantLock());
WxQidianService mpService = new WxQidianServiceHttpClientImpl();
mpService.setWxMpConfigStorage(config);
mpService.addConfigStorage("another", config);
binder.bind(WxQidianConfigStorage.class).toInstance(config);
binder.bind(WxQidianService.class).toInstance(mpService);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
private <T> T fromXml(Class<T> clazz, InputStream is) {
XStream xstream = XStreamInitializer.getInstance();
xstream.alias("xml", clazz);
xstream.processAnnotations(clazz);
return (T) xstream.fromXML(is);
}
}
| 34.538462 | 105 | 0.759465 |
88c825b3844126bed27e3fd9234ffc3198d3a975
| 1,014 |
package p09_trafficLights;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
List<TrafficMachine> trafficMachines = new ArrayList<>();
String[] tokens = reader.readLine().split("\\s+");
for (String light : tokens) {
trafficMachines.add(new TrafficMachine(light));
}
int rotations = Integer.parseInt(reader.readLine());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < rotations; i++) {
for (TrafficMachine machine : trafficMachines) {
machine.changeLight();
sb.append(machine.toString()).append(" ");
}
sb.append(System.lineSeparator());
}
System.out.print(sb.toString());
}
}
| 30.727273 | 85 | 0.626233 |
96fc0ab8208cc8d437de898bef342e2ad427dd0f
| 2,826 |
/*
* 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.accumulo.core.util.format;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.text.DateFormat;
import org.junit.Test;
public class FormatterConfigTest {
@Test
public void testConstructor() {
FormatterConfig config = new FormatterConfig();
assertFalse(config.willLimitShowLength());
assertFalse(config.willPrintTimestamps());
}
@Test
public void testSetShownLength() {
FormatterConfig config = new FormatterConfig();
try {
config.setShownLength(-1);
fail("Should throw on negative length.");
} catch (IllegalArgumentException e) {}
config.setShownLength(0);
assertEquals(0, config.getShownLength());
assertTrue(config.willLimitShowLength());
config.setShownLength(1);
assertEquals(1, config.getShownLength());
assertTrue(config.willLimitShowLength());
}
@Test
public void testDoNotLimitShowLength() {
FormatterConfig config = new FormatterConfig();
assertFalse(config.willLimitShowLength());
config.setShownLength(1);
assertTrue(config.willLimitShowLength());
config.doNotLimitShowLength();
assertFalse(config.willLimitShowLength());
}
@Test
public void testGetDateFormat() {
FormatterConfig config1 = new FormatterConfig();
DateFormat df1 = config1.getDateFormatSupplier().get();
FormatterConfig config2 = new FormatterConfig();
assertNotSame(df1, config2.getDateFormatSupplier().get());
config2.setDateFormatSupplier(config1.getDateFormatSupplier());
assertSame(df1, config2.getDateFormatSupplier().get());
// even though copying, it can't copy the Generator, so will pull out the same DateFormat
FormatterConfig configCopy = new FormatterConfig(config1);
assertSame(df1, configCopy.getDateFormatSupplier().get());
}
}
| 32.482759 | 93 | 0.745223 |
320bd9fbe7cb44e708a08a7992c338e4fc280145
| 1,149 |
/*
* Copyright 2003-2009 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.jdon.jivejdon.domain.event;
import com.jdon.jivejdon.domain.model.attachment.UploadFile;
import java.util.Collection;
public class UploadFilesAttachedEvent {
private final Long messageId;
private final Collection<UploadFile> uploads;
public UploadFilesAttachedEvent(Long messageId, Collection<UploadFile> uploads) {
super();
this.messageId = messageId;
this.uploads = uploads;
}
public Long getMessageId() {
return messageId;
}
public Collection<UploadFile> getUploads() {
return uploads;
}
}
| 26.72093 | 82 | 0.75544 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.