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
|
|---|---|---|---|---|---|
9f33e36b53c1b79262f548561d85ef33b74be678
| 4,510
|
package com.manager;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.swing.ImageIcon;
import com.element.ElementObj;
import com.element.Maps;
import com.element.Floor;
/**
* @说明 加载器(工具:用户读取配置文件的工具)工具类,大多数提供的是static方法
* @author linkaizhe
*
*/
public class GameLoad {
private static ElementManager em = ElementManager.getManager();
public static Map<String,ImageIcon> imgMap = new HashMap<>();
public static Map<String, List<String>> gameBasicMap = new HashMap<>();
// 单例模式
private static GameLoad gameLoad = null;
public static GameLoad getGameLoad() {
if(gameLoad == null) {//空值判定
gameLoad = new GameLoad();
}
return gameLoad;
}
private static Properties pro = new Properties();
/**
* @说明 传入地图id有加载方法根据文件规则自动产生地图文件名称、加载文件
* @param mapId 文件编号 文件id
*/
public static void MapLoad(int mapId) {
String mapName1= "com/text/Map/floor.map";
ClassLoader classLoader1 = GameLoad.class.getClassLoader();
InputStream maps1 = classLoader1.getResourceAsStream(mapName1);
try {
pro.clear();
pro.load(maps1);
Enumeration<?> names1 = pro.propertyNames();
while(names1.hasMoreElements()) {
String key = names1.nextElement().toString();
pro.getProperty(key);
String [] arrs1=pro.getProperty(key).split(";");
for(int i=0;i<arrs1.length;i++) {
ElementObj element2 = new Floor().createElement(key+","+arrs1[i]);
em.addElement(element2, GameElement.FLOOR);
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
String mapName= "com/text/Map/"+mapId+".map";
ClassLoader classLoader = GameLoad.class.getClassLoader();
InputStream maps = classLoader.getResourceAsStream(mapName);
if(maps == null) {
System.out.println("配置文件读取异常,请重新安装");
return;
}
try {
pro.clear();
pro.load(maps);
Enumeration<?> names = pro.propertyNames();
while(names.hasMoreElements()) {
String key = names.nextElement().toString();
pro.getProperty(key);
String [] arrs=pro.getProperty(key).split(";");
for(int i=0;i<arrs.length;i++) {
ElementObj element = new Maps().createElement(key+","+arrs[i]);
em.addElement(element, GameElement.MAPS);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @说明 加载图片代码
*/
public static void loadImg() {
String imgurl = "com/text/Pro/GameData.pro";
ClassLoader classLoader = GameLoad.class.getClassLoader();
InputStream texts = classLoader.getResourceAsStream(imgurl);
pro.clear();
try {
pro.load(texts);
Set<Object> set = pro.keySet();
for(Object o:set) {
String url = pro.getProperty(o.toString());
imgMap.put(o.toString(), new ImageIcon(url));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 加载玩家
*/
public static void loadPlay() {
loadObj();
String playStr="75,75,up";
ElementObj obj= getObj("play");
ElementObj play = obj.createElement(playStr);
em.addElement(play, GameElement.PLAY);
}
/**
* 加载NPC
*/
public static void loadNpc() {
loadObj();
String npcStr = "677,675,down";
ElementObj obj = getObj("npc");
ElementObj npc = obj.createElement(npcStr);
em.addElement(npc, GameElement.NPC);
}
public static ElementObj getObj(String str) {
try {
Class<?> class1 = objMap.get(str);
Object newInstance = class1.newInstance();
if(newInstance instanceof ElementObj) {
return (ElementObj)newInstance;
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
private static Map<String,Class<?>> objMap=new HashMap<>();
public static void loadObj() {
String texturl= "com/text/Pro/obj.pro";
ClassLoader classLoader = GameLoad.class.getClassLoader();
InputStream texts = classLoader.getResourceAsStream(texturl);
pro.clear();
try {
pro.load(texts);
Set<Object> set = pro.keySet();
for(Object o:set) {
String classUrl= pro.getProperty(o.toString());
Class<?> forName = Class.forName(classUrl);
objMap.put(o.toString(), forName);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| 27.168675
| 73
| 0.651885
|
934cb8143e7fba5bceaf0f5150fda4b15349aecb
| 3,933
|
/*
* 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.pdfbox.pdmodel.interactive.pagenavigation;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.junit.Assert;
import org.junit.Test;
/**
* @author Andrea Vacondio
*
*/
public class PDTransitionTest {
@Test
public void defaultStyle() {
final PDTransition transition = new PDTransition();
Assert.assertEquals(COSName.TRANS, transition.getCOSObject().getCOSName(COSName.TYPE));
Assert.assertEquals(PDTransitionStyle.R.name(), transition.getStyle());
}
@Test
public void getStyle() {
final PDTransition transition = new PDTransition(PDTransitionStyle.Fade);
Assert.assertEquals(COSName.TRANS, transition.getCOSObject().getCOSName(COSName.TYPE));
Assert.assertEquals(PDTransitionStyle.Fade.name(), transition.getStyle());
}
@Test
public void defaultValues() {
final PDTransition transition = new PDTransition(new COSDictionary());
Assert.assertEquals(PDTransitionStyle.R.name(), transition.getStyle());
Assert.assertEquals(PDTransitionDimension.H.name(), transition.getDimension());
Assert.assertEquals(PDTransitionMotion.I.name(), transition.getMotion());
Assert.assertEquals(COSInteger.ZERO, transition.getDirection());
Assert.assertEquals(1, transition.getDuration(), 0);
Assert.assertEquals(1, transition.getFlyScale(), 0);
Assert.assertFalse(transition.isFlyAreaOpaque());
}
@Test
public void dimension() {
final PDTransition transition = new PDTransition();
transition.setDimension(PDTransitionDimension.H);
Assert.assertEquals(PDTransitionDimension.H.name(), transition.getDimension());
}
@Test
public void directionNone() {
final PDTransition transition = new PDTransition();
transition.setDirection(PDTransitionDirection.NONE);
Assert.assertEquals(COSName.class.getName(), transition.getDirection().getClass().getName());
Assert.assertEquals(COSName.NONE, transition.getDirection());
}
@Test
public void directionNumber() {
final PDTransition transition = new PDTransition();
transition.setDirection(PDTransitionDirection.LEFT_TO_RIGHT);
Assert.assertEquals(COSInteger.class.getName(), transition.getDirection().getClass().getName());
Assert.assertEquals(COSInteger.ZERO, transition.getDirection());
}
@Test
public void motion() {
final PDTransition transition = new PDTransition();
transition.setMotion(PDTransitionMotion.O);
Assert.assertEquals(PDTransitionMotion.O.name(), transition.getMotion());
}
@Test
public void duration() {
final PDTransition transition = new PDTransition();
transition.setDuration(4);
Assert.assertEquals(4, transition.getDuration(), 0);
}
@Test
public void flyScale() {
final PDTransition transition = new PDTransition();
transition.setFlyScale(4);
Assert.assertEquals(4, transition.getFlyScale(), 0);
}
@Test
public void flyArea() {
final PDTransition transition = new PDTransition();
transition.setFlyAreaOpaque(true);
Assert.assertTrue(transition.isFlyAreaOpaque());
}
}
| 36.416667
| 100
| 0.74625
|
aac0539e7683dd9e625816f507331a6610ea1902
| 171
|
package omari.hamza.storyview.callback;
public interface TouchCallbacks {
void touchPull();
void touchDown(float xValue, float yValue);
void touchUp();
}
| 14.25
| 47
| 0.71345
|
2ceec0ae6d53ecff5e88eeb7ace4f17290b274cb
| 3,616
|
package net.minecraft.entity.ai.goal;
import net.minecraft.entity.Entity;
import net.minecraft.entity.passive.DolphinEntity;
import net.minecraft.fluid.FluidState;
import net.minecraft.tags.FluidTags;
import net.minecraft.util.Direction;
import net.minecraft.util.SoundEvents;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.vector.Vector3d;
public class DolphinJumpGoal extends JumpGoal {
private static final int[] STEPS_TO_CHECK = new int[]{0, 1, 4, 5, 6, 7};
private final DolphinEntity dolphin;
private final int interval;
private boolean breached;
public DolphinJumpGoal(DolphinEntity p_i50329_1_, int p_i50329_2_) {
this.dolphin = p_i50329_1_;
this.interval = p_i50329_2_;
}
public boolean canUse() {
if (this.dolphin.getRandom().nextInt(this.interval) != 0) {
return false;
} else {
Direction direction = this.dolphin.getMotionDirection();
int i = direction.getStepX();
int j = direction.getStepZ();
BlockPos blockpos = this.dolphin.blockPosition();
for(int k : STEPS_TO_CHECK) {
if (!this.waterIsClear(blockpos, i, j, k) || !this.surfaceIsClear(blockpos, i, j, k)) {
return false;
}
}
return true;
}
}
private boolean waterIsClear(BlockPos p_220709_1_, int p_220709_2_, int p_220709_3_, int p_220709_4_) {
BlockPos blockpos = p_220709_1_.offset(p_220709_2_ * p_220709_4_, 0, p_220709_3_ * p_220709_4_);
return this.dolphin.level.getFluidState(blockpos).is(FluidTags.WATER) && !this.dolphin.level.getBlockState(blockpos).getMaterial().blocksMotion();
}
private boolean surfaceIsClear(BlockPos p_220708_1_, int p_220708_2_, int p_220708_3_, int p_220708_4_) {
return this.dolphin.level.getBlockState(p_220708_1_.offset(p_220708_2_ * p_220708_4_, 1, p_220708_3_ * p_220708_4_)).isAir() && this.dolphin.level.getBlockState(p_220708_1_.offset(p_220708_2_ * p_220708_4_, 2, p_220708_3_ * p_220708_4_)).isAir();
}
public boolean canContinueToUse() {
double d0 = this.dolphin.getDeltaMovement().y;
return (!(d0 * d0 < (double)0.03F) || this.dolphin.xRot == 0.0F || !(Math.abs(this.dolphin.xRot) < 10.0F) || !this.dolphin.isInWater()) && !this.dolphin.isOnGround();
}
public boolean isInterruptable() {
return false;
}
public void start() {
Direction direction = this.dolphin.getMotionDirection();
this.dolphin.setDeltaMovement(this.dolphin.getDeltaMovement().add((double)direction.getStepX() * 0.6D, 0.7D, (double)direction.getStepZ() * 0.6D));
this.dolphin.getNavigation().stop();
}
public void stop() {
this.dolphin.xRot = 0.0F;
}
public void tick() {
boolean flag = this.breached;
if (!flag) {
FluidState fluidstate = this.dolphin.level.getFluidState(this.dolphin.blockPosition());
this.breached = fluidstate.is(FluidTags.WATER);
}
if (this.breached && !flag) {
this.dolphin.playSound(SoundEvents.DOLPHIN_JUMP, 1.0F, 1.0F);
}
Vector3d vector3d = this.dolphin.getDeltaMovement();
if (vector3d.y * vector3d.y < (double)0.03F && this.dolphin.xRot != 0.0F) {
this.dolphin.xRot = MathHelper.rotlerp(this.dolphin.xRot, 0.0F, 0.2F);
} else {
double d0 = Math.sqrt(Entity.getHorizontalDistanceSqr(vector3d));
double d1 = Math.signum(-vector3d.y) * Math.acos(d0 / vector3d.length()) * (double)(180F / (float)Math.PI);
this.dolphin.xRot = (float)d1;
}
}
}
| 39.304348
| 252
| 0.676991
|
155fbb4a78c8d5eedbf5626908d53a8d053a0e44
| 1,379
|
package com.dyn.schematics.network.messages;
import com.dyn.schematics.SchematicMod;
import com.dyn.schematics.gui.ContainerArchitect;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
public class MessageUpdateArchitectDesk implements IMessage {
public static class Handler implements IMessageHandler<MessageUpdateArchitectDesk, IMessage> {
@Override
public IMessage onMessage(final MessageUpdateArchitectDesk message, final MessageContext ctx) {
SchematicMod.proxy.addScheduledTask(() -> {
EntityPlayerMP player = ctx.getServerHandler().player;
ContainerArchitect desk = (ContainerArchitect) player.openContainer;
desk.detectAndSendChanges();
desk.updateSchematicContents(message.getDir());
});
return null;
}
}
private boolean direction;
public MessageUpdateArchitectDesk() {
}
public MessageUpdateArchitectDesk(boolean direction) {
this.direction = direction;
}
@Override
public void fromBytes(ByteBuf buf) {
direction = buf.readBoolean();
}
public boolean getDir() {
return direction;
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeBoolean(direction);
}
}
| 27.039216
| 97
| 0.788252
|
1fb0c3b70ba515ff10ca5cc8b565fcbae64c6207
| 482
|
package com.laotan.easyreader.injector.module.fragment;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.laotan.easyreader.adapter.NBAAdapter;
import java.util.ArrayList;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
/**
* Created by quantan.liu on 2017/4/8.
*/
@Module
public class NBAModule {
@Provides
@Singleton
public BaseQuickAdapter provideAdapter() {
return new NBAAdapter(new ArrayList());
}
}
| 20.083333
| 55
| 0.748963
|
3dad6aa47896f0b2e027b28238f854060824304d
| 2,387
|
/**
* Copyright 2015 Microsoft Open Technologies 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.microsoftopentechnologies.intellij.ui.libraries;
import javax.swing.*;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.ui.wizard.WizardNavigationState;
import com.intellij.ui.wizard.WizardStep;
import com.microsoftopentechnologies.intellij.actions.LibraryConfigurationAction;
import com.microsoftopentechnologies.intellij.ui.components.Validatable;
import static com.microsoftopentechnologies.intellij.ui.messages.AzureBundle.message;
public class LibraryPropertiesStep extends WizardStep<AddLibraryWizardModel> implements Validatable {
private LibraryPropertiesPanel libraryPropertiesPanel;
private final AddLibraryWizardModel myModel;
public LibraryPropertiesStep(String title, final AddLibraryWizardModel model) {
super(title, message("libraryPropertiesDesc"));
myModel = model;
}
@Override
public JComponent prepare(final WizardNavigationState state) {
libraryPropertiesPanel = new LibraryPropertiesPanel(myModel.getMyModule(), myModel.getSelectedLibrary());
return libraryPropertiesPanel.prepare();
}
@Override
public ValidationInfo doValidate() {
if (myModel.getSelectedLibrary() == LibraryConfigurationAction.ACS_FILTER) {
ValidationInfo result = libraryPropertiesPanel.doValidate();
myModel.getCurrentNavigationState().FINISH.setEnabled(result == null);
}
return null;
// return libraryPropertiesPanel.doValidate();
}
@Override
public boolean onFinish() {
boolean result = libraryPropertiesPanel.onFinish();
if (result) {
myModel.setExported(libraryPropertiesPanel.isExported());
return super.onFinish();
}
return false;
}
}
| 37.296875
| 113
| 0.741935
|
f240179a3ae33d3b820df516e2ecf086f9f336a0
| 2,721
|
package org.thegalactic.io;
/*
* Filer.java
*
* Copyright: 2010-2015 Karell Bertet, France
* Copyright: 2015-2016 The Galactic Organization, France
*
* License: http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html CeCILL-B license
*
* This file is part of java-lattices.
* You can redistribute it and/or modify it under the terms of the CeCILL-B license.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* This class is used to provide a generic way for saving and parsing objects
* using the extension file.
*
* @param <E> The element to be saved/parsed
*/
public final class Filer<E> {
/**
* The singleton instance.
*/
private static final Filer INSTANCE = new Filer();
/**
* Return the singleton instance of this class.
*
* @return the singleton instance
*/
public static Filer getInstance() {
return INSTANCE;
}
/**
* Get the filename extension.
*
* @param filename Filename to get extension from
*
* @return the filename extension
*/
private static String getExtension(final String filename) {
String extension = "";
final int index = filename.lastIndexOf('.');
if (index > 0) {
extension = filename.substring(index + 1);
}
return extension;
}
/**
* This class is not designed to be publicly instantiated.
*/
private Filer() {
}
/**
* Save the description of this component in a file whose name is specified.
*
* @param e the element to save
* @param factory the reader/writer factory
* @param filename the name of the file
*
* @throws IOException When an IOException occurs
*/
public void save(final E e, final IOFactory factory, final String filename) throws IOException {
final BufferedWriter file = new BufferedWriter(new FileWriter(filename));
factory.getWriter(Filer.getExtension(filename)).write(e, file);
file.close();
}
/**
* Parse the description of this component from a file whose name is
* specified.
*
* @param e the element to parse
* @param factory the reader/writer factory
* @param filename the name of the file
*
* @throws IOException When an IOException occurs
*/
public void parse(final E e, final IOFactory factory, final String filename) throws IOException {
final BufferedReader file = new BufferedReader(new FileReader(filename));
factory.getReader(Filer.getExtension(filename)).read(e, file);
file.close();
}
}
| 28.642105
| 101
| 0.648291
|
291afd0873e80ec9ee659c0eb8f132e2e17df45c
| 1,092
|
package ch01Exercise;
/**
* 1.编写一个实现将整型数组中的数据元素按值递增的顺序进行排序的Java程序。
*
* @author zou
*
*/
public class Exercise1_3_1 {
/**
*
* @param a
* 无序的整数数组
* @return 按值递增的顺序排序的数组
*/
public int[] bubbleSort(int[] a) {
int n = a.length;
boolean isExchange = true; // 交换标志
for (int i = 0; i < n - 1&&isExchange; i++) { // 最多做n-1趟排序
isExchange = false;
for (int j = 0; j < n - i - 1; j++) {// 对当前无序区进行排序
if (a[j] > a[j + 1]) {// 交换数据元素
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
isExchange = true; // 发生了交换,故将交换标志置为真
}
}
if (!isExchange)
break; // 本趟排序未发生交换,提前终止算法
}
return a;
}
public static void main(String[] args) {
int[] values = { 49, 38, 65, 97, 76, 13, 27, 49 };
System.out.println("排序前数组中数据元素:49 38 65 97 76 13 27 49");
System.out.print("排序后数组中数据元素:");
Exercise1_3_1 e = new Exercise1_3_1();
values = e.bubbleSort(values);
for (int i = 0; i < values.length; i++)
System.out.print(values[i] + " ");
}
}
//调试结果:
//排序前数组中数据元素:49 38 65 97 76 13 27 49
//排序后数组中数据元素:13 27 38 49 49 65 76 97
| 22.285714
| 60
| 0.567766
|
0a84f4f1b2a693e33bc9675211a72c6674f6395f
| 1,896
|
/*
* Copyright 2014 NAVER Corp.
* 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.navercorp.pinpoint.plugin.jetty;
import com.navercorp.pinpoint.bootstrap.config.ExcludePathFilter;
import com.navercorp.pinpoint.bootstrap.config.Filter;
import com.navercorp.pinpoint.bootstrap.config.ProfilerConfig;
import com.navercorp.pinpoint.bootstrap.config.SkipFilter;
import java.util.List;
public class JettyConfiguration {
private final boolean jettyEnabled;
private final List<String> jettyBootstrapMains;
private final Filter<String> jettyExcludeUrlFilter;
public JettyConfiguration(ProfilerConfig config) {
this.jettyEnabled = config.readBoolean("profiler.jetty.enable", true);
this.jettyBootstrapMains = config.readList("profiler.jetty.bootstrap.main");
final String jettyExcludeURL = config.readString("profiler.jetty.excludeurl", "");
if (!jettyExcludeURL.isEmpty()) {
this.jettyExcludeUrlFilter = new ExcludePathFilter(jettyExcludeURL);
} else{
this.jettyExcludeUrlFilter = new SkipFilter<String>();
}
}
public boolean isJettyEnabled() {
return jettyEnabled;
}
public List<String> getJettyBootstrapMains() {
return jettyBootstrapMains;
}
public Filter<String> getJettyExcludeUrlFilter() {
return jettyExcludeUrlFilter;
}
}
| 35.111111
| 90
| 0.732068
|
db47e46aae899ed40ce94fab0b04364a7283c447
| 4,425
|
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.designer.internal.ui.views.actions;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.dialogs.UseCssInReportDialog;
import org.eclipse.birt.report.designer.ui.dialogs.UseCssInThemeDialog;
import org.eclipse.birt.report.model.api.AbstractThemeHandle;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.IncludedCssStyleSheet;
import org.eclipse.jface.dialogs.Dialog;
/**
*
*/
public class UseCssStyleAction extends AbstractViewAction
{
public static final String ID = "org.eclipse.birt.report.designer.internal.ui.views.UseCssStyleAction"; //$NON-NLS-1$
public static final String ACTION_TEXT = Messages.getString( "UseCssStyleAction.text" ); //$NON-NLS-1$
public UseCssStyleAction( Object selectedObject )
{
this( selectedObject, ACTION_TEXT );
}
public UseCssStyleAction( Object selectedObject, String text )
{
super( selectedObject, text );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#isEnabled()
*/
public boolean isEnabled( )
{
// TODO Auto-generated method stub
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run( )
{
// TODO Auto-generated method stub
Object selection = getSelection( );
if ( selection == null )
{
return;
}
if ( ( selection instanceof SlotHandle )
&& ( ( (SlotHandle) selection ).getElementHandle( ) instanceof ReportDesignHandle ) )
{
useCssInReportDesign( );
}
else if ( selection instanceof AbstractThemeHandle )
{
useCssInTheme( (AbstractThemeHandle) selection );
}
}
private void useCssInReportDesign( )
{
UseCssInReportDialog dialog = new UseCssInReportDialog( );
String relativeFileName = null;
dialog.setFileName( relativeFileName );
if ( dialog.open( ) == Dialog.OK )
{
CommandStack stack = SessionHandleAdapter.getInstance( )
.getCommandStack( );
stack.startTrans( ACTION_TEXT );
try
{
ReportDesignHandle moduleHandle = (ReportDesignHandle) SessionHandleAdapter.getInstance( )
.getReportDesignHandle( );
{
IncludedCssStyleSheet css = StructureFactory.createIncludedCssStyleSheet( );
css.setExternalCssURI( dialog.getURI( ) );
css.setUseExternalCss( dialog.isUseUri( ) );
css.setFileName( dialog.getFileName( ) );
moduleHandle.addCss( css );
}
}
catch ( SemanticException e )
{
// TODO Auto-generated catch block
ExceptionHandler.handle( e );
stack.rollback( );
return;
}
stack.commit( );
}
}
private void useCssInTheme( AbstractThemeHandle oldTheme )
{
UseCssInThemeDialog dialog = new UseCssInThemeDialog( );
String relativeFileName = null;
dialog.setFileName( relativeFileName );
dialog.setTheme( oldTheme );
if ( dialog.open( ) == Dialog.OK )
{
CommandStack stack = SessionHandleAdapter.getInstance( )
.getCommandStack( );
stack.startTrans( ACTION_TEXT );
AbstractThemeHandle themeHandle = dialog.getTheme( );
try
{
IncludedCssStyleSheet css = StructureFactory.createIncludedCssStyleSheet( );
css.setUseExternalCss( dialog.isUseUri( ) );
css.setExternalCssURI( dialog.getURI( ) );
css.setFileName( dialog.getFileName( ) );
themeHandle.addCss( css );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
stack.rollback( );
return;
}
stack.commit( );
}
}
}
| 29.304636
| 118
| 0.698757
|
270b59e025d137776a23f85062cd0cae7061c99c
| 678
|
package com.zzw.github.graphql.schema.enums;
import com.zzw.github.graphql.schema.annotations.Argument;
import com.zzw.github.graphql.schema.annotations.Arguments;
import com.zzw.github.graphql.schema.annotations.Description;
import com.zzw.github.graphql.schema.annotations.ImplementedBy;
import com.zzw.github.graphql.schema.annotations.NonNull;
@Description("The possible states of a pull request.")
public enum PullRequestState {
@Description("A pull request that has been closed without being merged.")
CLOSED,
@Description("A pull request that has been closed by being merged.")
MERGED,
@Description("A pull request that is still open.")
OPEN,
}
| 37.666667
| 77
| 0.778761
|
3a8199cc2d59846ba2c60d579f9b2ca8bb7bba2d
| 341
|
package com.bourdi_bay.currencyconverter;
class Currency {
private final String m_name;
private final double m_value;
Currency(String name, Double value) {
m_name = name;
m_value = value;
}
double getValue() {
return m_value;
}
public String getName() {
return m_name;
}
}
| 17.05
| 41
| 0.609971
|
5dba008c18339edeed155e3914d318b73ccbfcb2
| 163
|
package com.ming.blog.service.primary;
import java.util.HashMap;
public interface StudentService {
HashMap<String, Object> findAll();
void insert();
}
| 14.818182
| 38
| 0.723926
|
141b2579b3599dd37d3e56d7c34a5016b49e5f29
| 411
|
public class Cav09_Fig3a {
public static void vtrace_post(int n, int tCtr){}
public static void main (String[] args) {}
public static int mainQ(int n){
int x = 0;
int y = 0;
int tCtr = 0;
while(x < n){
y = x;
while (y < n){
tCtr++;
y++;
}
x=y+1;
}
vtrace_post(n, tCtr);
//%%%traces: int n, int t
//dig2: n*t - (t*t) == 0, -t <= 0, n - t <= 0
return 0;
}
}
| 17.125
| 53
| 0.50365
|
ef80b8365f5ddb687d0f38c8777d10830349058a
| 362
|
package net.baroi.messaging.server.simple.message;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
*
* @author Aldrin Baroi
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MailMessage implements Message {
private String from;
private String to;
private String subject;
private String text;
}
| 16.454545
| 50
| 0.779006
|
f463afc9ef7172bbf11c49032906482dc60c2096
| 3,989
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storage.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The PermissionScope model. */
@Fluent
public final class PermissionScope {
@JsonIgnore private final ClientLogger logger = new ClientLogger(PermissionScope.class);
/*
* The permissions for the local user. Possible values include: Read (r),
* Write (w), Delete (d), List (l), and Create (c).
*/
@JsonProperty(value = "permissions", required = true)
private String permissions;
/*
* The service used by the local user, e.g. blob, file.
*/
@JsonProperty(value = "service", required = true)
private String service;
/*
* The name of resource, normally the container name or the file share
* name, used by the local user.
*/
@JsonProperty(value = "resourceName", required = true)
private String resourceName;
/**
* Get the permissions property: The permissions for the local user. Possible values include: Read (r), Write (w),
* Delete (d), List (l), and Create (c).
*
* @return the permissions value.
*/
public String permissions() {
return this.permissions;
}
/**
* Set the permissions property: The permissions for the local user. Possible values include: Read (r), Write (w),
* Delete (d), List (l), and Create (c).
*
* @param permissions the permissions value to set.
* @return the PermissionScope object itself.
*/
public PermissionScope withPermissions(String permissions) {
this.permissions = permissions;
return this;
}
/**
* Get the service property: The service used by the local user, e.g. blob, file.
*
* @return the service value.
*/
public String service() {
return this.service;
}
/**
* Set the service property: The service used by the local user, e.g. blob, file.
*
* @param service the service value to set.
* @return the PermissionScope object itself.
*/
public PermissionScope withService(String service) {
this.service = service;
return this;
}
/**
* Get the resourceName property: The name of resource, normally the container name or the file share name, used by
* the local user.
*
* @return the resourceName value.
*/
public String resourceName() {
return this.resourceName;
}
/**
* Set the resourceName property: The name of resource, normally the container name or the file share name, used by
* the local user.
*
* @param resourceName the resourceName value to set.
* @return the PermissionScope object itself.
*/
public PermissionScope withResourceName(String resourceName) {
this.resourceName = resourceName;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (permissions() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property permissions in model PermissionScope"));
}
if (service() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property service in model PermissionScope"));
}
if (resourceName() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property resourceName in model PermissionScope"));
}
}
}
| 32.169355
| 119
| 0.637754
|
1ba96123a7a866d32c240bb11937091567a46805
| 3,160
|
/*
* 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.jcs.jcache.extras.writer;
import org.apache.commons.jcs.jcache.extras.InternalCacheRule;
import org.junit.Rule;
import org.junit.Test;
import javax.cache.Cache;
import javax.cache.configuration.Configuration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.integration.CacheWriterException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class CompositeCacheWriterTest
{
@Rule
public final InternalCacheRule rule = new InternalCacheRule(this);
private final Map<String, String> copy1 = new HashMap<String, String>();
private final Map<String, String> copy2 = new HashMap<String, String>();
private final CacheWriterAdapter<String, String> writer1 = new CacheWriterAdapter<String, String>()
{
@Override
public void write(final Cache.Entry<? extends String, ? extends String> entry) throws CacheWriterException
{
copy1.put(entry.getKey(), entry.getValue());
}
@Override
public void delete(final Object key) throws CacheWriterException
{
copy1.remove(key);
}
};
private final CacheWriterAdapter<String, String> writer2 = new CacheWriterAdapter<String, String>()
{
@Override
public void write(final Cache.Entry<? extends String, ? extends String> entry) throws CacheWriterException
{
copy2.put(entry.getKey(), entry.getValue());
}
@Override
public void delete(final Object key) throws CacheWriterException
{
copy2.remove(key);
}
};
private final Configuration<?, ?> config = new MutableConfiguration<String, String>()
.setStoreByValue(false)
.setWriteThrough(true)
.setCacheWriterFactory(new CompositeCacheWriter<String, String>(writer1, writer2));
private Cache<String, String> cache;
@Test
public void checkComposite()
{
cache.put("a", "b");
assertEquals("b", copy1.get("a"));
assertEquals("b", copy2.get("a"));
assertEquals(1, copy1.size());
assertEquals(1, copy2.size());
cache.remove("a");
assertTrue(copy1.isEmpty());
assertTrue(copy2.isEmpty());
}
}
| 34.725275
| 114
| 0.688291
|
0fa0b93a1eb3d7bac22ab59eb9bc8c0f039bbbc9
| 770
|
package com.cx.entity;
public class Admi {
private Integer admiID;
private String admiName;
private String admiPassword;
public Admi() {
// TODO 自动生成的构造函数存根
}
public Integer getAdmiID() {
return admiID;
}
public void setAdmiID(Integer admiID) {
this.admiID = admiID;
}
public String getAdmiName() {
return admiName;
}
public void setAdmiName(String admiName) {
this.admiName = admiName;
}
public String getAdmiPassword() {
return admiPassword;
}
public void setAdmiPassword(String admiPassword) {
this.admiPassword = admiPassword;
}
@Override
public String toString() {
return "Admi [admiID=" + admiID + ", admiName=" + admiName + ", admiPassword=" + admiPassword + "]";
}
}
| 17.5
| 103
| 0.654545
|
6e0fba13b1ee6ee18909fd45f4855971d5aa62d9
| 10,188
|
/* **********************************************************
* Copyright 2010 VMware, Inc. All rights reserved. -- VMware Confidential
* **********************************************************/
package com.emc.storageos.vasa.util;
import java.io.FileReader;
import java.io.IOException;
import java.lang.String;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.vmware.vim.vasa._1_0.data.xsd.MountInfo;
import com.vmware.vim.vasa._1_0.data.xsd.HostInitiatorInfo;
import com.vmware.vim.vasa._1_0.data.xsd.StorageFileSystem;
import com.vmware.vim.vasa._1_0.InvalidArgument;
import org.apache.log4j.Logger;
/**
* Helper functions
*/
public class Util {
private static String configPath = "/config/parameters/";
private static Logger log = Logger.getLogger(Util.class);
public static boolean isEmpty(MountInfo[] mi) {
return mi == null || mi.length == 0
|| ((mi.length == 1) && mi[0] == null);
}
public static boolean isEmpty(HostInitiatorInfo[] hii) {
return hii == null || hii.length == 0
|| ((hii.length == 1) && hii[0] == null);
}
private static boolean stringsAreEqual(String s1, String s2) {
if ((s1 == null) && (s2 == null)) {
// both null means equal
return true;
}
if ((s1 == null) || (s2 == null)) {
// one is null, the other is not
return false;
}
return s1.equals(s2);
}
private static boolean objectsAreEqual(HostInitiatorInfo hii1,
HostInitiatorInfo hii2) {
if (!stringsAreEqual(hii1.getPortWwn(), hii2.getPortWwn())) {
return false;
}
if (!stringsAreEqual(hii1.getNodeWwn(), hii2.getNodeWwn())) {
return false;
}
if (!stringsAreEqual(hii1.getIscsiIdentifier(),
hii2.getIscsiIdentifier())) {
return false;
}
return true;
}
private static boolean objectsAreEqual(Object o1, Object o2)
throws InvalidArgument {
if ((o1 instanceof HostInitiatorInfo)
&& (o2 instanceof HostInitiatorInfo)) {
return objectsAreEqual((HostInitiatorInfo) o1,
(HostInitiatorInfo) o2);
}
log.error("objectsAreEqual: unknown object type");
throw FaultUtil.InvalidArgument();
}
public static boolean listsAreEqual(ArrayList l1, ArrayList l2)
throws InvalidArgument {
if ((l1 == null) && (l2 == null)) {
// both null means equal
return true;
}
if ((l1 == null) || (l2 == null)) {
// one is null, the other is not
return false;
}
if (l1.size() != l2.size()) {
// sizes not equal, lists cannot be equal
return false;
}
/*
* make sure that the same object is not found more than one in the list
*
* it is only necessary to do this check for one of the lists
*/
for (int i = 0; i < l1.size() - 1; i++) {
for (int j = i + 1; j < l1.size(); j++) {
if (objectsAreEqual(l1.get(i), l1.get(j))) {
log.error("listsAreEqual: list contains the same object more than once");
throw FaultUtil.InvalidArgument();
}
}
}
/*
* check that each object in l1 is found in l2 since there are no
* duplicate objects in l1 this means there are no extra objects in l2
*/
for (int i = 0; i < l1.size(); i++) {
boolean matchFound = false;
for (int j = 0; j < l2.size(); j++) {
if (objectsAreEqual(l1.get(i), l2.get(j))) {
matchFound = true;
}
}
if (!matchFound) {
return false;
}
}
return true;
}
public static boolean isEmpty(StorageFileSystem[] sfs) {
return sfs == null || sfs.length == 0
|| ((sfs.length == 1) && sfs[0] == null);
}
public static boolean isEmpty(String[] s) {
return s == null || s.length == 0 || ((s.length == 1) && s[0] == null);
}
public static boolean isEmpty(String s) {
return s == null || s.trim().length() == 0;
}
/**
* All the UniqueIds used by the VP are integers If any of the
* UniqueIds in the String array are not integers then they cannot possibly
* be valid ids and so the expection is thrown.
*/
public static void allUniqueIdsAreValid(String[] uniqueIds,
boolean allowEmpty) throws InvalidArgument {
if (isEmpty(uniqueIds)) {
if (!allowEmpty) {
throw FaultUtil
.InvalidArgument("UniqueId list cannot be empty");
}
return;
}
for (int i = 0; i < uniqueIds.length; i++) {
uniqueIdIsValid(uniqueIds[i]);
}
}
/*
* Verify that the uniqueId is composed of characters only in the range of
* '0' - '9'. The assumption is that uniqueId will not be NULL.
*/
public static void uniqueIdIsValid(String uniqueId) throws InvalidArgument {
try {
if (uniqueId == null) {
throw FaultUtil.InvalidArgument("UniqueId[" + uniqueId
+ "] is not a valid id for VP");
}
} catch (Exception e) {
throw FaultUtil.InvalidArgument("UniqueId " + uniqueId
+ " unexpected exception: " + e);
}
}
/*
* Verify that the event or alarm Id is -1 or greater.
*/
public static void eventOrAlarmIdIsValid(long id) throws InvalidArgument {
if (id < -1) {
throw FaultUtil.InvalidArgument("invalid id " + id);
}
}
/*
* Convert to comma separated string
*/
public static String getIdString(String[] id) {
if (id == null || id.length < 1) {
return null;
}
StringBuffer buff = new StringBuffer();
for (int i = 0; i < id.length - 1; i++) {
buff.append(id[i]);
buff.append(",");
}
buff.append(id[id.length - 1]);
return buff.toString();
}
public static String getConfigParameter(String configName) {
try {
XmlParser configParser = new XmlParser();
configParser.loadResource("com/emc/sos/vasa/config.xml");
return configParser.getString(configPath + configName, null);
} catch (Exception e) {
log.error("getStringConfigValue ", e);
return null;
}
}
public static String getConfigValue(String configName) {
try {
XmlParser configParser = new XmlParser();
configParser.loadResource("com/emc/sos/vasa/config.xml");
return configParser.getString(configName, null);
} catch (Exception e) {
log.error("getConfigValue ", e);
return null;
}
}
public static String getCanonicalNameOfLocalHost() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
String hostnameCanonical = addr.getCanonicalHostName();
if (hostnameCanonical.contains("null")) {
return null;
}
if ("localhost".equals(hostnameCanonical)) {
return null;
}
return hostnameCanonical;
} catch (UnknownHostException e) {
log.error("UnknownHostException occurred: " + e.getMessage());
return null;
}
}
public static String getIPAddressOfLocalHost() {
InetAddress addr = null;
try {
addr = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("UnknownHostException occurred: " + e.getMessage());
return null;
}
String ipAddress = addr.getHostAddress();
if ("127.0.0.1".equals(ipAddress)) {
return null;
}
return ipAddress;
}
public static String getPropertyValue(String filePath, String propertyKey) {
final String methodName = "getPropertyValue(): ";
log.trace(methodName + "Entering with input filePath[" + filePath
+ "] propertyKey[" + propertyKey + "]");
FileReader fileReader = null;
Properties prop = new Properties();
try {
fileReader = new FileReader(filePath);
prop.load(fileReader);
String value = null;
value = prop.getProperty(propertyKey);
log.trace(methodName + "returning [" + value + "]");
return value;
} catch (IOException ex) {
log.warn(methodName + "IOException occured: " + ex.getMessage());
log.trace(methodName + "returning [null]");
return null;
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
// Do nothing
}
}
}
}
public static boolean areListsEqual(List<String> list1, List<String> list2) {
if (list1 == null && list2 == null) {
return true;
}
if ((list1 == null) || (list2 == null)) {
// one is null, the other is not
return false;
}
if (list1.size() != list2.size()) {
// sizes not equal, lists cannot be equal
return false;
}
for (int i = 0; i < list1.size(); i++) {
boolean matchFound = false;
for (int j = 0; j < list2.size(); j++) {
if (list1.get(i).equals(list2.get(j))) {
matchFound = true;
}
}
if (!matchFound) {
return false;
}
}
return true;
}
}
| 31.155963
| 93
| 0.524342
|
cc39cce331a49e34c2a8b61bc77e192080c218e2
| 416
|
/*
* Copyright (c) 2014 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.security.keystore.impl;
import org.apache.commons.codec.binary.Base64;
public class Base64Util {
private static final int PEM_OUTPUT_LINE_SIZE = 64;
public static byte[] encodeWithNewLine(byte[] bytes) {
Base64 encoder = new Base64(PEM_OUTPUT_LINE_SIZE);
return encoder.encode(bytes);
}
}
| 21.894737
| 58
| 0.716346
|
e0d371ce503451b4160c14068a02ca3347840614
| 2,047
|
/*
* Copyright 2007-2017 Michele Mostarda ( michele.mostarda@gmail.com ).
* All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asemantics.rdfcoder.model.java;
import com.asemantics.rdfcoder.model.Identifier;
import com.asemantics.rdfcoder.model.QueryModelException;
/**
* Represents a <i>Java</i> method.
*
* @author Michele Mostarda (michele.mostarda@gmail.com)
*/
public class JMethod extends JModifiable {
/**
* Constructor by path.
* @param queryModel
* @param pathToMethod
*/
protected JMethod(JavaQueryModel queryModel, Identifier pathToMethod)
throws QueryModelException {
super(queryModel, pathToMethod);
}
/**
* Returns the method name.
*
* @return the string identifying the method.
*/
public String getName() {
return getIdentifier().getLastFragmentWithQualifier(JavaCodeModel.METHOD_KEY);
}
/**
* Returns the signatures of a method.
*
* @return list of signatures.
*/
public JSignature[] getSignatures() throws QueryModelException {
return getQueryModel().getSignatures( super.getIdentifier() );
}
/**
* Check wether a method exists.
*
* @param identifier
* @return <code>true</code> if exists.
*/
public boolean exists(Identifier identifier) {
return getQueryModel().methodExists(identifier);
}
protected String getHierarchyElemType() {
return this.getClass().getSimpleName();
}
}
| 27.662162
| 86
| 0.680997
|
61df95add890670247e14b4e4631d0d4b067bdbd
| 7,510
|
/*
* Jigasi, the JItsi GAteway to SIP.
*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jigasi.osgi;
import net.java.sip.communicator.impl.protocol.jabber.*;
import org.jitsi.impl.neomedia.*;
import org.jitsi.impl.neomedia.device.*;
import org.jitsi.impl.neomedia.transform.csrc.*;
import org.jitsi.impl.neomedia.transform.srtp.*;
import org.jitsi.impl.osgi.framework.launch.*;
import org.jitsi.meet.*;
import org.jitsi.service.configuration.*;
import org.jitsi.stats.media.*;
import java.util.*;
/**
* Jigasi OSGi bundle config
*
* @author Pawel Domas
*/
public class JigasiBundleConfig
extends OSGiBundleConfig
{
/**
* Indicates whether 'mock' protocol providers should be used instead of
* original Jitsi protocol providers. For the purpose of unit testing.
*/
private static boolean _useMockProtocols = false;
/**
* Indicates whether mock protocol providers should be used instead of
* original Jitsi protocol providers.
*/
public static boolean isUseMockProtocols()
{
return _useMockProtocols;
}
/**
* Make OSGi use mock protocol providers instead of original Jitsi protocols
* implementation.
* @param useMockProtocols <tt>true</tt> if Jitsi protocol providers should
* be replaced with mock version.
*/
public static void setUseMockProtocols(boolean useMockProtocols)
{
_useMockProtocols = useMockProtocols;
}
/**
* The locations of the OSGi bundles (or rather of the class files of their
* <tt>BundleActivator</tt> implementations) comprising Jitsi Videobridge.
* An element of the <tt>BUNDLES</tt> array is an array of <tt>String</tt>s
* and represents an OSGi start level.
*/
@Override
protected String[][] getBundlesImpl()
{
String[] protocols =
{
"net/java/sip/communicator/impl/protocol/sip/SipActivator",
"net/java/sip/communicator/impl/protocol/jabber/JabberActivator"
};
String[] mockProtocols =
{
"net/java/sip/communicator/service/protocol/mock/MockActivator"
};
String[][] bundles = {
{
"org/jitsi/service/libjitsi/LibJitsiActivator"
},
{
"net/java/sip/communicator/util/UtilActivator",
"net/java/sip/communicator/impl/fileaccess/FileAccessActivator"
},
{
"net/java/sip/communicator/impl/configuration/ConfigurationActivator"
},
{
"net/java/sip/communicator/impl/resources/ResourceManagementActivator"
},
{
"net/java/sip/communicator/impl/dns/DnsUtilActivator"
},
{
"net/java/sip/communicator/impl/credentialsstorage/CredentialsStorageActivator"
},
{
"net/java/sip/communicator/impl/netaddr/NetaddrActivator",
"net/java/sip/communicator/impl/sysactivity/SysActivityActivator"
},
{
"net/java/sip/communicator/impl/packetlogging/PacketLoggingActivator"
},
{
"net/java/sip/communicator/service/gui/internal/GuiServiceActivator"
},
{
"net/java/sip/communicator/service/protocol/media/ProtocolMediaActivator"
},
{
"net/java/sip/communicator/service/notification/NotificationServiceActivator",
"net/java/sip/communicator/impl/globaldisplaydetails/GlobalDisplayDetailsActivator"
},
{
"net/java/sip/communicator/impl/neomedia/NeomediaActivator"
},
{
"net/java/sip/communicator/impl/certificate/CertificateVerificationActivator"
},
{
"org/jitsi/jigasi/version/VersionActivator"
},
{
"net/java/sip/communicator/service/protocol/ProtocolProviderActivator"
},
{
"net/java/sip/communicator/plugin/reconnectplugin/ReconnectPluginActivator"
},
// Shall we use mock protocol providers ?
_useMockProtocols ? mockProtocols : protocols,
{
"org/jitsi/jigasi/JigasiBundleActivator"
},
{
"org/jitsi/jigasi/rest/RESTBundleActivator"
},
{
"org/jitsi/jigasi/rest/TranscriptServerBundleActivator"
},
{
"org/jitsi/jigasi/xmpp/CallControlMucActivator"
},
{
"org/jitsi/ddclient/Activator"
}
};
return bundles;
}
@Override
protected Map<String, String> getSystemPropertyDefaults()
{
// FIXME: some threads must be kept alive that prevent JVM
// from shutting down
FrameworkImpl.killAfterShutdown = true;
Map<String, String> defaults = super.getSystemPropertyDefaults();
String true_ = Boolean.toString(true);
String false_ = Boolean.toString(false);
// Audio system should not be disabled
defaults.put(
MediaServiceImpl.DISABLE_AUDIO_SUPPORT_PNAME,
false_);
defaults.put(
DeviceConfiguration.PROP_AUDIO_SYSTEM,
AudioSystem.LOCATOR_PROTOCOL_AUDIOSILENCE);
defaults.put(
"org.jitsi.impl.neomedia.device.PortAudioSystem.disabled",
true_);
defaults.put(
"org.jitsi.impl.neomedia.device.PulseAudioSystem.disabled",
true_);
// Disables COIN notifications
defaults.put(
OperationSetTelephonyConferencingJabberImpl.DISABLE_COIN_PROP_NAME,
true_);
// FIXME not sure about this one
// It makes no sense for Jitsi Videobridge to pace its RTP output.
defaults.put(
DeviceConfiguration.PROP_VIDEO_RTP_PACING_THRESHOLD,
Integer.toString(Integer.MAX_VALUE));
/*
* Drops silent audio packets that has the
* rtp extension(rfc6464) with sound level information.
*/
defaults.put(
SsrcTransformEngine
.DROP_MUTED_AUDIO_SOURCE_IN_REVERSE_TRANSFORM,
true_);
defaults.put(SRTPCryptoContext.CHECK_REPLAY_PNAME, false_);
// override defaults with passed to the Main
defaults.put(
ConfigurationService.PNAME_CONFIGURATION_FILE_IS_READ_ONLY,
System.getProperty(
ConfigurationService.PNAME_CONFIGURATION_FILE_IS_READ_ONLY,
true_));
// java-stats(stats-java-sdk)
Utils.getCallStatsJavaSDKSystemPropertyDefaults(defaults);
return defaults;
}
}
| 33.828829
| 99
| 0.60972
|
79ff6ebac9ef2c172baf975c9f01b773d586d9fa
| 2,398
|
/*
* 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.
*
* $Header:$
*/
package org.apache.beehive.netui.pageflow;
/**
* Exception that occurs when an output form has been added to a Forward that resolves to a
* {@link org.apache.beehive.netui.pageflow.annotations.Jpf.Forward @Jpf.Forward} annotation marked with
* <code>{@link org.apache.beehive.netui.pageflow.annotations.Jpf.Forward#redirect redirect}=true</code>.
* Output forms may not be used on redirect forwards.
*
* @see Forward#addOutputForm
*/
public class IllegalRedirectOutputFormException extends IllegalOutputFormException
{
/**
* @param forwardName the name of the relevant {@link Forward}.
* @param actionName the name of the current action being run.
* @param flowController the current {@link FlowController} instance.
* @param outputFormType the type name of the relevant output form.
*/
public IllegalRedirectOutputFormException( String forwardName, String actionName, FlowController flowController,
String outputFormType )
{
super( forwardName, actionName, flowController, outputFormType );
}
protected Object[] getMessageArgs()
{
return new Object[]{ getForwardName(), getActionName(), getFlowControllerURI(), getOutputFormType() };
}
public String[] getMessageParts()
{
return new String[]
{
"The forward \"", "\" on action ", " in page flow ", " has at least one output form (type ",
"), but is set to redirect=\"true\". Output forms may not be used on redirect forwards."
};
}
}
| 41.344828
| 116
| 0.699333
|
fe4cc72844bdabfa5f0c2c24376030e3289790cd
| 8,380
|
/*
* Nexd API
* Swagger API description
*
* The version of the OpenAPI document: 1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package app.nexd.android.api.model;
import java.util.Objects;
import java.util.Arrays;
import app.nexd.android.api.model.HelpRequest;
import app.nexd.android.api.model.User;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* HelpList
*/
public class HelpList {
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Long id;
public static final String SERIALIZED_NAME_HELP_REQUESTS_IDS = "helpRequestsIds";
@SerializedName(SERIALIZED_NAME_HELP_REQUESTS_IDS)
private List<Long> helpRequestsIds = new ArrayList<Long>();
public static final String SERIALIZED_NAME_OWNER_ID = "ownerId";
@SerializedName(SERIALIZED_NAME_OWNER_ID)
private String ownerId;
public static final String SERIALIZED_NAME_OWNER = "owner";
@SerializedName(SERIALIZED_NAME_OWNER)
private User owner;
public static final String SERIALIZED_NAME_CREATED_AT = "created_at";
@SerializedName(SERIALIZED_NAME_CREATED_AT)
private Date createdAt;
public static final String SERIALIZED_NAME_UPDATED_AT = "updated_at";
@SerializedName(SERIALIZED_NAME_UPDATED_AT)
private Date updatedAt;
/**
* Gets or Sets status
*/
@JsonAdapter(StatusEnum.Adapter.class)
public enum StatusEnum {
ACTIVE("active"),
CANCELED("canceled"),
COMPLETED("completed");
private String value;
StatusEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<StatusEnum> {
@Override
public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public StatusEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return StatusEnum.fromValue(value);
}
}
}
public static final String SERIALIZED_NAME_STATUS = "status";
@SerializedName(SERIALIZED_NAME_STATUS)
private StatusEnum status = StatusEnum.ACTIVE;
public static final String SERIALIZED_NAME_HELP_REQUESTS = "helpRequests";
@SerializedName(SERIALIZED_NAME_HELP_REQUESTS)
private List<HelpRequest> helpRequests = new ArrayList<HelpRequest>();
public HelpList id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@ApiModelProperty(required = true, value = "")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public HelpList helpRequestsIds(List<Long> helpRequestsIds) {
this.helpRequestsIds = helpRequestsIds;
return this;
}
public HelpList addHelpRequestsIdsItem(Long helpRequestsIdsItem) {
this.helpRequestsIds.add(helpRequestsIdsItem);
return this;
}
/**
* List of help request IDs
* @return helpRequestsIds
**/
@ApiModelProperty(required = true, value = "List of help request IDs")
public List<Long> getHelpRequestsIds() {
return helpRequestsIds;
}
public void setHelpRequestsIds(List<Long> helpRequestsIds) {
this.helpRequestsIds = helpRequestsIds;
}
public HelpList ownerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
/**
* Get ownerId
* @return ownerId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public HelpList owner(User owner) {
this.owner = owner;
return this;
}
/**
* Get owner
* @return owner
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public HelpList createdAt(Date createdAt) {
this.createdAt = createdAt;
return this;
}
/**
* Get createdAt
* @return createdAt
**/
@ApiModelProperty(required = true, value = "")
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public HelpList updatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
return this;
}
/**
* Get updatedAt
* @return updatedAt
**/
@ApiModelProperty(required = true, value = "")
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public HelpList status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Get status
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public HelpList helpRequests(List<HelpRequest> helpRequests) {
this.helpRequests = helpRequests;
return this;
}
public HelpList addHelpRequestsItem(HelpRequest helpRequestsItem) {
this.helpRequests.add(helpRequestsItem);
return this;
}
/**
* Get helpRequests
* @return helpRequests
**/
@ApiModelProperty(required = true, value = "")
public List<HelpRequest> getHelpRequests() {
return helpRequests;
}
public void setHelpRequests(List<HelpRequest> helpRequests) {
this.helpRequests = helpRequests;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
HelpList helpList = (HelpList) o;
return Objects.equals(this.id, helpList.id) &&
Objects.equals(this.helpRequestsIds, helpList.helpRequestsIds) &&
Objects.equals(this.ownerId, helpList.ownerId) &&
Objects.equals(this.owner, helpList.owner) &&
Objects.equals(this.createdAt, helpList.createdAt) &&
Objects.equals(this.updatedAt, helpList.updatedAt) &&
Objects.equals(this.status, helpList.status) &&
Objects.equals(this.helpRequests, helpList.helpRequests);
}
@Override
public int hashCode() {
return Objects.hash(id, helpRequestsIds, ownerId, owner, createdAt, updatedAt, status, helpRequests);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class HelpList {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" helpRequestsIds: ").append(toIndentedString(helpRequestsIds)).append("\n");
sb.append(" ownerId: ").append(toIndentedString(ownerId)).append("\n");
sb.append(" owner: ").append(toIndentedString(owner)).append("\n");
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" helpRequests: ").append(toIndentedString(helpRequests)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 23.149171
| 105
| 0.677566
|
72d1208d64d00518062c4b53c8ee8bae7c139844
| 1,813
|
package com.example.kafka.topology.processor.external;
import javax.validation.constraints.NotBlank;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import com.example.kafka.data.WorkforceData;
import com.example.kafka.request.RetrieveStoreWorkforceRequest;
import com.example.kafka.request.SaveStoreWorkforceRequest;
import com.example.kafka.response.store.RetrieveStoreWorkforceResponse;
import com.example.kafka.response.store.SaveStoreWorkforceResponse;
import com.example.kafka.service.merge.IMergeService;
import com.example.kafka.service.store.IStoreWorkforceService;
import com.example.kafka.topology.processor.AbstractMergeProcessor;
public class ExternalMergeProcessor extends AbstractMergeProcessor {
private static final Logger logger = LoggerFactory.getLogger(ExternalMergeProcessor.class);
public ExternalMergeProcessor() {}
public ExternalMergeProcessor(@NonNull IMergeService mergeService, @NonNull IStoreWorkforceService storeService) {
super(null, mergeService);
_storeService = storeService;
}
@Override
protected void initializeStore() {
}
@Override
protected WorkforceData loadWorkforceData(@NotBlank String key) {
RetrieveStoreWorkforceResponse response = _storeService.retrieve(new RetrieveStoreWorkforceRequest(key));
return response.isSuccess() ? response.data : null;
}
@Override
protected boolean storeWorkforceData(@NotBlank String key, WorkforceData workforce) {
SaveStoreWorkforceResponse response = _storeService.save(new SaveStoreWorkforceRequest(workforce));
return response.isSuccess();
}
private IStoreWorkforceService _storeService;
public static final String TAG = ExternalMergeProcessor.class.getName();
}
| 37.770833
| 118
| 0.797022
|
22b1d57ed3e0889e90be8992064482a475d733a8
| 207
|
package com.xiaomihu.jump;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JumpApplicationTests {
@Test
void contextLoads() {
}
}
| 14.785714
| 60
| 0.782609
|
4a4edbececb960f37b9356a147ce15493e6eb8bc
| 5,181
|
/**
This file is part of a jTEM project.
All jTEM projects are licensed under the FreeBSD license
or 2-clause BSD license (see http://www.opensource.org/licenses/bsd-license.php).
Copyright (c) 2002-2009, Technische Universität Berlin, jTEM
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
**/
package de.jtem.mfc.field;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* An instance of this class is a JPanel containing one JSlider and 3
* JTextFields representing the Sliders minimum, maximum and current value.
*
* @author marcel
*/
public class MinMaxPanel extends JPanel
implements ActionListener, ChangeListener
{
private JSlider scrol;
private DoubleBoundedRangeModel minMaxModel;
private JTextField minTF, maxTF, valTF;
private double target;
/**
* Creates a MinMaxPanel instance with 1 JSlider, 3 JTextFields and 1 JLabel
* with the specified name.
* The JLabel only represents what kind of value is showing by the JSlider
* (for a better handling with 2 or more MinMaxPanels, e.g.:
* de.jtem.mfc.field.QuaternionEditor).
*/
public MinMaxPanel(String name)
{
super(new GridBagLayout());
GridBagConstraints lab=new GridBagConstraints();
GridBagConstraints gbc=new GridBagConstraints();
lab.insets.right=2;
gbc.anchor=GridBagConstraints.NORTHWEST;
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.weightx=1f;
add(scrol=new JSlider(minMaxModel=new DoubleBoundedRangeModel()), gbc);
minMaxModel.addChangeListener(this);
gbc.insets.top=0;
lab.gridwidth=1;
add(new JLabel("min"), lab);
gbc.gridwidth=2;
gbc.weightx=0.f;
add(minTF=new JTextField(), gbc);
minTF.addActionListener(this);
minTF.setColumns(4);
minTF.setHorizontalAlignment(JTextField.LEFT);
lab.gridwidth=3;
lab.insets.left=20;
add(new JLabel(name, JLabel.RIGHT), lab);
gbc.gridwidth=4;
gbc.weightx=1f;
add(valTF=new JTextField(), gbc);
valTF.addActionListener(this);
valTF.setColumns(12);
valTF.setHorizontalAlignment(JTextField.LEFT);
lab.gridwidth=5;
add(new JLabel("max"), lab);
gbc.gridwidth=GridBagConstraints.REMAINDER;
gbc.weightx=0.f;
add(maxTF=new JTextField(), gbc);
maxTF.addActionListener(this);
maxTF.setColumns(4);
maxTF.setHorizontalAlignment(JTextField.LEFT);
}
public DoubleBoundedRangeModel getModel()
{
return minMaxModel;
}
public void setMinimum(double min)
{
minMaxModel.setDoubleMinimum(min);
}
public double getMinimum()
{
return minMaxModel.getDoubleMinimum();
}
public void setMaximum(double max)
{
minMaxModel.setDoubleMaximum(max);
}
public double getMaximum()
{
return minMaxModel.getDoubleMaximum();
}
public void setValue(double val)
{
minMaxModel.setDoubleValue(val);
}
public double getValue()
{
return minMaxModel.getDoubleValue();
}
//-------------------------event-handling------------------------------------
public void actionPerformed(ActionEvent ev)
{
final JTextField src=(JTextField)ev.getSource();
final double v=Double.parseDouble(ev.getActionCommand());
if (src==minTF)
setMinimum(v);
else if(src==maxTF)
setMaximum(v);
else if(src==valTF)
setValue(v);
}
public void stateChanged(ChangeEvent ev)
{
double doubleVal=minMaxModel.getDoubleValue();
double doubleMin=minMaxModel.getDoubleMinimum();
double doubleMax=minMaxModel.getDoubleMaximum();
minTF.setText(String.valueOf(doubleMin));
maxTF.setText(String.valueOf(doubleMax));
valTF.setText(String.valueOf(doubleVal));
}
}
| 33
| 82
| 0.735186
|
56a0d9ec7dc8a05da09a3fbdeaefaee629103bcb
| 665
|
/**
*
*/
package jscenegraph.coin3d.inventor;
/**
* @author Yves Boyadjian
*
*/
public class SbHeapFuncs {
public interface Eval {
float eval_func(Object obj);
}
public interface Get_index {
int get_index_func(Object obj);
}
public interface Set_index {
void set_index_func(Object obj, int index);
}
Eval eval_func;
Get_index get_index_func;
Set_index set_index_func;
/**
* Constructor
* @param eval
* @param get_index
* @param set_index
*/
public SbHeapFuncs(Eval eval, Get_index get_index, Set_index set_index) {
super();
this.eval_func = eval;
this.get_index_func = get_index;
this.set_index_func = set_index;
}
}
| 16.625
| 74
| 0.703759
|
8bada6267e8a3a5431a3c345bfe273eb8479bf32
| 3,636
|
package io.opensphere.controlpanels.layers.base;
import java.util.Collection;
import org.apache.log4j.Logger;
import io.opensphere.mantle.data.DataGroupInfo;
import io.opensphere.mantle.data.DataTypeInfo;
import io.opensphere.mantle.data.impl.DataGroupActivator;
/**
* Activates or deactivates data groups.
*
*/
public class GroupActivator
{
/** Logger reference. */
private static final Logger LOGGER = Logger.getLogger(GroupActivator.class);
/** The data group activator. */
private final DataGroupActivator myDataGroupActivator;
/**
* Constructs a new group activator.
*
* @param activator The activator.
*/
public GroupActivator(DataGroupActivator activator)
{
myDataGroupActivator = activator;
}
/**
* Activate deactivates a group and its descendants and ancestors.
*
* @param activate True if the group and its descendants should be
* activated, false if it should be deactivated.
* @param dataGroupInfo The data group to activate or deactivate.
* @param confirmer Interface to an object that asks the user yes no
* questions.
*/
public void activateDeactivateGroup(boolean activate, DataGroupInfo dataGroupInfo, UserConfirmer confirmer)
{
if (confirmWithUser(activate, dataGroupInfo, confirmer))
{
try
{
// Activate self and children
myDataGroupActivator.setGroupsActive(dataGroupInfo.groupStream().parallel(), activate);
// Activate (grand)parents
for (DataGroupInfo parent = dataGroupInfo.getParent(); parent != null; parent = parent.getParent())
{
if (activate || canDeactivate(parent))
{
myDataGroupActivator.setGroupActive(parent, activate);
}
}
}
catch (InterruptedException e)
{
LOGGER.error(e, e);
}
}
}
/**
* If activating a lot of data types, asks the user if they are sure they
* want to do that.
*
* @param activate True if the group and its descendants should be
* activated, false if it should be deactivated.
* @param dataGroupInfo The data group to activate or deactivate.
* @param confirmer Interface to an object that asks the user yes no
* questions.
* @return True if activation should proceed, false otherwise.
*/
private boolean confirmWithUser(boolean activate, DataGroupInfo dataGroupInfo, UserConfirmer confirmer)
{
boolean proceed = true;
if (activate && confirmer != null)
{
Collection<DataTypeInfo> members = dataGroupInfo.getMembers(true);
if (members.size() > Constants.SELECT_WARN_THRESHOLD)
{
proceed = confirmer.askUser("Are you sure you want to activate " + members.size() + " items?",
"Confirm Activation");
}
}
return proceed;
}
/**
* Determines if the group can be deactivated.
*
* @param group the data group
* @return whether the group can be deactivated
*/
private boolean canDeactivate(DataGroupInfo group)
{
return group.getChildren().stream()
.noneMatch(g -> g.activationProperty().isActivatingOrDeactivating() || g.activationProperty().isActive());
}
}
| 33.981308
| 123
| 0.596535
|
e3ad7ea3377205eac18c49b286c3ae8bf48a35d9
| 2,437
|
package net.serenitybdd.screenplay.targets;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.core.pages.WebElementFacade;
import net.serenitybdd.screenplay.abilities.BrowseTheWeb;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import static java.util.Optional.empty;
public class TargetBuilder<T> {
private String targetElementName;
private Optional<IFrame> iFrame=empty();
public TargetBuilder(String targetElementName) {
this.targetElementName = targetElementName;
}
public TargetBuilder inIFrame(IFrame iFrame) {
this.iFrame = Optional.ofNullable(iFrame);
return this;
}
public Target locatedBy(String cssOrXPathSelector) {
return new XPathOrCssTarget(targetElementName, cssOrXPathSelector, iFrame, Optional.empty());
}
/**
* Locate an element using a location strategy function.
* The function takes a Serenity Page Object representing the current web page, and returns a list of matching WebElementFacade objects.
*/
public Target locatedBy(Function<PageObject, List<WebElementFacade>> locationStrategy) {
return new LambdaTarget(targetElementName, locationStrategy, iFrame, Optional.empty());
}
public Target locatedByFirstMatching(String... cssOrXPathSelectors) {
return new MultiXPathOrCssTarget(targetElementName, iFrame, Optional.empty(), cssOrXPathSelectors);
}
public Target located(By locator) {
return new ByTarget(targetElementName, locator, iFrame);
}
public LocatesCrossPlatform locatedForAndroid(By androidLocator) {
return new CrossPlatformTargetBuilder(targetElementName, androidLocator, iFrame);
}
static class CrossPlatformTargetBuilder implements LocatesCrossPlatform {
private String targetElementName;
private By androidLocator;
private Optional<IFrame> iFrame;
CrossPlatformTargetBuilder(String targetElementName, By androidLocator, Optional<IFrame> iFrame) {
this.targetElementName = targetElementName;
this.androidLocator = androidLocator;
this.iFrame = iFrame;
}
public Target locatedForIOS(By iosLocator) {
return new ByTarget(this.targetElementName, this.androidLocator, iosLocator, this.iFrame);
}
}
}
| 34.814286
| 140
| 0.735741
|
17d239ab03355ca4739c199cc64786608f44b8ae
| 6,836
|
/*
* Tencent is pleased to support the open source community by making TENCENT SOTER available.
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* https://opensource.org/licenses/BSD-3-Clause
* 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.tencent.soter.core.model;
import android.util.Base64;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayInputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
/**
* The public key model for App Secure Key and Auth Key. It consists the whole JSON that wrapper in the
* TEE, and the signature of the JSON generated in TEE. Developers should upload the JSON and signature to server
*/
@SuppressWarnings("unused")
public class SoterPubKeyModel {
private static final String TAG = "Soter.SoterPubKeyModel";
public static final String JSON_KEY_PUBLIC = "pub_key";
public static final String JSON_KEY_COUNTER = "counter";
public static final String JSON_KEY_CPU_ID = "cpu_id";
public static final String JSON_KEY_UID = "uid";
public static final String JSON_KEY_CERTS = "certs";
private long counter = -1;
private int uid = -1;
private String cpu_id = "";
private String pub_key_in_x509 = "";
private String rawJson = "";
private ArrayList<String> certs = null;
@Override
public String toString() {
return "SoterPubKeyModel{" +
"counter=" + counter +
", uid=" + uid +
", cpu_id='" + cpu_id + '\'' +
", pub_key_in_x509='" + pub_key_in_x509 + '\'' +
", rawJson='" + rawJson + '\'' +
", signature='" + signature + '\'' +
'}';
}
private String signature = "";
@SuppressWarnings("unused")
public SoterPubKeyModel(long counter, int uid, String cpu_id, String pub_key_in_x509, String signature) {
this.counter = counter;
this.uid = uid;
this.cpu_id = cpu_id;
this.pub_key_in_x509 = pub_key_in_x509;
this.signature = signature;
}
public SoterPubKeyModel(String rawJson, String signature) {
JSONObject jsonObj;
setRawJson(rawJson);
try {
jsonObj = new JSONObject(rawJson);
// this.rawJson = jsonObj.toString();
if(jsonObj.has(JSON_KEY_CERTS)){
JSONArray certJsonArray = jsonObj.optJSONArray(JSON_KEY_CERTS);
if (certJsonArray.length() < 2) {
SLogger.e(TAG,"certificates train not enough");
}
SLogger.i(TAG,"certs size: [%d]", certJsonArray.length());
certs = new ArrayList<String>();
for (int i = 0; i < certJsonArray.length(); i++) {
String certText = certJsonArray.getString(i);
certs.add(certText);
}
CertificateFactory factory = CertificateFactory.getInstance("X.509");
X509Certificate askCertificate = (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(certs.get(0).getBytes()));
loadDeviceInfo(askCertificate);
jsonObj.put(JSON_KEY_CPU_ID, cpu_id);
jsonObj.put(JSON_KEY_UID, uid);
jsonObj.put(JSON_KEY_COUNTER, counter);
setRawJson(jsonObj.toString());
}else{
this.counter = jsonObj.optLong(JSON_KEY_COUNTER);
this.uid = jsonObj.optInt(JSON_KEY_UID);
this.cpu_id = jsonObj.optString(JSON_KEY_CPU_ID);
this.pub_key_in_x509 = jsonObj.optString(JSON_KEY_PUBLIC);
}
} catch (Exception e) {
SLogger.e(TAG, "soter: pub key model failed");
}
this.signature = signature;
}
public SoterPubKeyModel(Certificate[] certificates){
try {
if(certificates != null){
ArrayList<String> certTexts = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < certificates.length; i++) {
Certificate certificate = certificates[i];
String certText = Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP);
certText = CertUtil.format(certificate);
if (i == 0){
loadDeviceInfo((X509Certificate)certificate);
}
jsonArray.put(certText);
certTexts.add(certText);
}
certs = certTexts;
JSONObject jsonObj = new JSONObject();
jsonObj.put(JSON_KEY_CERTS, jsonArray);
jsonObj.put(JSON_KEY_CPU_ID, cpu_id);
jsonObj.put(JSON_KEY_UID, uid);
jsonObj.put(JSON_KEY_COUNTER, counter);
setRawJson(jsonObj.toString());
}
}catch (Exception e){
SLogger.e(TAG, "soter: pub key model failed");
}
}
private void loadDeviceInfo(X509Certificate attestationCert) {
try{
CertUtil.extractAttestationSequence(attestationCert,this);
}catch (Exception e){
SLogger.e(TAG, "soter: loadDeviceInfo from attestationCert failed" + e.getStackTrace());
}
}
public void setCounter(long counter) {
this.counter = counter;
}
public void setUid(int uid) {
this.uid = uid;
}
public void setCpu_id(String cpu_id) {
this.cpu_id = cpu_id;
}
public void setPub_key_in_x509(String pub_key_in_x509) {
this.pub_key_in_x509 = pub_key_in_x509;
}
public void setSignature(String signature) {
this.signature = signature;
}
public long getCounter() {
return counter;
}
public int getUid() {
return uid;
}
public String getCpu_id() {
return cpu_id;
}
public String getPub_key_in_x509() {
return pub_key_in_x509;
}
public String getSignature() {
return signature;
}
public String getRawJson() {
return rawJson;
}
public void setRawJson(String rawJson) {
this.rawJson = rawJson;
}
}
| 35.604167
| 308
| 0.607958
|
927dec271782644d46ac77a74d64505fc53d53df
| 2,083
|
/*
* Copyright 2019 The Getty Project
*
* The Getty Project 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.gettyio.expansion.handler.timeout;
import com.gettyio.core.channel.SocketChannel;
import com.gettyio.core.constant.IdleState;
import com.gettyio.core.logging.InternalLogger;
import com.gettyio.core.logging.InternalLoggerFactory;
import com.gettyio.core.pipeline.in.ChannelInboundHandlerAdapter;
import com.gettyio.core.util.LinkedBlockQueue;
/**
* HeartBeatTimeOutHandler.java
*
* @description:心跳检测
* @author:gogym
* @date:2020/4/9
* @copyright: Copyright by gettyio.com
*/
public class HeartBeatTimeOutHandler extends ChannelInboundHandlerAdapter {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(HeartBeatTimeOutHandler.class);
private int loss_connect_time = 0;
@Override
public void userEventTriggered(SocketChannel socketChannel, IdleState evt) throws Exception {
if (evt == IdleState.READER_IDLE) {
loss_connect_time++;
if (loss_connect_time > 2) {
// 超过3次检测没有心跳就关闭这个连接
logger.info("[closed inactive channel:" + socketChannel.getRemoteAddress().getHostString() + "]");
socketChannel.close();
}
}
super.userEventTriggered(socketChannel, evt);
}
@Override
public void decode(SocketChannel socketChannel, Object obj, LinkedBlockQueue<Object> out) throws Exception {
loss_connect_time = 0;
super.decode(socketChannel, obj, out);
}
}
| 35.305085
| 114
| 0.724436
|
97250f5bf0a40cf20d2ef0b8f4238c273d4a28eb
| 1,215
|
package com.huangtao.user.model;
import java.util.ArrayList;
import java.util.List;
public class SearchResult {
int totalCount;
List<Meeting> meetings = new ArrayList<>();
List<MeetingNote> meetingNotes = new ArrayList<>();
List<User> users = new ArrayList<>();
List<MeetingRoom> meetingRooms = new ArrayList<>();
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<Meeting> getMeetings() {
return meetings;
}
public void setMeetings(List<Meeting> meetings) {
this.meetings = meetings;
}
public List<MeetingNote> getMeetingNotes() {
return meetingNotes;
}
public void setMeetingNotes(List<MeetingNote> meetingNotes) {
this.meetingNotes = meetingNotes;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<MeetingRoom> getMeetingRooms() {
return meetingRooms;
}
public void setMeetingRooms(List<MeetingRoom> meetingRooms) {
this.meetingRooms = meetingRooms;
}
}
| 20.948276
| 65
| 0.645267
|
caa2bd941028b22014f35440fd2a1433fac671a8
| 1,862
|
/*
Copyright 2000-2005 University Duisburg-Essen, Working group "Information Systems"
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.
*/
// $Id: Costs.java,v 1.6 2005/03/14 17:33:14 nottelma Exp $
package de.unidu.is.rs;
import java.util.HashMap;
import java.util.Iterator;
/**
* A class for estimated costs when retrieving of i documents,
* 1<=i<query.getNumDocs() for different cost sources.
*
* @author Henrik Nottelmann
* @version $Revision: 1.6 $, $Date: 2005/03/14 17:33:14 $
* @since 2002-06-06
*/
public class Costs extends HashMap {
/**
* Returns the costs when retrieving of i documents,
* 1<=i<query.getNumDocs() for the specified cost source.
*
* @param source cost source
* @return cost array
*/
public double[] getCosts(String source) {
return (double[]) get(source);
}
/**
* Sets the costs when retrieving of i documents,
* 1<=i<query.getNumDocs() for the specified cost source.
*
* @param source cost source
* @param costs cost array
*/
public void setCosts(String source, double[] costs) {
put(source, costs);
}
/**
* Returns the names of all cost sources for which costs are
* stored in this instance.
*
* @return iterator over cost names
*/
public Iterator costSources() {
return keySet().iterator();
}
}
| 28.212121
| 82
| 0.677229
|
4fdc60fc8e35d220a47b5acfb4d1205df4df3955
| 5,575
|
package com.yitong.ChuangKeYuan.ui;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.gson.Gson;
import com.yitong.ChuangKeYuan.Application.MyApplication;
import com.yitong.ChuangKeYuan.R;
import com.yitong.ChuangKeYuan.domain.ReturnResult;
import com.yitong.ChuangKeYuan.utils.DatasUtil;
import com.yitong.ChuangKeYuan.utils.HttpDataUtil;
import com.yitong.ChuangKeYuan.utils.ToastUtil;
import okhttp3.FormBody;
/**
* 作者:FBL 时间: 2016/9/20.
* 修改密码
*/
public class RevisePass extends Activity implements View.OnClickListener {
TextView title;
ImageView back;
EditText oldpass, newpass, agreenewpass;
Button pass_ok;
private ImageView search;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.revisepass_activity);
initView();
}
private void initView() {
title = (TextView) findViewById(R.id.tv_teach_title);
back = (ImageView) findViewById(R.id.iv_teach_back);
search = (ImageView) findViewById(R.id.iv_teach_search);
title.setText("修改密码");
back.setOnClickListener(this);
search.setVisibility(View.GONE);
oldpass = (EditText) findViewById(R.id.oldpass);
newpass = (EditText) findViewById(R.id.newpass);
agreenewpass = (EditText) findViewById(R.id.agreenewpass);
pass_ok = (Button) findViewById(R.id.pass_ok);
pass_ok.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_teach_back:
finish();
break;
case R.id.pass_ok:
String oldpassstr = oldpass.getText().toString();
String newpassstr = newpass.getText().toString();
final String agreenewpassstr = agreenewpass.getText().toString();
if ("".equals(oldpassstr) || oldpassstr == null ||
"".equals(newpassstr) || newpassstr == null ||
"".equals(agreenewpassstr) || agreenewpassstr == null) {
ToastUtil.showToast(RevisePass.this, "请依次填完");
} else {
if (!oldpassstr.equals(MyApplication.getuserpassword())) {
ToastUtil.showToast(RevisePass.this, "旧密码不正确,请重新输入!");
oldpass.setText("");
} else {
if (!newpassstr.equals(agreenewpassstr)) {
ToastUtil.showToast(RevisePass.this, "新密码两次不一致!");
newpass.setText("");
agreenewpass.setText("");
} else {
final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
ToastUtil.showToast(RevisePass.this, "修改成功");
preferences = MyApplication.getContext().getSharedPreferences("USER", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("password", agreenewpassstr);
finish();
super.handleMessage(msg);
}
};
new Thread(new Runnable() {
@Override
public void run() {
FormBody body = new FormBody.Builder()
.add("username", MyApplication.getusername())
.add("password", MyApplication.getuserpassword())
.add("newpassword", agreenewpassstr).build();
try {
String data = HttpDataUtil.getPublicData_POST(DatasUtil.URL_BASE + DatasUtil.URL_ChangePassword, body);
if (data!= null &&!"".equals(data)){
System.out.println(data);
}
Gson gson = new Gson();
ReturnResult result = gson.fromJson(data, ReturnResult.class);
if (Integer.parseInt(result.getCode()) == 0) {
Message msg = handler.obtainMessage();
handler.sendMessage(msg);
} else {
ToastUtil.showToast(RevisePass.this, "修改密码失败,请稍后再试!");
}
} catch (Exception e) {
return;
}
}
}).start();
}
}
}
break;
}
}
}
| 42.234848
| 143
| 0.489507
|
b451cbe823b10e9ed38d4da634735dec4fa39df2
| 5,947
|
/*
* Copyright 2010-2013 Hippo B.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.frontend.plugins.standards.picker;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.string.Strings;
import org.hippoecm.frontend.plugin.config.IPluginConfig;
import org.hippoecm.frontend.plugin.config.impl.JavaPluginConfig;
public class NodePickerControllerSettings implements IClusterable {
private static final long serialVersionUID = 1L;
//IPluginconfig keys
private static final String SELECTION_SERVICE_KEY = "wicket.model";
private static final String FOLDER_SERVICE_KEY = "model.folder";
public static final String BASE_UUID = "base.uuid";
public static final String BASE_PATH = "base.path";
public static final String SELECTABLE_NODETYPES = "nodetypes";
public static final String LAST_VISITED_KEY = "last.visited.key";
public static final String LAST_VISITED_ENABLED = "last.visited.enabled";
public static final String LAST_VISITED_NODETYPES = "last.visited.nodetypes";
//Default values
private static final String DEFAULT_CLUSTER = "cms-pickers/documents";
private static final String DEFAULT_LAST_VISITED_KEY = "node-picker-controller";
private static final boolean DEFAULT_LAST_VISITED_ENABLED = true;
private String clusterName;
private IPluginConfig clusterOptions;
private String selectionServiceKey;
private String folderServiceKey;
private String[] selectableNodeTypes;
private String lastVisitedKey;
private String[] lastVisitedNodeTypes;
private boolean lastVisitedEnabled;
private String defaultModelUUID;
public NodePickerControllerSettings() {
selectionServiceKey = SELECTION_SERVICE_KEY;
folderServiceKey = FOLDER_SERVICE_KEY;
clusterName = DEFAULT_CLUSTER;
lastVisitedKey = DEFAULT_LAST_VISITED_KEY;
lastVisitedEnabled = DEFAULT_LAST_VISITED_ENABLED;
}
public static NodePickerControllerSettings fromPluginConfig(final IPluginConfig config) {
NodePickerControllerSettings settings = new NodePickerControllerSettings();
settings.setClusterName(config.getString("cluster.name", DEFAULT_CLUSTER));
settings.setClusterOptions(new JavaPluginConfig(config.getPluginConfig("cluster.options")));
// enforce a unique ID for this node picker
settings.getClusterOptions().remove("wicket.id");
settings.setSelectionServiceKey(
config.getString("selection.service.key", SELECTION_SERVICE_KEY));
settings.setFolderServiceKey(
config.getString("folder.service.key", FOLDER_SERVICE_KEY));
settings.setSelectableNodeTypes(config.getStringArray(SELECTABLE_NODETYPES));
settings.setLastVisitedNodeTypes(config.getStringArray(LAST_VISITED_NODETYPES));
settings.setLastVisitedKey(config.getString(LAST_VISITED_KEY, DEFAULT_LAST_VISITED_KEY));
settings.setLastVisitedEnabled(config.getAsBoolean(LAST_VISITED_ENABLED, DEFAULT_LAST_VISITED_ENABLED));
settings.setDefaultModelUUID(config.getString(BASE_UUID, null));
return settings;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public IPluginConfig getClusterOptions() {
return clusterOptions;
}
public void setClusterOptions(IPluginConfig clusterOptions) {
this.clusterOptions = clusterOptions;
}
public String getSelectionServiceKey() {
return selectionServiceKey;
}
public void setSelectionServiceKey(String selectionServiceKey) {
this.selectionServiceKey = selectionServiceKey;
}
public String getFolderServiceKey() {
return folderServiceKey;
}
public void setFolderServiceKey(String folderServiceKey) {
this.folderServiceKey = folderServiceKey;
}
public boolean hasLastVisitedNodeTypes() {
return lastVisitedNodeTypes != null && lastVisitedNodeTypes.length > 0;
}
public String[] getLastVisitedNodeTypes() {
return lastVisitedNodeTypes;
}
public void setLastVisitedNodeTypes(String[] lastVisitedNodeTypes) {
this.lastVisitedNodeTypes = lastVisitedNodeTypes;
}
public boolean hasSelectableNodeTypes() {
return selectableNodeTypes != null && selectableNodeTypes.length > 0;
}
public String[] getSelectableNodeTypes() {
return selectableNodeTypes;
}
public void setSelectableNodeTypes(String[] selectableNodeTypes) {
this.selectableNodeTypes = selectableNodeTypes;
}
public boolean isLastVisitedEnabled() {
return lastVisitedEnabled;
}
public void setLastVisitedEnabled(boolean lastVisitedEnabled) {
this.lastVisitedEnabled = lastVisitedEnabled;
}
public String getLastVisitedKey() {
return lastVisitedKey;
}
public void setLastVisitedKey(String name) {
this.lastVisitedKey = name;
}
public String getBaseUUID() {
return defaultModelUUID;
}
public void setDefaultModelUUID(String uuid) {
this.defaultModelUUID = uuid;
}
public boolean hasBaseUUID() {
return !Strings.isEmpty(defaultModelUUID);
}
}
| 34.178161
| 112
| 0.724231
|
213cc04297fe11a2dda73a9c332fc01ad0a8ccc6
| 457
|
package com.lemilliard.mapper;
import java.util.ArrayList;
import java.util.List;
/**
* @author Thomas Kint
*/
class Dictionary {
private String type;
private List<Word> words;
String getType() {
return type;
}
List<Word> getMatches(String phrase) {
List<Word> matches = new ArrayList<>();
for (Word word : words) {
if (word.isPresentInPhrase(phrase)) {
matches.add(word);
}
}
return matches;
}
}
| 16.321429
| 42
| 0.628009
|
33ecae5effa124193da53b33a0898d1e93ea14b5
| 1,638
|
package calculator.calculate.impl;
import java.util.ArrayList;
import java.util.List;
import org.osgi.service.component.ComponentContext;
import calculator.operator.IOperator;
import calculator.calculate.ICalculate;
public class CalculateImpl implements ICalculate{
private ComponentContext context;
private List<IOperator> operators = new ArrayList<IOperator>();;
public void bindOperator(IOperator operator) {
if (operator != null) {
this.operators.add(operator);
if(operators.size() > 1) {
this.sortOperators();
}
}
}
public void unbindOperator(IOperator operator) {
this.operators.remove(operator);
}
public void sortOperators() {
for (int n = operators.size() ; n > 1; n = n - 1) {
for (int i = 0; i < operators.size()-1; i++) {
if (operators.get(i).getPriority() > operators.get(i + 1).getPriority()) {
IOperator tempOperator = operators.get(i);
operators.set(i, operators.get(i + 1));
operators.set(i + 1, tempOperator);
}
}
}
}
protected void activate(final ComponentContext cxt){
context = cxt;
}
protected void deactivate(final ComponentContext cxt){
context = null;
}
public String calculate (String x1) {
for (IOperator operator : operators) {
if (x1.contains(operator.getOperatorSymbol())) {
String x2 = x1.substring(x1.indexOf(operator.getOperatorSymbol()) + 2);
x1 = x1.substring(0, x1.indexOf(operator.getOperatorSymbol()));
x1 = String.valueOf(operator.calculate(Double.parseDouble(calculate(x1)), Double.parseDouble(calculate(x2))));
}
}
return x1;
}
}
| 27.3
| 115
| 0.672772
|
8cfb5bcb6335682b51f475895a337e83f9deb053
| 1,645
|
/*
Foilen Infra Plugins Core
https://github.com/foilen/foilen-infra-plugins-core
Copyright (c) 2018-2021 Foilen (https://foilen.com)
The MIT License
http://opensource.org/licenses/MIT
*/
package com.foilen.infra.resource.global;
import com.foilen.infra.plugin.v1.core.visual.editor.simpleresourceditor.SimpleResourceEditor;
import com.foilen.infra.plugin.v1.core.visual.editor.simpleresourceditor.SimpleResourceEditorDefinition;
import com.foilen.infra.plugin.v1.core.visual.helper.CommonFormatting;
import com.foilen.infra.plugin.v1.core.visual.helper.CommonValidation;
public class UpgraderItemEditor extends SimpleResourceEditor<UpgraderItem> {
public static final String EDITOR_NAME = "Upgrader Item";
@Override
protected void getDefinition(SimpleResourceEditorDefinition simpleResourceEditorDefinition) {
simpleResourceEditorDefinition.addInputText(UpgraderItem.PROPERTY_NAME, fieldConfigConsumer -> {
fieldConfigConsumer.addFormator(CommonFormatting::trimSpacesAround);
fieldConfigConsumer.addValidator(CommonValidation::validateNotNullOrEmpty);
fieldConfigConsumer.addValidator(CommonValidation::validateAlphaNumLowerAndUpper);
});
simpleResourceEditorDefinition.addListInputText(UpgraderItem.PROPERTY_APPLIED, fieldConfigConsumer -> {
fieldConfigConsumer.addFormator(CommonFormatting::trimSpacesAround);
fieldConfigConsumer.addValidator(CommonValidation::validateNotNullOrEmpty);
});
}
@Override
public Class<UpgraderItem> getForResourceType() {
return UpgraderItem.class;
}
}
| 38.255814
| 111
| 0.772644
|
2ea140942cf1946d1f0e8ea1d417df4fa013dd4e
| 419
|
package com.hashicraft.nomad.util;
import net.minecraft.util.StringIdentifiable;
public enum NodeStatus implements StringIdentifiable {
READY("ready"),
DOWN("down"),
ERROR("error");
private final String name;
private NodeStatus(String name) {
this.name = name;
}
public String asString() {
return this.name;
}
public static NodeStatus asEnum(String name) {
return valueOf(name.toUpperCase());
}
}
| 17.458333
| 54
| 0.73031
|
559dd7ff8c047b830b303b97f266a370e3b24c56
| 8,103
|
/**
* Copyright 2011 Francisco Ernesto Teixeira e Jady Pâmella Barbacena
* 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 br.org.olimpiabarbacena.client.formulario;
import br.org.olimpiabarbacena.client.Principal;
import br.org.olimpiabarbacena.client.rpc.MembroService;
import br.org.olimpiabarbacena.client.rpc.MembroServiceAsync;
import br.org.olimpiabarbacena.shared.InputValidator;
import br.org.olimpiabarbacena.shared.dados.Sexo;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;
/**
* <p>
* Este é o formulário para inserção e
* edição de Membro.
* </p>
* <p>
* Esta classe está no pacote <code>formulario</code> porque é
* onde se encontram todos os formulários do cliente. No cliente,
* nós permitimos o fornecimento de informações para serem
* enviados por uma requisição RPC. No servidor, nós
* inserimos os dados fornecidos caso não possua uma
* identificação ou salvamos caso exista uma
* identificação.
* </p>
*/
public class Membro extends Composite {
private static MembroUiBinder uiBinder = GWT.create(MembroUiBinder.class);
@UiField
Hidden hiddenId;
@UiField
TextBox textboxNome;
@UiField
DateBox dateboxNascimento;
@UiField
RadioButton radioSexoMasculino;
@UiField
RadioButton radioSexoFeminino;
@UiField
TextBox textboxCPF;
@UiField
TextBox textboxTelefone;
@UiField
TextBox textboxEmail;
@UiField
TextBox textboxEndereco;
@UiField
TextBox textboxCidade;
@UiField
ListBox comboEstado;
@UiField
TextBox textboxCEP;
@UiField
public Button buttonHistorico;
@UiField
public Button buttonSalvar;
@UiField
public Button buttonFechar;
Principal principal;
DialogBox dialogo;
private final MembroServiceAsync membroService = GWT
.create(MembroService.class);
interface MembroUiBinder extends UiBinder<Widget, Membro> {
}
public Membro(Principal principal, DialogBox dialogo) {
this.principal = principal;
this.dialogo = dialogo;
initWidget(uiBinder.createAndBindUi(this));
dateboxNascimento.setFormat(new DateBox.DefaultFormat(DateTimeFormat
.getFormat("dd/MM/yyyy")));
// Let's disallow non-numeric entry in the normal text box.
textboxCPF.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (!InputValidator.isInteger(event.getCharCode())) {
// TextBox.cancelKey() suppresses the current keyboard
((TextBox) event.getSource()).cancelKey();
}
}
});
// Let's disallow non-numeric entry in the normal text box.
textboxCEP.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
if (!InputValidator.isInteger(event.getCharCode())) {
// TextBox.cancelKey() suppresses the current keyboard
((TextBox) event.getSource()).cancelKey();
}
}
});
// adiciona a lista dos estados brasileiros
comboEstado.addItem("AC");
comboEstado.addItem("AL");
comboEstado.addItem("AP");
comboEstado.addItem("AM");
comboEstado.addItem("BA");
comboEstado.addItem("CE");
comboEstado.addItem("DF");
comboEstado.addItem("ES");
comboEstado.addItem("GO");
comboEstado.addItem("MA");
comboEstado.addItem("MT");
comboEstado.addItem("MS");
comboEstado.addItem("MG");
comboEstado.addItem("PA");
comboEstado.addItem("PB");
comboEstado.addItem("PR");
comboEstado.addItem("PE");
comboEstado.addItem("PI");
comboEstado.addItem("RJ");
comboEstado.addItem("RN");
comboEstado.addItem("RS");
comboEstado.addItem("RO");
comboEstado.addItem("RR");
comboEstado.addItem("SC");
comboEstado.addItem("SP");
comboEstado.addItem("SE");
comboEstado.addItem("TO");
}
public void get(String id) {
membroService
.obter(id,
new AsyncCallback<br.org.olimpiabarbacena.shared.dados.Membro>() {
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(
br.org.olimpiabarbacena.shared.dados.Membro membro) {
if (membro != null) {
hiddenId.setValue(membro.getId());
textboxNome.setText(membro.getNome());
dateboxNascimento.setValue(membro
.getNascimento());
switch (membro.getSexo().ordinal()) {
case 0: // Sexo.MASCULINO
radioSexoMasculino.setValue(true);
radioSexoFeminino.setValue(false);
break;
case 1: // Sexo.FEMININO
radioSexoMasculino.setValue(false);
radioSexoFeminino.setValue(true);
break;
}
textboxCPF.setValue(membro.getCPF());
textboxTelefone.setValue(membro
.getTelefone());
textboxEmail.setValue(membro.getEmail());
textboxEndereco.setValue(membro
.getEndereco());
textboxCidade.setValue(membro.getCidade());
for (int index = 0; index < comboEstado
.getItemCount(); index++) {
if (comboEstado.getItemText(index)
.equals(membro.getEstado())) {
comboEstado.setSelectedIndex(index);
break;
}
}
textboxCEP.setValue(membro.getCEP());
}
}
});
}
@UiHandler("buttonSalvar")
void onButtonSalvarClick(ClickEvent event) {
br.org.olimpiabarbacena.shared.dados.Membro membro = new br.org.olimpiabarbacena.shared.dados.Membro();
membro.setId(hiddenId.getValue());
membro.setNome(textboxNome.getText());
membro.setNascimento(dateboxNascimento.getValue());
if (radioSexoMasculino.getValue()) {
membro.setSexo(Sexo.MASCULINO);
} else {
membro.setSexo(Sexo.FEMININO);
}
membro.setCPF(textboxCPF.getText());
membro.setTelefone(textboxTelefone.getText());
membro.setEmail(textboxEmail.getText());
membro.setEndereco(textboxEndereco.getText());
membro.setCidade(textboxCidade.getText());
membro.setEstado(comboEstado.getItemText(comboEstado.getSelectedIndex()));
membro.setCEP(textboxCEP.getText());
membroService.salvar(membro, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
}
@Override
public void onSuccess(Void result) {
principal.getPesquisar().limpar();
principal.getPesquisar().listarMembro();
dialogo.hide();
}
});
}
@UiHandler("buttonFechar")
void onButtonFecharClick(ClickEvent event) {
dialogo.hide();
}
}
| 32.282869
| 106
| 0.694928
|
6cff972b47e78a0221a38642848133a220cb9482
| 664
|
package com.vshow.vshowapp.download;
/**
* 下载监听�?
*
* @author liupeng
*
*/
public interface DownloadListener<T extends DownloadBaseTask> {
/**
* 下载前
*
* @param task
*/
public void onPreDownload(T task);
/**
* 下载开始
*
* @param task
*/
public void onStartDownload(T task);
/**
* 下载中更新下载进度
*
* @param task
* @param progress
* 当前进度
* @param maxProgress
* 最大进度
*/
public void onUpdateProgress(T task, int progress, int maxProgress);
/**
* 下载完成
*
* @param task
*/
public void onFinish(T task);
/**
* 下载出错
*
* @param task
*/
public void onError(T task, String errorMsg);
}
| 13.019608
| 69
| 0.575301
|
a5438eac59a3126a15e1ff19e61076de6dcd7b8d
| 5,682
|
/*
* This project is licensed as below.
*
* **************************************************************************
*
* Copyright 2020-2022 Intel Corporation. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* **************************************************************************
*
*/
package com.intel.bkp.crypto.ecdh;
import com.intel.bkp.crypto.CryptoUtils;
import com.intel.bkp.crypto.exceptions.EcdhKeyPairException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import java.security.KeyPair;
/**
* Unit tests for the EcdhKeyPairTest class.
*
* @see EcdhKeyPair
*/
/*
* This project is licensed as below.
*
* **************************************************************************
*
* Copyright 2020-2022 Intel Corporation. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* **************************************************************************
*
*/
@ExtendWith(MockitoExtension.class)
public class EcdhKeyPairTest {
@Test
public void generate_ReturnObject() throws EcdhKeyPairException {
// when
final EcdhKeyPair result = EcdhKeyPair.generate();
// then
Assertions.assertNotNull(result);
Assertions.assertNotNull(result.getPrivateKey());
Assertions.assertNotNull(result.getPublicKey());
}
@Test
public void fromKeyPair_ReturnValidObject() throws Exception {
// given
KeyPair keyPair = CryptoUtils.genEcdhBC();
// when
final EcdhKeyPair ecdhKeyPair = EcdhKeyPair.fromKeyPair(keyPair);
// then
Assertions.assertNotNull(ecdhKeyPair);
Assertions.assertNotNull(ecdhKeyPair.getPrivateKey());
Assertions.assertNotNull(ecdhKeyPair.getPublicKey());
}
@Test
public void fromKeyPair_NullKeyPair_ThrowException() {
// given
final KeyPair keyPair = null;
// when
Assertions.assertThrows(EcdhKeyPairException.class, () -> EcdhKeyPair.fromKeyPair(keyPair));
}
@Test
public void fromBytes_ValidPub_ReturnValidObject() throws EcdhKeyPairException {
// given
final byte[] gaBytes = new byte[]{1, 2, 3, 4};
// when
EcdhKeyPair ecdhKeyPair = EcdhKeyPair.fromPublicBytes(gaBytes);
// then
Assertions.assertNotNull(ecdhKeyPair);
Assertions.assertNotNull(ecdhKeyPair.getPublicKey());
Assertions.assertArrayEquals(gaBytes, ecdhKeyPair.getPublicKey());
Assertions.assertNull(ecdhKeyPair.getPrivateKey());
}
@Test
public void fromBytes_NullPubKey_ThrowException() {
// given
byte[] gaBytes = null;
// when
Assertions.assertThrows(EcdhKeyPairException.class, () -> EcdhKeyPair.fromPublicBytes(gaBytes));
}
@Test
public void fromBytes_EmptyPubKey_ThrowException() {
// given
byte[] gaBytes = new byte[0];
// when
Assertions.assertThrows(EcdhKeyPairException.class, () -> EcdhKeyPair.fromPublicBytes(gaBytes));
}
}
| 36.658065
| 104
| 0.687786
|
469a72decff93fcfe7901b14fc2f2b37c22c0b59
| 2,099
|
/*******************************************************************************
* Copyright 2019 Huawei Technologies Co., Ltd.
*
* 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.huawei.openstack.sample.v1;
import com.huawei.openstack4j.api.OSClient.OSClientV3;
import com.huawei.openstack4j.model.common.ActionResponse;
import com.huawei.openstack4j.model.common.Identifier;
import com.huawei.openstack4j.openstack.OSFactory;
import com.huawei.openstack4j.openstack.bms.v1.domain.VolumeAttachment;
public class VolumeDemo {
public static void main(String[] args) {
String user = "******";
String password = "******";
String projectId = "******";
String userDomainId = "******";
String authUrl = "******";
OSClientV3 osclient = OSFactory.builderV3().endpoint(authUrl)
.credentials(user, password, Identifier.byId(userDomainId)).scopeToProject(Identifier.byId(projectId))
.authenticate();
String serverId = "******";
String volumeId = "******";
String device = "******";
//1.bms detach Volume
ActionResponse detachVolume = osclient.bms().servers().detachVolume(serverId, volumeId);
System.out.println(detachVolume);
System.out.println("detach Volume success...");
//2.bms attach Volume
VolumeAttachment volume = new VolumeAttachment(volumeId,device);
ActionResponse attachVolume = osclient.bms().servers().attachVolume(serverId, volume);
System.out.println(attachVolume);
System.out.println("attach Volume success...");
}
}
| 38.87037
| 106
| 0.667461
|
e5d295f18e4d518bfd0af5ed4cba33fd17e3b094
| 3,329
|
package org.sfvl.doctesting.utils;
import org.sfvl.docformatter.Formatter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
public class Config {
public static final String DEFAULT_CONFIGURATION_FILE = "docAsTest.properties";
public static final String DOC_PATH_TAG = "ROOT_PATH";
static enum Key {
/** Path of source code. */
SOURCE_PATH,
/** Path of test code. */
TEST_PATH,
/** Path where documentation is generated. */
DOC_PATH,
/** Path of resources. */
RESOURCE_PATH,
/** Full qualified name of the formatter class. */
FORMATTER;
}
private static Config instance = new Config();
public static final Path SOURCE_PATH = instance.getSourcePath();
public static final Path TEST_PATH = instance.getTestPath();
public static final Path DOC_PATH = instance.getDocPath();
public static final Path RESOURCE_PATH = instance.getResourcePath();
public static final Formatter FORMATTER = instance.getFormatter();
private Properties prop = new Properties();
public Config() {
this(DEFAULT_CONFIGURATION_FILE);
}
public Config(String configFile) {
setDefaultProperties();
loadProperties(configFile);
}
private Path getSourcePath() {
return getPath(Key.SOURCE_PATH);
}
private Path getTestPath() {
return getPath(Key.TEST_PATH);
}
private Path getDocPath() {
return getPath(Key.DOC_PATH);
}
private Path getResourcePath() {
return getPath(Key.RESOURCE_PATH);
}
private Formatter getFormatter() {
final String property = getProperty(Key.FORMATTER);
try {
final Class<?> classFormatter = Class.forName(property);
return (Formatter) classFormatter.getConstructor().newInstance();
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(String.format("Unable to instantiate formatter from `̀%s`", property), e);
}
}
Path getPath(Key key) {
return Paths.get(getProperty(key));
}
String getProperty(Key key) {
return prop.getProperty(key.name());
}
private void setDefaultProperties() {
prop.setProperty(Key.SOURCE_PATH.name(), Paths.get("src", "main", "java").toString());
prop.setProperty(Key.TEST_PATH.name(), Paths.get("src", "test", "java").toString());
prop.setProperty(Key.DOC_PATH.name(), Paths.get("src", "test", "docs").toString());
prop.setProperty(Key.RESOURCE_PATH.name(), Paths.get("src", "test", "resources").toString());
prop.setProperty(Key.FORMATTER.name(), "org.sfvl.docformatter.asciidoc.AsciidocFormatter");
}
private void loadProperties(String name) {
try (InputStream input = Config.class.getClassLoader().getResourceAsStream(name)) {
if (input != null) {
prop.load(input);
}
} catch (IOException ex) {
throw new RuntimeException("Error loading resource file " + name, ex);
}
}
}
| 32.320388
| 146
| 0.654851
|
4e219f4b100c3454a8d747f52ad7c2dd6e5c2111
| 3,038
|
package game.block;
import static java.lang.Math.*;
import static util.MathUtil.*;
import util.BmpRes;
import game.world.*;
import game.entity.*;
import game.item.*;
import java.io.*;
import graphics.Canvas;
public abstract class CircuitBlock extends Block{
private static final long serialVersionUID=1844677L;
Block block;
CircuitBlock(Block _block){
block=_block;
}
@Override
public boolean isDeep(){return block.isDeep();}
public boolean ins(int x,int y,int v,int vs){return false;}
public Block rootBlock(){return block;}
//basic info and event
int maxDamage(){return block.maxDamage();}
public int mass(){return block.mass();}
public double transparency(){return block.transparency();}
public double light(){return block.light();}
public boolean isCoverable(){return block.isCoverable();}//return whether you can place a block on the position of "this"
public boolean isSolid(){return block.isSolid();}
//public void onFall(game.entity.FallingBlock b){}
public void onPlace(int x,int y){block.onPlace(x,y);}
public void onLight(int x,int y,double v){block.onLight(x,y,v);}
public void onPress(int x,int y,Item item){block.onPress(x,y,item);}
public boolean onClick(int x,int y,Agent agent){return block.onClick(x,y,agent);}
@Override
public void onOverlap(int x,int y,Entity ent,double k){
block.onOverlap(x,y,ent,k);
}
public boolean onSpannerClick(int x,int y){
onCircuitDestroy(x,y);
World.cur.set(x,y,rootBlock());
return true;
}
public boolean onCheck(int x,int y){
if(block.onCheck(x,y)){
onCircuitDestroy(x,y);
return true;
}
return false;
}
public boolean onUpdate(int x,int y){
if(block.onUpdate(x,y)){
onCircuitDestroy(x,y);
return true;
}
return false;
}
protected void des(int x,int y,int v){block.des(x,y,v);}
public void onDestroy(int x,int y){
block.onDestroy(x,y);
onCircuitDestroy(x,y);
}
abstract public void onCircuitDestroy(int x,int y);
@Override
public String getName(){return block.getName();}
//fire
public int fuelVal(){return block.fuelVal();}
public int heatingTime(boolean in_furnace){return block.heatingTime(in_furnace);}
public Item heatingProduct(boolean in_furnace){return block.heatingProduct(in_furnace);}
public void onFireUp(int x,int y){block.onFireUp(x,y);}
public void onBurn(int x,int y){block.onBurn(x,y);}
public void onDestroyByFire(int x,int y){block.onDestroyByFire(x,y);}
//energy
public int energyValL(){return block.energyValL();}
public int energyValR(){return block.energyValR();}
public int energyValD(){return block.energyValD();}
public int energyValU(){return block.energyValU();}
public final boolean circuitCanBePlaced(){return false;}
//physics
double friction(){return block.friction();}
public void touchEnt(int x,int y,Entity ent){block.touchEnt(x,y,ent);}
public double getJumpAcc(){return block.getJumpAcc();}
public double hardness(){return block.hardness();}
//draw
public BmpRes getBmp(){return block.getBmp();}
public void draw(Canvas cv){block.draw(cv);}
};
| 31.978947
| 122
| 0.73239
|
311b25cf29c748311878c425c83398a6584dd211
| 6,570
|
package com.ewgvip.buyer.android.fragment;
import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import com.ewgvip.buyer.android.R;
import com.ewgvip.buyer.android.activity.BaseActivity;
import com.ewgvip.buyer.android.utils.CommonUtil;
import com.ewgvip.buyer.android.utils.FastDoubleClickTools;
import com.ewgvip.buyer.android.utils.MySingleRequestQueue;
import com.ewgvip.buyer.android.volley.NormalPost3Request;
import com.ewgvip.buyer.android.volley.NormalPostRequest;
import com.ewgvip.buyer.android.volley.Request;
import com.ewgvip.buyer.android.volley.RequestQueue;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* A simple {@link Fragment} subclass.
*/
public class BindNewBankCardFragment extends Fragment {
private static BindNewBankCardFragment fragment;
private BaseActivity mActivity;
private View rootView;
private SharedPreferences preferences;
private String pay_password;
@Override
public void onAttach(Context context) {
super.onAttach(context);
}
@Override
public void onDetach() {
super.onDetach();
this.rootView = null;
}
public BindNewBankCardFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mActivity = (BaseActivity)getActivity();
rootView = inflater.inflate(R.layout.fragment_bind_new_bank_card, container, false);
preferences = mActivity.getSharedPreferences("user", Context.MODE_PRIVATE);
initView();
return rootView;
}
private void initView() {
//返回键
ImageView iv_back = (ImageView) rootView.findViewById(R.id.iv_back);
iv_back.setOnClickListener(v -> {
if (FastDoubleClickTools.isFastDoubleClick()) {
mActivity.onBackPressed();
mActivity.hide_keyboard(v);
}
});
//保存
rootView.findViewById(R.id.bt_save_bind_bank_card_info).setOnClickListener(v -> save());
}
private void save() {
EditText et_my_name = (EditText) rootView.findViewById(R.id.et_my_name);
EditText et_my_bank_card_number = (EditText) rootView.findViewById(R.id.et_my_bank_card_number);
EditText et_pay_passord = (EditText) rootView.findViewById(R.id.et_pay_passord);
EditText et_bank_bind_phone = (EditText) rootView.findViewById(R.id.et_bank_bind_phone);
final String user_name = et_my_name.getText().toString().trim();
final String card_number = et_my_bank_card_number.getText().toString().trim();
final String passwd = et_pay_passord.getText().toString().trim();
final String mobile = et_bank_bind_phone.getText().toString().trim();
if (TextUtils.isEmpty(user_name)){
CommonUtil.showSafeToast(mActivity,"持卡人姓名不能为空,请输入哦");
return;
}
if (TextUtils.isEmpty(passwd)){
CommonUtil.showSafeToast(mActivity,"支付密码姓名不能为空,请输入哦");
return;
}
if (TextUtils.isEmpty(mobile)){
CommonUtil.showSafeToast(mActivity, "手机号不能为空,请输入哦");
return;
}
if (TextUtils.isEmpty(card_number)){
CommonUtil.showSafeToast(mActivity,"银行卡号不能为空,请输入哦");
return;
}else{
final Map paramap = new HashMap();
paramap.put("card_number", card_number);
final RequestQueue mRequestQueue = MySingleRequestQueue.getInstance(mActivity).getRequestQueue();
Request<Boolean> requestVerifyBankCard=new NormalPost3Request(mActivity, getResources().getString(R.string.http_url) + "/verify_bankcard.htm", response -> {
if (response.toString().equals("true")){
if (mobile.matches("1[3|4|5|7|8|][0-9]{9}")){
String user_id = preferences.getString("user_id", "");
String token = preferences.getString("token", "");
Map paraMap = new HashMap();
paraMap.put("user_id", user_id);
paraMap.put("token", token);
paraMap.put("user_name", user_name);
paraMap.put("card_number", card_number);
paraMap.put("passwd",passwd);
paraMap.put("mobile", mobile);
Request<JSONObject> request =new NormalPostRequest(mActivity, getResources().getString(R.string.http_url) + "/app/save_bankcard.htm", response1 -> {
try {
String ret = response1.get("ret").toString();
if (ret.equals("1")){
CommonUtil.showSafeToast(mActivity, "保存成功");
mActivity.go_to_my_bank_card();
}else if(ret.equals("-1")){
CommonUtil.showSafeToast(mActivity, "登录异常,请重新登录");
mActivity.go_login();
}else if(ret.equals("-4")){
CommonUtil.showSafeToast(mActivity,"银行卡已经绑定");
}else if(ret.equals("-5")){
CommonUtil.showSafeToast(mActivity,"银行卡号错,请输入正确的银行卡号,再次提交");
}else if(ret.equals("-3")){
CommonUtil.showSafeToast(mActivity,"支付密码错误");
}else {
CommonUtil.showSafeToast(mActivity,"信息不全");
}
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> Log.i("test",error.toString()),paraMap);
mRequestQueue.add(request);
}
}else {
CommonUtil.showSafeToast(mActivity,"银行卡号错误,请检查重新输入哦");
}
}, error -> Log.i("test",error.toString()),paramap);
mRequestQueue.add(requestVerifyBankCard);
}
}
}
| 39.818182
| 172
| 0.586149
|
bd185e5023dcdbdfc9d377d8d3fb5dd31ff59bc3
| 6,109
|
// Copyright (C) 2014 Guibing Guo
//
// This file is part of LibRec.
//
// LibRec is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// LibRec is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with LibRec. If not, see <http://www.gnu.org/licenses/>.
//
package i5.las2peer.services.recommender.librec.main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import i5.las2peer.services.recommender.librec.util.FileIO;
import i5.las2peer.services.recommender.librec.util.Logs;
import i5.las2peer.services.recommender.librec.util.Strings;
import i5.las2peer.services.recommender.librec.util.Systems;
/**
* A demo created for the UMAP'15 demo session, could be useful for other users.
*
* @author Guo Guibing
*
*/
public class Demo {
public static void main(String[] args) {
try {
new Demo().execute(args);
} catch (Exception e) {
e.printStackTrace();
}
}
public void execute(String[] args) throws Exception {
// config logger
String dirPath = FileIO.makeDirPath("demo");
Logs.config(dirPath + "log4j.xml", true);
// set the folder path for configuration files
String configDirPath = FileIO.makeDirPath(dirPath, "config");
// prepare candidate options
List<String> candOptions = new ArrayList<>();
candOptions.add("General Usage:");
candOptions.add(" 0: the format of rating prediction results;");
candOptions.add(" 1: the format of item recommendation results;");
candOptions.add(" 2: run an algorithm by name [Input: 2 algoName];");
candOptions.add(" 3: help & about this demo;");
candOptions.add("-1: quit the demo!");
candOptions.add("");
candOptions.add("Part I: baselines");
candOptions.add("10: Global Average; 11: User Average; 12: Item Average;");
candOptions.add("13: Most Popularity; 14: User Cluster; 15: Item Cluster;");
candOptions.add("16: Association Rule; 17: Non-neg MF; 18: Slope One;");
candOptions.add("");
candOptions.add("Part II: rating prediction");
candOptions.add("20: UserKNN;\t 21: ItemKNN; \t 22: TrustSVD; ");
candOptions.add("23: RegSVD; \t 24: BiasedMF;\t 25: SVD++; ");
candOptions.add("");
candOptions.add("Part III: item recommendation");
candOptions.add("30: LDA; \t 31: BPR; \t 32: FISM; ");
candOptions.add("33: WRMF; \t 34: SLIM; \t 35: RankALS. ");
int option = 0;
boolean flag = false;
Scanner reader = new Scanner(System.in);
String configFile = "librec.conf";
do {
Logs.debug(Strings.toSection(candOptions));
System.out.print("Please choose your command id: ");
option = reader.nextInt();
// print an empty line
Logs.debug();
flag = false;
// get algorithm-specific configuration file
switch (option) {
case 10:
configFile = "GlobalAvg.conf";
break;
case 11:
configFile = "UserAvg.conf";
break;
case 12:
configFile = "ItemAvg.conf";
break;
case 13:
configFile = "MostPop.conf";
break;
case 14:
configFile = "UserCluster.conf";
break;
case 15:
configFile = "ItemCluster.conf";
break;
case 16:
configFile = "AR.conf";
break;
case 17:
configFile = "NMF.conf";
break;
case 18:
configFile = "SlopeOne.conf";
break;
case 20:
configFile = "UserKNN.conf";
break;
case 21:
configFile = "ItemKNN.conf";
break;
case 22:
configFile = "TrustSVD.conf";
break;
case 23:
configFile = "RegSVD.conf";
break;
case 24:
configFile = "BiasedMF.conf";
break;
case 25:
configFile = "SVD++.conf";
break;
case 30:
configFile = "LDA.conf";
break;
case 31:
configFile = "BPR.conf";
break;
case 32:
configFile = "FISM.conf";
break;
case 33:
configFile = "WRMF.conf";
break;
case 34:
configFile = "SLIM.conf";
break;
case 35:
configFile = "RankALS.conf";
break;
case -1:
flag = true;
break;
case 0:
Logs.debug("Prediction results: MAE, RMSE, NMAE, rMAE, rRMSE, MPE, <configuration>, training time, test time\n");
Systems.pause();
continue;
case 1:
Logs.debug("Ranking results: Prec@5, Prec@10, Recall@5, Recall@10, AUC, MAP, NDCG, MRR, <configuration>, training time, test time\n");
Systems.pause();
continue;
case 2:
// System.out.print("Please input the method name: ");
String algoName = reader.next().trim();
configFile = algoName + ".conf";
break;
case 3:
StringBuilder about = new StringBuilder();
about.append("About. This demo was created by Guo Guibing, the author of the LibRec library.\n")
.append("It is based on LibRec-v1.3 (http://www.librec.net/). Although initially designed\n")
.append("for a demo session at UMAP'15, it may be useful for those who want to take a \n")
.append("quick trial of LibRec. Source code: https://github.com/guoguibing/librec.\n\n")
.append("Usage. To run a predefined recommender, simply choose a recommender id.\n")
.append("To run a customized recommender, give the input '2 algoName' (e.g., '2 RegSVD').\n")
.append("For case 2, make sure you have a configuration file named by 'algoName.conf'\n");
Logs.debug(about.toString());
Systems.pause();
continue;
default:
Logs.error("Wrong input id!\n");
Systems.pause();
continue;
}
if (flag)
break;
// run algorithm
LibRecDemo librec = new LibRecDemo();
librec.setConfigFiles(configDirPath + configFile);
librec.execute(args);
// await next command
Logs.debug();
Systems.pause();
} while (option != -1);
reader.close();
Logs.debug("Thanks for trying out LibRec! See you again!");
}
}
| 29.229665
| 138
| 0.659682
|
4ca93b8812077202e8fa37353a561252d7629abd
| 2,641
|
package org.hy.common.report.bean;
/**
* 系统变量信息
*
* @author ZhengWei(HY)
* @createDate 2017-03-28
* @version v1.0
* v2.0 2020-04-10 添加:在多个不同模板,以追加模式写入时,对模板中图片作偏移量的修正。
*/
public class RSystemValue
{
/** 数据行号的变量名称。下标从1开始 */
private int rowNo;
/** 数据总量的变量名称 */
private int rowCount;
/** 数据小计总量的变量名称 */
private int rowSubtotalCount;
/** 分页页号的变量名称。下标从1开始 */
private int pageNo;
/** 分页总页数的变量名称 */
private int pageSize;
/** 追加模式下的,记录追加前已有数据的最大行号。下标从0开始。默认为:0 */
private int appendStartRowIndex;
public RSystemValue()
{
this.appendStartRowIndex = 0;
}
/**
* 获取:数据行号的变量名称。下标从1开始
*/
public int getRowNo()
{
return rowNo;
}
/**
* 设置:数据行号的变量名称。下标从1开始
*
* @param rowNo
*/
public void setRowNo(int rowNo)
{
this.rowNo = rowNo;
}
/**
* 获取:数据索引号的变量名称。下标从0开始
*/
public int getRowIndex()
{
return this.rowNo - 1;
}
/**
* 获取:数据总量的变量名称
*/
public int getRowCount()
{
return rowCount;
}
/**
* 设置:数据总量的变量名称
*
* @param rowCount
*/
public void setRowCount(int rowCount)
{
this.rowCount = rowCount;
}
/**
* 获取:数据小计总量的变量名称
*/
public int getRowSubtotalCount()
{
return rowSubtotalCount;
}
/**
* 设置:数据小计总量的变量名称
*
* @param rowSubtotalCount
*/
public void setRowSubtotalCount(int rowSubtotalCount)
{
this.rowSubtotalCount = rowSubtotalCount;
}
/**
* 获取:分页页号的变量名称。下标从1开始
*/
public int getPageNo()
{
return pageNo;
}
/**
* 设置:分页页号的变量名称。下标从1开始
*
* @param pageNo
*/
public void setPageNo(int pageNo)
{
this.pageNo = pageNo;
}
/**
* 获取:分页总页数的变量名称
*/
public int getPageSize()
{
return pageSize;
}
/**
* 设置:分页总页数的变量名称
*
* @param pageSize
*/
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}
/**
* 获取:追加模式下的,记录追加前已有数据的最大行号。下标从0开始。默认为:0
*/
public int getAppendStartRowIndex()
{
return appendStartRowIndex;
}
/**
* 设置:追加模式下的,记录追加前已有数据的最大行号。下标从0开始。默认为:0
*
* @param appendStartRowIndex
*/
public void setAppendStartRowIndex(int appendStartRowIndex)
{
this.appendStartRowIndex = appendStartRowIndex;
}
}
| 15.265896
| 68
| 0.509655
|
1f17f552e53cfd197f1766f9e6c145ea14d600ba
| 605
|
package com.github.donmahallem.common.recycler.model;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
public class OffsetDateTimeConverter {
private final static DateTimeFormatter mFormatter=DateTimeFormatter.ISO_OFFSET_DATE_TIME;
public static OffsetDateTime toDate(String value) {
if(value==null)
return null;
return OffsetDateTime.from(mFormatter.parse(value));
}
public static String toLong(OffsetDateTime value) {
if(value==null)
return null;
return value.format(mFormatter);
}
}
| 30.25
| 94
| 0.720661
|
b0f9c67b6df5f802b1b798e78d5d20479c67488d
| 2,355
|
package com.reporting.mocks.controllers;
import com.reporting.mocks.configuration.Configurations;
import com.reporting.mocks.configuration.PricingGroupConfig;
import com.reporting.mocks.interfaces.persistence.IPersistenceStoreFactory;
import com.reporting.mocks.interfaces.persistence.ITradePopulation;
import com.reporting.mocks.interfaces.persistence.ITradeStore;
import com.reporting.mocks.model.PricingGroup;
import com.reporting.mocks.model.id.TradePopulationId;
import com.reporting.mocks.model.trade.Trade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
@RestController
public class TradeController {
@Autowired
IPersistenceStoreFactory<ITradeStore> tradeStoreFactory;
@Autowired
Configurations configurations;
@Autowired
public TradeController(IPersistenceStoreFactory<ITradeStore> tradeStoreFactory) {
this.tradeStoreFactory = tradeStoreFactory;
}
@GetMapping("/tradepopulations/{pricingGroupName}")
public List<TradePopulationId> tradePopulations(@PathVariable String pricingGroupName) {
PricingGroupConfig pricingGroupConfig = this.configurations.getPricingGroup(pricingGroupName);
if (pricingGroupConfig != null) {
ITradeStore store = this.tradeStoreFactory.get(pricingGroupConfig.getPricingGroupId());
if (store != null) {
return store.getTradePopulationsIds();
}
}
return new ArrayList<>();
}
@GetMapping("/tradepopulation/{pricingGroupName}/{id}")
public Collection<Trade> tradePopulation(@PathVariable String pricingGroupName, @PathVariable UUID id) {
PricingGroupConfig pricingGroupConfig = this.configurations.getPricingGroup(pricingGroupName);
if (pricingGroupConfig != null) {
ITradeStore store = this.tradeStoreFactory.get(pricingGroupConfig.getPricingGroupId());
if (store != null) {
ITradePopulation tradePopulation = store.getTradePopulationById(new TradePopulationId(pricingGroupName, id));
if (tradePopulation != null)
return tradePopulation.getTrades();
}
}
return new ArrayList<>();
}
}
| 40.603448
| 125
| 0.738854
|
6cd9b9b1d16ff39f4c1283719b8dea03f741b09d
| 5,756
|
/*
* Copyright 2014-2018 Groupon, Inc
* Copyright 2014-2018 The Billing Project, LLC
*
* The Billing Project 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.killbill.billing.beatrix.integration.db;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import javax.inject.Inject;
import org.joda.time.DateTime;
import org.killbill.billing.account.api.Account;
import org.killbill.billing.api.TestApiListener.NextEvent;
import org.killbill.billing.beatrix.integration.TestIntegrationBase;
import org.killbill.billing.callcontext.DefaultTenantContext;
import org.killbill.billing.catalog.api.BillingPeriod;
import org.killbill.billing.catalog.api.ProductCategory;
import org.killbill.billing.entitlement.api.DefaultEntitlement;
import org.killbill.billing.notification.plugin.api.ExtBusEvent;
import org.killbill.billing.osgi.api.ROTenantContext;
import org.killbill.billing.util.callcontext.TenantContext;
import org.killbill.bus.api.PersistentBus.EventBusException;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.eventbus.Subscribe;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.awaitility.Awaitility.await;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
public class TestDBRouter extends TestIntegrationBase {
@Inject
private TestDBRouterAPI testDBRouterAPI;
private PublicListener publicListener;
private AtomicInteger externalBusCount;
@Override
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
if (hasFailed()) {
return;
}
super.beforeMethod();
this.externalBusCount = new AtomicInteger(0);
testDBRouterAPI.reset();
}
@Override
protected void registerHandlers() throws EventBusException {
super.registerHandlers();
publicListener = new PublicListener();
externalBus.register(publicListener);
}
@AfterMethod(groups = "slow")
public void afterMethod() throws Exception {
if (hasFailed()) {
return;
}
externalBus.unregister(publicListener);
super.afterMethod();
}
@Test(groups = "slow")
public void testWithBusEvents() throws Exception {
final DateTime initialDate = new DateTime(2012, 2, 1, 0, 3, 42, 0, testTimeZone);
clock.setTime(initialDate);
final Account account = createAccountWithNonOsgiPaymentMethod(getAccountData(2));
assertNotNull(account);
final DefaultEntitlement bpEntitlement = createBaseEntitlementAndCheckForCompletion(account.getId(), "externalKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE);
assertNotNull(bpEntitlement);
await().atMost(10, SECONDS)
.until(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
// Expecting ACCOUNT_CREATE, ACCOUNT_CHANGE, SUBSCRIPTION_CREATION (2), ENTITLEMENT_CREATE INVOICE_CREATION
return externalBusCount.get() == 6;
}
});
}
private void assertNbCalls(final int expectedNbRWCalls, final int expectedNbROCalls) {
assertEquals(testDBRouterAPI.getNbRWCalls(), expectedNbRWCalls);
assertEquals(testDBRouterAPI.getNbRoCalls(), expectedNbROCalls);
}
public class PublicListener {
@Subscribe
public void handleExternalEvents(final ExtBusEvent event) {
testDBRouterAPI.reset();
final TenantContext tenantContext = new DefaultTenantContext(callContext.getAccountId(), callContext.getTenantId());
// Only RO tenant will trigger use of RO DBI (initiated by plugins)
final ROTenantContext roTenantContext = new ROTenantContext(tenantContext);
// RO calls goes to RW DB by default
testDBRouterAPI.doROCall(tenantContext);
assertNbCalls(1, 0);
testDBRouterAPI.doROCall(callContext);
assertNbCalls(2, 0);
// Even if the thread is dirty (previous RW calls), the plugin asked for RO DBI
testDBRouterAPI.doROCall(roTenantContext);
assertNbCalls(2, 1);
// Make sure subsequent calls go back to the RW DB
testDBRouterAPI.doROCall(tenantContext);
assertNbCalls(3, 1);
testDBRouterAPI.doRWCall(callContext);
assertNbCalls(4, 1);
testDBRouterAPI.doROCall(roTenantContext);
assertNbCalls(4, 2);
testDBRouterAPI.doROCall(callContext);
assertNbCalls(5, 2);
testDBRouterAPI.doROCall(tenantContext);
assertNbCalls(6, 2);
testDBRouterAPI.doChainedROCall(tenantContext);
assertNbCalls(7, 2);
testDBRouterAPI.doChainedRWCall(callContext);
assertNbCalls(8, 2);
// Increment only if there are no errors
externalBusCount.incrementAndGet();
}
}
}
| 35.751553
| 234
| 0.695448
|
0ec17a771f32dc75953feadb57e379b2c1d84655
| 1,136
|
package com.dcits.dcwlt.common.pay.validator;
import com.dcits.dcwlt.common.pay.validator.annotation.Amount;
import org.apache.commons.lang3.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;
/**
* <p>采用正则表达式校验金额格式</p>
*/
public class AmountValidator implements ConstraintValidator<Amount, String> {
private static final Pattern centPattern = Pattern.compile("^[1-9]\\d*\\.\\d{2}$");
private static final Pattern centPatternZero = Pattern.compile("^0\\.\\d{2}$");
private boolean required;
@Override
public void initialize(Amount constraintAnnotation) {
required = constraintAnnotation.required();
}
@Override
public boolean isValid(String amount, ConstraintValidatorContext context) {
if(!required && StringUtils.isBlank(amount)){
return true;
}
if(StringUtils.isBlank(amount)){
return false;
}
return centPattern.matcher(amount).matches() || centPatternZero.matcher(amount).matches();
}
}
| 30.702703
| 99
| 0.681338
|
afd30735042abb0c5615d1f18fc4570b90658b53
| 1,044
|
package com.thesurix.gesturerecycler.transactions;
import com.thesurix.gesturerecycler.GestureAdapter;
import com.thesurix.gesturerecycler.GestureViewHolder;
/**
* @author thesurix
*/
public class InsertTransaction<T> implements AdapterTransaction {
private final GestureAdapter<T, ? extends GestureViewHolder> mAdapter;
private final T mItem;
private final int mPosition;
public InsertTransaction(final GestureAdapter<T, ? extends GestureViewHolder> adapter, final T item, final int position) {
mAdapter = adapter;
mItem = item;
mPosition = position;
}
@Override
public boolean perform() {
mAdapter.getData().add(mPosition, mItem);
mAdapter.notifyItemInserted(mPosition);
return true;
}
@Override
public boolean revert() {
final T item = mAdapter.getData().remove(mPosition);
final boolean success = item != null;
if (success) {
mAdapter.notifyItemRemoved(mPosition);
}
return success;
}
}
| 26.769231
| 126
| 0.678161
|
1160e90c4c5cdc8218be485f02269c00cbb9b259
| 2,688
|
package javasmmr.zoowsome.controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javasmmr.zoowsome.models.animals.Animal;
import javasmmr.zoowsome.views.animals.create.CreateAFrame;
/**
*
* @author Marius Bologa
*
*/
public class CreateAController extends AbstractController {
/**
*
*/
private CreateAFrame frame1;
/**
*
* @param frame
* Add a new frame .
* @param hasBackButton
* If the back button was pushed or not.
*/
public CreateAController(final CreateAFrame frame, final boolean hasBackButton) {
super(frame, hasBackButton);
frame.setCreateButtonActionListener(new CreateAquaticButtonActionListener());
this.frame1 = frame;
try {
sf = abstractFactory.getSpeciesFactory(species[0]);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @author Marius Bologa
*
*/
public class CreateAquaticButtonActionListener implements ActionListener {
@Override
public void actionPerformed(final ActionEvent e) {
if (frame1.getShark().isSelected()) {
try {
Animal animal = sf.getAnimal(animalsF[0][1]);
animal.setName(frame1.getTheName());
animal.setNrOfLegs(frame1.getNrOfLegs());
animal.setMaintenanceCost(frame1.getMaintenanceCost());
animal.setDangerPerc(frame1.getDangerPerc());
animals = animalRepository.load();
animals.add(animal);
animalRepository.save(animals);
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
} else if (frame1.getTuna().isSelected()) {
try {
Animal animal = sf.getAnimal(animalsF[0][0]);
animal.setName(frame1.getTheName());
animal.setNrOfLegs(frame1.getNrOfLegs());
animal.setMaintenanceCost(frame1.getMaintenanceCost());
animal.setDangerPerc(frame1.getDangerPerc());
animals = animalRepository.load();
animals.add(animal);
animalRepository.save(animals);
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
} else {
try {
Animal animal = sf.getAnimal(animalsF[0][2]);
animal.setName(frame1.getTheName());
animal.setNrOfLegs(frame1.getNrOfLegs());
animal.setMaintenanceCost(frame1.getMaintenanceCost());
animal.setDangerPerc(frame1.getDangerPerc());
animals = animalRepository.load();
animals.add(animal);
animalRepository.save(animals);
} catch (Exception e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
JOptionPane.showMessageDialog(frame, "Successfully created!");
}
}
}
| 28
| 82
| 0.68936
|
97aaaad4693601db69bd2cc195ca1e56fc3259d0
| 351
|
package io.github.jaredpetersen.kafkaconnectredis.sink.writer.record;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class RedisExpireatCommand implements RedisCommand {
Command command = Command.EXPIREAT;
Payload payload;
@Value
@lombok.Builder
public static class Payload {
String key;
long timestamp;
}
}
| 18.473684
| 69
| 0.766382
|
245c02a0a6187ea03b39cc1882dc5da9d603eebc
| 3,871
|
package xyz.rk0cc.josev.constraint;
import xyz.rk0cc.josev.NonStandardSemVerException;
import xyz.rk0cc.josev.SemVer;
import xyz.rk0cc.josev.SemVerRangeNode;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
@SemVerConstraintParser
public final class SampleConstraint extends SemVerConstraint<SampleConstraintPattern> {
private SampleConstraint(
@Nonnull SampleConstraintPattern constraintPattern,
@Nullable String rawConstraint,
@Nullable SemVerRangeNode start,
@Nullable SemVerRangeNode end
) {
super(constraintPattern, rawConstraint, start, end);
}
@Nonnull
public static SampleConstraint parse(@Nullable String versionConstraint) {
List<SampleConstraintPattern> appliedPattern = Arrays.stream(SampleConstraintPattern.values())
.filter(p -> p.isValidConstraintMethods(versionConstraint))
.toList();
assert appliedPattern.size() == 1;
final SampleConstraintPattern pattern = appliedPattern.get(0);
switch (pattern) {
case TRADITIONAL -> {
assert versionConstraint != null;
final String[] spiltedTRange = versionConstraint.split("\\s");
final Function<String, SemVerRangeNode> tvcNodeMaker = s -> {
assert !(s.contains(">") && s.contains("<"));
boolean orEquals = s.contains("=");
try {
return new SemVerRangeNode(
SemVer.parse(s.substring(orEquals ? 2 : 1)),
s.charAt(0),
orEquals
);
} catch (NonStandardSemVerException nssv) {
throw new AssertionError(nssv);
}
};
switch (spiltedTRange.length) {
case 1:
final SemVerRangeNode svcn = tvcNodeMaker.apply(spiltedTRange[0]);
return svcn.operator() == '>'
? new SampleConstraint(pattern, versionConstraint, svcn, null)
: new SampleConstraint(pattern, versionConstraint, null, svcn);
case 2:
return new SampleConstraint(
pattern,
versionConstraint,
tvcNodeMaker.apply(spiltedTRange[0]),
tvcNodeMaker.apply(spiltedTRange[1])
);
default:
throw new AssertionError(
"Found illegal traditional constraint '" + versionConstraint + "'"
);
}
}
case CARET -> {
assert versionConstraint != null;
try {
SemVer importedVer = SemVer.parse(versionConstraint.substring(1));
return new SampleConstraint(
pattern,
versionConstraint,
new SemVerRangeNode(importedVer, '>', true),
new SemVerRangeNode(
new SemVer(importedVer.major() + 1, 0, 0),
'<',
false
)
);
} catch (NonStandardSemVerException nssv) {
throw new AssertionError(nssv);
}
}
default -> throw new IllegalArgumentException("Found undefined pattern '" + pattern + "'");
}
}
}
| 41.623656
| 103
| 0.497546
|
ed9966dc6f68a91edd08dee63aacf21e2787d8bb
| 3,312
|
package com.solares.calculadorasolar.activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.solares.calculadorasolar.R;
import com.solares.calculadorasolar.classes.AutoSizeText;
import com.solares.calculadorasolar.classes.CalculadoraOnGrid;
import com.solares.calculadorasolar.classes.Constants;
import java.util.Locale;
import static com.solares.calculadorasolar.activity.MainActivity.GetPhoneDimensions;
public class AnaliseActivity extends AppCompatActivity {
public final float porcent = 3f;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analise);
Intent intent = getIntent();
CalculadoraOnGrid calculadora = (CalculadoraOnGrid) intent.getSerializableExtra(Constants.EXTRA_CALCULADORAON);
//Pegando informações sobre o dispositivo, para regular o tamanho da letra (fonte)
//Essa função pega as dimensões e as coloca em váriaveis globais
GetPhoneDimensions(this);
TextView textResultado = findViewById(R.id.text_resultado_analise);
AutoSizeText.AutoSizeTextView(textResultado, MainActivity.alturaTela, MainActivity.larguraTela, 4f);
// Essas variáveis são as referências para os textos que aparecem no layout.
TextView textEstaticoCustoParcial = findViewById(R.id.text_custo_parcial_1);
TextView textCustoParcial = findViewById(R.id.text_custo_parcial);
textCustoParcial.setText(String.format(Locale.ITALY,"R$ %.2f", calculadora.pegaCustoParcial()));
AutoSizeText.AutoSizeTextView(textEstaticoCustoParcial, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
AutoSizeText.AutoSizeTextView(textCustoParcial, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
TextView textEstaticoCustoTotal = findViewById(R.id.text_custo_total_1);
TextView textCustoTotal = findViewById(R.id.text_custo_total);
textCustoTotal.setText(String.format(Locale.ITALY,"R$ %.2f", calculadora.pegaCustoTotal()));
AutoSizeText.AutoSizeTextView(textEstaticoCustoTotal, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
AutoSizeText.AutoSizeTextView(textCustoTotal, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
TextView textEstaticoGeracao = findViewById(R.id.text_geracao_anual_1);
AutoSizeText.AutoSizeTextView(textEstaticoGeracao, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
TextView textGeracao = findViewById(R.id.text_geracao_anual);
textGeracao.setText(String.format(Locale.ITALY,"%.2f kWh", calculadora.pegaGeracaoAnual()/12));
AutoSizeText.AutoSizeTextView(textGeracao, MainActivity.alturaTela, MainActivity.larguraTela, porcent);
Button buttonVoltar = findViewById(R.id.button_voltar);
AutoSizeText.AutoSizeButton(buttonVoltar, MainActivity.alturaTela, MainActivity.larguraTela, 4f);
buttonVoltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| 49.432836
| 124
| 0.764795
|
39479bdda515ba17c2040dffd881f8893176131b
| 6,287
|
package org.jhaws.common.lang;
import static org.jhaws.common.lang.CollectionUtils8.newList;
import static org.jhaws.common.lang.CollectionUtils8.toCollector;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class MappingFactoryTest {
private MappingFactory mappingFactory = new MappingFactory();
private Pojo getTestPojo(String suffix, int index) {
Pojo pojo = new Pojo();
pojo.setVeld1("veld1_" + suffix);
pojo.setVeld2(index);
pojo.setVeld3("veld3_" + suffix);
{
CommonNestedPojo commonNested = new CommonNestedPojo();
commonNested.setCommonNestedField("commonNestedField");
pojo.setCommonNested(commonNested);
}
{
CommonNestedPojo commonNested = new CommonNestedPojo();
commonNested.setCommonNestedField("commonNestedField");
pojo.getCollection().add(commonNested);
}
{
CommonNestedPojo commonNested = new CommonNestedPojo();
commonNested.setCommonNestedField("commonNestedField");
pojo.setArray(new CommonNestedPojo[] { commonNested });
}
return pojo;
}
protected Mapping<Pojo, DTO> init() {
Mapping<Pojo, DTO> mapping = this.mappingFactory.build(Pojo.class, DTO.class)//
.add((ctx, s, t) -> t.setNestedDTOVeld(s.getNestedPojo().getNestedVeld()))//
.add((ctx, s, t) -> t.getNestedDTO().setNestedVeld(s.getNestedPojoVeld()))//
.collect(this.mappingFactory, Pojo::getCollection, DTO::getCollection, CommonNestedDTO.class)//
.collectAA(this.mappingFactory, Pojo::getArray, DTO::getArray, CommonNestedDTO.class)//
;
this.mappingFactory.build(CommonNestedPojo.class, CommonNestedDTO.class);
this.mappingFactory.build(Retro.class, RetroB.class);
this.mappingFactory.build(SourceProb.class, TargetProb.class);
return mapping;
}
@Test
public void test1() {
this.init();
Pojo pojo = this.getTestPojo("test1", 1);
DTO dto = this.mappingFactory.map(pojo, DTO.class);
Assert.assertEquals(pojo.getVeld1(), dto.getVeld1());
Assert.assertEquals(pojo.getVeld2(), dto.getVeld2().intValue());
Assert.assertEquals(pojo.getVeld3(), dto.getVeld3());
Assert.assertEquals(pojo.getNestedPojo().getNestedVeld(), dto.getNestedDTOVeld());
Assert.assertEquals(pojo.getNestedPojoVeld(), dto.getNestedDTO().getNestedVeld());
Assert.assertEquals(pojo.getCommonNested().getCommonNestedField(), dto.getCommonNested().getCommonNestedField());
Assert.assertEquals(pojo.getCollection().iterator().next().getCommonNestedField(),
dto.getCollection().iterator().next().getCommonNestedField());
}
@Test
public void test2() {
this.init();
Retro r1 = new Retro();
Retro r2 = new Retro();
r1.setRetro(r2);
r2.setRetro(r1);
this.mappingFactory.map(r1, RetroB.class);
}
@Test
public void test3() {
this.init();
List<Pojo> pc = new ArrayList<>();
Pojo p1 = this.getTestPojo("test3a", 30);
pc.add(p1);
Pojo p2 = this.getTestPojo("test3b", 31);
pc.add(p2);
Pojo[] pa = { p1, p2 };
{
List<DTO> c = this.mappingFactory.map(pc, DTO.class, toCollector(newList()));
Assert.assertEquals(pc.size(), c.size());
Assert.assertEquals(c.get(0).getVeld1(), p1.getVeld1());
Assert.assertEquals(c.get(0).getVeld2().intValue(), p1.getVeld2());
Assert.assertEquals(c.get(0).getVeld3(), p1.getVeld3());
Assert.assertEquals(c.get(1).getVeld1(), p2.getVeld1());
Assert.assertEquals(c.get(1).getVeld2().intValue(), p2.getVeld2());
Assert.assertEquals(c.get(1).getVeld3(), p2.getVeld3());
}
{
DTO[] a = this.mappingFactory.map(pc, DTO.class);
Assert.assertEquals(pc.size(), a.length);
Assert.assertEquals(a[0].getVeld1(), p1.getVeld1());
Assert.assertEquals(a[0].getVeld2().intValue(), p1.getVeld2());
Assert.assertEquals(a[0].getVeld3(), p1.getVeld3());
Assert.assertEquals(a[1].getVeld1(), p2.getVeld1());
Assert.assertEquals(a[1].getVeld2().intValue(), p2.getVeld2());
Assert.assertEquals(a[1].getVeld3(), p2.getVeld3());
}
{
DTO[] a = this.mappingFactory.map(pa, DTO.class);
Assert.assertEquals(pc.size(), a.length);
Assert.assertEquals(a[0].getVeld1(), p1.getVeld1());
Assert.assertEquals(a[0].getVeld2().intValue(), p1.getVeld2());
Assert.assertEquals(a[0].getVeld3(), p1.getVeld3());
Assert.assertEquals(a[1].getVeld1(), p2.getVeld1());
Assert.assertEquals(a[1].getVeld2().intValue(), p2.getVeld2());
Assert.assertEquals(a[1].getVeld3(), p2.getVeld3());
}
{
List<DTO> c = this.mappingFactory.map(pa, DTO.class, toCollector(newList()));
Assert.assertEquals(pc.size(), c.size());
Assert.assertEquals(c.get(0).getVeld1(), p1.getVeld1());
Assert.assertEquals(c.get(0).getVeld2().intValue(), p1.getVeld2());
Assert.assertEquals(c.get(0).getVeld3(), p1.getVeld3());
Assert.assertEquals(c.get(1).getVeld1(), p2.getVeld1());
Assert.assertEquals(c.get(1).getVeld2().intValue(), p2.getVeld2());
Assert.assertEquals(c.get(1).getVeld3(), p2.getVeld3());
}
}
@Test
public void test4() {
this.init();
SourceProb s = new SourceProb();
s.setDate(new Date());
TargetProb t = new TargetProb();
this.mappingFactory.map(s, t);
Assert.assertEquals(s.getDate(), t.getDate());
}
@Test
public void test5() {
SourceProb s = new SourceProb();
s.test();
SourceProb p = Mapping.proxy(s, SourceProb.class, this.mappingFactory.info(SourceProb.class));
p.test();
Assert.assertNotNull(p.getDate());
Assert.assertEquals(s.getDate(), p.getDate());
}
}
| 41.361842
| 121
| 0.607921
|
0bf8e260d7f2f4b28e3849d4794ebc73837cebe5
| 1,469
|
/* Copyright 2017 Zutubi Pty Ltd
*
* 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.zutubi.pulse.master.security;
import com.zutubi.pulse.master.tove.config.user.UserConfiguration;
import com.zutubi.tove.security.AuthorityProvider;
import com.zutubi.tove.security.DefaultAccessManager;
import java.util.HashSet;
import java.util.Set;
/**
* Allows users to perform actions on their own configuration.
*/
public class UserConfigurationAuthorityProvider implements AuthorityProvider<UserConfiguration>
{
public Set<String> getAllowedAuthorities(String action, UserConfiguration resource)
{
Set<String> result = new HashSet<String>(1);
// The user can do whatever to themself.
result.add(resource.getDefaultAuthority());
return result;
}
public void setAccessManager(DefaultAccessManager accessManager)
{
accessManager.registerAuthorityProvider(UserConfiguration.class, this);
}
}
| 34.162791
| 95
| 0.753574
|
167f8d421cc6531756e379145ccae17e52b4b5ee
| 2,353
|
package com.daiwf.javalearndemos.io;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class BIOPlainEchoServer
{
public void serve(int port) throws IOException {
//将ServerSockect绑定到指定的端口里
final ServerSocket socket = new ServerSocket();
while (true) {
//阻塞直到接收到新的客户端连接
final Socket clientSocket = socket.accept();
System.out.println("Accepted connection from " + clientSocket);
new Thread(new Runnable()
{
@Override public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
//从客户端读取数据并原封不动会写回去
while (true) {
writer.println(reader.readLine());
writer.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
public void improvedServe(int port) throws IOException {
//将ServerSocket绑定到指定的端口里
final ServerSocket socket = new ServerSocket(port);
//创建一个线程池
ExecutorService executorService =Executors.newFixedThreadPool(6);
while(true){
//阻塞直到新的客户端连接
final Socket clientSocket =socket.accept();
System.out.println("Accepted connection from "+clientSocket);
//将请求提交给线程去执行
executorService.execute(()->{
try(BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
PrintWriter writer =new PrintWriter(clientSocket.getOutputStream(),true);
while(true){
writer.println(reader.readLine());
writer.flush();
}
}
catch (IOException e) {
e.printStackTrace();
}
});
}
}
}
| 34.101449
| 119
| 0.520612
|
183fe571d940fc4a9df7115ef2b69215549c44e3
| 2,824
|
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.model.hateoas;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.dspace.app.rest.model.RestModel;
import org.dspace.app.rest.utils.Utils;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
/**
* A base class for DSpace Rest HAL Resource. The HAL Resource wraps the REST
* Resource adding support for the links and embedded resources. Each property
* of the wrapped REST resource is automatically translated in a link and the
* available information included as embedded resource
*
* @author Andrea Bollini (andrea.bollini at 4science.it)
*
*/
public abstract class DSpaceResource<T extends RestModel> extends ResourceSupport {
@JsonUnwrapped
private final T data;
@JsonProperty(value = "_embedded")
@JsonInclude(Include.NON_EMPTY)
private Map<String, Object> embedded = new HashMap<String, Object>();
public DSpaceResource(T data, Utils utils, String... rels) {
this.data = data;
if (data != null) {
try {
for (PropertyDescriptor pd : Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors()) {
Method readMethod = pd.getReadMethod();
if (readMethod != null && !"class".equals(pd.getName())) {
if (RestModel.class.isAssignableFrom(readMethod.getReturnType())) {
this.add(utils.linkToSubResource(data, pd.getName()));
RestModel linkedObject = (RestModel) readMethod.invoke(data);
if (linkedObject != null) {
embedded.put(pd.getName(),
utils.getResourceRepository(linkedObject.getCategory(), linkedObject.getType())
.wrapResource(linkedObject));
} else {
embedded.put(pd.getName(), null);
}
Method writeMethod = pd.getWriteMethod();
writeMethod.invoke(data, new Object[] { null });
}
}
}
} catch (IntrospectionException | IllegalArgumentException | IllegalAccessException
| InvocationTargetException e) {
throw new RuntimeException(e.getMessage(), e);
}
this.add(utils.linkToSingleResource(data, Link.REL_SELF));
}
}
public Map<String, Object> getEmbedded() {
return embedded;
}
public T getData() {
return data;
}
}
| 33.223529
| 102
| 0.731941
|
dc67daea7d90ab319e3bb64954cf961f2f6cb413
| 1,681
|
package org.zstack.header.zone;
import org.zstack.header.message.APIEvent;
import org.zstack.header.rest.RestResponse;
import java.sql.Timestamp;
/**
* @apiResult api event for message :ref:`APIChangeZoneStateMsg`
* @example {
* "org.zstack.header.zone.APIChangeZoneStateEvent": {
* "inventory": {
* "uuid": "1b830f5bd1cb469b821b4b77babfdd6f",
* "name": "test",
* "description": "test",
* "state": "Disabled",
* "type": "zstack",
* "createDate": "Apr 28, 2014 5:26:34 PM",
* "lastOpDate": "Apr 28, 2014 5:26:34 PM"
* },
* "success": true
* }
* }
* @since 0.1.0
*/
@RestResponse(allTo = "inventory")
public class APIChangeZoneStateEvent extends APIEvent {
/**
* @desc zone inventory (see :ref:`ZoneInventory`)
*/
private ZoneInventory inventory;
public APIChangeZoneStateEvent() {
super(null);
}
public APIChangeZoneStateEvent(String apiId) {
super(apiId);
}
public ZoneInventory getInventory() {
return inventory;
}
public void setInventory(ZoneInventory inventory) {
this.inventory = inventory;
}
public static APIChangeZoneStateEvent __example__() {
APIChangeZoneStateEvent event = new APIChangeZoneStateEvent();
ZoneInventory zone = new ZoneInventory();
zone.setName("TestZone");
zone.setUuid(uuid());
zone.setDescription("Test");
zone.setState(ZoneState.Enabled.toString());
zone.setType("zstack");
zone.setCreateDate(new Timestamp(System.currentTimeMillis()));
zone.setLastOpDate(new Timestamp(System.currentTimeMillis()));
event.setInventory(zone);
return event;
}
}
| 25.089552
| 70
| 0.654967
|
4f7363373673c3a9fdbd6d823b8ac0cbaed48253
| 17,941
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.hdfs.server.datanode
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|datanode
package|;
end_package
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|InputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|OutputStream
import|;
end_import
begin_import
import|import
name|java
operator|.
name|net
operator|.
name|URI
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|LocalFileSystem
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|protocol
operator|.
name|Block
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|datanode
operator|.
name|fsdataset
operator|.
name|FsVolumeSpi
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|datanode
operator|.
name|fsdataset
operator|.
name|FsVolumeSpi
operator|.
name|ScanInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|datanode
operator|.
name|fsdataset
operator|.
name|LengthInputStream
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hdfs
operator|.
name|server
operator|.
name|protocol
operator|.
name|ReplicaRecoveryInfo
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|util
operator|.
name|LightWeightResizableGSet
import|;
end_import
begin_comment
comment|/** * This class is used by datanodes to maintain meta data of its replicas. * It provides a general interface for meta information of a replica. */
end_comment
begin_class
annotation|@
name|InterfaceAudience
operator|.
name|Private
DECL|class|ReplicaInfo
specifier|abstract
specifier|public
class|class
name|ReplicaInfo
extends|extends
name|Block
implements|implements
name|Replica
implements|,
name|LightWeightResizableGSet
operator|.
name|LinkedElement
block|{
comment|/** For implementing {@link LightWeightResizableGSet.LinkedElement}. */
DECL|field|next
specifier|private
name|LightWeightResizableGSet
operator|.
name|LinkedElement
name|next
decl_stmt|;
comment|/** volume where the replica belongs. */
DECL|field|volume
specifier|private
name|FsVolumeSpi
name|volume
decl_stmt|;
comment|/** This is used by some tests and FsDatasetUtil#computeChecksum. */
DECL|field|DEFAULT_FILE_IO_PROVIDER
specifier|private
specifier|static
specifier|final
name|FileIoProvider
name|DEFAULT_FILE_IO_PROVIDER
init|=
operator|new
name|FileIoProvider
argument_list|(
literal|null
argument_list|,
literal|null
argument_list|)
decl_stmt|;
comment|/** * Constructor. * @param block a block * @param vol volume where replica is located */
DECL|method|ReplicaInfo (Block block, FsVolumeSpi vol)
name|ReplicaInfo
parameter_list|(
name|Block
name|block
parameter_list|,
name|FsVolumeSpi
name|vol
parameter_list|)
block|{
name|this
argument_list|(
name|vol
argument_list|,
name|block
operator|.
name|getBlockId
argument_list|()
argument_list|,
name|block
operator|.
name|getNumBytes
argument_list|()
argument_list|,
name|block
operator|.
name|getGenerationStamp
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|/** * Constructor * @param vol volume where replica is located * @param blockId block id * @param len replica length * @param genStamp replica generation stamp */
DECL|method|ReplicaInfo (FsVolumeSpi vol, long blockId, long len, long genStamp)
name|ReplicaInfo
parameter_list|(
name|FsVolumeSpi
name|vol
parameter_list|,
name|long
name|blockId
parameter_list|,
name|long
name|len
parameter_list|,
name|long
name|genStamp
parameter_list|)
block|{
name|super
argument_list|(
name|blockId
argument_list|,
name|len
argument_list|,
name|genStamp
argument_list|)
expr_stmt|;
name|this
operator|.
name|volume
operator|=
name|vol
expr_stmt|;
block|}
comment|/** * Copy constructor. * @param from where to copy from */
DECL|method|ReplicaInfo (ReplicaInfo from)
name|ReplicaInfo
parameter_list|(
name|ReplicaInfo
name|from
parameter_list|)
block|{
name|this
argument_list|(
name|from
argument_list|,
name|from
operator|.
name|getVolume
argument_list|()
argument_list|)
expr_stmt|;
block|}
comment|/** * @return the volume where this replica is located on disk */
DECL|method|getVolume ()
specifier|public
name|FsVolumeSpi
name|getVolume
parameter_list|()
block|{
return|return
name|volume
return|;
block|}
comment|/** * Get the {@link FileIoProvider} for disk IO operations. */
DECL|method|getFileIoProvider ()
specifier|public
name|FileIoProvider
name|getFileIoProvider
parameter_list|()
block|{
comment|// In tests and when invoked via FsDatasetUtil#computeChecksum, the
comment|// target volume for this replica may be unknown and hence null.
comment|// Use the DEFAULT_FILE_IO_PROVIDER with no-op hooks.
return|return
operator|(
name|volume
operator|!=
literal|null
operator|)
condition|?
name|volume
operator|.
name|getFileIoProvider
argument_list|()
else|:
name|DEFAULT_FILE_IO_PROVIDER
return|;
block|}
comment|/** * Set the volume where this replica is located on disk. */
DECL|method|setVolume (FsVolumeSpi vol)
name|void
name|setVolume
parameter_list|(
name|FsVolumeSpi
name|vol
parameter_list|)
block|{
name|this
operator|.
name|volume
operator|=
name|vol
expr_stmt|;
block|}
comment|/** * Get the storageUuid of the volume that stores this replica. */
annotation|@
name|Override
DECL|method|getStorageUuid ()
specifier|public
name|String
name|getStorageUuid
parameter_list|()
block|{
return|return
name|volume
operator|.
name|getStorageID
argument_list|()
return|;
block|}
comment|/** * Number of bytes reserved for this replica on disk. */
DECL|method|getBytesReserved ()
specifier|public
name|long
name|getBytesReserved
parameter_list|()
block|{
return|return
literal|0
return|;
block|}
comment|/** * Get the {@code URI} for where the data of this replica is stored. * @return {@code URI} for the location of replica data. */
DECL|method|getBlockURI ()
specifier|abstract
specifier|public
name|URI
name|getBlockURI
parameter_list|()
function_decl|;
comment|/** * Returns an {@link InputStream} to the replica's data. * @param seekOffset the offset at which the read is started from. * @return the {@link InputStream} to read the replica data. * @throws IOException if an error occurs in opening a stream to the data. */
DECL|method|getDataInputStream (long seekOffset)
specifier|abstract
specifier|public
name|InputStream
name|getDataInputStream
parameter_list|(
name|long
name|seekOffset
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Returns an {@link OutputStream} to the replica's data. * @param append indicates if the block should be opened for append. * @return the {@link OutputStream} to write to the replica. * @throws IOException if an error occurs in creating an {@link OutputStream}. */
DECL|method|getDataOutputStream (boolean append)
specifier|abstract
specifier|public
name|OutputStream
name|getDataOutputStream
parameter_list|(
name|boolean
name|append
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * @return true if the replica's data exists. */
DECL|method|blockDataExists ()
specifier|abstract
specifier|public
name|boolean
name|blockDataExists
parameter_list|()
function_decl|;
comment|/** * Used to deletes the replica's block data. * * @return true if the replica's data is successfully deleted. */
DECL|method|deleteBlockData ()
specifier|abstract
specifier|public
name|boolean
name|deleteBlockData
parameter_list|()
function_decl|;
comment|/** * @return the length of the block on storage. */
DECL|method|getBlockDataLength ()
specifier|abstract
specifier|public
name|long
name|getBlockDataLength
parameter_list|()
function_decl|;
comment|/** * Get the {@code URI} for where the metadata of this replica is stored. * * @return {@code URI} for the location of replica metadata. */
DECL|method|getMetadataURI ()
specifier|abstract
specifier|public
name|URI
name|getMetadataURI
parameter_list|()
function_decl|;
comment|/** * Returns an {@link InputStream} to the replica's metadata. * @param offset the offset at which the read is started from. * @return the {@link LengthInputStream} to read the replica metadata. * @throws IOException */
DECL|method|getMetadataInputStream (long offset)
specifier|abstract
specifier|public
name|LengthInputStream
name|getMetadataInputStream
parameter_list|(
name|long
name|offset
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Returns an {@link OutputStream} to the replica's metadata. * @param append indicates if the block metadata should be opened for append. * @return the {@link OutputStream} to write to the replica's metadata. * @throws IOException if an error occurs in creating an {@link OutputStream}. */
DECL|method|getMetadataOutputStream (boolean append)
specifier|abstract
specifier|public
name|OutputStream
name|getMetadataOutputStream
parameter_list|(
name|boolean
name|append
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * @return true if the replica's metadata exists. */
DECL|method|metadataExists ()
specifier|abstract
specifier|public
name|boolean
name|metadataExists
parameter_list|()
function_decl|;
comment|/** * Used to deletes the replica's metadata. * * @return true if the replica's metadata is successfully deleted. */
DECL|method|deleteMetadata ()
specifier|abstract
specifier|public
name|boolean
name|deleteMetadata
parameter_list|()
function_decl|;
comment|/** * @return the length of the metadata on storage. */
DECL|method|getMetadataLength ()
specifier|abstract
specifier|public
name|long
name|getMetadataLength
parameter_list|()
function_decl|;
comment|/** * Rename the metadata {@link URI} to that referenced by {@code destURI}. * * @param destURI the target {@link URI}. * @return true if the rename is successful. * @throws IOException if an exception occurs in the rename. */
DECL|method|renameMeta (URI destURI)
specifier|abstract
specifier|public
name|boolean
name|renameMeta
parameter_list|(
name|URI
name|destURI
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Rename the data {@link URI} to that referenced by {@code destURI}. * * @param destURI the target {@link URI}. * @return true if the rename is successful. * @throws IOException if an exception occurs in the rename. */
DECL|method|renameData (URI destURI)
specifier|abstract
specifier|public
name|boolean
name|renameData
parameter_list|(
name|URI
name|destURI
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Update this replica with the {@link StorageLocation} found. * @param replicaLocation the {@link StorageLocation} found for this replica. */
DECL|method|updateWithReplica (StorageLocation replicaLocation)
specifier|abstract
specifier|public
name|void
name|updateWithReplica
parameter_list|(
name|StorageLocation
name|replicaLocation
parameter_list|)
function_decl|;
comment|/** * Check whether the block was pinned. * @param localFS the local filesystem to use. * @return true if the block is pinned. * @throws IOException */
DECL|method|getPinning (LocalFileSystem localFS)
specifier|abstract
specifier|public
name|boolean
name|getPinning
parameter_list|(
name|LocalFileSystem
name|localFS
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Set a block to be pinned on this datanode so that it cannot be moved * by Balancer/Mover. * * @param localFS the local filesystem to use. * @throws IOException if there is an exception in the pinning. */
DECL|method|setPinning (LocalFileSystem localFS)
specifier|abstract
specifier|public
name|void
name|setPinning
parameter_list|(
name|LocalFileSystem
name|localFS
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Bump a replica's generation stamp to a new one. * Its on-disk meta file name is renamed to be the new one too. * * @param newGS new generation stamp * @throws IOException if the change fails */
DECL|method|bumpReplicaGS (long newGS)
specifier|abstract
specifier|public
name|void
name|bumpReplicaGS
parameter_list|(
name|long
name|newGS
parameter_list|)
throws|throws
name|IOException
function_decl|;
DECL|method|getOriginalReplica ()
specifier|abstract
specifier|public
name|ReplicaInfo
name|getOriginalReplica
parameter_list|()
function_decl|;
comment|/** * Get the recovery id. * @return the generation stamp that the replica will be bumped to */
DECL|method|getRecoveryID ()
specifier|abstract
specifier|public
name|long
name|getRecoveryID
parameter_list|()
function_decl|;
comment|/** * Set the recovery id. * @param recoveryId the new recoveryId */
DECL|method|setRecoveryID (long recoveryId)
specifier|abstract
specifier|public
name|void
name|setRecoveryID
parameter_list|(
name|long
name|recoveryId
parameter_list|)
function_decl|;
DECL|method|breakHardLinksIfNeeded ()
specifier|abstract
specifier|public
name|boolean
name|breakHardLinksIfNeeded
parameter_list|()
throws|throws
name|IOException
function_decl|;
DECL|method|createInfo ()
specifier|abstract
specifier|public
name|ReplicaRecoveryInfo
name|createInfo
parameter_list|()
function_decl|;
DECL|method|compareWith (ScanInfo info)
specifier|abstract
specifier|public
name|int
name|compareWith
parameter_list|(
name|ScanInfo
name|info
parameter_list|)
function_decl|;
DECL|method|truncateBlock (long newLength)
specifier|abstract
specifier|public
name|void
name|truncateBlock
parameter_list|(
name|long
name|newLength
parameter_list|)
throws|throws
name|IOException
function_decl|;
DECL|method|copyMetadata (URI destination)
specifier|abstract
specifier|public
name|void
name|copyMetadata
parameter_list|(
name|URI
name|destination
parameter_list|)
throws|throws
name|IOException
function_decl|;
DECL|method|copyBlockdata (URI destination)
specifier|abstract
specifier|public
name|void
name|copyBlockdata
parameter_list|(
name|URI
name|destination
parameter_list|)
throws|throws
name|IOException
function_decl|;
comment|/** * Number of bytes originally reserved for this replica. The actual * reservation is adjusted as data is written to disk. * * @return the number of bytes originally reserved for this replica. */
DECL|method|getOriginalBytesReserved ()
specifier|public
name|long
name|getOriginalBytesReserved
parameter_list|()
block|{
return|return
literal|0
return|;
block|}
annotation|@
name|Override
comment|//Object
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
return|return
name|getClass
argument_list|()
operator|.
name|getSimpleName
argument_list|()
operator|+
literal|", "
operator|+
name|super
operator|.
name|toString
argument_list|()
operator|+
literal|", "
operator|+
name|getState
argument_list|()
operator|+
literal|"\n getNumBytes() = "
operator|+
name|getNumBytes
argument_list|()
operator|+
literal|"\n getBytesOnDisk() = "
operator|+
name|getBytesOnDisk
argument_list|()
operator|+
literal|"\n getVisibleLength()= "
operator|+
name|getVisibleLength
argument_list|()
operator|+
literal|"\n getVolume() = "
operator|+
name|getVolume
argument_list|()
operator|+
literal|"\n getBlockURI() = "
operator|+
name|getBlockURI
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|isOnTransientStorage ()
specifier|public
name|boolean
name|isOnTransientStorage
parameter_list|()
block|{
return|return
name|volume
operator|.
name|isTransientStorage
argument_list|()
return|;
block|}
annotation|@
name|Override
DECL|method|getNext ()
specifier|public
name|LightWeightResizableGSet
operator|.
name|LinkedElement
name|getNext
parameter_list|()
block|{
return|return
name|next
return|;
block|}
annotation|@
name|Override
DECL|method|setNext (LightWeightResizableGSet.LinkedElement next)
specifier|public
name|void
name|setNext
parameter_list|(
name|LightWeightResizableGSet
operator|.
name|LinkedElement
name|next
parameter_list|)
block|{
name|this
operator|.
name|next
operator|=
name|next
expr_stmt|;
block|}
block|}
end_class
end_unit
| 21.98652
| 814
| 0.78184
|
6d22c7166e953149db91b0d0158bb39f1633ef7e
| 1,564
|
package com.easemob.im.server.api.attachment;
import com.easemob.im.server.api.Context;
import com.easemob.im.server.api.attachment.download.Download;
import com.easemob.im.server.api.attachment.upload.Upload;
import com.easemob.im.server.model.EMAttachment;
import reactor.core.publisher.Mono;
import java.nio.file.Path;
/**
* 附件API,提供附件上传和下载。目前,只支持本地文件的上传和下载。
* TODO: 支持上传和下载带有密码的附件
*/
public class AttachmentApi {
private Context context;
private Upload upload;
private Download download;
public AttachmentApi(Context context) {
this.context = context;
this.upload = new Upload(context);
this.download = new Download(context);
}
/**
* 上传附件
*
* @param path 要上传的文件的路径
* @return 上传完成后返回附件的id
* @see <a href="http://docs-im.easemob.com/im/server/basics/fileoperation#%E4%B8%8A%E4%BC%A0%E8%AF%AD%E9%9F%B3%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6">上传附件</a>
*/
public Mono<EMAttachment> uploadFile(Path path) {
return this.upload.fromLocalFile(path, false);
}
/* TODO: 上传带有密码保护的附件 */
/**
* 下载附件
* @param fileId 附件的id
* @param dir 下载到哪个目录,如果不存在会自动创建
* @param filename 下载到哪个文件
* @return 下载完成后返回文件路径
*
* @see <a href="http://docs-im.easemob.com/im/server/basics/fileoperation#%E4%B8%8B%E8%BD%BD%E8%AF%AD%E9%9F%B3%E5%9B%BE%E7%89%87%E6%96%87%E4%BB%B6">下载附件</a>
*/
public Mono<Path> downloadFile(String fileId, Path dir, String filename) {
return this.download.toLocalFile(fileId, dir, filename);
}
}
| 27.438596
| 161
| 0.66688
|
ffecf8039931003fa0529197580d5d14181c5efd
| 4,065
|
/*
* Copyright (c) 2003-2004, KNOPFLERFISH project
* 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 KNOPFLERFISH 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.knopflerfish.bundle.jini;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import java.net.URL;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* DOCUMENT ME!
*
* @author Nico Goeminne
*/
class BundleHttpContext implements HttpContext {
private PackageAdmin packageAdmin = null;
private ArrayList exportedPackages = new ArrayList();
/**
* Creates a new BundleHttpContext object.
*/
public BundleHttpContext() {
ServiceReference ref = Activator.bc.getServiceReference(
"org.osgi.service.packageadmin.PackageAdmin");
packageAdmin = (PackageAdmin) Activator.bc.getService(ref);
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getMimeType(String name) {
return null;
}
/**
* DOCUMENT ME!
*
* @param req DOCUMENT ME!
* @param resp DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean handleSecurity(HttpServletRequest req,
HttpServletResponse resp) {
return true;
}
/**
* DOCUMENT ME!
*
* @param name DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public URL getResource(String name) {
name = name.substring(1);
String temp = name.substring(0, name.lastIndexOf("/"));
String packageName = temp.replace('/', '.');
for (int i = 0; i < exportedPackages.size(); i++) {
Bundle b = ((Bundle) exportedPackages.get(i));
ExportedPackage[] exp = packageAdmin.getExportedPackages(b);
if (exp != null) {
for (int j = 0; j < exp.length; j++) {
if (exp[j].getName().equals(packageName)) {
return b.getResource(name);
}
}
}
}
return null;
}
/**
* DOCUMENT ME!
*
* @param b DOCUMENT ME!
*/
void ensureCodebaseFor(Bundle b) {
exportedPackages.add(b);
}
/**
* DOCUMENT ME!
*
* @param b DOCUMENT ME!
*/
void removeCodebaseFor(Bundle b) {
exportedPackages.remove(b);
}
}
| 29.035714
| 72
| 0.653383
|
c21ec171fad58d1a58b60311a9790f970568bb39
| 661
|
package com.openvehicletracking.protocols.xtakip;
import com.openvehicletracking.core.alert.AlertAction;
import java.util.ArrayList;
import java.util.List;
public class XTakipAlert {
private int id;
private String desciption;
private List<AlertAction> actions = new ArrayList<>();
public XTakipAlert(int i, String s, List<AlertAction> infoAction) {
this.id = i;
this.desciption = s;
this.actions = infoAction;
}
public int getId() {
return id;
}
public String getDesciption() {
return desciption;
}
public List<AlertAction> getActions() {
return actions;
}
}
| 19.441176
| 71
| 0.656581
|
4dd0f8553d6ace3211c03c7caa951a89e13cca46
| 995
|
package org.brapi.v2.model.germ;
import org.brapi.v2.model.BrAPIEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
public enum BrAPICrossType implements BrAPIEnum {
BIPARENTAL("BIPARENTAL"),
SELF("SELF"),
OPEN_POLLINATED("OPEN_POLLINATED"),
BULK("BULK"),
BULK_SELFED("BULK_SELFED"),
BULK_OPEN_POLLINATED("BULK_OPEN_POLLINATED"),
DOUBLE_HAPLOID("DOUBLE_HAPLOID");
private String value;
BrAPICrossType(String value) {
this.value = value;
}
@Override
@JsonValue
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static BrAPICrossType fromValue(String text) {
for (BrAPICrossType b : BrAPICrossType.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
@Override
public String getBrapiValue() {
return value;
}
}
| 19.9
| 57
| 0.652261
|
c22185cadc170ab1436f2ab54c06a1b683e61892
| 2,730
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.google.android.exoplayer2.audio;
import com.google.android.exoplayer2.PlaybackParameters;
// Referenced classes of package com.google.android.exoplayer2.audio:
// DefaultAudioSink
private static final class DefaultAudioSink$PlaybackParametersCheckpoint
{
private final long mediaTimeUs;
private final PlaybackParameters playbackParameters;
private final long positionUs;
/*
static PlaybackParameters access$200(DefaultAudioSink$PlaybackParametersCheckpoint defaultaudiosink$playbackparameterscheckpoint)
{
return defaultaudiosink$playbackparameterscheckpoint.playbackParameters;
// 0 0:aload_0
// 1 1:getfield #19 <Field PlaybackParameters playbackParameters>
// 2 4:areturn
}
*/
/*
static long access$400(DefaultAudioSink$PlaybackParametersCheckpoint defaultaudiosink$playbackparameterscheckpoint)
{
return defaultaudiosink$playbackparameterscheckpoint.positionUs;
// 0 0:aload_0
// 1 1:getfield #23 <Field long positionUs>
// 2 4:lreturn
}
*/
/*
static long access$500(DefaultAudioSink$PlaybackParametersCheckpoint defaultaudiosink$playbackparameterscheckpoint)
{
return defaultaudiosink$playbackparameterscheckpoint.mediaTimeUs;
// 0 0:aload_0
// 1 1:getfield #21 <Field long mediaTimeUs>
// 2 4:lreturn
}
*/
private DefaultAudioSink$PlaybackParametersCheckpoint(PlaybackParameters playbackparameters, long l, long l1)
{
// 0 0:aload_0
// 1 1:invokespecial #17 <Method void Object()>
playbackParameters = playbackparameters;
// 2 4:aload_0
// 3 5:aload_1
// 4 6:putfield #19 <Field PlaybackParameters playbackParameters>
mediaTimeUs = l;
// 5 9:aload_0
// 6 10:lload_2
// 7 11:putfield #21 <Field long mediaTimeUs>
positionUs = l1;
// 8 14:aload_0
// 9 15:lload 4
// 10 17:putfield #23 <Field long positionUs>
// 11 20:return
}
DefaultAudioSink$PlaybackParametersCheckpoint(PlaybackParameters playbackparameters, long l, long l1, DefaultAudioSink._cls1 _pcls1)
{
this(playbackparameters, l, l1);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:lload_2
// 3 3:lload 4
// 4 5:invokespecial #27 <Method void DefaultAudioSink$PlaybackParametersCheckpoint(PlaybackParameters, long, long)>
// 5 8:return
}
}
| 32.117647
| 133
| 0.664103
|
a63388988546a300eae74e919c2cef4626e7b39b
| 378
|
package com.twu.biblioteca.services;
import com.twu.biblioteca.model.User;
public class NewBookListItem implements NewOptionalItem{
private BookService bookService;
public NewBookListItem(BookService bookService) {
this.bookService = bookService;
}
@Override
public int run(User user) {
bookService.listBooks();
return 1;
}
}
| 21
| 56
| 0.703704
|
821870de1789ca7301e960b282462e906f0aecc8
| 21,039
|
/*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.angel.psagent.matrix.transport.adapter;
import com.tencent.angel.PartitionKey;
import com.tencent.angel.ml.math.TVector;
import com.tencent.angel.ml.math.vector.*;
import com.tencent.angel.ml.matrix.MatrixMeta;
import com.tencent.angel.ps.impl.matrix.*;
import com.tencent.angel.ml.matrix.RowType;
import com.tencent.angel.psagent.PSAgentContext;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Row splits combine tool.
*/
public class RowSplitCombineUtils {
private static final Log LOG = LogFactory.getLog(RowSplitCombineUtils.class);
private static final Comparator serverRowComp = new StartColComparator();
private static final Comparator partKeyComp = new PartitionKeyComparator();
static class StartColComparator implements Comparator<ServerRow> {
@Override public int compare(ServerRow r1, ServerRow r2) {
return compareStartCol(r1, r2);
}
private int compareStartCol(ServerRow r1, ServerRow r2) {
if(r1.getStartCol() > r2.getStartCol()) {
return 1;
} else if(r1.getStartCol() < r2.getStartCol()) {
return -1;
} else {
return 0;
}
}
}
static class PartitionKeyComparator implements Comparator<PartitionKey> {
@Override public int compare(PartitionKey p1, PartitionKey p2) {
return comparePartitionKey(p1, p2);
}
private int comparePartitionKey(PartitionKey p1, PartitionKey p2) {
if(p1.getStartCol() > p2.getStartCol()) {
return 1;
} else if(p1.getStartCol() < p2.getStartCol()) {
return -1;
} else {
return 0;
}
}
}
/**
* Combine the row splits use pipeline mode.
*
* @param cache the result cache for GET_ROW sub-requests
* @param matrixId matrix id
* @param rowIndex row index
* @return TVector merged row
* @throws InterruptedException interrupted while waiting for row splits
*/
public static TVector combineRowSplitsPipeline(GetRowPipelineCache cache, int matrixId,
int rowIndex) throws Exception {
MatrixMeta matrixMeta = PSAgentContext.get().getMatrixMetaManager().getMatrixMeta(matrixId);
RowType rowType = matrixMeta.getRowType();
switch (rowType) {
case T_DOUBLE_DENSE:
return combineDenseDoubleRowSplits(cache, matrixMeta, rowIndex);
case T_DOUBLE_SPARSE:
return combineServerSparseDoubleRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_LONGKEY:
return combineServerSparseDoubleLongKeyRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_FLOAT_SPARSE:
return combineServerSparseFloatRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_INT_DENSE:
return combineDenseIntRowSplits(cache, matrixMeta, rowIndex);
case T_FLOAT_DENSE:
return combineDenseFloatRowSplits(cache, matrixMeta, rowIndex);
case T_INT_SPARSE:
return combineServerSparseIntRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_COMPONENT:
return combineComponentServerSparseDoubleRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_FLOAT_SPARSE_COMPONENT:
return combineComponentServerSparseFloatRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_INT_SPARSE_COMPONENT:
return combineComponentServerSparseIntRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_LONGKEY_COMPONENT:
return combineCompServerSparseDoubleLongKeyRowSplits(getAllRowSplitsFromCache(cache), matrixMeta, rowIndex);
default:
throw new UnsupportedOperationException("Unsupport operation: merge " + rowType + " vector splits");
}
}
private static List<ServerRow> getAllRowSplitsFromCache(GetRowPipelineCache cache)
throws InterruptedException {
int splitNum = cache.getTotalRequestNum();
List<ServerRow> splits = new ArrayList<ServerRow>(splitNum);
ServerRow split = null;
int index = 0;
while ((split = cache.poll()) != null && index < splitNum) {
splits.add(split);
index++;
}
return splits;
}
private static TVector combineDenseIntRowSplits(GetRowPipelineCache pipelineCache,
MatrixMeta matrixMeta, int rowIndex) throws InterruptedException {
int colNum = (int)matrixMeta.getColNum();
int[] dataArray = new int[colNum];
int clock = Integer.MAX_VALUE;
while (true) {
ServerRow split = pipelineCache.poll();
if (split == null) {
TVector row = new DenseIntVector(colNum, dataArray);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
if (split.getClock() < clock) {
clock = split.getClock();
}
((ServerDenseIntRow) split).mergeTo(dataArray);
}
}
private static TVector combineDenseFloatRowSplits(GetRowPipelineCache pipelineCache,
MatrixMeta matrixMeta, int rowIndex) throws InterruptedException {
int colNum = (int)matrixMeta.getColNum();
float[] dataArray = new float[colNum];
int clock = Integer.MAX_VALUE;
while (true) {
ServerRow split = pipelineCache.poll();
if (split == null) {
TVector row = new DenseFloatVector(colNum, dataArray);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
if (split.getClock() < clock) {
clock = split.getClock();
}
((ServerDenseFloatRow) split).mergeTo(dataArray);
}
}
private static TVector combineDenseDoubleRowSplits(GetRowPipelineCache pipelineCache,
MatrixMeta matrixMeta, int rowIndex) throws InterruptedException {
int colNum = (int)matrixMeta.getColNum();
double[] dataArray = new double[colNum];
int clock = Integer.MAX_VALUE;
while (true) {
ServerRow split = pipelineCache.poll();
if (split == null) {
TVector row = new DenseDoubleVector(colNum, dataArray);
row.setClock(clock);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
return row;
}
if (split.getClock() < clock) {
clock = split.getClock();
}
((ServerDenseDoubleRow) split).mergeTo(dataArray);
}
}
/**
* Combine row splits of a single matrix row.
*
* @param rowSplits row splits
* @param matrixId matrix id
* @param rowIndex row index
* @return TVector merged row
*/
public static TVector combineServerRowSplits(List<ServerRow> rowSplits, int matrixId, int rowIndex) {
MatrixMeta matrixMeta = PSAgentContext.get().getMatrixMetaManager().getMatrixMeta(matrixId);
RowType rowType = matrixMeta.getRowType();
switch (rowType) {
case T_DOUBLE_DENSE:
return combineServerDenseDoubleRowSplits(rowSplits, matrixMeta, rowIndex);
case T_FLOAT_DENSE:
return combineServerDenseFloatRowSplits(rowSplits, matrixMeta, rowIndex);
case T_DOUBLE_SPARSE:
return combineServerSparseDoubleRowSplits(rowSplits, matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_LONGKEY:
return combineServerSparseDoubleLongKeyRowSplits(rowSplits, matrixMeta, rowIndex);
case T_FLOAT_SPARSE:
return combineServerSparseFloatRowSplits(rowSplits, matrixMeta, rowIndex);
case T_INT_DENSE:
return combineServerDenseIntRowSplits(rowSplits, matrixMeta, rowIndex);
case T_INT_SPARSE:
return combineServerSparseIntRowSplits(rowSplits, matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_COMPONENT:
return combineComponentServerSparseDoubleRowSplits(rowSplits, matrixMeta, rowIndex);
case T_FLOAT_SPARSE_COMPONENT:
return combineComponentServerSparseFloatRowSplits(rowSplits, matrixMeta, rowIndex);
case T_INT_SPARSE_COMPONENT:
return combineComponentServerSparseIntRowSplits(rowSplits, matrixMeta, rowIndex);
case T_DOUBLE_SPARSE_LONGKEY_COMPONENT:
return combineCompServerSparseDoubleLongKeyRowSplits(rowSplits, matrixMeta, rowIndex);
case T_INT_ARBITRARY:
return combineServerArbitaryIntRowSplits(rowSplits, matrixMeta, rowIndex);
default:
throw new UnsupportedOperationException("Unsupport operation: merge " + rowType + " vector splits");
}
}
private static TVector combineServerArbitaryIntRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
// TODO Auto-generated method stub
return null;
}
private static TVector combineServerSparseIntRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
int splitNum = rowSplits.size();
int totalElemNum = 0;
int[] lens = new int[splitNum];
Collections.sort(rowSplits, serverRowComp);
int elemNum = 0;
for (int i = 0; i < splitNum; i++) {
elemNum = rowSplits.get(i).size();
totalElemNum += elemNum;
lens[i] = elemNum;
}
int[] indexes = new int[totalElemNum];
int[] values = new int[totalElemNum];
int clock = Integer.MAX_VALUE;
int startPos = 0;
for (int i = 0; i < splitNum; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerSparseIntRow) rowSplits.get(i)).mergeTo(indexes, values, startPos, lens[i]);
startPos += lens[i];
}
TVector row = new SparseIntVector(colNum, indexes, values);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineServerDenseIntRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
int[] dataArray = new int[colNum];
Collections.sort(rowSplits, serverRowComp);
int clock = Integer.MAX_VALUE;
int size = rowSplits.size();
for (int i = 0; i < size; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerDenseIntRow) rowSplits.get(i)).mergeTo(dataArray);
}
TVector row = new DenseIntVector(colNum, dataArray);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineServerSparseDoubleRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
int splitNum = rowSplits.size();
int totalElemNum = 0;
int[] lens = new int[splitNum];
Collections.sort(rowSplits, serverRowComp);
int elemNum = 0;
for (int i = 0; i < splitNum; i++) {
elemNum = rowSplits.get(i).size();
totalElemNum += elemNum;
lens[i] = elemNum;
}
int[] indexes = new int[totalElemNum];
double[] values = new double[totalElemNum];
int clock = Integer.MAX_VALUE;
int startPos = 0;
for (int i = 0; i < splitNum; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerSparseDoubleRow) rowSplits.get(i)).mergeTo(indexes, values, startPos, lens[i]);
startPos += lens[i];
}
TVector row = new SparseDoubleVector(colNum, indexes, values);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineServerSparseDoubleLongKeyRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
long colNum = matrixMeta.getColNum();
int splitNum = rowSplits.size();
int totalElemNum = 0;
int[] lens = new int[splitNum];
Collections.sort(rowSplits, serverRowComp);
int elemNum = 0;
for (int i = 0; i < splitNum; i++) {
elemNum = rowSplits.get(i).size();
totalElemNum += elemNum;
lens[i] = elemNum;
}
long[] indexes = new long[totalElemNum];
double[] values = new double[totalElemNum];
int clock = Integer.MAX_VALUE;
int startPos = 0;
assert(rowSplits.size() > 0);
double defaultValue = ((ServerSparseDoubleLongKeyRow) rowSplits.get(0)).getDefaultValue();
for (int i = 0; i < splitNum; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
ServerSparseDoubleLongKeyRow row = (ServerSparseDoubleLongKeyRow) rowSplits.get(i);
row.mergeTo(indexes, values, startPos, lens[i]);
assert(defaultValue == row.getDefaultValue());
startPos += lens[i];
}
Long2DoubleOpenHashMap data = new Long2DoubleOpenHashMap(indexes, values);
data.defaultReturnValue(defaultValue);
SparseLongKeyDoubleVector row = new SparseLongKeyDoubleVector(colNum, data);
row.setModelNnz(matrixMeta.getValidIndexNum());
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineCompServerSparseDoubleLongKeyRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
List<PartitionKey> partitionKeys = PSAgentContext.get().getMatrixMetaManager().getPartitions(matrixMeta.getId(), rowIndex);
assert rowSplits.size() == partitionKeys.size();
Collections.sort(rowSplits, serverRowComp);
Collections.sort(partitionKeys, partKeyComp);
SparseLongKeyDoubleVector[] splits = new SparseLongKeyDoubleVector[rowSplits.size()];
int size = rowSplits.size();
int clock = Integer.MAX_VALUE;
for(int i = 0; i < size; i++) {
splits[i] = new SparseLongKeyDoubleVector(matrixMeta.getColNum(), ((ServerSparseDoubleLongKeyRow)(rowSplits.get(i))).getIndex2ValueMap());
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
}
CompSparseLongKeyDoubleVector row = new CompSparseLongKeyDoubleVector(matrixMeta.getId(),
rowIndex, matrixMeta.getColNum(), partitionKeys.toArray(new PartitionKey[0]), splits);
row.setClock(clock);
return row;
}
private static TVector combineComponentServerSparseIntRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
List<PartitionKey> partitionKeys = PSAgentContext.get().getMatrixMetaManager().getPartitions(matrixMeta.getId(), rowIndex);
assert rowSplits.size() == partitionKeys.size();
Collections.sort(rowSplits, serverRowComp);
Collections.sort(partitionKeys, partKeyComp);
TIntVector [] splits = new TIntVector[rowSplits.size()];
int size = rowSplits.size();
int clock = Integer.MAX_VALUE;
for(int i = 0; i < size; i++) {
splits[i] = new SparseIntVector((int)matrixMeta.getColNum(), ((ServerSparseIntRow)(rowSplits.get(i))).getData());
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
}
CompSparseIntVector row = new CompSparseIntVector(matrixMeta.getId(),
rowIndex, (int)matrixMeta.getColNum(), partitionKeys.toArray(new PartitionKey[0]), splits);
row.setClock(clock);
return row;
}
private static TVector combineComponentServerSparseDoubleRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
List<PartitionKey> partitionKeys = PSAgentContext.get().getMatrixMetaManager().getPartitions(matrixMeta.getId(), rowIndex);
assert rowSplits.size() == partitionKeys.size();
Collections.sort(rowSplits, serverRowComp);
Collections.sort(partitionKeys, partKeyComp);
TIntDoubleVector[] splits = new TIntDoubleVector[rowSplits.size()];
int size = rowSplits.size();
int clock = Integer.MAX_VALUE;
for(int i = 0; i < size; i++) {
splits[i] = new SparseDoubleVector((int)matrixMeta.getColNum(), ((ServerSparseDoubleRow)(rowSplits.get(i))).getData());
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
}
CompSparseDoubleVector row = new CompSparseDoubleVector(matrixMeta.getId(),
rowIndex, (int)matrixMeta.getColNum(), partitionKeys.toArray(new PartitionKey[0]), splits);
row.setClock(clock);
return row;
}
private static TVector combineComponentServerSparseFloatRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
long startTs = System.currentTimeMillis();
List<PartitionKey> partitionKeys = PSAgentContext.get().getMatrixMetaManager().getPartitions(matrixMeta.getId(), rowIndex);
assert rowSplits.size() == partitionKeys.size();
Collections.sort(rowSplits, serverRowComp);
Collections.sort(partitionKeys, partKeyComp);
TFloatVector [] splits = new TFloatVector[rowSplits.size()];
int size = rowSplits.size();
int clock = Integer.MAX_VALUE;
for(int i = 0; i < size; i++) {
splits[i] = new SparseFloatVector((int)matrixMeta.getColNum(), ((ServerSparseFloatRow)(rowSplits.get(i))).getData());
LOG.info("SparseFloatVector " + i + " sum=" + splits[i].sum());
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
}
CompSparseFloatVector row = new CompSparseFloatVector(matrixMeta.getId(),
rowIndex, (int)matrixMeta.getColNum(), partitionKeys.toArray(new PartitionKey[0]), splits);
row.setClock(clock);
LOG.info("generate vector, split number=" + size + ", use time=" + (System.currentTimeMillis() - startTs));
return row;
}
private static TVector combineServerSparseFloatRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
int splitNum = rowSplits.size();
int totalElemNum = 0;
int[] lens = new int[splitNum];
Collections.sort(rowSplits, serverRowComp);
int elemNum = 0;
for (int i = 0; i < splitNum; i++) {
elemNum = rowSplits.get(i).size();
totalElemNum += elemNum;
lens[i] = elemNum;
}
int[] indexes = new int[totalElemNum];
float[] values = new float[totalElemNum];
int clock = Integer.MAX_VALUE;
int startPos = 0;
for (int i = 0; i < splitNum; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerSparseFloatRow) rowSplits.get(i)).mergeTo(indexes, values, startPos, lens[i]);
startPos += lens[i];
}
TVector row = new SparseFloatVector(colNum, indexes, values);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineServerDenseDoubleRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
double[] dataArray = new double[colNum];
Collections.sort(rowSplits, serverRowComp);
int clock = Integer.MAX_VALUE;
int size = rowSplits.size();
for (int i = 0; i < size; i++) {
if(rowSplits.get(i) == null) {
continue;
}
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerDenseDoubleRow) rowSplits.get(i)).mergeTo(dataArray);
}
TVector row = new DenseDoubleVector(colNum, dataArray);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
private static TVector combineServerDenseFloatRowSplits(List<ServerRow> rowSplits,
MatrixMeta matrixMeta, int rowIndex) {
int colNum = (int)matrixMeta.getColNum();
float[] dataArray = new float[colNum];
Collections.sort(rowSplits, serverRowComp);
int clock = Integer.MAX_VALUE;
int size = rowSplits.size();
for (int i = 0; i < size; i++) {
if (rowSplits.get(i).getClock() < clock) {
clock = rowSplits.get(i).getClock();
}
((ServerDenseFloatRow) rowSplits.get(i)).mergeTo(dataArray);
}
TVector row = new DenseFloatVector(colNum, dataArray);
row.setMatrixId(matrixMeta.getId());
row.setRowId(rowIndex);
row.setClock(clock);
return row;
}
}
| 35.478921
| 144
| 0.690432
|
2a764f526bc80230ec1143f950d97ac0be1b4c87
| 1,980
|
package wraith.fabricaeexnihilo.util;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.SemanticVersion;
import net.fabricmc.loader.api.VersionParsingException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.stream.Stream;
// If a mod ever breaks a mixin you can set up an entry here and in Plugin with a slower, more compatible mixin.
public final class MixinCompatibility {
private MixinCompatibility() {
}
private record ModEntry(
@NotNull String modId,
@Nullable SemanticVersion version
) {
ModEntry {
Objects.requireNonNull(modId, "modId can not be null");
}
private ModEntry(@NotNull String modId) {
this(modId, (SemanticVersion) null);
}
private ModEntry(@NotNull String modId, @Nullable String version) throws VersionParsingException {
this(modId, version == null ? null : SemanticVersion.parse(version));
}
private boolean test() {
var container = FabricLoader.getInstance().getModContainer(modId());
if (container.isPresent()) {
if (version == null) {
return true;
}
var metadata = container.get();
// Is the mod greater than the incompatible version?
return metadata.getMetadata().getVersion().compareTo(version) > 0;
}
return false;
}
}
public enum Modes {
// This is one of those things that is likely to break in another mod...
BLOCK_COLOR_OVERRIDE();
private final boolean enabled;
Modes(ModEntry... mods) {
enabled = Stream.of(mods).anyMatch(ModEntry::test);
}
public boolean enabled() {
return enabled;
}
}
}
| 31.935484
| 112
| 0.59899
|
587cc4f22227c6e6955d42257aaa0a6beb1a9d07
| 690
|
package com.github.quiram.course.collectors.a.safer.commands;
import org.junit.jupiter.api.Test;
import static com.github.quiram.utils.Random.randomString;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ReverseCommandTest extends CommandTestBase {
@Override
protected Command command() {
return new ReverseCommand();
}
@Override
protected String supportedSample() {
return randomString() + " in reverse";
}
@Test
void returnWordsInReverseWhenApplying() {
final String result = command().apply("something anything everything in reverse");
assertEquals("everything anything something", result);
}
}
| 27.6
| 90
| 0.718841
|
ef8d5f88f83111a5bba0e0af9e69cf71267c2a07
| 921
|
package org.alltiny.chorus.xml;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.alltiny.xml.handler.XMLHandler;
import org.alltiny.xml.handler.AssignHandler;
/**
* This class represents
*
* @author <a href="mailto:ralf.hergert.de@gmail.com">Ralf Hergert</a>
* @version 08.11.2008 13:49:35
*/
public class StringXMLHandler extends XMLHandler<String> {
private String text = "";
public StringXMLHandler(AssignHandler<String> assignHandler) {
super(assignHandler);
}
public void characters(char ch[], int start, int length) throws SAXException {
text = new String(ch, start, length);
}
protected XMLHandler getHandlerInstance(String uri, String localName, String qName, Attributes attributes) throws SAXException {
throw new SAXException("No child elements supposed.");
}
public String getObject() {
return text;
}
}
| 27.088235
| 132
| 0.709012
|
8d425b4313af0f912a708b3d28cebf2119638ed9
| 730
|
package uk.co.quidos.gdsap.framework.enums;
import uk.co.quidos.gdsap.framework.sys.lang.enums.BaseEnum;
/**
* <strong>UserLevel</strong><br>
* <strong>Create on : 2012-3-11<br></strong>
* <p><strong>Copyright (C) Ecointel Software Co.,Ltd.<br></strong></p>
* @author peng.shi peng.shi@ecointel.com.cn<br>
* @version <strong>ecointel-roomyi v1.0.0</strong><br>
*/
public enum UserLevel implements BaseEnum<Integer>
{
;
private String desc;
private Integer code;
private UserLevel(String desc,Integer code)
{
this.desc = desc;
this.code = code;
}
@Override
public Integer getCode()
{
return this.code;
}
@Override
public String getDesc()
{
return this.desc;
}
}
| 20.277778
| 72
| 0.660274
|
785b85f5ce7f2d4a1fb5aec0641d8237e12917bb
| 1,419
|
package quickstart.Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.aventstack.extentreports.model.Test;
import Constants.TimeOuts;
import functionLibrary.ReportLog;
public class GoogleSearchPage {
WebDriver driver;
/**
* Each Page class has all the WeblElements in the form of By.
* These WebElements can be used in the page class across all the methods.
*/
By searchBox= By.xpath("//input[@name='q']");
By firstResult= By.xpath("//div[@class='g']//h3/span");
/**
* Constructor of the Page class to set the driver.
* @param driver
*/
public GoogleSearchPage(WebDriver driver) {
this.driver=driver;
}
public void enterKeyWord(String keyword) {
driver.findElement(searchBox).sendKeys(keyword);
driver.findElement(searchBox).sendKeys(Keys.ENTER);
}
public void waitForResultLink(String keyword) {
String searchResultLink="//h3[contains(.,'"+keyword+"')]";
WebDriverWait wait= new WebDriverWait(driver, TimeOuts.DEFAULT_TIMEOUT);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(searchResultLink)));
}
public void searchKeyword(String keyword) {
this.enterKeyWord(keyword);
this.waitForResultLink(keyword);
}
}
| 24.465517
| 88
| 0.748414
|
7c513815220c5cf0d8a69d15b0161e1cc3c63d2e
| 389
|
package gov.samhsa.c2s.pcm.service.consent;
import gov.samhsa.c2s.pcm.domain.consent.ConsentRevocationTermsVersions;
import gov.samhsa.c2s.pcm.service.dto.ConsentRevocationTermsVersionsDto;
public interface ConsentRevocationTermsVersionsService {
ConsentRevocationTermsVersions findByLatestEnabledVersion();
ConsentRevocationTermsVersionsDto findDtoByLatestEnabledVersion();
}
| 32.416667
| 72
| 0.858612
|
4b9199a487980ef10ee560c38751a17da709ca56
| 1,191
|
package ru.job4j.chess;
public class King extends Figure {
public King(Cell cell) {
super(cell);
}
public Cell[] way(Cell source, Cell dest) throws ImpossibleMoveException {
int x0 = source.getPosX();
int y0 = source.getPosY();
int x1 = dest.getPosX();
int y1 = dest.getPosY();
int deltaX = Integer.compare(x0, x1);
int deltaY = Integer.compare(y0, y1);
if (deltaX == 0 && Math.abs(y0 - y1) == 1) {
Cell[] moveArray = new Cell[1];
moveArray[0] = new Cell(x0, y0 + deltaY);
return moveArray;
} else if (deltaY == 0 && Math.abs(x0 - x1) == 1) {
Cell[] moveArray = new Cell[1];
moveArray[0] = new Cell(x0 + deltaX, y0);
return moveArray;
} else if (Math.abs(x0 - x1) == 1 && Math.abs(y0 - y1) == 1) {
Cell[] moveArray = new Cell[1];
moveArray[0] = new Cell(x0 + deltaX, y0 + deltaY);
return moveArray;
} else {
throw new ImpossibleMoveException("Your king can't move such way");
}
}
public Figure copy(Cell dest) {
return new King(dest);
}
}
| 32.189189
| 79
| 0.525609
|
7507c21076f1004f970031ce88f9e7b4e507eeb7
| 366
|
package org.gradle;
import java.security.Permission;
import static org.junit.Assert.assertEquals;
public class MySecurityManager extends SecurityManager {
public MySecurityManager() {
assertEquals(getClass().getName(), System.getProperty("java.security.manager"));
}
@Override
public void checkPermission(Permission permission) {
}
}
| 22.875
| 88
| 0.740437
|
00cf9c3c70230cb77cdb603c6dde487a0dbba6db
| 1,604
|
package com.example.administrator.boshide2.Modular.Fragment.HuiYuanGuanLi.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.administrator.boshide2.R;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2017-5-9.
* 经办人适配器
*/
public class BSD_hygl_jingban_adp extends BaseAdapter{
LayoutInflater inflater;
Context context;
List<Map<String, String>> list;
public BSD_hygl_jingban_adp(Context context, List<Map<String, String>> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
class Holder {
TextView tv_hygl_bumen_name;}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Holder holder = null;
if (view == null) {
holder = new Holder();
view = inflater.inflate(R.layout.bsd_hygl_bumen_item, null);
holder.tv_hygl_bumen_name = (TextView) view.findViewById(R.id.tv_hygl_bumen_name);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.tv_hygl_bumen_name.setText(list.get(i).get("name"));
return view;
}
}
| 22.914286
| 94
| 0.65212
|
c316f0b5a2c2b3bae3a97502f0572cc07fb2b78d
| 4,015
|
package com.jukusoft.erp.gui.app;
import com.jukusoft.erp.gui.cache.Cache;
import com.jukusoft.erp.gui.eventbus.EventBus;
import com.jukusoft.erp.gui.logging.LocalConsoleLogger;
import com.jukusoft.erp.gui.utils.JavaFXUtils;
import com.jukusoft.erp.gui.window.LoginWindow;
import com.jukusoft.erp.gui.window.MainWindow;
import com.jukusoft.erp.network.manager.NetworkManager;
import com.jukusoft.erp.network.user.Account;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.ini4j.Ini;
import org.ini4j.Profile;
import java.io.File;
import java.io.IOException;
/**
* Created by Justin on 29.08.2017.
*/
public class JavaFXApplication extends Application {
//primary stage
protected Stage primaryStage = null;
//login window
protected LoginWindow loginWindow = null;
//main window
protected MainWindow mainWindow = null;
//default configuration
protected Ini ini = new Ini();
protected Profile.Section defaultCfg = null;
//network manager
protected NetworkManager networkManager = null;
/**
* default constructor
*/
public JavaFXApplication() {
//
}
@Override
public void start(Stage primaryStage) throws Exception {
//save primary stage
this.primaryStage = primaryStage;
primaryStage.setOnCloseRequest(event -> {
System.out.println("close application now.");
//shutdown network engine
NetworkManager.getInstance().shutdown();
System.exit(0);
});
//read default config
this.readDefaultConfig();
//initialize networking
this.networkManager = NetworkManager.getInstance();
this.networkManager.init();
//initialize caching
Cache.init(new File("./cache"), new LocalConsoleLogger());
//create and show new login window
this.loginWindow = new LoginWindow(this.primaryStage, "ERP System - Login, (c) 2017 JuKuSoft.com", defaultCfg.getOrDefault("serverIP", ""), defaultCfg.getOrDefault("user", ""), this::onLogin);
this.loginWindow.setVisible(true);
}
/**
* read default login values from configuration
*/
protected void readDefaultConfig () {
try {
this.ini = new Ini(new File("./config/default.cfg"));
this.defaultCfg = this.ini.get("Default");
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
protected void onLogin (Account account) {
System.out.println("User '" + account.getUsername() + "' (userID: " + account.getUserID() + ") logged in successfully.");
//hide login window
this.loginWindow.setVisible(false);
//redirect internal events to event bus
NetworkManager.getInstance().addGlobalSubscriber(msg -> {
if (msg.getEvent().startsWith("internal:")) {
//call eventbus
EventBus.getInstance().raiseEvent(msg);
}
});
//add event listener for warnings notifications
EventBus.getInstance().addListener("warning_notification", (event, eventData) -> {
Platform.runLater(() -> {
String title = eventData.getString("title");
String text = eventData.getString("text");
JavaFXUtils.showErrorDialog(title, text);
});
});
//add event listener for important notifications
EventBus.getInstance().addListener("info_notification", (event, eventData) -> {
Platform.runLater(() -> {
String title = eventData.getString("title");
String text = eventData.getString("text");
JavaFXUtils.showInfoDialog(title, text);
});
});
//create and show new main window
this.mainWindow = new MainWindow(this.primaryStage, "OS ERP System");
this.mainWindow.setVisible(true);
}
}
| 30.648855
| 200
| 0.634371
|
743f33da3479b1e7c26aa83040b8f565ff05f0cc
| 829
|
package org.fieldsight.naxa.survey;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Query;
import androidx.room.Transaction;
import org.fieldsight.naxa.common.database.BaseDaoFieldSight;
import java.util.ArrayList;
import java.util.List;
@Dao
public abstract class SurveyFormDAO implements BaseDaoFieldSight<SurveyForm> {
@Query("SELECT * FROM survey_forms")
public abstract LiveData<List<SurveyForm>> getAllSurveyForms();
@Query("DELETE FROM survey_forms")
public abstract void deleteAll();
@Transaction
public void updateAll(ArrayList<SurveyForm> items) {
deleteAll();
insert(items);
}
@Query("SELECT * FROM survey_forms WHERE projectId= :projectId")
public abstract LiveData<List<SurveyForm>> getByProjectId(String projectId);
}
| 25.121212
| 80
| 0.752714
|
3a575dc06f2975e2f66bd5541cea8ca69700656c
| 379
|
package hr.fer.zemris.java.custom.scripting.elems;
/**
* Class representing int value node element.
* @author Blaz Bagic
* @version 1.0
*/
public class ElementConstantInteger extends Element {
private final int value;
public ElementConstantInteger(int value) {
this.value = value;
}
@Override
public String asText() {
return String.valueOf(value);
}
}
| 18.95
| 53
| 0.709763
|
c58c6cd52422ee0483b337840660b663d7af5e18
| 1,944
|
package org.anddev.andengine.entity.scene.background;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:44:31 - 19.07.2010
*/
public class AutoParallaxBackground extends ParallaxBackground {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mParallaxChangePerSecond;
// ===========================================================
// Constructors
// ===========================================================
public AutoParallaxBackground(final float pRed, final float pGreen, final float pBlue, final float pParallaxChangePerSecond) {
super(pRed, pGreen, pBlue);
this.mParallaxChangePerSecond = pParallaxChangePerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public void setParallaxChangePerSecond(final float pParallaxChangePerSecond) {
this.mParallaxChangePerSecond = pParallaxChangePerSecond;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
this.mParallaxValue += this.mParallaxChangePerSecond * pSecondsElapsed;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 32.949153
| 128
| 0.389918
|
69bd2358e5d470597acdec6d529aa805c20083ba
| 6,154
|
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Eugen [WebDucer] Richter
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package de.webducer.android.utilities;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.util.Log;
import java.io.ByteArrayInputStream;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
/**
* Log Helper
*
* @author WebDucer - IT & Internet Service
* @version 0.4
* @since 2015-02-23
*/
public class LogHelper {
private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
private static boolean _DEBUG = false;
private static boolean _IsDebugStateRead = false;
public static final boolean isDebuggable(Context ctx) {
if (!_IsDebugStateRead) {
_DEBUG = false;
try {
PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), PackageManager.GET_SIGNATURES);
Signature signatures[] = pinfo.signatures;
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int i = 0; i < signatures.length; i++) {
ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
_DEBUG = cert.getSubjectX500Principal().equals(DEBUG_DN);
if (_DEBUG) {
break;
}
}
} catch (PackageManager.NameNotFoundException e) {
// debuggable variable will remain false
} catch (CertificateException e) {
// debuggable variable will remain false
}
_IsDebugStateRead = true;
}
return _DEBUG;
}
/**
* Log formatted message for DEBUG level
*
* @param tag Log tag
* @param formatString Log formating string
* @param formatParams Log formating parameters
* @return 0: not logged
*/
public final static int d(String tag, String formatString, Object... formatParams) {
if (_DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
if (formatParams != null && formatParams.length > 0) {
return Log.d(tag, String.format(formatString, formatParams));
} else {
return Log.d(tag, formatString);
}
} else {
return 0;
}
}
/**
* Log message and exception for DEBUG level
*
* @param tag Log tag
* @param message Log message
* @param exception Exception to log
* @return 0: not logged
*/
public final static int d(String tag, String message, Throwable exception) {
if (_DEBUG || Log.isLoggable(tag, Log.DEBUG)) {
return Log.d(tag, message, exception);
} else {
return 0;
}
}
/**
* Log formatted message for INFO level
*
* @param tag Log tag
* @param formatString Log formating string
* @param formatParams Log formating parameters
* @return 0: not logged
*/
public final static int i(String tag, String formatString, Object... formatParams) {
if (Log.isLoggable(tag, Log.INFO)) {
if (formatParams != null && formatParams.length > 0) {
return Log.i(tag, String.format(formatString, formatParams));
} else {
return Log.i(tag, formatString);
}
} else {
return 0;
}
}
/**
* Log message and exception for INFO level
*
* @param tag Log tag
* @param message Log message
* @param exception Exception to log
* @return 0: not logged
*/
public final static int i(String tag, String message, Throwable exception) {
if (Log.isLoggable(tag, Log.INFO)) {
return Log.i(tag, message, exception);
} else {
return 0;
}
}
/**
* Log formatted message for ERROR level
*
* @param tag Log tag
* @param formatString Log message format string
* @param formatParams Log message parameters
* @return 0: not logged
*/
public final static int e(String tag, String formatString, Object... formatParams) {
if (Log.isLoggable(tag, Log.ERROR)) {
if (formatParams != null && formatParams.length > 0) {
return Log.e(tag, String.format(formatString, formatParams));
} else {
return Log.e(tag, formatString);
}
} else {
return 0;
}
}
/**
* Log message and exception for ERROR level
*
* @param tag Log tag
* @param message Log message
* @param exception Exception to log
* @return 0: not logged
*/
public final static int e(String tag, String message, Throwable exception) {
if (Log.isLoggable(tag, Log.ERROR)) {
return Log.i(tag, message, exception);
} else {
return 0;
}
}
}
| 32.219895
| 124
| 0.638284
|
353eade621a1bdb182a6dfde0204742005be0b1f
| 8,853
|
package io.github.n34t0.platform.impl.services.impl;
import io.github.n34t0.platform.impl.edt.EdtUtil;
import io.github.n34t0.platform.impl.edt.EdtAdapter;
import io.github.n34t0.platform.impl.services.ApplicationService;
import com.intellij.BundleBase;
import com.intellij.codeInsight.completion.CodeCompletionHandlerBase;
import com.intellij.codeInsight.completion.CompletionProgressIndicator;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings;
import com.intellij.codeInsight.editorActions.CompletionAutoPopupHandler;
import com.intellij.concurrency.IdeaForkJoinWorkerThreadFactory;
import com.intellij.diagnostic.StartUpMeasurer;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.execution.process.ProcessIOExecutorService;
import com.intellij.ide.AppLifecycleListener;
import com.intellij.ide.IpwEventQueue;
import com.intellij.ide.DataManager;
import com.intellij.ide.impl.HeadlessDataManager;
import com.intellij.ide.plugins.IdeaPluginDescriptorImpl;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.idea.ApplicationLoader;
import com.intellij.idea.Main;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.application.impl.ApplicationImpl;
import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkProvider;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil;
import com.intellij.openapi.projectRoots.ProjectJdkTable;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.encoding.EncodingManager;
import com.intellij.openapi.vfs.encoding.EncodingManagerImpl;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFS;
import com.intellij.openapi.vfs.newvfs.persistent.PersistentFSImpl;
import com.intellij.testFramework.TestModeFlags;
import com.intellij.util.concurrency.AppExecutorUtil;
import com.intellij.util.indexing.FileBasedIndex;
import com.intellij.util.indexing.FileBasedIndexEx;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.ui.EdtInvocationManager;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class ApplicationServiceImpl extends IpwService implements ApplicationService {
private static final boolean IS_STRESS_TEST = true;
private static final boolean IS_UNIT_TEST = true;
private static final String IPW_JDK = "ipw.jdk";
private Sdk mySdk;
@Override
protected void doInit() {
setEdtInvocationManager();
Main.setHeadlessInTestMode(true);
IdeaForkJoinWorkerThreadFactory.setupForkJoinCommonPool(true);
// stop the startup measuring
StartUpMeasurer.disable();
StartUpMeasurer.stopPluginCostMeasurement();
if (IS_STRESS_TEST) {
// it might add a bit of performance
ApplicationInfoImpl.setInStressTest(true);
}
// exclude errors about missing plugins
PluginManagerCore.isUnitTestMode = true;
EdtUtil.runInEdtAndWait(this::runAppAndLoadPluginsAndServices);
// fix the returning of an incomplete result by code completion
TestModeFlags.set(CompletionAutoPopupHandler.ourTestingAutopopup, true);
CompletionProgressIndicator.setGroupingTimeSpan(3600 * 1000);
CodeCompletionHandlerBase.setAutoInsertTimeout(3600 * 1000);
DaemonCodeAnalyzerSettings.getInstance().setImportHintEnabled(false);
EdtUtil.runInEdtAndWait(this::registerSdk);
}
@Override
public void dispose() {
try {
EdtUtil.runInEdtAndWait(() -> {
var app = (ApplicationImpl)ApplicationManager.getApplication();
var encodingManager = app.getServiceIfCreated(EncodingManager.class);
if (encodingManager instanceof EncodingManagerImpl) {
((EncodingManagerImpl)encodingManager).clearDocumentQueue();
}
IpwUtil.cleanupSwingDataStructures();
UIUtil.dispatchAllInvocationEvents();
sendClosingMessage(app);
var fileBasedIndex = app.getServiceIfCreated(FileBasedIndex.class);
if (fileBasedIndex instanceof FileBasedIndexEx) {
((FileBasedIndexEx)fileBasedIndex).waitUntilIndicesAreInitialized();
}
IpwUtil.appWaitForThreads();
app.invokeAndWait(app::disposeContainer);
ProcessIOExecutorService.INSTANCE.shutdownNow();
UIUtil.dispatchAllInvocationEvents();
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Application getApplication() {
return ApplicationManager.getApplication();
}
@Override
public Sdk getSdk() {
return mySdk;
}
private void registerSdk() {
String jdkPath = System.getProperty(IPW_JDK);
mySdk = jdkPath != null
? ExternalSystemJdkProvider.getInstance().createJdk(null, jdkPath)
: ExternalSystemJdkUtil.resolveJdkName(null, ExternalSystemJdkUtil.USE_JAVA_HOME);
getApplication().runWriteAction(() -> ProjectJdkTable.getInstance().addJdk(mySdk, this));
}
@Override
public void setDataProvider(DataProvider provider) {
getDataManager().setTestDataProvider(provider);
}
@Override
public void dispatchAllInvocationEvents() {
EdtAdapter.dispatchAllInvocationEvents();
}
private void runAppAndLoadPluginsAndServices() {
var loadedPluginFuture = CompletableFuture.supplyAsync(
() -> PluginManagerCore.getLoadedPlugins(PathManager.class.getClassLoader()),
AppExecutorUtil.getAppExecutorService());
var app = new ApplicationImpl(false, IS_UNIT_TEST, true, true);
// disable error messages about missing keys
BundleBase.assertOnMissedKeys(false);
try {
List<IdeaPluginDescriptorImpl> plugins = ApplicationLoader.registerRegistryAndInitStore(
ApplicationLoader.registerAppComponents(loadedPluginFuture, app),
app
).get(40, TimeUnit.SECONDS);
Executor boundedExecutor = ApplicationLoader.createExecutorToPreloadServices();
Registry.getInstance().markAsLoaded();
var preloadedServiceFuture =
ApplicationLoader.preloadServices(plugins, app, "", false, boundedExecutor);
app.loadComponents(null);
preloadedServiceFuture
.thenCompose(v -> ApplicationLoader.callAppInitialized(app, boundedExecutor))
.get(40, TimeUnit.SECONDS);
((PersistentFSImpl)PersistentFS.getInstance()).cleanPersistedContents();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(Objects.requireNonNullElse(e.getCause(), e));
} catch (TimeoutException e) {
throw new RuntimeException("Cannot preload services in 40 seconds: "
+ ThreadDumper.dumpThreadsToString(), e);
}
}
private HeadlessDataManager getDataManager() {
return ((HeadlessDataManager)DataManager.getInstance());
}
private void setEdtInvocationManager() {
EdtInvocationManager.setEdtInvocationManager(new EdtInvocationManager() {
@Override
public boolean isEventDispatchThread() {
return IpwEventQueue.isDispatchThread();
}
@Override
public void invokeLater(@NotNull Runnable task) {
IpwEventQueue.invokeLater(task);
}
@Override
public void invokeAndWait(@NotNull Runnable task) throws InvocationTargetException, InterruptedException {
IpwEventQueue.invokeAndWait(task);
}
});
}
private void sendClosingMessage(ApplicationImpl app) {
MessageBus messageBus = app.getMessageBus();
if (messageBus != null) {
var appLifecycleListener = messageBus.syncPublisher(AppLifecycleListener.TOPIC);
if (appLifecycleListener != null) {
appLifecycleListener.appWillBeClosed(false);
}
}
}
}
| 41.56338
| 118
| 0.717836
|
b1656223df1cccbb29809d535c5bdb9b95445def
| 130
|
package testPullUpGen.test13.expectedresult;
public abstract class SS extends S <String> {
abstract void m(String s);
}
| 18.571429
| 45
| 0.730769
|
5e1813b404dceeffafdac3fca98667de96d49c18
| 3,498
|
/*
* Copyright (C) 2016-2020, Stichting Mapcode Foundation (http://www.mapcode.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mapcode.services.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.mapcode.Alphabet;
import com.tomtom.speedtools.apivalidation.ApiDTO;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import javax.annotation.Nonnull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@SuppressWarnings({"NullableProblems", "InstanceVariableMayNotBeInitialized"})
@ApiModel(
value = "alphabets",
description = "A list of alphabet objects, such as returned by `GET /mapcode/alphabets`.")
@JsonInclude(Include.NON_EMPTY)
@XmlRootElement(name = "alphabets")
@XmlAccessorType(XmlAccessType.FIELD)
public final class AlphabetsDTO extends ApiDTO {
@ApiModelProperty(
name = "total",
value = "The total number of alphabet objects (not just the ones in this response).")
@JsonProperty("total")
@XmlElement(name = "total")
@Nonnull
private int total;
@ApiModelProperty(
name = "alphabets",
value = "A list of alphabet objects.",
dataType = "com.mapcode.services.dto.AlphabetDTO",
reference = "com.mapcode.services.dto.AlphabetDTO")
@JsonProperty("alphabets")
@JsonUnwrapped
@XmlElement(name = "alphabet")
@Nonnull
private AlphabetListDTO alphabets;
@Override
public void validate() {
validator().start();
validator().checkInteger(true, "total", total, 0, Alphabet.values().length);
validator().checkNotNullAndValidateAll(false, "alphabets", alphabets);
validator().done();
}
public AlphabetsDTO(
final int total,
@Nonnull final AlphabetListDTO alphabets) {
this.total = total;
this.alphabets = alphabets;
}
public AlphabetsDTO(
final int total,
@Nonnull final Alphabet... alphabets) {
this(total, new AlphabetListDTO(alphabets));
}
@SuppressWarnings("UnusedDeclaration")
@Deprecated
private AlphabetsDTO() {
// Default constructor required by JAX-B.
super();
}
public int getTotal() {
beforeGet();
return total;
}
public void setTotal(final int total) {
beforeSet();
this.total = total;
}
@Nonnull
public AlphabetListDTO getAlphabets() {
beforeGet();
return alphabets;
}
public void setAlphabets(@Nonnull final AlphabetListDTO alphabets) {
beforeSet();
this.alphabets = alphabets;
}
}
| 31.513514
| 98
| 0.688107
|
eb31ff97587bec48bdaf8dccf84d54a7363c6d33
| 9,129
|
package mobi.cangol.mobile.actionbar;
import android.app.Activity;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import androidx.annotation.RequiresApi;
import java.util.ArrayList;
import mobi.cangol.mobile.actionbar.internal.ActionBarImpl;
import mobi.cangol.mobile.actionbar.view.ActionBarView;
import mobi.cangol.mobile.actionbar.view.SearchView;
/**
* @author Cangol
*/
public class ActionBarActivityDelegate {
private ActionBarActivity mActivity;
private ViewGroup mContainerView;
private RelativeLayout mRootView;
private ActionBar mActionBar;
private FrameLayout mContentView;
private FrameLayout mMaskView;
private SearchView mSearchView;
private boolean mActionbarOverlay = false;
public ActionBarActivityDelegate(ActionBarActivity activity) {
mActivity = activity;
}
protected void onCreate(Bundle savedInstanceState) {
mContainerView = (ViewGroup) LayoutInflater.from(mActivity).inflate(R.layout.actionbar_activity_main, null);
mRootView = mContainerView.findViewById(R.id.container_view);
mContentView = (FrameLayout) mContainerView.findViewById(R.id.actionbar_content_view);
mMaskView = (FrameLayout) mContainerView.findViewById(R.id.actionbar_mask_view);
mActionBar = new ActionBarImpl((ActionBarView) mContainerView.findViewById(R.id.actionbar_view));
}
public RelativeLayout getRootView() {
return mRootView;
}
public boolean isActionbarOverlay() {
return mActionbarOverlay;
}
public void setActionbarOverlay(boolean mActionbarOverlay) {
this.mActionbarOverlay = mActionbarOverlay;
if (mActionbarOverlay) {
mContentView.setPadding(0, 0, 0, 0);
} else {
mContentView.setPadding(0, (mActivity.getResources().getDimensionPixelSize(R.dimen.actionbar_height)), 0, 0);
}
}
public ActionBar getCustomActionBar() {
return mActionBar;
}
public void setBackgroundColor(int color) {
mContainerView.setBackgroundColor(color);
}
public void setBackgroundResource(int resId) {
mContainerView.setBackgroundResource(resId);
}
protected void onPostCreate(Bundle savedInstanceState) {
this.attachToActivity(mActivity, mContainerView);
if (savedInstanceState != null) {
CharSequence title = savedInstanceState.getCharSequence("ActionBar.title");
mActionBar.setTitle(title);
String[] navs = savedInstanceState.getStringArray("ActionBar.navs");
mActionBar.clearListNavigation();
mActionBar.setListNavigation(navs);
// ArrayList<ActionMenuItem> menus = savedInstanceState.getParcelableArrayList("ActionBar.menus");
// mActionBar.clearActionMenus();
// mActionBar.setMenus(menus);
ArrayList<ActionTabItem> tabs = savedInstanceState.getParcelableArrayList("ActionBar.tabs");
mActionBar.clearActionTabs();
mActionBar.setTabs(tabs);
mActionBar.getActionTab().setTabSelected(savedInstanceState.getInt("ActionBar.tabs.selected"));
}
mActionBar.clearActionMenus();
mActivity.onMenuActionCreated(mActionBar.getActionMenu());
if (!mActionBar.getTabs().isEmpty()) {
mActionBar.setTitleVisibility(View.GONE);
} else {
mActionBar.setTitleVisibility(View.VISIBLE);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void attachToActivity(Activity activity, View layout) {
// get the window background
int background=0;
int type=0;
{
TypedArray a= activity.getTheme().obtainStyledAttributes(new int[]{android.R.attr.windowBackground});
type=a.getType(0);
if(type==TypedValue.TYPE_INT_COLOR_RGB8){
background = a.getColor(0, 0);
}else {
background = a.getResourceId(0, 0);
}
a.recycle();
}
ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView();
ViewGroup decorChild = (ViewGroup) decor.getChildAt(0);
if(decor.getBackground()==null){
if(type==TypedValue.TYPE_INT_COLOR_RGB8){
decor.setBackgroundColor(background);
}else{
decor.setBackgroundResource(background);
}
}
if (decorChild.getBackground() != null) {
mContainerView.setBackgroundDrawable(decorChild.getBackground());
decorChild.setBackgroundDrawable(null);
}
decor.removeView(decorChild);
decor.addView(layout, 0,decorChild.getLayoutParams());
decorChild.setFitsSystemWindows(false);
View view=decorChild.findViewById(android.R.id.content);
ViewGroup parent= (ViewGroup) view.getParent();
parent.removeView(view);
setContentView(view);
}
public void setContent(View view) {
setContentView(view);
}
public void setContentView(View v) {
mContentView.removeAllViews();
mContentView.addView(v);
}
public void setContentView(View v, LayoutParams params) {
mContentView.removeAllViews();
mContentView.addView(v, params);
}
public View findViewById(int id) {
View v;
if (mContainerView != null) {
v = mContainerView.findViewById(id);
if (v != null)
return v;
}
return null;
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) {
if (mSearchView != null) {
stopSearchMode();
return true;
} else {
return mActionBar.onBackPressed();
}
}
return false;
}
public void onSaveInstanceState(Bundle outState) {
outState.putCharSequence("ActionBar.title", mActionBar.getTitle());
outState.putStringArray("ActionBar.navs", mActionBar.getListNavigation());
outState.putParcelableArrayList("ActionBar.menus", (ArrayList<? extends Parcelable>) mActionBar.getMenus());
outState.putParcelableArrayList("ActionBar.tabs", (ArrayList<? extends Parcelable>) mActionBar.getTabs());
outState.putInt("ActionBar.tabs.selected", mActionBar.getActionTab().getTabSelected());
}
public void setTitle(int titleId) {
mActionBar.setTitle(titleId);
}
public void setTitle(CharSequence title) {
mActionBar.setTitle(title);
}
public FrameLayout getMaskView() {
return mMaskView;
}
public void displayMaskView(boolean show) {
mMaskView.setVisibility(show ? View.VISIBLE : View.GONE);
}
public SearchView startSearchMode() {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
mSearchView = new SearchView(this.mActivity);
int aIndex = mContainerView.indexOfChild(mContainerView.findViewById(R.id.actionbar_view));
mContainerView.addView(mSearchView, aIndex + 1, layoutParams);
mSearchView.show();
return mSearchView;
}
public void stopSearchMode() {
if (mSearchView != null) {
mContainerView.removeView(mSearchView);
mSearchView.hide();
mSearchView = null;
}
}
public boolean isActionbarShow() {
return mActionBar.isShow();
}
public void setActionbarShow(boolean show) {
mActionBar.setShow(show);
}
public void setActionbarShadow(boolean shadow) {
if (shadow) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContainerView.findViewById(R.id.actionbar_view).setElevation(1.5f * mActivity.getResources().getDisplayMetrics().density);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContainerView.findViewById(R.id.actionbar_view).setElevation(0);
}
}
}
public void setActionbarShadow(boolean shadow, float elevation) {
if (shadow) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContainerView.findViewById(R.id.actionbar_view).setElevation(elevation * mActivity.getResources().getDisplayMetrics().density);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mContainerView.findViewById(R.id.actionbar_view).setElevation(elevation);
}
}
}
}
| 34.711027
| 144
| 0.660532
|
908cf087e416cfe3b5bce78bb5315b990c72c4bf
| 4,416
|
package edu.harvard.iq.dataverse.engine;
import edu.harvard.iq.dataverse.authorization.providers.builtin.BuiltinUserServiceBean;
import edu.harvard.iq.dataverse.*;
import edu.harvard.iq.dataverse.authorization.AuthenticationServiceBean;
import edu.harvard.iq.dataverse.authorization.groups.impl.explicit.ExplicitGroupServiceBean;
import edu.harvard.iq.dataverse.datacapturemodule.DataCaptureModuleServiceBean;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.ingest.IngestServiceBean;
import edu.harvard.iq.dataverse.privateurl.PrivateUrlServiceBean;
import edu.harvard.iq.dataverse.search.IndexServiceBean;
import edu.harvard.iq.dataverse.search.SearchServiceBean;
import edu.harvard.iq.dataverse.search.SolrIndexServiceBean;
import edu.harvard.iq.dataverse.search.savedsearch.SavedSearchServiceBean;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import edu.harvard.iq.dataverse.util.SystemConfig;
import edu.harvard.iq.dataverse.workflow.WorkflowServiceBean;
import javax.persistence.EntityManager;
/**
* A base CommandContext for tests. Provides no-op implementations. Should probably be
* overridden for actual tests.
*
* @author michael
*/
public class TestCommandContext implements CommandContext {
@Override
public DatasetServiceBean datasets() {
return null;
}
@Override
public DataverseServiceBean dataverses() {
return null;
}
@Override
public DataverseRoleServiceBean roles() {
return null;
}
@Override
public BuiltinUserServiceBean builtinUsers() {
return null;
}
@Override
public IndexServiceBean index() {
return null;
}
@Override
public SolrIndexServiceBean solrIndex() {
return null;
}
@Override
public SearchServiceBean search() {
return null;
}
@Override
public IngestServiceBean ingest() {
return null;
}
@Override
public PermissionServiceBean permissions() {
return null;
}
@Override
public DvObjectServiceBean dvObjects() {
return null;
}
@Override
public EntityManager em() {
return null;
}
@Override
public DataverseFacetServiceBean facets() {
return null;
}
@Override
public FeaturedDataverseServiceBean featuredDataverses() {
return null;
}
@Override
public TemplateServiceBean templates() {
return null;
}
@Override
public SavedSearchServiceBean savedSearches() {
return null;
}
@Override
public DataverseFieldTypeInputLevelServiceBean fieldTypeInputLevels() {
return null;
}
@Override
public DOIEZIdServiceBean doiEZId() {
return null;
}
@Override
public DOIDataCiteServiceBean doiDataCite() {
return null;
}
@Override
public HandlenetServiceBean handleNet() {
return null;
}
@Override
public SettingsServiceBean settings() {
return null;
}
@Override
public GuestbookServiceBean guestbooks() {
return null;
}
@Override
public GuestbookResponseServiceBean responses() {
return null;
}
@Override
public DataverseLinkingServiceBean dvLinking() {
return null;
}
@Override
public DatasetLinkingServiceBean dsLinking() {
return null;
}
@Override
public AuthenticationServiceBean authentication() {
return null;
}
@Override
public DataverseEngine engine() { return new TestDataverseEngine(this); }
@Override
public DataFileServiceBean files() {
return null;
}
@Override
public ExplicitGroupServiceBean explicitGroups() {
return null;
}
@Override
public RoleAssigneeServiceBean roleAssignees() {
return null;
}
@Override
public UserNotificationServiceBean notifications() {
return null;
}
@Override
public SystemConfig systemConfig() {
return null;
}
@Override
public PrivateUrlServiceBean privateUrl() {
return null;
}
@Override
public DatasetVersionServiceBean datasetVersion() {
return null;
}
@Override
public WorkflowServiceBean workflows() {
return null;
}
@Override
public MapLayerMetadataServiceBean mapLayerMetadata() {
return null;
}
@Override
public DataCaptureModuleServiceBean dataCaptureModule() {
return null;
}
}
| 21.333333
| 92
| 0.706069
|
d9d746a07196a8e1c54ebcff8a5d11e0a4a02c93
| 2,719
|
package com.sicdlib.dto.phoenixEntity;
import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Property;
@Entity(value="\"douban_group_author\"")
public class DoubanGroupAuthorEntity {
@Property(value="PK")
private String pk;
@Property(value="author_id")
private String authorID;
@Property(value="author_name")
private String authorName;
@Property(value="introduction")
private String introduction;
@Property(value="join_time")
private String joinTime;
@Property(value="location")
private String location;
@Property(value="logff_time")
private String logffTime;
@Property(value="signature")
private String signature;
@Property(value="url")
private String url;
public String getPk() {
return pk;
}
public void setPk(String pk) {
this.pk = pk;
}
public String getAuthorID() {
return authorID;
}
public void setAuthorID(String authorID) {
this.authorID = authorID;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getJoinTime() {
return joinTime;
}
public void setJoinTime(String joinTime) {
this.joinTime = joinTime;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getLogffTime() {
return logffTime;
}
public void setLogffTime(String logffTime) {
this.logffTime = logffTime;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return "DoubanGroupAuthorEntity{" +
"pk='" + pk + '\'' +
", authorID='" + authorID + '\'' +
", authorName='" + authorName + '\'' +
", introduction='" + introduction + '\'' +
", joinTime='" + joinTime + '\'' +
", location='" + location + '\'' +
", logffTime='" + logffTime + '\'' +
", signature='" + signature + '\'' +
", url='" + url + '\'' +
'}';
}
}
| 22.105691
| 58
| 0.575947
|
5920cffc21d7fa3a1363dd9d6ce7f641f0b959f2
| 3,170
|
package com.tz.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.tz.pojo.ZaPlatManager;
import com.tz.pojo.vo.ZaPlatManagerVo;
import com.tz.remote.PlatManagerRemote;
import com.tz.res.AppMsgResult;
/**
* 管理者WEB请求处理层
* @author Administrator
*
*/
@RestController
@RequestMapping("admin/api")
public class PlatManagerController {
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
@Autowired
private PlatManagerRemote platManagerRemote;
/**
* 注册添加或者更新管理员
* @param platManager
* @param roleIds 角色id 逗号分隔的字符串
* @param type 注册添加"add" 更新"update"
* @param userId
* @param userToken
* @return
*/
@PostMapping("/addOrUpdaterPlatManager")
public AppMsgResult addPlatManager(ZaPlatManager platManager,String roleIds,@RequestParam(required=true) String type,@RequestParam(required=true) String userId,@RequestParam(required=true)String token) {
LOG.info("invoke-----------addOrUpdatePlatManager");
AppMsgResult result=platManagerRemote.addOrUpdatePlatManager(platManager,roleIds,type,userId, token);
return result;
}
/**
* 分页查询平台管理员列表信息
*/
@PostMapping("/getPlatManagerList")
public AppMsgResult getPlatManagerList(ZaPlatManagerVo zaPlatManagerVo,Integer curPage, Integer rows) {
LOG.info("invoke-----------getPlatManagerList");
AppMsgResult result=platManagerRemote.getPlatManagerList(zaPlatManagerVo,curPage,rows);
return result;
}
/**
* 根据id查询管理员信息
* @param id
* @param userId
* @param token
* @return
*/
@GetMapping("/queryPlatManagerById")
public AppMsgResult queryPlatManagerById(@RequestParam(required=true) String id,@RequestParam(required=true) String userId,@RequestParam(required=true)String token) {
LOG.info("invoke-----------queryPlatManagerById");
AppMsgResult result=platManagerRemote.queryPlatManagerById(id,userId,token);
return result;
}
/**
* 删除管理员信息
* @param id
* @param userId
* @param token
* @return
*/
@PostMapping("/delManagerById")
public AppMsgResult delManagerById(@RequestParam(required=true)String id,@RequestParam(required=true)String userId,@RequestParam(required=true)String token) {
LOG.info("invoke-----------delManagerById");
AppMsgResult result=platManagerRemote.delManagerById(id,userId,token);
return result;
}
/**
* 账户冻解账户
* @param id
* @param status 0冻结 1正常
* @param userId
* @param token
* @return
*/
@PostMapping("/accountFreezeById")
public AppMsgResult accountFreezeById(@RequestParam(required=true)String id,@RequestParam(required=true)Integer status,@RequestParam(required=true)String userId,@RequestParam(required=true)String token) {
LOG.info("invoke-----------accountFreezeById");
AppMsgResult result=platManagerRemote.accountFreezeById(id,status,userId,token);
return result;
}
}
| 31.386139
| 205
| 0.764353
|
f5d231d569d4742abf1370690d383d7ee5830ead
| 431
|
package com.commercetools.sunrise.framework.controllers;
import play.data.Form;
import play.data.FormFactory;
public interface WithForm<F> {
default Form<? extends F> bindForm() {
return createForm().bindFromRequest();
}
default Form<? extends F> createForm() {
return getFormFactory().form(getFormDataClass());
}
Class<? extends F> getFormDataClass();
FormFactory getFormFactory();
}
| 21.55
| 57
| 0.691415
|
a1e3f90001f561b651a13f6c22e880c40374e921
| 238
|
package simple.universe;
import simple.obj.ISimpleObject;
public interface ISimpleObjectRemover {
/**
* Remove this game object from the container.
* @param toRemove
*/
public void removeGameObject(ISimpleObject toRemove);
}
| 17
| 54
| 0.756303
|
4ddfba5f6e56ecb36728ab36a6efb14b2b20a3e3
| 3,572
|
package com.scand.realmbrowser;
import android.content.Context;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmObject;
/**
* Created by Slabodeniuk on 6/15/15.
*/
public class RealmBrowser {
private static RealmBrowser sInstance = new RealmBrowser();
private Map<Class<? extends RealmObject>, RealmConfiguration> displayedRealmConfigs;
private List<RealmConfiguration> activeRealmConfigs;
static RealmBrowser getInstance() {
return sInstance;
}
private RealmBrowser() {
displayedRealmConfigs = new HashMap<>();
activeRealmConfigs = new ArrayList<>();
}
List<Class<? extends RealmObject>> getDisplayedRealmObjects(RealmConfiguration realm) {
List<Class<? extends RealmObject>> result = new ArrayList<>();
for (Class<? extends RealmObject> clazz : displayedRealmConfigs.keySet()) {
RealmConfiguration config = displayedRealmConfigs.get(clazz);
if (config.getPath().equals(realm.getPath())) {
result.add(clazz);
}
}
Collections.sort(result, new Comparator<Class<? extends RealmObject>>() {
@Override
public int compare(Class<? extends RealmObject> lhs, Class<? extends RealmObject> rhs) {
return lhs.getSimpleName().compareTo(rhs.getSimpleName());
}
});
return result;
}
RealmConfiguration getRealmConfig(Class<? extends RealmObject> clazz) {
return displayedRealmConfigs.get(clazz);
}
List<RealmConfiguration> getActiveRealmConfigs() {
return activeRealmConfigs;
}
private void addRealmConfig(RealmConfiguration config) {
if (activeRealmConfigs.isEmpty()) {
activeRealmConfigs.add(config);
} else {
for (RealmConfiguration configuration : activeRealmConfigs) {
if (configuration.getPath().equals(config.getPath())) {
return;
}
}
activeRealmConfigs.add(config);
}
}
public static class Builder {
private Context mContext;
private RealmBrowser mBrowser;
public Builder(Context c) {
mContext = c;
mBrowser = RealmBrowser.getInstance();
}
public Builder add(Realm realm, List<Class<? extends RealmObject>> classes) {
for (Class<? extends RealmObject> clazz : classes) {
add(realm, clazz);
}
return this;
}
public Builder add(Realm realm, Class<? extends RealmObject> clazz) {
add(realm.getConfiguration(), clazz);
return this;
}
public Builder add(RealmConfiguration config, List<Class<? extends RealmObject>> classes) {
for (Class<? extends RealmObject> clazz : classes) {
add(config, clazz);
}
return this;
}
public Builder add(RealmConfiguration config, Class<? extends RealmObject> clazz) {
mBrowser.displayedRealmConfigs.put(clazz, config);
mBrowser.addRealmConfig(config);
return this;
}
public void show() {
BrowserActivity.startActivity(mContext);
}
public void showNotification() {
RealmBrowserService.startService(mContext);
}
}
}
| 30.793103
| 100
| 0.618421
|
2b395490a0d320f016816c862d598ebc3f719ce7
| 2,087
|
// generated with ast extension for cup
// version 0.8
// 14/0/2021 23:44:48
package rs.ac.bg.etf.pp1.ast;
public class StmtIf extends Statement {
private IfKw IfKw;
private StatementIfBody StatementIfBody;
public StmtIf (IfKw IfKw, StatementIfBody StatementIfBody) {
this.IfKw=IfKw;
if(IfKw!=null) IfKw.setParent(this);
this.StatementIfBody=StatementIfBody;
if(StatementIfBody!=null) StatementIfBody.setParent(this);
}
public IfKw getIfKw() {
return IfKw;
}
public void setIfKw(IfKw IfKw) {
this.IfKw=IfKw;
}
public StatementIfBody getStatementIfBody() {
return StatementIfBody;
}
public void setStatementIfBody(StatementIfBody StatementIfBody) {
this.StatementIfBody=StatementIfBody;
}
public void accept(Visitor visitor) {
visitor.visit(this);
}
public void childrenAccept(Visitor visitor) {
if(IfKw!=null) IfKw.accept(visitor);
if(StatementIfBody!=null) StatementIfBody.accept(visitor);
}
public void traverseTopDown(Visitor visitor) {
accept(visitor);
if(IfKw!=null) IfKw.traverseTopDown(visitor);
if(StatementIfBody!=null) StatementIfBody.traverseTopDown(visitor);
}
public void traverseBottomUp(Visitor visitor) {
if(IfKw!=null) IfKw.traverseBottomUp(visitor);
if(StatementIfBody!=null) StatementIfBody.traverseBottomUp(visitor);
accept(visitor);
}
public String toString(String tab) {
StringBuffer buffer=new StringBuffer();
buffer.append(tab);
buffer.append("StmtIf(\n");
if(IfKw!=null)
buffer.append(IfKw.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
if(StatementIfBody!=null)
buffer.append(StatementIfBody.toString(" "+tab));
else
buffer.append(tab+" null");
buffer.append("\n");
buffer.append(tab);
buffer.append(") [StmtIf]");
return buffer.toString();
}
}
| 26.417722
| 76
| 0.632487
|
e3dfb0f847acb7ada2717ac845d9991fe4795b8d
| 505
|
package vekta.spawner.terrain;
import vekta.object.planet.TerrestrialPlanet;
import vekta.spawner.TerrainGenerator;
import vekta.terrain.MoltenTerrain;
import vekta.terrain.Terrain;
public class MoltenTerrainSpawner implements TerrainGenerator.TerrainSpawner {
@Override
public boolean isValid(TerrestrialPlanet planet) {
return true;
}
@Override
public float getWeight() {
return .2F;
}
@Override
public Terrain spawn(TerrestrialPlanet planet) {
return new MoltenTerrain(planet);
}
}
| 20.2
| 78
| 0.794059
|
34667392f80752c3547008661225e993710c1dee
| 7,024
|
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.openvr;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
/** Shared Resource Methods. */
public class VRResources {
protected VRResources() {
throw new UnsupportedOperationException();
}
// --- [ VRResources_LoadSharedResource ] ---
/** Unsafe version of: {@link #VRResources_LoadSharedResource LoadSharedResource} */
public static int nVRResources_LoadSharedResource(long pchResourceName, long pchBuffer, int unBufferLen) {
long __functionAddress = OpenVR.VRResources.LoadSharedResource;
if (CHECKS) {
check(__functionAddress);
}
return callPPI(__functionAddress, pchResourceName, pchBuffer, unBufferLen);
}
/**
* Loads the specified resource into the provided buffer if large enough.
*
* @return the size in bytes of the buffer required to hold the specified resource
*/
@NativeType("uint32_t")
public static int VRResources_LoadSharedResource(@NativeType("char const *") ByteBuffer pchResourceName, @Nullable @NativeType("char *") ByteBuffer pchBuffer) {
if (CHECKS) {
checkNT1(pchResourceName);
}
return nVRResources_LoadSharedResource(memAddress(pchResourceName), memAddressSafe(pchBuffer), remainingSafe(pchBuffer));
}
/**
* Loads the specified resource into the provided buffer if large enough.
*
* @return the size in bytes of the buffer required to hold the specified resource
*/
@NativeType("uint32_t")
public static int VRResources_LoadSharedResource(@NativeType("char const *") CharSequence pchResourceName, @Nullable @NativeType("char *") ByteBuffer pchBuffer) {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pchResourceNameEncoded = stack.ASCII(pchResourceName);
return nVRResources_LoadSharedResource(memAddress(pchResourceNameEncoded), memAddressSafe(pchBuffer), remainingSafe(pchBuffer));
} finally {
stack.setPointer(stackPointer);
}
}
/**
* Loads the specified resource into the provided buffer if large enough.
*
* @return the size in bytes of the buffer required to hold the specified resource
*/
@NativeType("uint32_t")
public static String VRResources_LoadSharedResource(@NativeType("char const *") CharSequence pchResourceName, @NativeType("uint32_t") int unBufferLen) {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pchResourceNameEncoded = stack.ASCII(pchResourceName);
ByteBuffer pchBuffer = stack.malloc(unBufferLen);
int __result = nVRResources_LoadSharedResource(memAddress(pchResourceNameEncoded), memAddress(pchBuffer), unBufferLen);
return memASCII(pchBuffer, __result - 1);
} finally {
stack.setPointer(stackPointer);
}
}
// --- [ VRResources_GetResourceFullPath ] ---
/** Unsafe version of: {@link #VRResources_GetResourceFullPath GetResourceFullPath} */
public static int nVRResources_GetResourceFullPath(long pchResourceName, long pchResourceTypeDirectory, long pchPathBuffer, int unBufferLen) {
long __functionAddress = OpenVR.VRResources.GetResourceFullPath;
if (CHECKS) {
check(__functionAddress);
}
return callPPPI(__functionAddress, pchResourceName, pchResourceTypeDirectory, pchPathBuffer, unBufferLen);
}
/**
* Provides the full path to the specified resource. Resource names can include named directories for drivers and other things, and this resolves all of
* those and returns the actual physical path. {@code pchResourceTypeDirectory} is the subdirectory of resources to look in.
*/
@NativeType("uint32_t")
public static int VRResources_GetResourceFullPath(@NativeType("char const *") ByteBuffer pchResourceName, @NativeType("char const *") ByteBuffer pchResourceTypeDirectory, @Nullable @NativeType("char *") ByteBuffer pchPathBuffer) {
if (CHECKS) {
checkNT1(pchResourceName);
checkNT1(pchResourceTypeDirectory);
}
return nVRResources_GetResourceFullPath(memAddress(pchResourceName), memAddress(pchResourceTypeDirectory), memAddressSafe(pchPathBuffer), remainingSafe(pchPathBuffer));
}
/**
* Provides the full path to the specified resource. Resource names can include named directories for drivers and other things, and this resolves all of
* those and returns the actual physical path. {@code pchResourceTypeDirectory} is the subdirectory of resources to look in.
*/
@NativeType("uint32_t")
public static int VRResources_GetResourceFullPath(@NativeType("char const *") CharSequence pchResourceName, @NativeType("char const *") CharSequence pchResourceTypeDirectory, @Nullable @NativeType("char *") ByteBuffer pchPathBuffer) {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pchResourceNameEncoded = stack.ASCII(pchResourceName);
ByteBuffer pchResourceTypeDirectoryEncoded = stack.ASCII(pchResourceTypeDirectory);
return nVRResources_GetResourceFullPath(memAddress(pchResourceNameEncoded), memAddress(pchResourceTypeDirectoryEncoded), memAddressSafe(pchPathBuffer), remainingSafe(pchPathBuffer));
} finally {
stack.setPointer(stackPointer);
}
}
/**
* Provides the full path to the specified resource. Resource names can include named directories for drivers and other things, and this resolves all of
* those and returns the actual physical path. {@code pchResourceTypeDirectory} is the subdirectory of resources to look in.
*/
@NativeType("uint32_t")
public static String VRResources_GetResourceFullPath(@NativeType("char const *") CharSequence pchResourceName, @NativeType("char const *") CharSequence pchResourceTypeDirectory, @NativeType("uint32_t") int unBufferLen) {
MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();
try {
ByteBuffer pchResourceNameEncoded = stack.ASCII(pchResourceName);
ByteBuffer pchResourceTypeDirectoryEncoded = stack.ASCII(pchResourceTypeDirectory);
ByteBuffer pchPathBuffer = stack.malloc(unBufferLen);
int __result = nVRResources_GetResourceFullPath(memAddress(pchResourceNameEncoded), memAddress(pchResourceTypeDirectoryEncoded), memAddress(pchPathBuffer), unBufferLen);
return memASCII(pchPathBuffer, __result - 1);
} finally {
stack.setPointer(stackPointer);
}
}
}
| 49.464789
| 238
| 0.716259
|
0e4d77ad100df13490df929b7ae67452e55a5323
| 5,831
|
// This file is part of OpenTSDB.
// Copyright (C) 2015 The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version. This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details. You should have received a copy
// of the GNU Lesser General Public License along with this program. If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.core;
import java.util.NoSuchElementException;
/**
* A specialized downsampler that returns special values, based on the fill
* policy, for intervals for which no data could be found. The default
* implementation, {@link Downsampler}, simply skips intervals that have no
* data, which causes the {@link AggregationIterator} up the chain to
* interpolate.
* @since 2.2
*/
public class FillingDownsampler extends Downsampler {
/** Track when the downsampled data should end. */
protected long end_timestamp;
/** Downsampling fill policy. */
protected final FillPolicy fill_policy;
/**
* Create a new nulling downsampler.
* @param source The iterator to access the underlying data.
* @param start_time The time in milliseconds at which the data begins.
* @param end_time The time in milliseconds at which the data ends.
* @param interval_ms The interval in milli seconds wanted between each data
* point.
* @param downsampler The downsampling function to use.
* @param fill_policy Policy specifying whether to interpolate or to fill
* missing intervals with special values.
* @throws IllegalArgumentException if fill_policy is interpolation.
*/
FillingDownsampler(final SeekableView source, final long start_time,
final long end_time, final long interval_ms,
final Aggregator downsampler, final FillPolicy fill_policy) {
// Lean on the superclass implementation.
super(source, interval_ms, downsampler);
// Ensure we aren't given a bogus fill policy.
if (FillPolicy.NONE == fill_policy) {
throw new IllegalArgumentException("Cannot instantiate this class with" +
" linear-interpolation fill policy");
}
this.fill_policy = fill_policy;
// Use the values-in-interval object to align the timestamps at which we
// expect data to arrive for the first and last intervals.
this.timestamp = values_in_interval.alignTimestamp(start_time);
this.end_timestamp = values_in_interval.alignTimestamp(end_time);
}
/**
* Please note that when this method returns true, the value yielded by the
* object returned by {@link #next()} might be NaN, which indicates no data
* could be found for the current interval.
* @return true if this iterator has not yet reached the end of the specified
* range of data; otherwise, false.
*/
@Override
public boolean hasNext() {
// No matter the state of the values-in-interval object, if our current
// timestamp hasn't reached the end of the requested overall interval, then
// we still have iterating to do.
return timestamp < end_timestamp;
}
/**
* Please note that the object returned by this method may return the value
* NaN, which indicates that no data count be found for the interval. This is
* intentional. Future intervals, if any, may still hava data and thus yield
* non-NaN values.
* @return the next data point, which might yield a NaN value.
* @throws NoSuchElementException if no more intervals remain.
*/
@Override
public DataPoint next() {
// Don't proceed if we've already completed iteration.
if (hasNext()) {
// Ensure that the timestamp we request is valid.
values_in_interval.initializeIfNotDone();
// Skip any leading data outside the query bounds.
long actual = values_in_interval.getIntervalTimestamp();
while (values_in_interval.hasNextValue() && actual < timestamp) {
// The actual timestamp precedes our expected, so there's data in the
// values-in-interval object that we wish to ignore.
downsampler.runDouble(values_in_interval);
values_in_interval.moveToNextInterval();
actual = values_in_interval.getIntervalTimestamp();
}
// Check whether the timestamp of the calculation interval matches what
// we expect.
if (actual == timestamp) {
// The calculated interval timestamp matches what we expect, so we can
// do normal processing.
value = downsampler.runDouble(values_in_interval);
values_in_interval.moveToNextInterval();
} else {
// Our expected timestamp precedes the actual, so the interval is
// missing. We will use a special value, based on the fill policy, to
// represent this case.
switch (fill_policy) {
case NOT_A_NUMBER:
case NULL:
value = Double.NaN;
break;
case ZERO:
value = 0.0;
break;
default:
throw new RuntimeException("unhandled fill policy");
}
}
// Advance the expected timestamp to the next interval.
timestamp += values_in_interval.interval_ms;
// This object also represents the data.
return this;
}
// Ideally, the user will not call this method when no data remains, but
// we can't enforce that.
throw new NoSuchElementException("no more data points in " + this);
}
@Override
public long timestamp() {
return timestamp - values_in_interval.interval_ms;
}
}
| 39.666667
| 79
| 0.704167
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.