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
|
|---|---|---|---|---|---|
b5b12de4a0630fb87449a6d06ef97d10460d2e9c
| 2,085
|
package mage.cards.g;
import java.util.UUID;
import mage.abilities.Mode;
import mage.abilities.effects.common.DamageAllEffect;
import mage.abilities.effects.common.combat.CantBlockAllEffect;
import mage.abilities.effects.common.continuous.GainControlAllEffect;
import mage.abilities.keyword.FlyingAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.TargetController;
import mage.filter.FilterPermanent;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.Predicates;
import mage.filter.predicate.mageobject.AbilityPredicate;
/**
*
* @author jeffwadsworth
*/
public final class GruulCharm extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent("Creatures without flying");
private static final FilterPermanent filter2 = new FilterPermanent("all permanents you own");
private static final FilterCreaturePermanent filter3 = new FilterCreaturePermanent("creature with flying");
static {
filter.add(Predicates.not(new AbilityPredicate(FlyingAbility.class)));
filter2.add(TargetController.YOU.getOwnerPredicate());
filter3.add(new AbilityPredicate(FlyingAbility.class));
}
public GruulCharm(UUID ownerId, CardSetInfo setInfo) {
super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{R}{G}");
// Choose one - Creatures without flying can't block this turn;
this.getSpellAbility().addEffect(new CantBlockAllEffect(filter, Duration.EndOfTurn));
// or gain control of all permanents you own;
this.getSpellAbility().addMode(new Mode(new GainControlAllEffect(Duration.EndOfGame, filter2)));
// or Gruul Charm deals 3 damage to each creature with flying.
this.getSpellAbility().addMode(new Mode(new DamageAllEffect(3, filter3)));
}
private GruulCharm(final GruulCharm card) {
super(card);
}
@Override
public GruulCharm copy() {
return new GruulCharm(this);
}
}
| 35.338983
| 114
| 0.754436
|
8aaf7e89e7b957a311d2bbc250f71b902e3999db
| 1,493
|
/*
* 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.jackrabbit.oak.segment.standby;
import java.io.File;
import org.apache.jackrabbit.oak.segment.test.TemporaryFileStore;
import org.junit.Rule;
import org.junit.rules.RuleChain;
import org.junit.rules.TemporaryFolder;
public class StandbyTest extends TestBase {
private TemporaryFolder folder = new TemporaryFolder(new File("target"));
private TemporaryFileStore serverFileStore = new TemporaryFileStore(folder, false);
private TemporaryFileStore clientFileStore = new TemporaryFileStore(folder, true);
@Rule
public RuleChain chain = RuleChain.outerRule(folder)
.around(serverFileStore)
.around(clientFileStore);
}
| 34.72093
| 87
| 0.758205
|
1eb726651f4c43380e9968fedca6cd17021a0dbb
| 1,820
|
package engine.command.util.node;
import engine.command.CommandSender;
import engine.command.suggestion.Suggester;
import engine.command.util.StringArgs;
import engine.command.util.context.LinkedContext;
import java.util.Arrays;
import java.util.Collections;
public class SenderNode extends CommandNode {
private Class<? extends CommandSender>[] allowedSenders;
public SenderNode(Class<? extends CommandSender>... clazz) {
allowedSenders = clazz;
}
@Override
public int getRequiredArgsNum() {
return 0;
}
@Override
public ParseResult parse(LinkedContext context, StringArgs args) {
if (allowedSender(context.getSender())) {
return ParseResult.success(context.getSender());
}
return ParseResult.fail();
}
public boolean allowedSender(CommandSender sender) {
for (Class clazz : allowedSenders) {
if (clazz.isAssignableFrom(sender.getClass())) {
return true;
}
}
return false;
}
public Class<? extends CommandSender>[] getAllowedSenders() {
return allowedSenders;
}
@Override
public String toString() {
return "SenderNode{" +
"allowedSender=" + Arrays.toString(allowedSenders) +
'}';
}
public boolean hasTip() {
return false;
}
@Override
public Suggester getSuggester() {
return (sender, command, args) -> Collections.EMPTY_LIST;
}
@Override
public int priority() {
return -5;
}
@Override
public boolean same(CommandNode node) {
if (super.same(node) && node instanceof SenderNode) {
return Arrays.equals(((SenderNode) node).allowedSenders, allowedSenders);
}
return false;
}
}
| 24.594595
| 85
| 0.626923
|
e14c4016a688e6993ae251a739ad4c996134b829
| 1,796
|
/*******************************************************************************
* Copyright 2018 Jarred Vardy
*
* 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.ibdiscord.formatting;
import net.dv8tion.jda.core.EmbedBuilder;
import net.dv8tion.jda.core.entities.MessageEmbed;
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/**
* @author vardy
* @since 2018.09.19
*/
public class Embedder {
private static final String EMBEDS_LOCATION = "./content/embeds/";
// Embedder-specific fields
private EmbedStyle style;
private EmbedType type;
private boolean multiPaged;
// Discord Embed fields
private String title;
private String title_url;
// Variables to serve
private EmbedBuilder builderFinal;
private MessageEmbed embedFinal;
public Embedder(String fileName) {
parse(EMBEDS_LOCATION + fileName, this);
}
private void parse(String fileLocation, Embedder embedder) {
EmbedFileParser parser = new EmbedFileParser();
builderFinal = parser.parse(fileLocation, embedder);
embedFinal = builderFinal.build();
}
}
| 32.654545
| 81
| 0.603007
|
ba1986fc8c1bb42009cd1ba3ec37a1df725d81d9
| 176
|
package com.yunmel.extreme.util;
public class NumberUtils {
// public static final getInt(String value){
// if(StringUtils.isNotBlank(value)){
//
// }
// }
}
| 16
| 45
| 0.630682
|
665ea1247b5bbf4cb7e1af826aab91421e73dfdf
| 356
|
package ru.majordomo.hms.rc.user.common;
public enum ExtendedAction {
/**
* загрузить пользовательскую программу из git
*/
LOAD,
/**
* установить зависимости
*/
INSTALL, SHELL,
/** выполнить команды из Website.appUpdateCommands */
SHELLUPDATE,
/** загрузка из git и команды установки */
LOAD_INSTALL;
}
| 20.941176
| 57
| 0.640449
|
61c2544f7d3b90e9a50b8ec8112ca7230009018e
| 3,666
|
package org.apache.hadoop.hbase.themis;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.NavigableSet;
import org.apache.hadoop.hbase.client.AbstractClientScanner;
import org.apache.hadoop.hbase.client.ClientScanner;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.themis.cp.ThemisCpUtil;
import org.apache.hadoop.hbase.themis.cp.ThemisScanObserver;
import org.apache.hadoop.hbase.util.Bytes;
// scanner for range read
public class ThemisScanner extends AbstractClientScanner {
protected final ResultScanner scanner;
protected final byte[] tableName;
protected Transaction transaction;
protected final Scan scan;
public ThemisScanner(final byte[] tableName, final Scan scan, final Transaction transaction)
throws IOException {
long beginTs = System.nanoTime();
try {
this.tableName = tableName;
this.transaction = transaction;
this.scan = scan;
// we need to set startTs to the attribute named '_themisTransationStartTs_'. Then, the loaded
// themis coprocessor could recognize this scanner from hbase scanners and do themis logics.
// TODO(cuijianwei): how to avoid no-themis users set this attribute when doing hbase scan?
setStartTsToScan(scan, transaction.startTs);
this.scanner = new ClientScanner(transaction.getConf(), scan, tableName,
transaction.getHConnection());
} finally {
ThemisStatistics.updateLatency(ThemisStatistics.getStatistics().getScannerLatency, beginTs);
}
}
protected static void setStartTsToScan(Scan scan, long startTs) {
scan.setAttribute(ThemisScanObserver.TRANSACTION_START_TS, Bytes.toBytes(startTs));
}
public static Get createGetFromScan(Scan scan, byte[] rowkey) {
Get get = new Get(rowkey);
for (Entry<byte[], NavigableSet<byte[]>> familyEntry : scan.getFamilyMap().entrySet()) {
if (familyEntry.getValue() != null && familyEntry.getValue().size() > 0) {
for (byte[] qualifier : familyEntry.getValue()) {
get.addColumn(familyEntry.getKey(), qualifier);
}
} else {
get.addFamily(familyEntry.getKey());
}
}
return get;
}
public Result next() throws IOException {
long beginTs = System.nanoTime();
Result pResult = null;
boolean lockClean = false;
try {
pResult = this.scanner.next();
if (pResult == null) {
return null;
}
// if we encounter conflict locks, we need to clean lock for this row and read again
if (ThemisCpUtil.isLockResult(pResult)) {
lockClean = true;
Get rowGet = createGetFromScan(scan, pResult.getRow());
pResult = transaction.tryToCleanLockAndGetAgain(tableName, rowGet, pResult.list());
// empty result indicates the current row has been erased, we should get next row
if (pResult.isEmpty()) {
return next();
} else {
return pResult;
}
}
return pResult;
} finally {
ThemisStatistics.updateLatency(ThemisStatistics.getStatistics().nextLatency, beginTs);
ThemisStatistics.logSlowOperation("themisNext", beginTs, "row=" + pResult + ", lockClean=" + lockClean);
}
}
public void close() {
if (scanner != null) {
this.scanner.close();
}
}
protected Scan getScan() {
return this.scan;
}
@Override
public Result[] next(int nbRows) throws IOException {
// TODO implement this method
throw new IOException("not supported");
}
}
| 35.25
| 110
| 0.69258
|
07b99a651bf9a8213731855baecf86978f13d637
| 454
|
package com.msplearning.repository;
import java.util.List;
import com.msplearning.entity.Lesson;
import com.msplearning.repository.generic.GenericRepository;
import com.msplearning.repository.jpa.LessonRepositoryJpa;
/**
* Interface of {@link LessonRepositoryJpa}.
*
* @author Venilton Falvo Junior (veniltonjr)
*/
public interface LessonRepository extends GenericRepository<Lesson, Long> {
List<Lesson> findByDiscipline(Long idDiscipline);
}
| 23.894737
| 75
| 0.799559
|
f0d7d37ef64c8287c5c479bb32c3d8f8307539d1
| 1,241
|
/*
* Copyright (c) 2017, William Hill Online. All rights reserved
*/
package com.stulsoft.kafkaj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author Yuriy Stul.
*/
public class CommonProducerRunner {
private static Logger logger = LoggerFactory.getLogger(CommonProducerRunner.class);
public static void main(String[] args) {
logger.info("==>CommonProducerRunner");
String topic = "main1TestTopic";
ExecutorService executor = Executors.newFixedThreadPool(4);
Producer producer = new CommonProducer(executor, topic, 1500);
Future<Void> startedProducer = producer.start();
System.out.println("Enter line to exit...");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
scanner.close();
logger.info("Stopping producer...");
try {
producer.stop().get();
} catch (Exception ignore) {
}
try {
startedProducer.get();
} catch (Exception ignore) {
}
logger.info("<==CommonProducerRunner");
}
}
| 29.547619
| 87
| 0.651894
|
b3af4d493f081b488bdcf89948a9ccb96f1cc35c
| 719
|
package com.lupinesoft.viewmodel_demo;
import android.arch.lifecycle.ViewModel;
import android.util.Log;
import java.util.Random;
public class MainActivityViewModel extends ViewModel {
String randomNumber;
public String getRandomNumber(){
Log.d("TAG", "getRandomNumber");
if(randomNumber == null){
createRandomNumber();
}
return randomNumber;
}
public void createRandomNumber(){
Log.d("TAG", "createRandomNumber");
Random random = new Random();
randomNumber = "Number: "+(random.nextInt(10-1)+1);
}
@Override
protected void onCleared() {
super.onCleared();
Log.d("TAG", "ViewModel Destroy");
}
}
| 22.46875
| 59
| 0.631433
|
f86241a7866399875dcb3d8468fa569fbe1466de
| 4,906
|
// **********************************************************************
// This file was generated by a TAF parser!
// TAF version 3.0.0.34 by WSRD Tencent.
// Generated from `/usr/local/resin_system.mqq.com/webapps/communication/taf/upload/noahyang/ws.jce'
// **********************************************************************
package com.qq.jce.ws;
public final class DockSearchFacePlateInfor extends com.qq.taf.jce.JceStruct implements java.lang.Cloneable
{
public String className()
{
return "ws.DockSearchFacePlateInfor";
}
public String fullClassName()
{
return "com.qq.jce.ws.DockSearchFacePlateInfor";
}
public com.qq.jce.ws.DockSearchBox dockSearchBox = null;
public java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup> dockSearchHotWordGroups = null;
public String reserved = "";
public com.qq.jce.ws.DockSearchBox getDockSearchBox()
{
return dockSearchBox;
}
public void setDockSearchBox(com.qq.jce.ws.DockSearchBox dockSearchBox)
{
this.dockSearchBox = dockSearchBox;
}
public java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup> getDockSearchHotWordGroups()
{
return dockSearchHotWordGroups;
}
public void setDockSearchHotWordGroups(java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup> dockSearchHotWordGroups)
{
this.dockSearchHotWordGroups = dockSearchHotWordGroups;
}
public String getReserved()
{
return reserved;
}
public void setReserved(String reserved)
{
this.reserved = reserved;
}
public DockSearchFacePlateInfor()
{
}
public DockSearchFacePlateInfor(com.qq.jce.ws.DockSearchBox dockSearchBox, java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup> dockSearchHotWordGroups, String reserved)
{
this.dockSearchBox = dockSearchBox;
this.dockSearchHotWordGroups = dockSearchHotWordGroups;
this.reserved = reserved;
}
public boolean equals(Object o)
{
if(o == null)
{
return false;
}
DockSearchFacePlateInfor t = (DockSearchFacePlateInfor) o;
return (
com.qq.taf.jce.JceUtil.equals(dockSearchBox, t.dockSearchBox) &&
com.qq.taf.jce.JceUtil.equals(dockSearchHotWordGroups, t.dockSearchHotWordGroups) &&
com.qq.taf.jce.JceUtil.equals(reserved, t.reserved) );
}
public int hashCode()
{
try
{
throw new Exception("Need define key first!");
}
catch(Exception ex)
{
ex.printStackTrace();
}
return 0;
}
public java.lang.Object clone()
{
java.lang.Object o = null;
try
{
o = super.clone();
}
catch(CloneNotSupportedException ex)
{
assert false; // impossible
}
return o;
}
public void writeTo(com.qq.taf.jce.JceOutputStream _os)
{
_os.write(dockSearchBox, 0);
_os.write(dockSearchHotWordGroups, 1);
if (null != reserved)
{
_os.write(reserved, 2);
}
}
static com.qq.jce.ws.DockSearchBox cache_dockSearchBox;
static java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup> cache_dockSearchHotWordGroups;
public void readFrom(com.qq.taf.jce.JceInputStream _is)
{
if(null == cache_dockSearchBox)
{
cache_dockSearchBox = new com.qq.jce.ws.DockSearchBox();
}
this.dockSearchBox = (com.qq.jce.ws.DockSearchBox) _is.read(cache_dockSearchBox, 0, true);
if(null == cache_dockSearchHotWordGroups)
{
cache_dockSearchHotWordGroups = new java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup>();
com.qq.jce.ws.DockSearchHotWordGroup __var_8 = new com.qq.jce.ws.DockSearchHotWordGroup();
((java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup>)cache_dockSearchHotWordGroups).add(__var_8);
}
this.dockSearchHotWordGroups = (java.util.ArrayList<com.qq.jce.ws.DockSearchHotWordGroup>) _is.read(cache_dockSearchHotWordGroups, 1, true);
this.reserved = _is.readString(2, false);
}
public void display(java.lang.StringBuilder _os, int _level)
{
com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level);
_ds.display(dockSearchBox, "dockSearchBox");
_ds.display(dockSearchHotWordGroups, "dockSearchHotWordGroups");
_ds.display(reserved, "reserved");
}
public void displaySimple(java.lang.StringBuilder _os, int _level)
{
com.qq.taf.jce.JceDisplayer _ds = new com.qq.taf.jce.JceDisplayer(_os, _level);
_ds.displaySimple(dockSearchBox, true);
_ds.displaySimple(dockSearchHotWordGroups, true);
_ds.displaySimple(reserved, false);
}
}
| 31.448718
| 178
| 0.635956
|
2d337400419e4f14397b41ffc11420ef52a54a85
| 340
|
package com.reinaldoarrosi.android.querybuilder.sqlite.criteria;
import com.reinaldoarrosi.android.querybuilder.sqlite.QueryBuilder;
public class NotExistsCriteria extends ExistsCriteria {
public NotExistsCriteria(QueryBuilder subQuery) {
super(subQuery);
}
@Override
public String build() {
return "NOT " + super.build();
}
}
| 22.666667
| 67
| 0.782353
|
0241ae3ce463a37e5b0da098b295c2c313b70c09
| 5,409
|
package org.smartregister.immunization.utils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import org.smartregister.Context;
import org.smartregister.commonregistry.CommonPersonObjectClient;
import org.smartregister.domain.Photo;
import org.smartregister.domain.ProfileImage;
import org.smartregister.immunization.BaseUnitTest;
import org.smartregister.immunization.ImmunizationLibrary;
import org.smartregister.immunization.R;
import org.smartregister.immunization.util.ImageUtils;
import org.smartregister.repository.ImageRepository;
import java.util.Collections;
/**
* Created by onaio on 29/08/2017.
*/
@PrepareForTest ({ImmunizationLibrary.class})
public class ImageUtilsTest extends BaseUnitTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
@Mock
private CommonPersonObjectClient commonPersonObjectClient;
@Mock
private ImmunizationLibrary immunizationLibrary;
@Mock
private Context context;
@Mock
private ImageRepository imageRepository;
@Before
public void setUp() {
org.mockito.MockitoAnnotations.initMocks(this);
}
@Test
public void assertProfileImageResourceByGenderWithEmptyStringParameterReturnsDefaultResource() {
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender(""), R.drawable.child_boy_infant);
}
@Test
public void assertProfileImageResourceByGenderWithMaleParameterReturnsMaleResource() {
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender("male"), R.drawable.child_boy_infant);
}
@Test
public void assertProfileImageResourceByGenderWithFemaleParameterReturnsFemaleResource() {
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender("female"), R.drawable.child_girl_infant);
}
@Test
public void assertProfileImageResourceByGenderWithTransgenderParameterReturnsTransgenderResource() {
org.junit.Assert
.assertEquals(ImageUtils.profileImageResourceByGender("transgender"), R.drawable.child_transgender_inflant);
}
@Test
public void assertProfileImageResourceByGenderObjectWithMaleGenderParameterReturnsMaleResource() {
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender(org.opensrp.api.constants.Gender.MALE),
R.drawable.child_boy_infant);
}
@Test
public void assertProfileImageResourceByGenderWithFemaleObjectReturnsFemaleResource() {
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender(org.opensrp.api.constants.Gender.FEMALE),
R.drawable.child_girl_infant);
}
@Test
public void assertProfileImageResourceByGenderWithNullObjectParameterReturnsTransgenderResource() {
org.opensrp.api.constants.Gender gender = null;
org.junit.Assert.assertEquals(ImageUtils.profileImageResourceByGender(gender), R.drawable.child_transgender_inflant);
}
@Test
public void assertImageUtilsClassConstructorReturnsNonNullObjectOnInstantiation() {
org.junit.Assert.assertNotNull(new ImageUtils());
}
@Test
public void assertProfilePhotoByClientReturnsDefaultInfantBoyPhoto() {
PowerMockito.mockStatic(ImmunizationLibrary.class);
PowerMockito.when(ImmunizationLibrary.getInstance()).thenReturn(immunizationLibrary);
PowerMockito.when(ImmunizationLibrary.getInstance().context()).thenReturn(context);
PowerMockito.when(ImmunizationLibrary.getInstance().context().imageRepository()).thenReturn(imageRepository);
PowerMockito.when(ImmunizationLibrary.getInstance().context().imageRepository()
.findByEntityId(org.mockito.ArgumentMatchers.anyString())).thenReturn(null);
Photo photo = ImageUtils.profilePhotoByClient(commonPersonObjectClient);
org.junit.Assert.assertNotNull(photo);
org.junit.Assert.assertEquals(photo.getResourceId(), R.drawable.child_boy_infant);
}
@Test
public void assertProfilePhotoByClientReturnsCorrectPhotoFilePathForCorrespondingClient() {
PowerMockito.mockStatic(ImmunizationLibrary.class);
PowerMockito.when(ImmunizationLibrary.getInstance()).thenReturn(immunizationLibrary);
PowerMockito.when(ImmunizationLibrary.getInstance().context()).thenReturn(context);
PowerMockito.when(ImmunizationLibrary.getInstance().context().imageRepository()).thenReturn(imageRepository);
ProfileImage profileImage = new ProfileImage();
String imagePath = "/dummy/test/path/image.png";
String dummyCaseId = "4400";
profileImage.setFilepath(imagePath);
PowerMockito.when(ImmunizationLibrary.getInstance().context().imageRepository().findByEntityId(dummyCaseId))
.thenReturn(profileImage);
commonPersonObjectClient = new CommonPersonObjectClient(dummyCaseId, Collections.<String, String>emptyMap(),
"Test Name");
commonPersonObjectClient.setCaseId(dummyCaseId);
Photo photo = ImageUtils.profilePhotoByClient(commonPersonObjectClient);
org.junit.Assert.assertNotNull(photo);
org.junit.Assert.assertEquals(imagePath, photo.getFilePath());
}
}
| 42.590551
| 125
| 0.768349
|
1a2e8bd408f49ac513c337248eddd62505603f41
| 3,011
|
/*
* 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.aliyuncs.ehpc.transform.v20180412;
import com.aliyuncs.ehpc.model.v20180412.DescribeAutoScaleConfigResponse;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeAutoScaleConfigResponseUnmarshaller {
public static DescribeAutoScaleConfigResponse unmarshall(DescribeAutoScaleConfigResponse describeAutoScaleConfigResponse, UnmarshallerContext context) {
describeAutoScaleConfigResponse.setRequestId(context.stringValue("DescribeAutoScaleConfigResponse.RequestId"));
describeAutoScaleConfigResponse.setUid(context.stringValue("DescribeAutoScaleConfigResponse.Uid"));
describeAutoScaleConfigResponse.setClusterId(context.stringValue("DescribeAutoScaleConfigResponse.ClusterId"));
describeAutoScaleConfigResponse.setClusterType(context.stringValue("DescribeAutoScaleConfigResponse.ClusterType"));
describeAutoScaleConfigResponse.setEnableAutoGrow(context.booleanValue("DescribeAutoScaleConfigResponse.EnableAutoGrow"));
describeAutoScaleConfigResponse.setEnableAutoShrink(context.booleanValue("DescribeAutoScaleConfigResponse.EnableAutoShrink"));
describeAutoScaleConfigResponse.setGrowIntervalInMinutes(context.integerValue("DescribeAutoScaleConfigResponse.GrowIntervalInMinutes"));
describeAutoScaleConfigResponse.setShrinkIntervalInMinutes(context.integerValue("DescribeAutoScaleConfigResponse.ShrinkIntervalInMinutes"));
describeAutoScaleConfigResponse.setShrinkIdleTimes(context.integerValue("DescribeAutoScaleConfigResponse.ShrinkIdleTimes"));
describeAutoScaleConfigResponse.setGrowTimeoutInMinutes(context.integerValue("DescribeAutoScaleConfigResponse.GrowTimeoutInMinutes"));
describeAutoScaleConfigResponse.setExtraNodesGrowRatio(context.integerValue("DescribeAutoScaleConfigResponse.ExtraNodesGrowRatio"));
describeAutoScaleConfigResponse.setGrowRatio(context.integerValue("DescribeAutoScaleConfigResponse.GrowRatio"));
describeAutoScaleConfigResponse.setMaxNodesInCluster(context.integerValue("DescribeAutoScaleConfigResponse.MaxNodesInCluster"));
describeAutoScaleConfigResponse.setExcludeNodes(context.stringValue("DescribeAutoScaleConfigResponse.ExcludeNodes"));
describeAutoScaleConfigResponse.setSpotStrategy(context.stringValue("DescribeAutoScaleConfigResponse.SpotStrategy"));
describeAutoScaleConfigResponse.setSpotPriceLimit(context.stringValue("DescribeAutoScaleConfigResponse.SpotPriceLimit"));
return describeAutoScaleConfigResponse;
}
}
| 68.431818
| 153
| 0.858187
|
2b38075e76f0ce847a26fef2f6aee1c21f2d0459
| 1,354
|
package com.xiongxh.cryptocoin.coindetails;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import com.xiongxh.cryptocoin.R;
public class SectionPagerAdapter extends FragmentPagerAdapter{
String mSymbol;
CoinDetailFragment mCoinDetailFragment;
NewsFragment mNewsFragment;
Context mContext;
public SectionPagerAdapter(FragmentManager fm, String symbol, Context context){
super(fm);
this.mSymbol = symbol;
this.mContext = context;
mCoinDetailFragment = CoinDetailFragment.newInstance(symbol);
mNewsFragment = NewsFragment.newInstance(symbol);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return mCoinDetailFragment;
case 1:
return mNewsFragment;
}
return null;
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position){
switch (position){
case 0:
return mContext.getString(R.string.market_capital);
case 1:
return mContext.getString(R.string.news_capital);
}
return null;
}
}
| 26.038462
| 83
| 0.652142
|
c048cbee3d4701066925fefec534c2197b4d12d5
| 403
|
package nl.blackmantha.sandbox.pub;
/**
*
* An abstract skeleton class for an Applet to be run in the sandbox.
*
* @author github.com/Black-Mantha
*
*/
public abstract class Applet implements IApplet {
protected Applet() { }
protected ISandboxConnector connector;
protected Applet(ISandboxConnector connector) {
this.connector = connector;
}
@Override
abstract public void init();
}
| 19.190476
| 69
| 0.729529
|
71ad3d3a27403613f32052a7eeec298dbf5f224a
| 764
|
package org.apache.spark.shuffle;
/**
* Obtained inside a map task to write out records to the shuffle system.
*/
abstract class ShuffleWriter<K extends java.lang.Object, V extends java.lang.Object> {
// not preceding
// TypeTree().setOriginal(TypeBoundsTree(TypeTree(), TypeTree()))
// TypeTree().setOriginal(TypeBoundsTree(TypeTree(), TypeTree()))
public ShuffleWriter () { throw new RuntimeException(); }
/** Close this writer, passing along whether the map completed */
public abstract scala.Option<org.apache.spark.scheduler.MapStatus> stop (boolean success) ;
/** Write a sequence of records to this task's output */
public abstract void write (scala.collection.Iterator<scala.Product2<K, V>> records) throws java.io.IOException ;
}
| 50.933333
| 116
| 0.736911
|
64fd28d110144e154a6719eda2fb3ca57264490a
| 5,647
|
package com.kefan.ui;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.kefan.service.ConfigurationPersistentService;
import javax.swing.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class GenerateConfigDialog extends JDialog {
private static final String EXTENSION_NAME = "proto";
private ConfigurationPersistentService persistentService = ConfigurationPersistentService.getInstance();
private AnActionEvent anActionEvent;
private JPanel contentPane;
private JButton buttonOK;
private JButton buttonCancel;
private JComboBox pluginComboBox;
private JComboBox languageComboBox;
private JLabel pluginSelected;
private JLabel languageSelected;
private Map<String,String> languageMap=new HashMap<>();
private Map<String,String> pluginMap=new HashMap<>();
public GenerateConfigDialog(AnActionEvent anActionEvent) {
this.anActionEvent=anActionEvent;
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
initView();
//初始胡数据
initData();
//选择框设置数据
languageMap.forEach( (key,value)->languageComboBox.addItem(key));
pluginMap.forEach((key,value)->pluginComboBox.addItem(key));
//添加监听事件
languageComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
String s = (String) e.getItem();
languageSelected.setText(s);
}
});
pluginComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
String s = (String) e.getItem();
pluginSelected.setText(s);
}
});
//设置默认选中
languageSelected.setText(String.valueOf(languageComboBox.getSelectedItem()));
pluginSelected.setText(String.valueOf(pluginComboBox.getSelectedItem()));
buttonOK.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onOK();
}
});
buttonCancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onCancel();
}
});
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
onCancel();
}
});
// call onCancel() on ESCAPE
contentPane.registerKeyboardAction(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void initView() {
this.setTitle("Configuration");
}
private void onOK() {
// add your code here
//逻辑处理部分
process();
dispose();
}
private void onCancel() {
// add your code here if necessary
dispose();
}
private void initData() {
languageMap.put("C++", "cpp_out");
languageMap.put("C#", "csharp_out");
languageMap.put("Go", "go_out");
languageMap.put("Java", "java_out");
languageMap.put("Pyhton", "python_out");
languageMap.put("Objective C", "objc_out");
languageMap.put("Javascript", "js_out");
languageMap.put("Php", "php_out");
pluginMap.put("None", "none");
pluginMap.put("GRPC", "grpc");
}
private void process() {
Project project = anActionEvent.getProject();
String extension = getFileExtension(anActionEvent.getDataContext());
if (extension!=null&&EXTENSION_NAME.equals(extension)) {
VirtualFile file = PlatformDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext());
if (file == null) {
Messages.showErrorDialog("The file is not found", "Error");
return;
}
//命令生成处理
String command ="";
//优先使用配置的protoc 路径
if (persistentService.getConfig().getProtocPath() != null&&persistentService.getConfig().getProtocPath().endsWith("protoc")) {
command += persistentService.getConfig().getProtocPath();
} else {
//使用 系统变量
command += "protoc";
}
command +=" --proto_path=" + file.getParent().getPath() + " ";
if (!pluginSelected.getText().equals("None")) {
command += "--" + languageMap.get(languageSelected.getText()) + "=plugins=" + pluginMap.get(pluginSelected.getText()) + ":" + file.getParent().getPath() + " " + file.getPath();
} else {
command += "--" + languageMap.get(languageSelected.getText()) + "=:" + file.getParent().getPath() + " " + file.getPath();
}
//执行命令
try {
Process process = Runtime.getRuntime().exec(command);
int exitValue = process.waitFor();
if (exitValue == 0) {
Messages.showInfoMessage(project, "success", "Generate");
System.out.println("generate success");
//刷新目录
file.getParent().refresh(false, false);
} else {
Messages.showErrorDialog(project, "error exit " + exitValue, "Generate Failed");
}
} catch (IOException e1) {
e1.printStackTrace();
Messages.showErrorDialog(e1.getMessage()+" "+command, "exception");
} catch (InterruptedException e1) {
e1.printStackTrace();
Messages.showErrorDialog(e1.getMessage()+" "+command, "exception");
}
} else {
Messages.showErrorDialog(project, "file not found", "Select Failed");
}
}
private String getFileExtension(DataContext dataContext) {
VirtualFile virtualFile =PlatformDataKeys.VIRTUAL_FILE.getData(dataContext);
return virtualFile == null?null:virtualFile.getExtension();
}
}
| 24.552174
| 180
| 0.708164
|
c6125ac97244f8d79889546f55a14e15bbd22f22
| 6,778
|
package com.skeqi.finance.service.impl.help;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.skeqi.common.exception.CustomException;
import com.skeqi.common.utils.PageUtils;
import com.skeqi.common.core.page.PagePlus;
import com.skeqi.common.core.page.TableDataInfo;
import com.skeqi.finance.pojo.vo.basicinformation.base.TBdBusinessAreaVo;
import com.skeqi.finance.service.basicinformation.base.ITBdBusinessAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.skeqi.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.skeqi.finance.pojo.bo.help.TBdHelpTypeAddBo;
import com.skeqi.finance.pojo.bo.help.TBdHelpTypeQueryBo;
import com.skeqi.finance.pojo.bo.help.TBdHelpTypeEditBo;
import com.skeqi.finance.domain.help.TBdHelpType;
import com.skeqi.finance.mapper.TBdHelpTypeMapper;
import com.skeqi.finance.pojo.vo.basicinformation.help.TBdHelpTypeVo;
import com.skeqi.finance.service.help.ITBdHelpTypeService;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
/**
* 辅助资料类别Service业务层处理
*
* @author toms
* @date 2021-07-13
*/
@Service
public class TBdHelpTypeServiceImpl extends ServicePlusImpl<TBdHelpTypeMapper, TBdHelpType> implements ITBdHelpTypeService {
@Autowired
ITBdBusinessAreaService iTBdBusinessAreaService;
@Autowired
TBdHelpTypeMapper tBdHelpTypeMapper;
private TBdHelpTypeQueryBo buildPage(TBdHelpTypeQueryBo bo){
bo.setPageSize(bo.getPageNum()>1?(bo.getPageNum()*bo.getPageSize()):bo.getPageSize());
bo.setPageNum(bo.getPageNum()>1?((bo.getPageNum()-1)*bo.getPageSize()):0);
return bo;
}
@Override
public TBdHelpTypeVo queryById(Integer fId){
TBdHelpTypeVo vo=getVoById(fId, TBdHelpTypeVo.class);
if(null==vo){
return null;
}
String p=tBdHelpTypeMapper.findByParentId(Integer.parseInt(vo.getFParentId()));
vo.setFParentName(p);
return vo;
}
@Override
public TableDataInfo<TBdHelpTypeVo> queryPageList(TBdHelpTypeQueryBo bo) {
PagePlus<TBdHelpType, TBdHelpTypeVo> result = pageVo(PageUtils.buildPagePlus(), buildQueryWrapper(bo), TBdHelpTypeVo.class);
return PageUtils.buildDataInfo(result);
}
@Override
public TableDataInfo<TBdHelpTypeVo> queryPageGroup(TBdHelpTypeQueryBo bo) {
if(bo.getFBusinessArea()!=null){
Integer parentId=tBdHelpTypeMapper.findByAreaId(Integer.parseInt(bo.getFBusinessArea()));
bo.setFParentId(parentId);
}
List<TBdHelpTypeVo> list=tBdHelpTypeMapper.queryPageGroup(buildPage(bo));
Integer total=0;
if(!CollectionUtil.isEmpty(list)){
total=tBdHelpTypeMapper.queryPageGroupCount(buildPage(bo));
}
return PageUtils.buildDataInfo(list,total);
}
@Override
public List<TBdHelpTypeVo> getNextGrade(TBdHelpTypeQueryBo bo){
if(null==bo.getFParentId()){
return null;
}
return listVo(buildQueryWrapper(bo), TBdHelpTypeVo.class);
}
@Override
public List<TBdHelpTypeVo> queryList(TBdHelpTypeQueryBo bo) {
return listVo(buildQueryWrapper(bo), TBdHelpTypeVo.class);
}
private LambdaQueryWrapper<TBdHelpType> buildQueryWrapper(TBdHelpTypeQueryBo bo) {
Map<String, Object> params = bo.getParams();
LambdaQueryWrapper<TBdHelpType> lqw = Wrappers.lambdaQuery();
lqw.eq(bo.getFBusinessArea() !=null, TBdHelpType::getFBusinessArea, bo.getFBusinessArea());
lqw.like(StrUtil.isNotBlank(bo.getFTypeName()), TBdHelpType::getFTypeName, bo.getFTypeName());
lqw.eq(StrUtil.isNotBlank(bo.getFDescription()), TBdHelpType::getFDescription, bo.getFDescription());
lqw.eq(bo.getFParentId()!=null, TBdHelpType::getFParentId, bo.getFParentId());
lqw.eq(bo.getFCreateOrgid() != null, TBdHelpType::getFCreateOrgid, bo.getFCreateOrgid());
lqw.eq(bo.getFUseOrgid() != null, TBdHelpType::getFUseOrgid, bo.getFUseOrgid());
lqw.eq(bo.getFCreatorid() != null, TBdHelpType::getFCreatorid, bo.getFCreatorid());
lqw.eq(bo.getFCreateDate() != null, TBdHelpType::getFCreateDate, bo.getFCreateDate());
lqw.eq(bo.getFModifierid() != null, TBdHelpType::getFModifierid, bo.getFModifierid());
lqw.eq(bo.getFModifyDate() != null, TBdHelpType::getFModifyDate, bo.getFModifyDate());
lqw.eq(StrUtil.isNotBlank(bo.getFDocumentStatus()), TBdHelpType::getFDocumentStatus, bo.getFDocumentStatus());
lqw.eq(bo.getFAuditorid() != null, TBdHelpType::getFAuditorid, bo.getFAuditorid());
lqw.eq(bo.getFAuditDate() != null, TBdHelpType::getFAuditDate, bo.getFAuditDate());
lqw.eq(StrUtil.isNotBlank(bo.getFForbidStatus()), TBdHelpType::getFForbidStatus, bo.getFForbidStatus());
lqw.eq(bo.getFForbidderid() != null, TBdHelpType::getFForbidderid, bo.getFForbidderid());
lqw.eq(bo.getFForbidDate() != null, TBdHelpType::getFForbidDate, bo.getFForbidDate());
lqw.eq(bo.getFIssysPreset() != null, TBdHelpType::getFIssysPreset, bo.getFIssysPreset());
lqw.eq(bo.getFMasterId() != null, TBdHelpType::getFMasterId, bo.getFMasterId());
return lqw;
}
@Transactional(rollbackFor = Exception.class)
@Override
public Boolean insertByAddBo(TBdHelpTypeAddBo bo) {
TBdBusinessAreaVo areaVo=iTBdBusinessAreaService.queryById(bo.getFBusinessArea());
if(areaVo==null){
throw new CustomException("领域不存在",1000);
}
TBdHelpType add = BeanUtil.toBean(bo, TBdHelpType.class);
add.setFBusinessAreaName(areaVo.getName());
validEntityBeforeSave(add);
add.setFCreateDate(new Date());
this.save(add);
return true;
}
@Override
public Boolean updateByEditBo(TBdHelpTypeEditBo bo) {
TBdHelpType old =getById(bo.getFId());
if(old==null){
throw new CustomException("辅助资料类别不存在",1000);
}
TBdBusinessAreaVo areaVo=iTBdBusinessAreaService.queryById(bo.getFBusinessArea());
if(areaVo==null){
throw new CustomException("领域不存在",1000);
}
BeanUtil.copyProperties(bo,old,"fid");
validEntityBeforeSave(old);
old.setFBusinessAreaName(areaVo.getName());
old.setFBusinessArea(bo.getFBusinessArea());
return updateById(old);
}
/**
* 保存前的数据校验
*
* @param entity 实体类数据
*/
private void validEntityBeforeSave(TBdHelpType entity){
//TODO 做一些数据校验,如唯一约束
}
@Override
public Boolean deleteWithValidByIds(Collection<Integer> ids, Boolean isValid) {
if(isValid){
//TODO 做一些业务上的校验,判断是否需要校验
}
return removeByIds(ids);
}
}
| 40.831325
| 132
| 0.741369
|
6663424503a8e87864dacb7d70f79b778ab0ffc8
| 5,491
|
package com.greatorator.tolkienmobs.entity.merchant.model;
import com.google.common.collect.ImmutableList;
import net.minecraft.client.renderer.entity.model.IHasHead;
import net.minecraft.client.renderer.entity.model.IHeadToggle;
import net.minecraft.client.renderer.entity.model.SegmentedModel;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.merchant.villager.AbstractVillagerEntity;
import net.minecraft.util.math.MathHelper;
/**
* Elf - GreatOrator
*/
public class ModelTTMElves<T extends Entity> extends SegmentedModel<T> implements IHasHead, IHeadToggle {
public ModelRenderer ElfBody;
public ModelRenderer ElfHead;
public ModelRenderer ElfLegRight;
public ModelRenderer bipedRightArm;
public ModelRenderer bipedLeftArm;
public ModelRenderer ElfLegLeft;
public ModelRenderer ElfEarLeft1;
public ModelRenderer ElfEarRight1;
public ModelRenderer ElfEarLeft2;
public ModelRenderer ElfEarLeft3;
public ModelRenderer ElfEarRight2;
public ModelRenderer ElfEarRight3;
public ModelTTMElves() {
this.texWidth = 64;
this.texHeight = 64;
this.ElfEarRight3 = new ModelRenderer(this, 35, 10);
this.ElfEarRight3.setPos(0.0F, -2.0F, 2.7F);
this.ElfEarRight3.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 1, 0.0F);
this.ElfEarRight1 = new ModelRenderer(this, 35, 10);
this.ElfEarRight1.setPos(-4.0F, -3.5F, -1.6F);
this.ElfEarRight1.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 2, 0.0F);
this.ElfEarLeft2 = new ModelRenderer(this, 35, 10);
this.ElfEarLeft2.setPos(0.0F, -1.0F, 1.0F);
this.ElfEarLeft2.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 2, 0.0F);
this.bipedRightArm = new ModelRenderer(this, 40, 16);
this.bipedRightArm.setPos(-5.0F, 2.0F, 0.0F);
this.bipedRightArm.addBox(-3.0F, -2.0F, -2.0F, 4, 12, 4, 0.0F);
this.ElfBody = new ModelRenderer(this, 16, 16);
this.ElfBody.setPos(0.0F, 0.0F, 0.0F);
this.ElfBody.addBox(-4.0F, 0.0F, -2.0F, 8, 12, 4, 0.0F);
this.ElfEarLeft1 = new ModelRenderer(this, 35, 10);
this.ElfEarLeft1.mirror = true;
this.ElfEarLeft1.setPos(4.0F, -3.5F, -1.6F);
this.ElfEarLeft1.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 2, 0.0F);
this.ElfHead = new ModelRenderer(this, 0, 0);
this.ElfHead.setPos(0.0F, 0.0F, 0.0F);
this.ElfHead.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.0F);
this.ElfLegRight = new ModelRenderer(this, 0, 16);
this.ElfLegRight.setPos(-1.9F, 12.0F, 0.0F);
this.ElfLegRight.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
this.ElfEarRight2 = new ModelRenderer(this, 35, 10);
this.ElfEarRight2.setPos(0.0F, -1.0F, 1.0F);
this.ElfEarRight2.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 2, 0.0F);
this.bipedLeftArm = new ModelRenderer(this, 32, 48);
this.bipedLeftArm.setPos(5.0F, 2.0F, 0.0F);
this.bipedLeftArm.addBox(-1.0F, -2.0F, -2.0F, 4, 12, 4, 0.0F);
this.ElfLegLeft = new ModelRenderer(this, 16, 48);
this.ElfLegLeft.setPos(1.9F, 12.0F, 0.0F);
this.ElfLegLeft.addBox(-2.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
this.ElfEarLeft3 = new ModelRenderer(this, 35, 10);
this.ElfEarLeft3.setPos(0.0F, -2.0F, 2.7F);
this.ElfEarLeft3.addBox(-0.5F, -0.5F, -0.5F, 1, 2, 1, 0.0F);
this.ElfEarRight1.addChild(this.ElfEarRight3);
this.ElfHead.addChild(this.ElfEarRight1);
this.ElfEarLeft1.addChild(this.ElfEarLeft2);
this.ElfBody.addChild(this.bipedRightArm);
this.ElfHead.addChild(this.ElfEarLeft1);
this.ElfBody.addChild(this.ElfHead);
this.ElfBody.addChild(this.ElfLegRight);
this.ElfEarRight1.addChild(this.ElfEarRight2);
this.ElfBody.addChild(this.bipedLeftArm);
this.ElfBody.addChild(this.ElfLegLeft);
this.ElfEarLeft1.addChild(this.ElfEarLeft3);
}
@Override
public Iterable<ModelRenderer> parts() {
return ImmutableList.of(this.ElfHead, this.ElfBody, this.ElfLegRight, this.ElfLegLeft, this.bipedLeftArm, this.bipedRightArm);
}
/**
* Sets this entity's model rotation angles
*/
@Override
public void setupAnim(T entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {
boolean flag = false;
if (entityIn instanceof AbstractVillagerEntity) {
flag = ((AbstractVillagerEntity)entityIn).getUnhappyCounter() > 0;
}
this.ElfHead.yRot = netHeadYaw * ((float)Math.PI / 180F);
this.ElfHead.xRot = headPitch * ((float)Math.PI / 180F);
if (flag) {
this.ElfHead.zRot = 0.3F * MathHelper.sin(0.45F * ageInTicks);
this.ElfHead.xRot = 0.4F;
} else {
this.ElfHead.zRot = 0.0F;
}
this.bipedRightArm.xRot = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount;
this.bipedLeftArm.xRot = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount;
this.ElfLegRight.xRot = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount * 0.5F;
this.ElfLegLeft.xRot = MathHelper.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount * 0.5F;
this.ElfLegRight.yRot = 0.0F;
this.ElfLegLeft.yRot = 0.0F;
}
@Override
public ModelRenderer getHead() {
return this.ElfHead;
}
@Override
public void hatVisible(boolean p_217146_1_) {
}
}
| 44.642276
| 134
| 0.658532
|
4df75b588a31ab489902798228d92fc634abacf0
| 557
|
package org.springframework.web.multipart;
import org.springframework.core.io.InputStreamSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public interface MultipartFile extends InputStreamSource {
String getName();
String getOriginalFilename();
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
@Override
InputStream getInputStream() throws IOException;
void transferTo(File dest) throws IOException, IllegalStateException;
}
| 19.892857
| 73
| 0.754039
|
86ce0c5abec2e6401eb1ed92ea861c219e02fa14
| 3,314
|
package nosi.webapps.sistema_de_avaliacao_igrpweb.pages.criacao_de_certificado;
import nosi.core.webapp.Controller;//
import nosi.core.webapp.databse.helpers.ResultSet;//
import nosi.core.webapp.databse.helpers.QueryInterface;//
import java.io.IOException;//
import nosi.core.webapp.Core;//
import nosi.core.webapp.Response;//
/* Start-Code-Block (import) */
/* End-Code-Block */
/*----#start-code(packages_import)----*/
import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.AvaliadoTbl;
import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.FormandoTbl;
import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.ImagensTbl;
import nosi.core.webapp.Report;
import nosi.webapps.sistema_de_avaliacao_igrpweb.dao.ImagensTbl;
import nosi.core.webapp.UploadedFile;
/*----#end-code----*/
public class Criacao_de_certificadoController extends Controller {
public Response actionIndex() throws IOException, IllegalArgumentException, IllegalAccessException {
Criacao_de_certificado model = new Criacao_de_certificado();
model.load();
Criacao_de_certificadoView view = new Criacao_de_certificadoView();
/*----#start-code(index)----*/
try {
Integer formando = Core.getParamInt("value_array");
FormandoTbl avaliadotbl = new FormandoTbl().findOne(formando);
if (avaliadotbl != null && !avaliadotbl.hasError()) {
// if(Core.isNotNull(Core.getLinkFileByUuid(avaliadotbl.getAvaliadoId().getIdFoto())))
// view.foto.setValue(Core.getLinkFileByUuid(avaliadotbl.getAvaliadoId().getIdFoto()));
model.setNome(avaliadotbl.getAvaliadoId().getNome());
model.setId_avaliado("" + avaliadotbl.getAvaliadoId().getIdAvaliado());
model.setTexto_1("que completou com sucesso a formação de");
model.setTitulo(avaliadotbl.getFormacaoId().getNome());
model.setTexto_2("com duração de " + avaliadotbl.getFormacaoId().getHora()
+ " horas e que se realizou de "
+ Core.convertLocalDateToString(avaliadotbl.getFormacaoId().getDataIn(), "dd-MM-yyyy") + " a "
+ Core.convertLocalDateToString(avaliadotbl.getFormacaoId().getDataFim(), "dd-MM-yyyy") + " em "
+ avaliadotbl.getFormacaoId().getLocal() + ".");
model.setCallback_url(
"http://cloud.nosi.cv/IGRP/app/webapps?r=sistema_de_avaliacao_igrpweb/Validar_certificado/index&dad=sistema_de_avaliacao_igrpweb&target=_blank&isPublic=1&lang=pt_PT&p_contra_prova="
+ avaliadotbl.getChaveAut());
model.setChave_de_validacao(avaliadotbl.getChaveAut());
}
model.setTexto_3("NOSI.CV/IGRPWEB");
ImagensTbl imagenslogo = new ImagensTbl().findOne(1);
if (imagenslogo != null && !imagenslogo.hasError()) {
if(Core.isNotNull(Core.getLinkFileByUuid(imagenslogo.getIdFoto())))
view.logo.setValue(Core.getLinkFileByUuid(imagenslogo.getIdFoto()));
}
ImagensTbl imagensfundo = new ImagensTbl().findOne(2);
if (imagensfundo != null && !imagensfundo.hasError()) {
if(Core.isNotNull(Core.getLinkFileByUuid(imagensfundo.getIdFoto())))
view.fundo.setValue(Core.getLinkFileByUuid(imagensfundo.getIdFoto()));
}
} catch (Exception e) {
e.printStackTrace();
}
/*----#end-code----*/
view.setModel(model);
return this.renderView(view);
}
/*----#start-code(custom_actions)----*/
/*----#end-code----*/
}
| 45.39726
| 188
| 0.722088
|
8b0e1bfe8a356319bf551417c4f1a40c32856345
| 9,828
|
package org.egc.ows.client;
import com.alibaba.fastjson.JSON;
import com.eviware.soapui.impl.WsdlInterfaceFactory;
import com.eviware.soapui.impl.wsdl.*;
import com.eviware.soapui.impl.wsdl.support.RequestFileAttachment;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.iface.Operation;
import com.eviware.soapui.model.iface.Response;
import com.eviware.soapui.support.SoapUIException;
import com.eviware.soapui.support.XmlHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.xmlbeans.XmlException;
import org.egc.ows.commons.OperationParameter;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* The Soap client.
*
* @author houzhiwei
* @date 2020 /11/2 16:21
*/
@Slf4j
public class SoapClient {
public String getWsdlLocation() {
return wsdlLocation;
}
private String wsdlLocation;
private WsdlInterface iface;
private WsdlProject project;
public String getEndpoint() {
return iface.getEndpoints()[0];
}
private String endpoint;
private boolean remoteEndpoint = false;
private int timeout = 3000;
public SoapClient(String wsdlLocation) throws XmlException, IOException, SoapUIException {
this.wsdlLocation = wsdlLocation;
// create new project
WsdlProject project = new WsdlProject();
this.project = project;
// import wsdl
this.iface = WsdlInterfaceFactory.importWsdl(project, this.wsdlLocation, true)[0];
}
public List<String> getOperations() {
List<String> operations = new ArrayList<>();
for (Operation suop : this.iface.getAllOperations()) {
String op = suop.getName();
operations.add(op);
}
return operations;
}
/**
* Gets default request content.
*
* @param operationName the operation name
* @return the default request content xml
*/
public String getDefaultRequestContent(String operationName, boolean buildOptional) {
WsdlOperation operation = iface.getOperationByName(operationName);
return operation.createRequest(buildOptional);
}
/**
* Gets operation parameters.
*
* @param operationName the operation name
* @param includeOptional the include optional
* @return operation parameters
* @throws XmlException the xml exception
*/
public List<OperationParameter> getOperationParameters(String operationName, boolean includeOptional) throws XmlException {
WsdlOperation operation = iface.getOperationByName(operationName);
String requestXml = operation.createRequest(includeOptional);
log.debug("Default request xml is \n {}", requestXml);
/*
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:taud="http://taudem.hydro.ws.egc.org">
<soap:Header/>
<soap:Body>
<taud:pitRemove>
<elevation>?</elevation>
<!--Optional:-->
<depressionMask>?</depressionMask>
<!--Optional:-->
<fillConsideringOnly4WayNeighbors>?</fillConsideringOnly4WayNeighbors>
<!--Optional:-->
<pitFilledElevation>?</pitFilledElevation>
</taud:pitRemove>
</soap:Body>
</soap:Envelope>
**/
Node body = new XmlHolder(requestXml).getDomNode("//*:Body");
List<OperationParameter> params = new ArrayList<>();
//ignore text child nodes
NodeList parameterNodes = body.getChildNodes().item(1).getChildNodes();
for (int i = 0; i < parameterNodes.getLength(); i++) {
Node item = parameterNodes.item(i);
if (item.getNodeType() == Node.TEXT_NODE) {
continue;
}
if (item.getNodeType() != Node.COMMENT_NODE) {
OperationParameter parameter = new OperationParameter(item.getNodeName());
params.add(parameter);
} else {
//<!--Optional:-->
//the first next sibling is a text node
Node optionalNode = item.getNextSibling().getNextSibling();
OperationParameter parameter = new OperationParameter(optionalNode.getNodeName());
parameter.setOptional(true);
params.add(parameter);
i += 2;
}
}
return params;
}
/**
* Generate request xml string.<br/>
* https://stackoverflow.com/questions/26046052/updating-a-wsdlrequest-value-via-soapui-pro
*
* @param operationName the operation name
* @param requestParameters the request parameter key-value paris
* @param includeOptional the include optional
* @return the string
* @throws XmlException the xml exception
*/
public String generateRequestXml(String operationName, Map<String, Object> requestParameters, boolean includeOptional) throws XmlException {
WsdlOperation operation = iface.getOperationByName(operationName);
String requestXml = operation.createRequest(includeOptional);
XmlHolder xmlHolder = new XmlHolder(requestXml);
for (Map.Entry<String, Object> entry : requestParameters.entrySet()) {
xmlHolder.setNodeValue("//*:" + entry.getKey(), entry.getValue());
}
return xmlHolder.getPrettyXml();
}
public String generateRequestXml(String operationName, Map<String, Object> requestParameters) throws XmlException {
WsdlOperation operation = iface.getOperationByName(operationName);
String requestXml = operation.createRequest(false);
XmlHolder xmlHolder = new XmlHolder(requestXml);
for (Map.Entry<String, Object> entry : requestParameters.entrySet()) {
xmlHolder.setNodeValue("//*:" + entry.getKey(), entry.getValue());
}
return xmlHolder.getPrettyXml();
}
public String invoke(WsdlOperation operation, String requestXml) throws Exception {
return invoke(operation, requestXml, false);
}
public String invoke(WsdlOperation operation, String requestXml, boolean async) throws Exception {
WsdlRequest request = operation.addNewRequest("request");
request.setRequestContent(requestXml);
WsdlSubmitContext context = new WsdlSubmitContext(request);
WsdlSubmit<WsdlRequest> submit = request.submit(context, async);
Response response = submit.getResponse();
if (submit.getError() != null) {
throw submit.getError();
}
String content = response.getContentAsString();
log.info(content);
return content;
}
//-----------------------------------------------------------
/**
* TODO NOT IMPLEMENTED !
* Invoke with attachments string.
* https://stackoverflow.com/questions/9066049/attaching-file-in-soapui-with-groovy
*
* @param operation the operation
* @param requestXml the request xml
* @param async the async
* @return the string
* @throws Exception the exception
*/
public String invokeWithAttachments(WsdlOperation operation, String requestXml, boolean async) throws Exception {
WsdlRequest request = operation.addNewRequest("request");
request.setRequestContent(requestXml);
request.setMtomEnabled(true);
request.getAttachmentCount();
Attachment attachment = new RequestFileAttachment(new File(""), true, request);
attachment.setContentType("application/octet-stream");
attachment.setPart("filename");
WsdlSubmitContext context = new WsdlSubmitContext(request);
WsdlSubmit<WsdlRequest> submit = request.submit(context, async);
Response response = submit.getResponse();
if (submit.getError() != null) {
throw submit.getError();
}
String content = response.getContentAsString();
log.info(content);
return content;
}
/**
* TODO NOT IMPLEMENTED !
* Generate request xml with attachments string.
*
* @param operationName the operation name
* @param requestParameters the request parameters
* @param includeOptional the include optional
* @return the string
* @throws XmlException the xml exception
*/
public String generateRequestXmlWithAttachments(String operationName, Map<String, Object> requestParameters, boolean includeOptional) throws XmlException {
WsdlOperation operation = iface.getOperationByName(operationName);
String requestXml = operation.createRequest(includeOptional);
XmlHolder xmlHolder = new XmlHolder(requestXml);
for (Map.Entry<String, Object> entry : requestParameters.entrySet()) {
xmlHolder.setNodeValue("//*:" + entry.getKey(), entry.getValue());
}
return xmlHolder.getPrettyXml();
}
//----------------------------
public void release() {
this.iface.release();
this.project.release();
}
public WsdlOperation getOperation(String operationName) {
return iface.getOperationByName(operationName);
}
final static String charset = "UTF-8";
private static String xmlToJson(String responseXml) {
if (StringUtils.isNotBlank(responseXml)) {
int beginIndex = responseXml.indexOf("<return>");
int endIndex = responseXml.indexOf("</return>");
responseXml = responseXml.substring(beginIndex, endIndex + 9);
}
return StringUtils.isNotBlank(responseXml) ? JSON.toJSONString(responseXml, true) : null;
}
}
| 38.241245
| 159
| 0.653236
|
417f8bc110ad1d7bb5e39897c769d8fe7d29e41c
| 5,848
|
package com.creditease.dbus.router.spout.handler.processor;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
import com.alibaba.fastjson.JSONObject;
import com.creditease.dbus.commons.ControlType;
import com.creditease.dbus.router.bean.Sink;
import com.creditease.dbus.router.spout.aware.ContextAware;
import com.creditease.dbus.router.spout.context.Context;
import com.creditease.dbus.router.spout.context.ProcessorContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MonitorSpoutControlProcessor extends AbstractProcessor implements ContextAware {
private static Logger logger = LoggerFactory.getLogger(MonitorSpoutControlProcessor.class);
private ProcessorContext context = null;
@Override
public void setContext(Context context) {
this.context = (ProcessorContext) context;
}
@Override
public boolean isBelong(String str) {
return isCtrlTopic(str);
}
@Override
public Object process(Object obj, Supplier... suppliers) {
Object ret = new Object();
ConsumerRecord<String, byte[]> record = (ConsumerRecord) obj;
logger.info("topic:{}, key:{}, offset:{}", record.topic(), record.key(), record.offset());
if (!isBelong(record.key())) return ret;
try {
processCtrlMsg(record);
} catch (Exception e) {
logger.error("monitor control processor error", e);
}
return ret;
}
private String obtainCtrlTopic() {
return StringUtils.joinWith("_", context.getInner().topologyId, "ctrl");
}
private boolean isCtrlTopic(String topic) {
return StringUtils.equals(topic, obtainCtrlTopic());
}
private boolean processCtrlMsg(ConsumerRecord<String, byte[]> record) throws Exception {
boolean ret = true;
String strCtrl = new String(record.value(), "UTF-8");
logger.info("monitor spout process ctrl msg. cmd:{}", strCtrl);
JSONObject jsonCtrl = JSONObject.parseObject(strCtrl);
ControlType cmd = ControlType.getCommand(jsonCtrl.getString("type"));
switch (cmd) {
case ROUTER_RELOAD:
reload(strCtrl);
break;
case ROUTER_TOPOLOGY_TABLE_START:
ret = startTopologyTable(jsonCtrl);
break;
case ROUTER_TOPOLOGY_TABLE_STOP:
ret = stopTopologyTable(jsonCtrl);
break;
default:
break;
}
return ret;
}
private void reload(String ctrl) throws Exception {
context.getInner().close(true);
context.getInner().init();
context.getSpout().postOpen();
context.getInner().zkHelper.saveReloadStatus(ctrl, "DBusRouterMonitorSpout-" + context.getSpout().getContext().getThisTaskId(), true);
logger.info("monitor spout reload completed.");
}
private boolean startTopologyTable(JSONObject ctrl) throws Exception {
boolean ret = false;
JSONObject payload = ctrl.getJSONObject("payload");
Integer projectTopologyTableId = payload.getInteger("projectTopoTableId");
List<Sink> sinks = context.getInner().dbHelper.loadSinks(context.getInner().topologyId, projectTopologyTableId);
if (sinks != null && sinks.size() > 0) {
boolean isUsing = context.getInner().dbHelper.isUsingTopic(projectTopologyTableId);
if (isUsing) {
logger.info("table:{} of out put topic is using, don't need assign.", projectTopologyTableId);
} else {
ret = true;
Optional.ofNullable(context.getSinks()).orElseGet(() -> {
List<Sink> list = new ArrayList<>();
context.setSinks(list);
return list;
}).addAll(sinks);
context.getSpout().initConsumer();
}
}
logger.info("monitor spout start topology table:{} completed.", projectTopologyTableId);
return ret;
}
private boolean stopTopologyTable(JSONObject ctrl) throws Exception {
boolean ret = false;
JSONObject payload = ctrl.getJSONObject("payload");
String dsName = payload.getString("dsName");
String schemaName = payload.getString("schemaName");
String tableName = payload.getString("tableName");
Integer projectTopologyTableId = payload.getInteger("projectTopoTableId");
String namespace = StringUtils.joinWith(".", dsName, schemaName, tableName);
List<Sink> sinks = context.getSinks();
if (sinks != null) {
Sink delSink = null;
for (Sink sink : sinks) {
String wkNs = StringUtils.joinWith(".", sink.getDsName(), sink.getSchemaName(), sink.getTableName());
if (StringUtils.equals(wkNs, namespace)) {
delSink = sink;
break;
}
}
if (delSink != null) {
sinks.remove(delSink);
boolean isUsing = context.getInner().dbHelper.isUsingTopic(projectTopologyTableId);
if (isUsing) {
logger.info("table:{} of out put topic is using, don't need remove.", projectTopologyTableId);
} else {
context.getSpout().initConsumer();
ret = true;
}
} else {
logger.error("don't find name space:{} target sink, stop table fail.", namespace);
}
}
logger.info("monitor spout stop topology table:{} completed.", projectTopologyTableId);
return ret;
}
}
| 39.782313
| 142
| 0.620212
|
88a73f67b48fe15046eeac94a0809dec22a5520a
| 491
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.drools.devguide.chapter05.utils;
import org.drools.devguide.eshop.model.Customer;
/**
*
* @author esteban
*/
public class CustomerUtils {
public static String formatCustomer(Customer c) {
return String.format(
"[%s] %s", c.getCategory(), c.getName());
}
}
| 23.380952
| 79
| 0.680244
|
66c2ca1444bc45c452d60f157276110ea7098885
| 9,144
|
package com.jstarcraft.core.communication.netty;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.jstarcraft.core.common.lifecycle.LifecycleState;
import com.jstarcraft.core.communication.annotation.CommunicationModule;
import com.jstarcraft.core.communication.annotation.CommunicationModule.ModuleSide;
import com.jstarcraft.core.communication.command.CommandDispatcher;
import com.jstarcraft.core.communication.command.CommandManager;
import com.jstarcraft.core.communication.command.MockClientClass;
import com.jstarcraft.core.communication.command.MockClientInterface;
import com.jstarcraft.core.communication.command.MockServerClass;
import com.jstarcraft.core.communication.command.MockServerInterface;
import com.jstarcraft.core.communication.command.UserObject;
import com.jstarcraft.core.communication.session.CommunicationSession;
import com.jstarcraft.core.communication.session.SessionManager;
import com.jstarcraft.core.utility.StringUtility;
public abstract class NettyTestCase<T> {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/** 用于测试{@link CommunicationModule} */
@Autowired
@Qualifier("clientDispatcher")
protected CommandDispatcher<T> clientDispatcher;
@Autowired
@Qualifier("serverDispatcher")
protected CommandDispatcher<T> serverDispatcher;
@Autowired
@Qualifier("clientSessionManager")
protected NettySessionManager<T> clientSessionManager;
@Autowired
@Qualifier("serverSessionManager")
protected NettySessionManager<T> serverSessionManager;
@Autowired
@Qualifier("clientCommandManager")
protected CommandManager clientCommandManager;
@Autowired
@Qualifier("serverCommandManager")
protected CommandManager serverCommandManager;
@Autowired
@Qualifier("nettyClientConnector")
protected NettyClientConnector<T> nettyClientConnector;
@Autowired
@Qualifier("nettyServerConnector")
protected NettyServerConnector<T> nettyServerConnector;
@Autowired
protected MockServerClass mockServerClass;
@Autowired
protected MockClientClass mockClientClass;
protected InetSocketAddress clientAddress = SessionManager.key2Address("127.0.0.1:6969");
protected InetSocketAddress serverAddress = SessionManager.key2Address("0.0.0.0:6969");
@Before
public void before() {
// 启动客户端与服务端的连接器
nettyServerConnector.start();
nettyClientConnector.start();
}
@After
public void after() {
// 关闭客户端与服务端的连接器
nettyClientConnector.stop();
nettyServerConnector.stop();
Assert.assertThat(clientSessionManager.getSessions(null).size(), CoreMatchers.equalTo(0));
Assert.assertThat(serverSessionManager.getSessions(null).size(), CoreMatchers.equalTo(0));
}
/**
* 测试基于Spring的装配自动化
*/
@Test
public void testAssemblage() {
// 保证@CommunicationModule注解的接口与类型能被自动装配
Assert.assertThat(clientDispatcher, CoreMatchers.notNullValue());
Assert.assertThat(clientDispatcher.getSide(), CoreMatchers.equalTo(ModuleSide.CLIENT));
Assert.assertThat(serverDispatcher, CoreMatchers.notNullValue());
Assert.assertThat(serverDispatcher.getSide(), CoreMatchers.equalTo(ModuleSide.SERVER));
Assert.assertThat(clientCommandManager, CoreMatchers.notNullValue());
Assert.assertThat(serverCommandManager, CoreMatchers.notNullValue());
Assert.assertThat(nettyClientConnector, CoreMatchers.notNullValue());
Assert.assertThat(nettyServerConnector, CoreMatchers.notNullValue());
}
/**
* 测试服务
*
* @throws Exception
*/
@Test
public void testService() throws Exception {
// 启动客户端与服务端的会话
CommunicationSession<T> clientSession = nettyClientConnector.open(clientAddress, 5000);
Assert.assertThat(clientSession.getKey(), CoreMatchers.equalTo(SessionManager.address2Key(clientAddress)));
// Thread.sleep(1000L);
// Assert.assertThat(serverSessionManager.getSessions(null).size(),
// CoreMatchers.equalTo(1));
// 相当于业务流程
long userId = 1;
String userName = "birdy";
MockServerInterface serverService = clientCommandManager.getProxy(MockServerInterface.class, SessionManager.address2Key(clientAddress), 10000);
UserObject user = UserObject.instanceOf(userId, userName);
int serverTimes = mockServerClass.getTimes();
Assert.assertThat(serverService.createUser(user), CoreMatchers.equalTo(user));
Assert.assertThat(serverService.getUser(userId), CoreMatchers.equalTo(user));
Assert.assertNull(serverService.deleteUser(userId));
Assert.assertThat(mockServerClass.getTimes() - serverTimes, CoreMatchers.equalTo(3));
Assert.assertThat(serverService.addition(1), CoreMatchers.equalTo(2));
Assert.assertThat(serverService.addition(1, 2), CoreMatchers.equalTo(3));
String string = "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjEsImlzcyI6Imh0dHA6Ly9zdmxhZGEuY29tIiwidGltZSI6IjIwMTctMDYtMTQgMDk6MDE6MzQiLCJleHAiOjE0OTc0MDI5OTQsImlhdCI6MTQ5NzQwMjA5NH0.8fELQQ-iAwa6Ue_pGUi8qzTu7tHScAxPBzp92ZWJDII9I4eXftXAaHF2qb8UgGzrbTPa_baIa7MKFLwujfZ16Q,eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjEsImlzcyI6Imh0dHA6Ly9zdmxhZGEuY29tIiwidGltZSI6IjIwMTctMDYtMTQgMDk6MDE6MzQiLCJzY29wZXMiOlsiUk9MRV9SRUZSRVNIX1RPS0VOIl0sImV4cCI6MTQ5NzQwNTY5NSwiaWF0IjoxNDk3NDAyMDk1LCJqdGkiOiIyNTFiYmViYy01NmNhLTQxOTUtOWY5OC0yMmU2ZDI3MWFkMmIifQ.2pu4DfpstAwRNVAH5mzzNg9fhNB-etuH9Zm6yc18C2LjDxzjCmUeZVVvntPvhcNAXNUma34L_t7CRtgSVCNc-Q";
Assert.assertThat(serverService.md5(string), CoreMatchers.equalTo(string));
int clientTimes = mockClientClass.getTimes();
MockClientInterface clientService = serverCommandManager.getProxy(MockClientInterface.class, serverSessionManager.getSessions(null).get(0).getKey(), 10000);
clientService.testExecute(user);
Thread.sleep(1000L);
Assert.assertThat(mockClientClass.getTimes() - clientTimes, CoreMatchers.equalTo(1));
// 停止客户端与服务端的会话
nettyClientConnector.close(clientAddress);
// // TODO 此处依赖于连接器清理时间,可能需要重构.
// Thread.sleep(15000L);
// Assert.assertThat(serverSessionManager.getSessions(null).size(),
// CoreMatchers.equalTo(0));
}
/**
* 测试连接
*/
@Test
public abstract void testConnect() throws Exception;
/**
* 测试性能
*/
@Test
public void testPerformance() throws Exception {
int count = 25; // 线程数
int times = 1000; // 任务数
nettyClientConnector.open(clientAddress, 5000);
// TODO 是否等待服务端?
ExecutorService executor = Executors.newFixedThreadPool(count);
CountDownLatch latch = new CountDownLatch(count);
for (int thread = 1; thread <= count; thread++) {
long userId = thread;
executor.submit(() -> {
try {
MockServerInterface service = clientCommandManager.getProxy(MockServerInterface.class, SessionManager.address2Key(clientAddress), 10000);
String userName = "birdy";
UserObject user = UserObject.instanceOf(userId, userName);
for (int time = 0; time < times; time++) {
Assert.assertThat(service.createUser(user), CoreMatchers.equalTo(user));
Assert.assertThat(service.getUser(userId), CoreMatchers.equalTo(user));
Assert.assertNull(service.deleteUser(userId));
}
latch.countDown();
} catch (Exception exception) {
logger.error(StringUtility.EMPTY, exception);
}
});
}
latch.await();
nettyClientConnector.close(clientAddress);
}
/**
* 测试状态
*/
@Test
public void testState() {
// 在停止服务器和启动服务器过程中,绝对不允许有其它操作(读写锁).
nettyClientConnector.stop();
Assert.assertThat(nettyClientConnector.getState(), CoreMatchers.equalTo(LifecycleState.STOPPED));
nettyServerConnector.stop();
Assert.assertThat(nettyServerConnector.getState(), CoreMatchers.equalTo(LifecycleState.STOPPED));
nettyServerConnector.start();
Assert.assertThat(nettyServerConnector.getState(), CoreMatchers.equalTo(LifecycleState.STARTED));
nettyClientConnector.start();
Assert.assertThat(nettyClientConnector.getState(), CoreMatchers.equalTo(LifecycleState.STARTED));
}
}
| 44.38835
| 610
| 0.710083
|
1a9577e076958cf57442ce4971de01725aba375f
| 204
|
package spencercjh.problems;
/**
* https://leetcode-cn.com/problems/k-inverse-pairs-array/
*
* @author spencercjh
*/
class KInversePairsArray {
public int kInversePairs(int n, int k) {
}
}
| 15.692308
| 58
| 0.676471
|
d6ecefee445c900e0eed56b0c483e0450e76f7d5
| 1,016
|
package com.oskarcah.exam.celebrity.dto;
import java.io.Serializable;
import java.util.List;
public class ProblemSetRequestDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private List<String> people;
private List<PeopleKnowRelationDTO> relations;
public ProblemSetRequestDTO() {
super();
}
public ProblemSetRequestDTO(List<String> people, List<PeopleKnowRelationDTO> relations) {
this.people = people;
this.relations = relations;
}
public List<String> getPeople() {
return people;
}
public void setPeople(List<String> people) {
this.people = people;
}
public List<PeopleKnowRelationDTO> getRelations() {
return relations;
}
public void setRelations(List<PeopleKnowRelationDTO> relations) {
this.relations = relations;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| 20.734694
| 93
| 0.656496
|
c6cf386cd00a6f627327816a596f5528b3c4951d
| 2,700
|
package com.oopdev.io.loader.finder.classes;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author unknown
*
*/
public class IOSystemClassLoader {
private final List<File> directories;
private final String packageName;
private final List<Class<?>> classes;
public IOSystemClassLoader(List<File> directories, String packageName) throws ClassNotFoundException {
this.directories = directories;
this.packageName = packageName;
classes = findAllClasses();
}
public static final IOSystemClassLoader getInstance(List<File> directories, String packageName)
throws ClassNotFoundException {
return new IOSystemClassLoader(directories, packageName);
}
public static final IOSystemClassLoader getInstance(File directory, String packageName){
if (packageName==null) {
packageName="";
}
directory=new File(directory.getPath()+"\\"+packageName.replace(".", "\\"));
List<File> list = new ArrayList<File>();
list.add(new File(directory.getPath()+""));
try {
return getInstance(list, packageName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
private List<Class<?>> findAllClasses() throws ClassNotFoundException {
ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
for (File directory : directories) {
classes.addAll(findClasses(directory, packageName));
}
return classes;
}
private List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<Class<?>>();
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
String fileName = file.getName();
if (file.isDirectory()) {
classes.addAll(findClasses(file, getClassName(packageName, fileName)));
} else if (isValidClassName(fileName)) {
classes.add(createClass(packageName, fileName));
}
}
}
return classes;
}
private String getClassName(String packageName, String fileName) {
String retVal;
if (packageName.length() == 0) {
retVal = fileName;
} else {
retVal = packageName + "." + fileName;
}
return retVal;
}
private boolean isValidClassName(String fileName) {
return fileName.endsWith(".class") && !fileName.contains("$");
}
private Class<?> createClass(String packageName, String fileName) throws ClassNotFoundException {
String className = getClassName(packageName, fileName.substring(0, fileName.length() - 6));
return Class.forName(className);
}
public List<Class<?>> getClasses() {
return Collections.unmodifiableList(classes);
}
public String getPackageName() {
return packageName;
}
}
| 26.470588
| 103
| 0.716667
|
4a117bce716cc4f7a429cd44c276ac31440b94b1
| 15,547
|
package com.houseelectrics.serializer;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Stack;
/**
* Created by roberttodd on 30/11/2014.
*/
public class Object2Json implements ExplorationListener
{
public interface ExplorerFactory
{
public Explorer create();
}
public Object2Json()
{
explorerFactory= new ExplorerFactory()
{
@Override
public Explorer create()
{
return new ObjectExplorerImpl();
}
};
}
private boolean alwaysDoubleQuotePropertyNames = false;
public boolean getAlwaysDoubleQuotePropertyNames() {return alwaysDoubleQuotePropertyNames;}
public void setAlwaysDoubleQuotePropertyNames(boolean value) {this.alwaysDoubleQuotePropertyNames=value;}
private TypeAliaser typeAliaser=null;
public TypeAliaser getTypeAliaser() {return typeAliaser;}
public void setTypeAliaser(TypeAliaser value) {this.typeAliaser=value;}
private boolean omitMarkAsArrayFunction = true;
public boolean getOmitMarkAsArrayFunction() {return omitMarkAsArrayFunction;}
public void setOmitMarkAsArrayFunction(boolean value) {this.omitMarkAsArrayFunction=value;}
private boolean omitDefaultLeafValuesInJs = false;
public boolean getOmitDefaultLeafValuesInJs() { return omitDefaultLeafValuesInJs; }
public void setOmitDefaultLeafValuesInJs(boolean value) { this.omitDefaultLeafValuesInJs = value; }
private LeafDefaultSet leafDefaultSet = null;
public LeafDefaultSet getLeafDefaultSet() { return this.leafDefaultSet; }
public void setLeafDefaultSet(LeafDefaultSet value) { this.leafDefaultSet = value; }
String objectResolverFunctionName = "resolveRefs";
public String getObjectResolverFunctionName() { return objectResolverFunctionName; }
public void setObjectResolverFunctionName(String value) { this.objectResolverFunctionName = value; }
String leafDefaultResolverFunctionName = "_resolveLeafDefaults";
public String getLeafDefaultResolverFunctionName() { return leafDefaultResolverFunctionName; }
public void setLeafDefaultResolverFunctionName(String value) { this.leafDefaultResolverFunctionName = value; }
String attachId2ArrayFunctionName="attachId2Array";
public String getAttachId2ArrayFunctionName() { return attachId2ArrayFunctionName; }
public void setAttachId2ArrayFunctionName(String value) { this.attachId2ArrayFunctionName = value; }
public String getAttachId2ArrayJSFunction()
{
return "function " + getAttachId2ArrayFunctionName() + "(id, arr) {arr." + idTag + "=id; arr." + isArrayIndicator + "='y'; return arr;}";
}
String markAsArrayFunctionName = "_a_";
public String getMarkAsArrayFunctionName() { return markAsArrayFunctionName; }
public void setMarkAsArrayFunctionName(String value) { markAsArrayFunctionName = value; }
public String getMarkAsArrayJSFunction()
{
return Object2JsonJavascript.getMarkAsArrayJSFunction(getMarkAsArrayFunctionName());
}
String idTag = "_id_";
String getIdTag() { return idTag; }
public void setIdTag(String value) { idTag = value; }
String referenceTag = "_ref_";
String getReferenceTag() { return referenceTag; }
public void setReferenceTag(String value) { referenceTag = value; }
boolean useReferences = false;
public boolean getUseReferences() { return useReferences; }
public void setUseReferences(boolean value) { useReferences = value; }
public final String NewLine = "\r\n";
NodeExpander nodeExpander;
public NodeExpander getNodeExpander() {return nodeExpander;}
public void setNodeExpander(NodeExpander value) {this.nodeExpander=value;}
public String toJson(Object o)
{
return toJson(o, getTypeAliaser());
}
public String toJson(Object o, TypeAliaser typeAliaser)
{
try
{
StringWriter sw = new StringWriter();
writeAsJson(o, sw, typeAliaser);
sw.flush();
String str = sw.toString();
sw.close();
return str;
}
catch (IOException ioex)
{
throw new RuntimeException("io failed to write json", ioex);
}
}
ExplorerFactory explorerFactory;
public void setExplorerFactory(ExplorerFactory value) { explorerFactory = value; }
public ExplorerFactory getExplorerFactory() { return explorerFactory; }
private void writePropertyName(String propertyName, Writer writer) throws IOException
{
boolean escapeRequired = this.getAlwaysDoubleQuotePropertyNames() || (propertyName.indexOf('.') >= 0);
if (escapeRequired) writer.write('\"');
writer.write(propertyName);
if (escapeRequired) writer.write('\"');
}
public boolean MoveAway(Object from, String propertyName, Object to, boolean isIndexed, Integer index)
{
try
{
return MoveAwayUnsafe(from, propertyName, to, isIndexed, index);
}
catch (Exception ex)
{
throw new RuntimeException("Mode away failed", ex);
}
}
public boolean MoveAwayUnsafe(Object from, String propertyName, Object to, boolean isIndexed, Integer index) throws IOException
{
ExploreStackFrame currentFrame = exploreStack.size()>0 ? exploreStack.peek():null;
if (currentFrame != null)
{
if (currentFrame.propertyCount > 0) writer.write(", ");
currentFrame.propertyCount++;
}
if (from != null && propertyName != null)
{
writePropertyName(propertyName, writer);
writer.write(":");
}
ExploreStackFrame childFrame = new ExploreStackFrame();
exploreStack.push(childFrame);
writeIndent(writer, exploreStack);
if (getUseReferences())
{
ObjectIDGenerator.IdResult idResult = idGenerator.getId(to);
int objectid = idResult.id;
boolean firstTime = idResult.isNew;
if (firstTime)
{
// could be done like this ! (function() {var x=[1,2]; x.id="uuu";return x;})()
if (!isIndexed)
{
writer.write("{" + this.getIdTag() + ":" + objectid + ' ');
childFrame.propertyCount++;
childFrame.propertyCount += writeTypeAliasProperty(writer, to, typeAliaser, childFrame.propertyCount);
}
else
{
// no need for type alias
writer.write(getAttachId2ArrayFunctionName() + "(" + objectid + ",[");
}
}
else
{
writer.write("{" + this.getReferenceTag() + ":" + objectid);
return false;
}
}
else // !Use References
{
if (!isIndexed)
{
writer.write('{');
// todo -- check this out ............
childFrame.propertyCount += writeTypeAliasProperty(writer, to, typeAliaser, childFrame.propertyCount);
}
else
{
if (!getOmitMarkAsArrayFunction())
{
writer.write(markAsArrayFunctionName);
writer.write("([");
}
else
{
writer.write("[");
}
}
}
return true;
}
public void MoveBack(Object from, String propertyName, Object to, boolean isIndexed)
{
try
{
if (!isIndexed) writer.write('}');
else
{
writer.write(']');
// is there a function wrapper ?
if (!getOmitMarkAsArrayFunction() || getUseReferences()) writer.write(")");
}
exploreStack.pop();
writeIndent(writer, exploreStack);
}
catch (IOException ioex)
{
throw new RuntimeException("failed to move back from " + from.getClass().getName() + "." + propertyName);
}
}
public void OnLeaf(Object from, String propertyName, Object to, Integer index)
{
try {
OnLeafUnsafe(from, propertyName, to, index);
}
catch (IOException ioex)
{
throw new RuntimeException("OnLeaf failed for " + from.getClass().getName() + "." + propertyName + "->" + to + " index=" + index);
}
}
public void OnLeafUnsafe(Object from, String propertyName, Object to, Integer index) throws IOException
{
//check for default leaf values
if (!this.getOmitDefaultLeafValuesInJs() ||
!isDefaultLeafValue(from, propertyName, to, getLeafDefaultSet()))
{
ExploreStackFrame currentFrame = exploreStack.peek();
if (currentFrame.propertyCount > 0) writer.write(", ");
currentFrame.propertyCount++;
if (propertyName!=null)
{
writePropertyName(propertyName, writer);
writer.write(":");
}
leafWriter.writeLeafValue(writer, to, propertyName);
}
}
ObjectIDGenerator idGenerator = null;
class ExploreStackFrame { public int propertyCount;}
public void writeAsJson(Object o, StringWriter writer)
{
writeAsJson(o, writer, null);
}
Stack<ExploreStackFrame> exploreStack = null;
Writer writer;
public void writeAsJson(Object o, StringWriter writer, TypeAliaser typeAliaser)
{
if (getLeafDefaultSet() != null && getOmitDefaultLeafValuesInJs() && getOmitMarkAsArrayFunction())
{
throw new RuntimeException("Leaf defaulting requires Array marker for js code");
}
this.writer = writer;
//this.typeAliaser = typeAliaser;
idGenerator = null;
if (getUseReferences())
{
idGenerator=new ObjectIDGenerator();
}
exploreStack = new Stack<ExploreStackFrame>();
Explorer explorerImpl = getExplorerFactory().create();
((Explorer)explorerImpl).setNodeExpander(getNodeExpander());
explorerImpl.explore(o, this);
}
int writeTypeAliasProperty(Writer writer, Object to, TypeAliaser typeAliaser, int currentFramePropertyCount) throws IOException
{
if (typeAliaser != null)
{
if (currentFramePropertyCount > 0) writer.write(',');
writer.write(this.getTypeAliasProperty() + ":'" + typeAliaser.alias (to.getClass()) + "'");
return 1;
}
else
{
return 0;
}
}
//public Func<Object, String, Object, LeafDefaultSet, boolean> isDefaultLeafValue = isDefaultLeafValueDefault;
protected boolean isDefaultLeafValue(Object from, String propertyName, Object leafValue, LeafDefaultSet LeafDefaultSet)
{
if ( LeafDefaultSet == null)
{
throw new RuntimeException("OmitDefaultLeafValuesInJs==true but LeafDefaultSet is unspecified - unable to determine what values are default !");
}
Class t = from.getClass();
if (LeafDefaultSet.getType2Defaults().containsKey(t))
{
Defaults4Class defaults = LeafDefaultSet.getType2Defaults().get(t);
if (!defaults.getPropertyName2DefaultValue().containsKey(propertyName))
{
return false;
}
Object defaultValue = defaults.getPropertyName2DefaultValue().get(propertyName);
return (leafValue == defaultValue) || leafValue != null && leafValue.equals(defaultValue);
}
{
// is this an error ?
return false;
}
}
void writeIndent(Writer writer, Stack<ExploreStackFrame> exploreStack) throws IOException
{
if (getIndentSize() != null)
{
writer.write(NewLine);
int fullIndentSize = (getIndentSize().intValue()) * exploreStack.size();
for (int done = 0; done < fullIndentSize; done++)
{
writer.write(' ');
}
}
}
private String isArrayIndicator = "_a_";
public interface LeafWriter
{
public void writeLeafValue(Writer writer, Object to, String propertyName) throws IOException;
}
private LeafWriter defaultLeafWriter = new LeafWriter()
{
@Override
public void writeLeafValue(Writer writer, Object to, String propertyName) throws IOException
{
if (to == null)
{
writer.write("null");
}
else if (to.getClass() == String.class || to.getClass() == Character.class)
{
writer.write("\"");
writer.write(to.toString());
writer.write("\"");
}//todo simplify below
else if (to.getClass() == Byte.class)
{
writer.write(to.toString());
}
else if (to.getClass() == Integer.class)
{
writer.write(to.toString());
}
else if (to.getClass() == Long.class)
{
writer.write(((Long)to).toString());
}
else if (to.getClass() == Float.class)
{
writer.write(((Float)to).toString());
}
else if (to.getClass() == Double.class)
{
writer.write(((Double)to).toString());
}
else if (to.getClass() == Boolean.class)
{
boolean bval = ((Boolean) to).booleanValue();
writer.write(bval ? "true" : "false");
}
else if (to.getClass() == Short.class)
{
writer.write(((Short)to).toString());
}
else throw new RuntimeException("not implemented writeLeafValue:" + to.getClass().getName() + " " + propertyName);
}
};
public LeafWriter getDefaultLeafWriter() {return defaultLeafWriter;}
private LeafWriter leafWriter = getDefaultLeafWriter();
public void setLeafWriter(LeafWriter value)
{
this.leafWriter = value;
}
public LeafWriter getLeafWriter()
{
return this.leafWriter;
}
private Integer indentSize=null;
public Integer getIndentSize() { return indentSize; }
public void setIndentSize(Integer value) { indentSize = value; }
public String getObjectResolverJS()
{
return Object2JsonJavascript.getObjectResolverJS(getObjectResolverFunctionName(), getIdTag(), getReferenceTag());
}
String typeAliasProperty = "_t_";
public String getTypeAliasProperty() {return typeAliasProperty; }
public void setTypeAliasProperty(String value) { this.typeAliasProperty = value; }
public String getLeafDefaultResolverJS()
{
return getLeafDefaultResolverJS(getTypeAliaser());
}
public String getLeafDefaultResolverJS(TypeAliaser typeAliaser)
{
//switch off type aliasing
String defaultsJS = toJson( getLeafDefaultSet().getAlias2Defaults(typeAliaser), null);
String defaultsVarName = "_typeAlias2LeafDefaults_";
String js =
"var "+ defaultsVarName +" = " + defaultsJS + ";\r\n" +
Object2JsonJavascript.ResolveLeafDefaultFunction;
return js;
}
}
| 34.937079
| 156
| 0.604876
|
e192c3e6e7e061f750513989d15347e4deb9da31
| 455
|
package org.apdoer.condition.job;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author apdoer
*/
@SpringBootApplication
@EnableEurekaClient
public class ConditionJobApplication {
public static void main(String[] args) {
SpringApplication.run(ConditionJobApplication.class, args);
}
}
| 23.947368
| 68
| 0.795604
|
a2e7013e95ad69d81f8cd31e1f6d28476d96bb0d
| 2,911
|
package com.cloudera.framework.testing.server.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import com.cloudera.framework.testing.TestConstants;
import com.cloudera.framework.testing.TestRunner;
import com.cloudera.framework.testing.server.KafkaServer;
import com.cloudera.framework.testing.server.ZooKeeperServer;
import org.apache.commons.io.IOUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(TestRunner.class)
public class TestKafkaServer implements TestConstants {
@ClassRule
public static final KafkaServer kafkaServer = KafkaServer.getInstance();
private static final String TOPIC_NAME_TEST = "mytopic";
@Test
public void testImplicitDependencies() {
assertTrue(ZooKeeperServer.getInstance().isStarted());
}
@Test
public void testKafka() throws InterruptedException, IOException, ExecutionException, TimeoutException {
int pollCount = 5;
int messageCount = 10;
kafkaServer.createTopic(TOPIC_NAME_TEST, 1, 1, new Properties());
Producer<String, String> producer = new KafkaProducer<>(kafkaServer.getProducerProperties());
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(kafkaServer.getConsumerProperties());
try {
consumer.subscribe(Collections.singletonList(TOPIC_NAME_TEST));
for (int i = 0; i < messageCount; i++) {
producer.send(new ProducerRecord<>(TOPIC_NAME_TEST, "" + i, "" + i)).get(KafkaServer.KAFKA_POLL_MS * 2, TimeUnit.MILLISECONDS);
}
producer.flush();
ConsumerRecords<String, String> records;
while ((records = consumer.poll(KafkaServer.KAFKA_POLL_MS * messageCount * 2)).count() == 0) {
if (pollCount-- == 0) {
throw new TimeoutException("Could not poll message batch");
}
}
assertEquals(messageCount, records.count());
for (ConsumerRecord<String, String> record : records) {
assertTrue(record.offset() >= Long.parseLong(record.key()));
assertEquals(Long.parseLong(record.key()), Long.parseLong(record.value()));
}
} finally {
IOUtils.closeQuietly(producer);
IOUtils.closeQuietly(consumer);
}
}
@Test
public void testKafkaAgain() throws InterruptedException, IOException, ExecutionException, TimeoutException {
testKafka();
}
}
| 37.805195
| 135
| 0.750258
|
0427d405d185c5dd4e2b02b230cbd9181d45df94
| 1,074
|
package uk.gov.di.authentication.frontendapi.entity;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotNull;
import uk.gov.di.authentication.shared.entity.BaseFrontendRequest;
import uk.gov.di.authentication.shared.entity.NotificationType;
public class SendNotificationRequest extends BaseFrontendRequest {
@JsonProperty(required = true, value = "notificationType")
@NotNull
private NotificationType notificationType;
@JsonProperty(value = "phoneNumber")
private String phoneNumber;
public NotificationType getNotificationType() {
return notificationType;
}
public String getPhoneNumber() {
return phoneNumber;
}
@Override
public String toString() {
return "SendNotificationRequest{"
+ "notificationType="
+ notificationType
+ ", phoneNumber='"
+ phoneNumber
+ '\''
+ ", email='"
+ email
+ '\''
+ '}';
}
}
| 27.538462
| 66
| 0.629423
|
90d21272fd8e71a87c5f0124867dcd064cb5a76b
| 571
|
package com.example.customerclient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class CustomerClientApplication {
public static void main(String[] args) {
SpringApplication.run(CustomerClientApplication.class, args);
}
}
| 31.722222
| 69
| 0.830123
|
3d7d4aa22267b80277c4cba6984f49683b461d4d
| 453
|
package org.zalando.stups.logsink.service;
import org.zalando.stups.logsink.api.TaupageLogData;
class DelegatingInstanceLogsService implements InstanceLogsService {
private final InstanceLogsService delegate;
DelegatingInstanceLogsService(InstanceLogsService delegate) {
this.delegate = delegate;
}
@Override
public void handleInstanceLogs(TaupageLogData payload) {
delegate.handleInstanceLogs(payload);
}
}
| 25.166667
| 68
| 0.770419
|
1d30a90d6f9ee5e5a8cf439e2328dccc2c07d248
| 714
|
package us.ihmc.kalman;
import org.ejml.data.DenseMatrix64F;
/**
* adapted from http://code.google.com/p/efficient-java-matrix-library/wiki/KalmanFilterExamples
*/
public interface KalmanFilter
{
public abstract void configure(DenseMatrix64F F, DenseMatrix64F G, DenseMatrix64F H);
public abstract void setProcessNoiseCovariance(DenseMatrix64F Q);
public abstract void setMeasurementNoiseCovariance(DenseMatrix64F R);
public abstract void setState(DenseMatrix64F x, DenseMatrix64F P);
public abstract void predict(DenseMatrix64F u);
public abstract void update(DenseMatrix64F y);
public abstract DenseMatrix64F getState();
public abstract DenseMatrix64F getCovariance();
}
| 27.461538
| 96
| 0.784314
|
747e5520399675069ac484ee53cb8833ebf5bda0
| 2,074
|
package io.github.vampirestudios.hgm.api.task;
import io.github.vampirestudios.hgm.HuskysGadgetMod;
import io.github.vampirestudios.hgm.network.PacketHandler;
import io.github.vampirestudios.hgm.network.task.MessageRequest;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
public final class TaskManager {
private static TaskManager instance = null;
private Map<String, Task> registeredRequests = new HashMap<>();
private Map<Integer, Task> requests = new HashMap<>();
private int currentId = 0;
private TaskManager() {
}
private static TaskManager get() {
if (instance == null) {
instance = new TaskManager();
}
return instance;
}
public static void registerTask(Class<? extends Task> clazz) {
try {
Constructor<? extends Task> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
Task task = constructor.newInstance();
HuskysGadgetMod.LOGGER.info("Registering task '" + task.getName() + "'");
get().registeredRequests.put(task.getName(), task);
} catch (InstantiationException e) {
System.err.println("- Missing constructor '" + clazz.getSimpleName() + "()'");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendTask(Task task) {
TaskManager manager = get();
if (!manager.registeredRequests.containsKey(task.getName())) {
throw new RuntimeException("Unregistered Task: " + task.getClass().getName() + ". Use TaskManager#requestRequest to register your task.");
}
int requestId = manager.currentId++;
manager.requests.put(requestId, task);
PacketHandler.INSTANCE.sendToServer(new MessageRequest(requestId, task));
}
public static Task getTask(String name) {
return get().registeredRequests.get(name);
}
public static Task getTaskAndRemove(int id) {
return get().requests.remove(id);
}
}
| 34.566667
| 150
| 0.653809
|
6ab659f31ea969b9f16a555516a922508cbc9e29
| 2,703
|
package com.mulgasoft.emacsplus.actions.info;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorAction;
import com.mulgasoft.emacsplus.actions.EmacsPlusAction;
import com.mulgasoft.emacsplus.handlers.EmacsPlusCaretHandler;
import org.jetbrains.annotations.NonNls;
public class WhatCursorPos extends EditorAction {
@NonNls
private static final String N_GEN = "\\c";
@NonNls
private static final String N_NEW = "\\n";
@NonNls
private static final String N_RET = "\\r";
@NonNls
private static final String N_TAB = "\\t";
@NonNls
private static final String N_BS = "\\b";
@NonNls
private static final String N_FF = "\\f";
@NonNls
private static final String N_SPC = "SPC";
private static final String CURSOR_POSITION = "Char: %s (%d, #o%o, #x%x) point=%d of %d (%d%%)";
private static final String EOB_POSITION = "point=%d of %d (EOB)";
protected WhatCursorPos() {
super(new WhatCursorPos.myHandler());
}
private static final class myHandler extends EmacsPlusCaretHandler {
@Override
protected void doXecute(Editor var1, Caret var2, DataContext var3) {
Document doc = var1.getDocument();
int offset = var2.getOffset();
int docLen = doc.getTextLength();
String msg = offset >= docLen ? getEob(offset, docLen) : getCurPos(offset, docLen, doc);
EmacsPlusAction.infoMessage(msg);
}
private static String getEob(int offset, int docLen) {
return String.format(EOB_POSITION, offset, docLen);
}
private static String getCurPos(int offset, int docLen, Document doc) {
char curChar = doc.getCharsSequence().charAt(offset);
int percent = (new Float((double) (offset * 100 / docLen) + 0.5D)).intValue();
String sChar = curChar <= ' ' ? normalizeChar(curChar) : String.valueOf(curChar);
return String.format(CURSOR_POSITION, sChar, (int) curChar, (int) curChar,
(int) curChar, offset, docLen, percent);
}
private static String normalizeChar(char cc) {
String result = null;
switch (cc) {
case '\b':
result = "\\b";
break;
case '\t':
result = "\\t";
break;
case '\n':
result = "\\n";
break;
case '\f':
result = "\\f";
break;
case '\r':
result = "\\r";
break;
case ' ':
result = "SPC";
break;
default:
result = "\\c" + cc;
}
return result;
}
}
}
| 31.430233
| 100
| 0.630041
|
0eba592e6d4edbebf80d8111a43f046030ec87e5
| 4,419
|
package org.altbeacon.beacon;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.altbeacon.beacon.logging.LogManager;
import org.altbeacon.beacon.logging.Loggers;
import org.robolectric.RobolectricTestRunner;
import org.junit.runner.RunWith;
import org.junit.Test;
import org.robolectric.annotation.Config;
@Config(sdk = 28)
@RunWith(RobolectricTestRunner.class)
/*
HOW TO SEE DEBUG LINES FROM YOUR UNIT TESTS:
1. set a line like this at the start of your test:
org.robolectric.shadows.ShadowLog.stream = System.err;
2. run the tests from the command line
3. Look at the test report file in your web browser, e.g.
file:///Users/dyoung/workspace/AndroidProximityLibrary/build/reports/tests/index.html
4. Expand the System.err section
*/
public class AltBeaconParserTest {
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
@Test
public void testRecognizeBeacon() {
BeaconManager.setDebug(true);
byte[] bytes = hexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.fromScanData(bytes, -55, null);
assertEquals ("Beacon should have one data field", 1, beacon.getDataFields().size());
assertEquals("manData should be parsed", 9, ((AltBeacon) beacon).getMfgReserved());
}
@Test
public void testDetectsDaveMHardwareBeacon() {
org.robolectric.shadows.ShadowLog.stream = System.err;
byte[] bytes = hexStringToByteArray("02011a1bff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600050003be020e09526164426561636f6e20555342020a0300000000000000000000000000");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.fromScanData(bytes, -55, null);
assertNotNull("Beacon should be not null if parsed successfully", beacon);
}
@Test
public void testDetectsAlternateBeconType() {
org.robolectric.shadows.ShadowLog.stream = System.err;
byte[] bytes = hexStringToByteArray("02011a1bff1801aabb2f234454cf6d4a0fadf2f4911ba9ffa600010002c50900");
AltBeaconParser parser = new AltBeaconParser();
parser.setMatchingBeaconTypeCode(0xaabbl);
Beacon beacon = parser.fromScanData(bytes, -55, null);
assertNotNull("Beacon should be not null if parsed successfully", beacon);
}
@Test
public void testParseWrongFormatReturnsNothing() {
BeaconManager.setDebug(true);
org.robolectric.shadows.ShadowLog.stream = System.err;
LogManager.d("XXX", "testParseWrongFormatReturnsNothing start");
byte[] bytes = hexStringToByteArray("02011a1aff1801ffff2f234454cf6d4a0fadf2f4911ba9ffa600010002c509");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.fromScanData(bytes, -55, null);
LogManager.d("XXX", "testParseWrongFormatReturnsNothing end");
assertNull("Beacon should be null if not parsed successfully", beacon);
}
@Test
public void testParsesBeaconMissingDataField() {
BeaconManager.setDebug(true);
org.robolectric.shadows.ShadowLog.stream = System.err;
byte[] bytes = hexStringToByteArray("02011a1aff1801beac2f234454cf6d4a0fadf2f4911ba9ffa600010002c5000000");
AltBeaconParser parser = new AltBeaconParser();
Beacon beacon = parser.fromScanData(bytes, -55, null);
assertEquals("mRssi should be as passed in", -55, beacon.getRssi());
assertEquals("uuid should be parsed", "2f234454-cf6d-4a0f-adf2-f4911ba9ffa6", beacon.getIdentifier(0).toString());
assertEquals("id2 should be parsed", "1", beacon.getIdentifier(1).toString());
assertEquals("id3 should be parsed", "2", beacon.getIdentifier(2).toString());
assertEquals("txPower should be parsed", -59, beacon.getTxPower());
assertEquals("manufacturer should be parsed", 0x118 ,beacon.getManufacturer());
assertEquals("missing data field zero should be zero", new Long(0l), beacon.getDataFields().get(0));
}
}
| 48.56044
| 172
| 0.712152
|
389114774379617e3c5935fee5834afd5852ffe2
| 355
|
package com.lexi.service;
import org.springframework.stereotype.Component;
@Component
public class HelloServiceWithManyArgsCons {
public HelloServiceWithManyArgsCons(HelloServiceAutowired1 helloServiceAutowired1,HelloServiceAutowired2 helloServiceAutowired2)
{
}
// public HelloServiceWithManyArgsCons(String helloServiceAutowired2)
// {
//
// }
}
| 20.882353
| 129
| 0.833803
|
d0c145e73071a8f4996cd971467936d486c0d3eb
| 1,418
|
package curso.jpa.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "TB003_VEICULO")
public class Veiculo {
@Id
@GeneratedValue
@Column(name="ID_VEICULO")
private Long id;
@Column(name="PLACA", unique = true)
private String placa;
@Column(name="MODELO", nullable=false)
private String modelo;
@Column(name="FABRICANTE", nullable=false)
private String fabricante;
@Column(name="ANO", nullable=false)
private Integer ano;
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getFabricante() {
return fabricante;
}
public void setFabricante(String fabricante) {
this.fabricante = fabricante;
}
public Integer getAno() {
return ano;
}
public void setAno(Integer ano) {
this.ano = ano;
}
@Override
public String toString() {
return "Veiculo{" +
"id=" + id +
", placa='" + placa + '\'' +
", modelo='" + modelo + '\'' +
", fabricante='" + fabricante + '\'' +
", ano=" + ano +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
| 17.292683
| 47
| 0.671368
|
fed89ca8d9106e2468981a1a36d48bc175b48d6a
| 4,890
|
package com.urgoo.profile.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.widget.EaseSwitchButton;
import com.urgoo.account.activity.HomeActivity;
import com.urgoo.base.ActivityBase;
import com.urgoo.client.DemoHelper;
import com.urgoo.client.DemoModel;
import com.urgoo.client.R;
import com.urgoo.data.SPManager;
public class UrgooSettingActivity extends ActivityBase implements OnClickListener {
private LinearLayout back;
/**
* 设置新消息通知布局
*/
private RelativeLayout rl_switch_notification;
/**
* 退出按钮
*/
private Button logoutBtn;
private EaseSwitchButton notifiSwitch;
private DemoModel settingsModel;
private EMOptions chatOptions;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.urgoosettingactivity_layout);
initView();
}
@Override
public void initView() {
$(R.id.re_wode_yyue).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(UrgooSettingActivity.this, ChangePwdActivity.class));
}
});
back = (LinearLayout) findViewById(R.id.back);
back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
UrgooSettingActivity.this.finish();
}
});
rl_switch_notification = (RelativeLayout) findViewById(R.id.rl_switch_notification);
notifiSwitch = (EaseSwitchButton) findViewById(R.id.switch_notification);
logoutBtn = (Button) findViewById(R.id.btn_logout);
settingsModel = DemoHelper.getInstance().getModel();
chatOptions = EMClient.getInstance().getOptions();
rl_switch_notification.setOnClickListener(this);
logoutBtn.setOnClickListener(this);
// 震动和声音总开关,来消息时,是否允许此开关打开
// the vibrate and sound notification are allowed or not?
if (settingsModel.getSettingMsgNotification()) {
notifiSwitch.openSwitch();
} else {
notifiSwitch.closeSwitch();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.rl_switch_notification:
if (notifiSwitch.isSwitchOpen()) {
notifiSwitch.closeSwitch();
settingsModel.setSettingMsgNotification(false);
} else {
notifiSwitch.openSwitch();
settingsModel.setSettingMsgNotification(true);
}
break;
case R.id.btn_logout: //退出登陆
logout();
break;
default:
break;
}
}
void logout() {
final ProgressDialog pd = new ProgressDialog(UrgooSettingActivity.this);
String st = getResources().getString(R.string.Are_logged_out);
pd.setMessage(st);
pd.setCanceledOnTouchOutside(false);
pd.show();
DemoHelper.getInstance().logout(false, new EMCallBack() {
@Override
public void onSuccess() {
UrgooSettingActivity.this.runOnUiThread(new Runnable() {
public void run() {
pd.dismiss();
// 重新显示登陆页面
SPManager.getInstance(UrgooSettingActivity.this).clearLoginInfo();
Intent intent = new Intent(UrgooSettingActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
UrgooSettingActivity.this.finish();
}
});
}
@Override
public void onProgress(int progress, String status) {
}
@Override
public void onError(int code, String message) {
UrgooSettingActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
pd.dismiss();
Toast.makeText(UrgooSettingActivity.this, "unbind devicetokens failed", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
| 30.185185
| 123
| 0.601636
|
341a18571ec28ab82685c168f6aed265afb40206
| 370
|
package pattern.proxy.DynamicProxy.section1;
/**
* @author cbf4Life cbf4life@126.com
* I'm glad to share my knowledge with you all.
*/
public class Client {
public static void main(String[] args) {
DynamicProxy proxy = new DynamicProxy(new RealSubject());
String[] str = {"1111"};
proxy.exec("doSomething", str);
}
}
| 23.125
| 66
| 0.621622
|
2bb6473282989a26aa1ad02b0d96f207c0678cff
| 927
|
package nl.praegus.fitnesse.junit.azuredevops.util;
public class Description {
private Description() {
// in order to hide
}
public static String getFullTestName(org.junit.runner.Description description) {
return description.getDisplayName().replaceAll("\\(.+\\)", "");
}
public static String getTestName(org.junit.runner.Description description) {
String[] testNameParts = getFullTestName(description).split("\\.");
return testNameParts[testNameParts.length - 1];
}
public static String getSuiteName(org.junit.runner.Description description) {
String[] testNameParts = getFullTestName(description).split("\\.");
if (testNameParts.length > 1) {
return testNameParts[testNameParts.length - 2];
} else {
return "default";
}
}
}
| 34.333333
| 88
| 0.598706
|
38bf7415832c913a1eaa88bc4a82686dcba02c3d
| 3,246
|
package io.github.shiryu.aquaannouncement.bungee.file;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class YamlEnvelope implements IYaml {
private final Plugin plugin;
private final String fileName;
private final String filePath;
private final String resourcePath;
private File file;
private Configuration configuration;
public YamlEnvelope(Plugin plugin, String fileName, String filePath) {
this.plugin = plugin;
if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
this.fileName = fileName.endsWith(".yml") ? fileName : (fileName + ".yml");
this.resourcePath = filePath.equals("") ? "" : (filePath + "/");
this
.filePath = filePath.equals("") ? (plugin.getDataFolder().getAbsolutePath() + "\\") : (plugin.getDataFolder().getAbsolutePath() + "\\" + filePath + "\\");
this.file = new File(this.filePath, this.fileName);
try {
this.configuration = ConfigurationProvider.getProvider(net.md_5.bungee.config.YamlConfiguration.class).load(this.file);
} catch (Exception e) {
this.configuration = null;
}
if (this.file.exists())
return;
init();
copy();
}
public void copy() {
InputStream in = this.plugin.getResourceAsStream(this.resourcePath + this.fileName);
try {
OutputStream out = new FileOutputStream(this.file);
byte[] buf = new byte[63];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} catch (Exception exception) {}
}
public void init() {
File __file = new File(this.filePath);
while (!__file.exists()) {
__file.mkdir();
__file = __file.getParentFile();
}
}
public String getName() { return this.fileName; }
public String getPath() { return this.filePath; }
public Configuration getSection(String path) { return this.configuration.getSection(path); }
public <T> T getOrSet(String path, T object) { return (T)this.configuration.get(path, object); }
public void set(String path, Object object) {
this.configuration.set(path, object);
save();
load();
}
public void save() {
try {
ConfigurationProvider.getProvider(net.md_5.bungee.config.YamlConfiguration.class).save(this.configuration, new File(this.filePath, this.fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void load() {
try {
this.configuration = ConfigurationProvider.getProvider(net.md_5.bungee.config.YamlConfiguration.class).load(new File(this.filePath, this.fileName));
} catch (Exception e) {
this.configuration = null;
}
}
}
| 31.211538
| 171
| 0.596426
|
ce2866984900311e0ea3cf73563c7cab7b559f35
| 703
|
package reuse.pipe.server;
import java.io.IOException;
import java.net.Socket;
public class BandwidthTestClient {
static org.slf4j.Logger log = org.slf4j.LoggerFactory
.getLogger(BandwidthTestClient.class);
public BandwidthTestClient(String host, int port) throws IOException {
log.debug("connecting to {} {}", host, port);
new PumpSocketTarget().send(new Socket(host, port));
}
public static void main(String[] args) throws IOException, InterruptedException {
String host = System.getProperty("host", "localhost");
int port = Integer.parseInt(System.getProperty("port", "2011"));
new BandwidthTestClient(host, port);
// TimeUnit.DAYS.sleep(1);
}
}
| 28.12
| 83
| 0.711238
|
5cc03316f503a3382cc34522a19b7279517c6dd7
| 1,604
|
package com.baidu.mapapi.search.bean.result.sugesstion;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiChildrenInfo;
import com.baidu.mapapi.search.sug.SuggestionResult;
import java.util.ArrayList;
import java.util.List;
public class SugesstionInfoBean {
/** 联想词联想词名称 */
public String key;
/** 联想结果经纬度坐标 */
public LatLng location;
/** 联想结果唯一标示,ID */
public String uid;
/** 联想结果所在城市 */
public String city;
/** 联想结果所在区县 */
public String district;
/** 联想结果分类,默认不召回,需要权限。*/
public String tag;
/** 联想结果地址,默认不召回,需要权限。*/
public String address;
/// 联想结果子节点,默认不召回,需要权限。
public List<PoiChildrenInfoBean> children = new ArrayList<>();
public SugesstionInfoBean(SuggestionResult.SuggestionInfo suggestionInfo){
if(null == suggestionInfo){
return;
}
this.address = suggestionInfo.address;
this.city = suggestionInfo.city;
this.district = suggestionInfo.district;
this.key = suggestionInfo.key;
this.tag = suggestionInfo.tag;
this.uid = suggestionInfo.uid;
this.location = suggestionInfo.pt;
List<PoiChildrenInfo> poiChildrenInfoList = suggestionInfo.getPoiChildrenInfoList();
if (null == poiChildrenInfoList || poiChildrenInfoList.size() <= 0) {
return;
}
for (PoiChildrenInfo poiChildrenInfo: poiChildrenInfoList){
PoiChildrenInfoBean poiChildrenInfoBean = new PoiChildrenInfoBean(poiChildrenInfo);
children.add(poiChildrenInfoBean);
}
}
}
| 27.186441
| 95
| 0.665835
|
76c100c6b2bd41cd007f1b42d4b6c41e0cbed069
| 1,237
|
package edu.formation.inscription;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
@Configuration
public class UtilisateurConfig implements WebMvcConfigurer {
// Création d'une méthode permettant d'avoir une localisation par défaut
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver slr = new SessionLocaleResolver();
slr.setDefaultLocale(Locale.FRANCE);
return slr;
}
// Intercepter une demande de changement de localisation
@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
lci.setParamName("lang");
return lci;
}
// Enregistrer l'intercepteur
@Override
public void addInterceptors(InterceptorRegistry registre) {
registre.addInterceptor(localeChangeInterceptor());
}
}
| 31.717949
| 77
| 0.821342
|
f6550c144c00f45e0568c62ce70ffdbcfa09cd54
| 2,102
|
package ru.valle.btc;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
/**
* Created with IntelliJ IDEA.
* User: Valentin
* Date: 9/15/13
* Time: 8:04 PM
*/
@SuppressWarnings("deprecation")
public final class PreferencesActivityForOlderDevices extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
private SharedPreferences preferences;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
preferences = getPreferenceManager().getSharedPreferences();
onSharedPreferenceChanged(preferences, PreferencesActivity.PREF_PRIVATE_KEY);
onSharedPreferenceChanged(preferences, PreferencesActivity.PREF_FEE_SAT_BYTE);
}
@Override
public void onResume() {
super.onResume();
preferences.registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onPause() {
super.onPause();
preferences.unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key) {
new Handler(Looper.getMainLooper()).post(
() -> {
if (key.equals(PreferencesActivity.PREF_PRIVATE_KEY)) {
ListPreference preference = (ListPreference) findPreference(key);
if (preference != null) {
preference.setSummary(preference.getEntry());
}
} else if (key.equals(PreferencesActivity.PREF_FEE_SAT_BYTE)) {
FeePreference preference = (FeePreference) findPreference(key);
if (preference != null) {
preference.setSummary(preference.getText());
}
}
});
}
}
| 36.877193
| 144
| 0.653663
|
4c12aaafd93a69c69c5d2b28f9a7aaeb8907abf7
| 10,481
|
package com.taskit.taskit_android.activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.taskit.taskit_android.R;
import com.taskit.taskit_android.component.CountDownButton;
import com.taskit.taskit_android.util.UserHttpUtil;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by nick on 2018/7/12.
*/
public class ForgotPasswordActivity extends AppCompatActivity {
private PasswordResetTask mAuthTask = null;
private SendCodeTask mSendCodeTask = null;
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if(bundle.getBoolean("success")){
Toast.makeText(ForgotPasswordActivity.this, "SUCCESS", Toast.LENGTH_SHORT).show();
}else{
if (bundle.containsKey("email"))
mEmailView.setError(bundle.getString("email"));
if (bundle.containsKey("password"))
mPasswordView.setError(bundle.getString("password"));
if (bundle.containsKey("code"))
mCodeView.setError(bundle.getString("code"));
}
}
};
private CountDownButton mCountDownButton;
private EditText mEmailView;
private EditText mCodeView;
private EditText mPasswordView;
private Button mResetPasswordButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
initView();
initEvernt();
}
private void initView(){
mEmailView = (EditText) findViewById(R.id.email_forgot_password);
mCodeView = (EditText) findViewById(R.id.code);
mPasswordView = (EditText) findViewById(R.id.password_forgot_password);
mCountDownButton = (CountDownButton) findViewById(R.id.count_down_button);
mResetPasswordButton = (Button) findViewById(R.id.button_forgot_password);
}
private void initEvernt(){
mCountDownButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptSendCode();
}
});
mResetPasswordButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
private void attemptSendCode(){
mEmailView.setError(null);
String email = mEmailView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
hideKeyBoard();
mSendCodeTask = new SendCodeTask(handler,email);
mSendCodeTask.execute((String[]) null);
mCountDownButton.start();
}
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
private void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mCodeView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mEmailView.getText().toString();
String password = mPasswordView.getText().toString();
String code = mCodeView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid email address.
if (TextUtils.isEmpty(email)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!isEmailValid(email)) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
}else if(isPasswordShort(password)){
mPasswordView.setError(getString(R.string.error_too_short_password));
focusView = mPasswordView;
cancel = true;
}else if(isPasswordSimple(password)){
mPasswordView.setError(getString(R.string.error_simple_password));
focusView = mPasswordView;
cancel = true;
}
if (TextUtils.isEmpty(code)) {
mCodeView.setError(getString(R.string.error_field_required));
focusView = mCodeView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
hideKeyBoard();
mAuthTask = new PasswordResetTask(handler,email,code, password);
mAuthTask.execute((String[]) null);
}
}
private boolean isEmailValid(String email) {
return email.contains("@");
}
private boolean isPasswordSimple(String password) {
String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{1,}$";
return !password.matches(regex);
}
private boolean isPasswordShort(String password) {
return password.length() < 8;
}
private void hideKeyBoard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive()) {
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class PasswordResetTask extends AsyncTask<String, Void, JSONObject> {
private Handler handler;
private final String mcode;
private final String mPassword;
private final String mEmail;
PasswordResetTask(Handler handler, String email,String code, String password) {
mcode = code;
mPassword = password;
mEmail = email;
this.handler=handler;
}
@Override
protected JSONObject doInBackground(String... params) {
return UserHttpUtil.set_password(mEmail,mcode,mPassword);
}
@Override
protected void onPostExecute(final JSONObject result) {
mAuthTask = null;
Message msg = new Message();
Bundle bundle = new Bundle();
try {
if (result.getBoolean("success")){
bundle.putBoolean("success",true);
}else{
bundle.putBoolean("success",false);
if (result.has("non_field_errors")){
String error = result.getString("non_field_errors");
if (error.contains("Email")){
bundle.putString("email",error);
}else if (error.contains("code")){
bundle.putString("code",error);
}
}
if (result.has("password")){
bundle.putString("password",result.getString("password"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
msg.setData(bundle);
handler.sendMessage(msg);
}
@Override
protected void onCancelled() {
mAuthTask = null;
}
}
public class SendCodeTask extends AsyncTask<String, Void, JSONObject> {
private Handler handler;
private final String memail;
SendCodeTask(Handler handler, String email) {
memail = email;
this.handler=handler;
}
@Override
protected JSONObject doInBackground(String... params) {
return UserHttpUtil.reset_password(memail);
}
@Override
protected void onPostExecute(final JSONObject result) {
Message msg = new Message();
Bundle bundle = new Bundle();
System.out.println(result.toString());
try {
if (result.getBoolean("success")){
bundle.putBoolean("success",true);
}else{
bundle.putBoolean("success",false);
if (result.has("email"))
bundle.putString("email",result.getString("email"));
else if (result.has("non_field_errors"))
bundle.putString("email",result.getString("non_field_errors"));
}
} catch (JSONException e) {
e.printStackTrace();
}
msg.setData(bundle);
handler.sendMessage(msg);
}
@Override
protected void onCancelled() {
mSendCodeTask = null;
}
}
}
| 34.363934
| 101
| 0.584391
|
6e70b52777464184170dbdcd99b56e5ae49a4923
| 2,148
|
package dev.bigwig.fastrest.common.filter;
import dev.bigwig.fastrest.common.annotation.FRawResponse;
import dev.bigwig.fastrest.common.annotation.FResponseStatus;
import dev.bigwig.fastrest.common.exception.FError;
import java.lang.reflect.Method;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/** 响应处理器 */
@RestControllerAdvice
public class FResponseHandler implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(
MethodParameter returnType, @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
return !returnType.hasMethodAnnotation(FRawResponse.class);
}
@Override
public Object beforeBodyWrite(
Object body,
@NotNull MethodParameter returnType,
@NotNull MediaType selectedContentType,
@NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
@NotNull ServerHttpRequest request,
@NotNull ServerHttpResponse response) {
HttpStatus status = HttpStatus.OK;
if (request.getMethod() != null) {
switch (request.getMethod()) {
case OPTIONS:
case DELETE:
status = HttpStatus.NO_CONTENT;
break;
case POST:
status = HttpStatus.CREATED;
break;
default:
break;
}
}
if (body instanceof FError) {
status = ((FError) body).getStatus();
} else {
Method method = returnType.getMethod();
if (method != null && method.isAnnotationPresent(FResponseStatus.class)) {
FResponseStatus annotation = method.getAnnotation(FResponseStatus.class);
status = annotation.value();
}
}
response.setStatusCode(status);
return body;
}
}
| 33.046154
| 100
| 0.731378
|
6f44981b73ee4bca8e366202a5d748605312ccde
| 1,892
|
package org.sharedhealth.datasense.dhis2.model;
public class DatasetJobSchedule {
private String datasetName;
private String nextFireTime;
private String prevFireTime;
private String startTime;
private String endTime;
private String facilityId;
private String previousPeriod;
private String nextPeriod;
private String facilityName;
public void setDatasetName(String datasetName) {
this.datasetName = datasetName;
}
public String getDatasetName() {
return datasetName;
}
public void setNextFireTime(String nextFireTime) {
this.nextFireTime = nextFireTime;
}
public String getNextFireTime() {
return nextFireTime;
}
public void setPrevFireTime(String prevFireTime) {
this.prevFireTime = prevFireTime;
}
public String getPrevFireTime() {
return prevFireTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getStartTime() {
return startTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getEndTime() {
return endTime;
}
public void setFacilityId(String facilityId) {
this.facilityId = facilityId;
}
public String getFacilityId() {
return facilityId;
}
public void setPreviousPeriod(String period) {
this.previousPeriod = period;
}
public String getPreviousPeriod() {
return previousPeriod;
}
public void setNextPeriod(String nextPeriod) {
this.nextPeriod = nextPeriod;
}
public String getNextPeriod() {
return nextPeriod;
}
public void setFacilityName(String facilityName) {
this.facilityName = facilityName;
}
public String getFacilityName() {
return facilityName;
}
}
| 21.747126
| 54
| 0.658562
|
3049503e2421fdc0283619f3303e62e8a604b5e3
| 7,709
|
/*
* Copyright 2021 LINE Corporation
*
* LINE Corporation 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License
*/
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.linecorp.armeria.server.management;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.management.ManagementFactory;
import java.lang.management.PlatformManagedObject;
import java.nio.file.Files;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.linecorp.armeria.common.ContentDisposition;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.QueryParams;
import com.linecorp.armeria.common.annotation.Nullable;
import com.linecorp.armeria.common.util.SystemInfo;
import com.linecorp.armeria.common.util.ThreadFactories;
import com.linecorp.armeria.server.HttpService;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.file.HttpFile;
enum HeapDumpService implements HttpService {
// Forked from https://github.com/spring-projects/spring-boot/blob/531ee83c6ae42d8027a5241faf42c2015b1a031c/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/management/HeapDumpWebEndpoint.java
INSTANCE;
private static final Logger logger = LoggerFactory.getLogger(HeapDumpService.class);
private static final Executor heapDumpExecutor = Executors.newSingleThreadExecutor(
ThreadFactories.newThreadFactory("armeria-heapdump-executor", true));
@Nullable
private HeapDumper heapDumper;
@Nullable
private Throwable unavailabilityCause;
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
if (unavailabilityCause != null) {
return HttpResponse.ofFailure(unavailabilityCause);
}
final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
heapDumpExecutor.execute(() -> {
if (ctx.isCancelled()) {
return;
}
if (heapDumper == null) {
try {
heapDumper = new HeapDumper();
} catch (Throwable ex) {
unavailabilityCause = ex;
responseFuture.complete(HttpResponse.ofFailure(ex));
return;
}
}
File tempFile = null;
try {
final QueryParams queryParams = QueryParams.fromQueryString(ctx.query());
final boolean live = queryParams.contains("live", "true");
final String date = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm").format(LocalDateTime.now());
final String fileName = "heapdump_pid" + SystemInfo.pid() + '_' + date + (live ? "_live" : "");
tempFile = createTempFile(fileName);
heapDumper.dumpHeap(tempFile, live);
final ContentDisposition disposition = ContentDisposition.builder("attachment")
.filename(fileName + ".hprof")
.build();
final HttpFile httpFile = HttpFile.builder(tempFile)
.addHeader(HttpHeaderNames.CONTENT_DISPOSITION, disposition)
.build();
final File heapDumpFile = tempFile;
final HttpResponse httpResponse = httpFile.asService().serve(ctx, req);
responseFuture.complete(httpResponse);
httpResponse.whenComplete().handleAsync((unused1, unused2) -> {
deleteTempFile(heapDumpFile);
return null;
}, heapDumpExecutor);
} catch (Throwable cause) {
logger.warn("Unexpected exception while creating a heap dump", cause);
if (tempFile != null) {
deleteTempFile(tempFile);
}
responseFuture.complete(HttpResponse.ofFailure(cause));
}
});
return HttpResponse.from(responseFuture);
}
private static File createTempFile(String fileName) throws IOException {
final File file = File.createTempFile(fileName, ".hprof");
file.delete();
return file;
}
private static void deleteTempFile(File file) {
try {
Files.delete(file.toPath());
} catch (IOException ex) {
logger.warn("Failed to delete temporary heap dump file '" + file + '\'', ex);
}
}
/**
* A {@link HeapDumper} that uses {@code com.sun.management.HotSpotDiagnosticMXBean}
* available on Oracle and OpenJDK to dump the heap to a file.
*/
private static class HeapDumper {
private final Object diagnosticMXBean;
private final MethodHandle dumpHeapMH;
HeapDumper() {
try {
final Class<?> diagnosticMXBeanClass =
Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
//noinspection unchecked
diagnosticMXBean = ManagementFactory
.getPlatformMXBean((Class<PlatformManagedObject>) diagnosticMXBeanClass);
final MethodType methodType = MethodType.methodType(void.class, String.class, boolean.class);
dumpHeapMH = MethodHandles.publicLookup()
.findVirtual(diagnosticMXBeanClass, "dumpHeap", methodType);
} catch (Throwable ex) {
throw new IllegalStateException("Unable to locate HotSpotDiagnosticMXBean", ex);
}
}
/**
* Dumps the current heap to the specified {@link File}.
* @param file the file to dump the heap to
* @param live if only {@code live} objects (i.e. objects that are reachable from others) should be
* dumped
*/
void dumpHeap(File file, boolean live) throws Throwable {
dumpHeapMH.invoke(diagnosticMXBean, file.getAbsolutePath(), live);
}
}
}
| 41.224599
| 235
| 0.643534
|
87d94e60dd16c51699f046261ad998d87b68c72d
| 424
|
package io.github.dev2.config.liquibase;
public interface IProperties {
/**
*获取数据库用户名
*/
String getUsername();
/**
*获取数据库密码
*/
String getPassword();
/**
*获取数据库url
*/
String getUrl();
/**
*获取数据库schema
*/
String getDefaultSchema();
/**
*获取是否同步
*/
String getIsSyncDBSchema();
/**
* liquibase配置文件
*/
String getConf();
}
| 15.142857
| 40
| 0.511792
|
6c27fccd273e7594062591b0d5f65d372245bf28
| 7,113
|
/*
* Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
*
* 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 vn.uiza.views.draggablepanel;
import android.support.v4.widget.ViewDragHelper;
import android.view.View;
/**
* ViewDragHelper.UZCallback implementation used to work with DraggableView to perform the scale
* effect and other animation when the view is released.
*
* @author Pedro Vicente Gómez Sánchez.
*/
class DraggableViewCallback extends ViewDragHelper.Callback {
private static final int MINIMUM_DX_FOR_HORIZONTAL_DRAG = 5;
private static final int MINIMUM_DY_FOR_VERTICAL_DRAG = 15;
private static final float X_MIN_VELOCITY = 1500;
private static final float Y_MIN_VELOCITY = 1000;
private DraggableView draggableView;
private View draggedView;
/**
* Main constructor.
*
* @param draggableView instance used to apply some animations or visual effects.
*/
public DraggableViewCallback(DraggableView draggableView, View draggedView) {
this.draggableView = draggableView;
this.draggedView = draggedView;
}
/**
* Override method used to apply different scale and alpha effects while the view is being
* dragged.
*
* @param left position.
* @param top position.
* @param dx change in X position from the last call.
* @param dy change in Y position from the last call.
*/
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
draggableView.onViewPositionChanged(left, top, dx, dy);
if (draggableView.isDragViewAtBottom()) {
draggableView.changeDragViewViewAlpha();
} else {
draggableView.restoreAlpha();
draggableView.changeDragViewScale();
draggableView.changeDragViewPosition();
draggableView.changeSecondViewAlpha();
draggableView.changeSecondViewPosition();
draggableView.changeBackgroundAlpha();
}
}
/**
* Override method used to apply different animations when the dragged view is released. The
* dragged view is going to be maximized or minimized if the view is above the middle of the
* custom view and the velocity is greater than a constant value.
*
* @param releasedChild the captured child view now being released.
* @param xVel X velocity of the pointer as it left the screen in pixels per second.
* @param yVel Y velocity of the pointer as it left the screen in pixels per second.
*/
@Override
public void onViewReleased(View releasedChild, float xVel, float yVel) {
super.onViewReleased(releasedChild, xVel, yVel);
if (draggableView.isDragViewAtBottom() && !draggableView.isDragViewAtRight()) {
triggerOnReleaseActionsWhileHorizontalDrag(xVel);
} else {
triggerOnReleaseActionsWhileVerticalDrag(yVel);
}
}
/**
* Override method used to configure which is going to be the dragged view.
*
* @param view child the user is attempting to capture.
* @param pointerId ID of the pointer attempting the capture,
* @return true if capture should be allowed, false otherwise.
*/
@Override
public boolean tryCaptureView(View view, int pointerId) {
return view.equals(draggedView);
}
/**
* Override method used to configure the horizontal drag. Restrict the motion of the dragged
* child view along the horizontal axis.
*
* @param child child view being dragged.
* @param left attempted motion along the X axis.
* @param dx proposed change in position for left.
* @return the new clamped position for left.
*/
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int newLeft = draggedView.getLeft();
if ((draggableView.isMinimized() && Math.abs(dx) > MINIMUM_DX_FOR_HORIZONTAL_DRAG) || (
draggableView.isDragViewAtBottom()
&& !draggableView.isDragViewAtRight())) {
newLeft = left;
}
return newLeft;
}
/**
* Override method used to configure the vertical drag. Restrict the motion of the dragged child
* view along the vertical axis.
*
* @param child child view being dragged.
* @param top attempted motion along the Y axis.
* @param dy proposed change in position for top.
* @return the new clamped position for top.
*/
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
int newTop = draggableView.getHeight() - draggableView.getDraggedViewHeightPlusMarginTop();
if (draggableView.isMinimized() && Math.abs(dy) >= MINIMUM_DY_FOR_VERTICAL_DRAG
|| (!draggableView.isMinimized() && !draggableView.isDragViewAtBottom())) {
final int topBound = draggableView.getPaddingTop();
final int bottomBound = draggableView.getHeight()
- draggableView.getDraggedViewHeightPlusMarginTop()
- draggedView.getPaddingBottom();
newTop = Math.min(Math.max(top, topBound), bottomBound);
}
return newTop;
}
/**
* Maximize or minimize the DraggableView using the draggableView position and the y axis
* velocity.
*/
private void triggerOnReleaseActionsWhileVerticalDrag(float yVel) {
if (yVel < 0 && yVel <= -Y_MIN_VELOCITY) {
draggableView.maximize();
} else if (yVel > 0 && yVel >= Y_MIN_VELOCITY) {
draggableView.minimize();
} else {
if (draggableView.isDragViewAboveTheMiddle()) {
draggableView.maximize();
} else {
draggableView.minimize();
}
}
}
/**
* Close the view to the right, to the left or minimize it using the draggableView position and
* the x axis velocity.
*/
private void triggerOnReleaseActionsWhileHorizontalDrag(float xVel) {
if (xVel < 0 && xVel <= -X_MIN_VELOCITY) {
draggableView.closeToLeft();
} else if (xVel > 0 && xVel >= X_MIN_VELOCITY) {
draggableView.closeToRight();
} else {
if (draggableView.isNextToLeftBound()) {
draggableView.closeToLeft();
} else if (draggableView.isNextToRightBound()) {
draggableView.closeToRight();
} else {
draggableView.minimize();
}
}
}
}
| 38.241935
| 100
| 0.651764
|
958c449cd11b75074940b694c3951dacdf10a44c
| 260
|
package LinkedList;
import java.util.*;
public class QueueNode {
Node first, last;
public void enqueue(Node n){
if(n != null){
n.next = first;
first = n;
}
}
public Node dequeue(){
return last;
}
}
| 13
| 31
| 0.523077
|
9019c69fa22ca33dd101623ad6e05618382f779b
| 5,117
|
/*
* Copyright 2016 Yahoo 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.yahoo.athenz.common.server.util;
import static org.testng.Assert.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import org.testng.annotations.Test;
import com.yahoo.athenz.common.server.util.StringUtils;
public class StringUtilsTest {
@Test
public void testPatternFromGlob() {
assertEquals("^abc$", StringUtils.patternFromGlob("abc"));
assertEquals("^abc.*$", StringUtils.patternFromGlob("abc*"));
assertEquals("^abc.$", StringUtils.patternFromGlob("abc?"));
assertEquals("^.*abc.$", StringUtils.patternFromGlob("*abc?"));
assertEquals("^abc\\.abc:.*$", StringUtils.patternFromGlob("abc.abc:*"));
assertEquals("^ab\\[a-c]c$", StringUtils.patternFromGlob("ab[a-c]c"));
assertEquals("^ab.*\\.\\(\\)\\^\\$c$", StringUtils.patternFromGlob("ab*.()^$c"));
assertEquals("^abc\\\\test\\\\$", StringUtils.patternFromGlob("abc\\test\\"));
assertEquals("^ab\\{\\|c\\+$", StringUtils.patternFromGlob("ab{|c+"));
assertEquals("^\\^\\$\\[\\(\\)\\\\\\+\\{\\..*.\\|$", StringUtils.patternFromGlob("^$[()\\+{.*?|"));
}
@Test
public void testContainsMatchCharacter() {
assertTrue(StringUtils.containsMatchCharacter("abc*"));
assertTrue(StringUtils.containsMatchCharacter("*abc"));
assertTrue(StringUtils.containsMatchCharacter("abc*abc"));
assertTrue(StringUtils.containsMatchCharacter("*"));
assertTrue(StringUtils.containsMatchCharacter("?abc"));
assertTrue(StringUtils.containsMatchCharacter("abc?"));
assertTrue(StringUtils.containsMatchCharacter("abc?abc"));
assertTrue(StringUtils.containsMatchCharacter("?"));
assertFalse(StringUtils.containsMatchCharacter("abc"));
assertFalse(StringUtils.containsMatchCharacter("a.bc[ab]"));
assertFalse(StringUtils.containsMatchCharacter("a(ab)[ab]"));
assertFalse(StringUtils.containsMatchCharacter("domain:role.rolename"));
}
@Test
public void testContainsControlCharacter() {
assertFalse(StringUtils.containsControlCharacter("abcd"));
assertFalse(StringUtils.containsControlCharacter("abc td"));
assertFalse(StringUtils.containsControlCharacter("abc2345423540908d"));
assertFalse(StringUtils.containsControlCharacter("abcd!@#$#@%$$^%&%*()_+=="));
assertFalse(StringUtils.containsControlCharacter("abc\\][\\|}{|}d"));
assertFalse(StringUtils.containsControlCharacter("abc\":\":\";;';';;d"));
assertFalse(StringUtils.containsControlCharacter("ab,./<>?cd"));
assertFalse(StringUtils.containsControlCharacter("abcd`~!@#$%^&*()_+-="));
assertTrue(StringUtils.containsControlCharacter("abc\t"));
assertTrue(StringUtils.containsControlCharacter("abc\n"));
assertTrue(StringUtils.containsControlCharacter("abc\b"));
assertTrue(StringUtils.containsControlCharacter("abc\r"));
assertTrue(StringUtils.containsControlCharacter("abc\t\r\b\t\n"));
}
@Test
public void testRequestUriMatch() {
assertFalse(StringUtils.requestUriMatch("/zts/v1/schema", null, null));
assertFalse(StringUtils.requestUriMatch("/zts/v1/schema", Collections.emptySet(), null));
assertFalse(StringUtils.requestUriMatch("/zts/v1/schema", null, Collections.emptyList()));
Set<String> uriSet = new HashSet<>();
uriSet.add("/zts/v1/domain");
uriSet.add("/zts/v1/schema");
assertFalse(StringUtils.requestUriMatch("/zts/v1/token", uriSet, null));
assertTrue(StringUtils.requestUriMatch("/zts/v1/domain", uriSet, null));
assertTrue(StringUtils.requestUriMatch("/zts/v1/schema", uriSet, null));
List<Pattern> uriList = new ArrayList<>();
uriList.add(Pattern.compile("/zts/v1/domain/.+/service/.+/publickey/.+"));
assertFalse(StringUtils.requestUriMatch("/zts/v1/domain/athenz/service/zms/publickey/", uriSet, uriList));
assertFalse(StringUtils.requestUriMatch("/zts/v1/domain/athenz", uriSet, uriList));
assertFalse(StringUtils.requestUriMatch("/zts/v1/domain/athenz/token", uriSet, uriList));
assertFalse(StringUtils.requestUriMatch("/zts/v1/domain/athenz/service/zms", uriSet, uriList));
assertTrue(StringUtils.requestUriMatch("/zts/v1/domain/athenz/service/zms/publickey/zms1", uriSet, uriList));
}
}
| 49.201923
| 117
| 0.680281
|
1a0b6ea129e991303e19c28e2d094fb64000d8f2
| 2,273
|
package com.kriptops.n98pos.cardlib.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLiteIVController extends SQLiteOpenHelper implements IVController {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "cardlib_database";
public static final String IV_TABLE_NAME = "t_iv";
public static final String IV_USAGE_COLUMN = "iv_usage";
public static final String IV_VALUE_COLUMN = "iv_value";
public SQLiteIVController(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(
"CREATE TABLE " + IV_TABLE_NAME + " (" +
IV_TABLE_NAME +" INTEGER PRIMARY KEY AUTOINCREMENT," +
IV_USAGE_COLUMN + " TEXT," +
IV_VALUE_COLUMN + " TEXT)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
@Override
public void saveIv(String usage, String iv) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
db.delete(IV_TABLE_NAME, IV_USAGE_COLUMN + " like ?", new String [] { usage });
ContentValues contentValues = new ContentValues();
contentValues.put(IV_USAGE_COLUMN, usage);
contentValues.put(IV_VALUE_COLUMN, iv);
db.insert(IV_TABLE_NAME, null, contentValues);
}
@Override
public String readIv(String usage) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(
IV_TABLE_NAME,
new String [] { IV_VALUE_COLUMN },
IV_USAGE_COLUMN + " like ?",
new String [] { usage },
null,
null,
null
);
try {
if (cursor.getCount() == 0) {
cursor.close();
return null;
}
cursor.moveToFirst();
return cursor.getString(1);
} finally {
cursor.close();
}
}
}
| 30.306667
| 87
| 0.603168
|
78b68cee52bca90ab1d3b027bb5c41e34edf5b0c
| 828
|
package com.lzq.life.Api.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lzq.echarts.Option;
import com.lzq.life.Api.WealthApi;
import com.lzq.life.common.ResponseFactroy;
import com.lzq.life.service.WealthService;
import com.lzq.life.vo.BaseResponse;
/**
*
* @Title WealthApiImpl.java
* @Package com.lzq.life.Api.impl
* @Description TODO(用一句话描述该文件做什么)
* @author lizhiqiang
* @date May 27, 2020 8:58:14 PM
*
*/
@Component
public class WealthApiImpl implements WealthApi{
@Autowired
private WealthService wealthService;
@Override
public BaseResponse<Option> getWealthChartPie() throws Exception {
Option option = wealthService.getWealthChartPie();
return ResponseFactroy.createSuccessResponse(option);
}
}
| 24.352941
| 67
| 0.766908
|
972984b228f673a016ea11d25d400065c37a8a2f
| 853
|
package org.springframework.jdbc.datasource;
import java.sql.Connection;
/**
* Subinterface of Connection to be implemented by connection proxies.
* Allows access to the target connection.
*
* <p>Can be checked for when needing to cast to a native Connection
* like OracleConnection. Spring's NativeJdbcExtractorAdapter automatically
* detects such proxies before delegating to the actual unwrapping for a
* specific connection pool.
*
* @author Juergen Hoeller
* @since 22.07.2004
* @see org.springframework.jdbc.support.nativejdbc.NativeJdbcExtractorAdapter#getNativeConnection
*/
public interface ConnectionProxy extends Connection {
/**
* Return the target connection of this proxy.
* <p>This will typically either be the native JDBC Connection
* or a wrapper from a connection pool.
*/
Connection getTargetConnection();
}
| 30.464286
| 98
| 0.776084
|
fb0dd26df81f54423ce98e28b42155271f362f19
| 12,806
|
package com.ibm.mysampleapp;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import com.google.android.exoplayer2.DefaultLoadControl;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.LoadControl;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.extractor.ExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.Formatter;
import java.util.Locale;
import java.util.zip.Inflater;
public class PlayerActivity extends AppCompatActivity {
private SimpleExoPlayer exoPlayer;
private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {
@Override
public void onTimelineChanged(Timeline timeline, @Nullable Object manifest, int reason) {
Log.i("TAG", "onTimelineChanged");
}
@Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
Log.i("TAG", "onTracksChanged");
}
@Override
public void onLoadingChanged(boolean isLoading) {
Log.i("TAG", "onLoadingChanged");
}
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
Log.i("TAG", "onPlayerStateChanged: playWhenReady = " + String.valueOf(playWhenReady)
+ " playbackState = " + playbackState);
switch (playbackState) {
case ExoPlayer.STATE_ENDED:
Log.i("TAG", "Playback ended!");
//Stop playback and return to start position
setPlayPause(true);
exoPlayer.seekTo(0);
break;
case ExoPlayer.STATE_READY:
Log.i("TAG", "ExoPlayer ready! pos: " + exoPlayer.getCurrentPosition()
+ " max: " + stringForTime((int) exoPlayer.getDuration()));
setProgress();
break;
case ExoPlayer.STATE_BUFFERING:
Log.i("TAG", "Playback buffering!");
break;
case ExoPlayer.STATE_IDLE:
Log.i("TAG", "ExoPlayer idle!");
break;
}
}
@Override
public void onPlayerError(ExoPlaybackException error) {
Log.i("TAG", "onPlaybackError: " + error.getMessage());
}
@Override
public void onPositionDiscontinuity(int reason) {
Log.i("TAG", "onPositionDiscontinuity");
}
};
Handler handler;
SeekBar seekBar;
ImageButton btnPlay, btnPause, btnStop, btnNext, btnPre, btnShare, btnInfo,
btnFavorite, btnFavoriteOn;
TextView txtStartTime, txtEndTime, txtProgram;
boolean isPlaying = false,isFav = false;
String soundPath;
String namePath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Intent intent = getIntent();
txtProgram = findViewById(R.id.txtProgram);
soundPath = intent.getStringExtra("url");
namePath = intent.getStringExtra("urlName");
Toolbar toolbar = findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
try {
prepareExoPlayerFromURL(Uri.parse(soundPath));
txtProgram.setText(namePath);
} catch (Exception e) {
Log.e("TAG", "Cant reach to sound Path");
}
setPointer();
}
private void setPointer() {
//SHARE BUTTON-----------------------------------------------------------------------
btnShare = findViewById(R.id.btnShare);
btnShare.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
String shareBody = soundPath;
String shareSub = namePath;
intent.putExtra(Intent.EXTRA_SUBJECT, shareSub);
intent.putExtra(Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(intent, "SHARE ME"));
}
});
//INFO DIALOG----------------------------------------------------------------------------------
btnInfo = findViewById(R.id.btnInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog alertDialog = new AlertDialog.Builder(PlayerActivity.this).create();
alertDialog.setTitle("INFO:");
alertDialog.setMessage(" תכנית עם מרחב מוהר, סגן אלוף העולם באגרוף.\n" +
" בגיל 22 עם התואר \"אלוף ישראל באגרוף\" וכרטיס בכיוון אחד לניו יורק יוצא מרחב מוהר לארה\"ב.\n" +
" הוא משאיר מאחוריו הורים, חברים ומעריצים ומבקש להגשים את חלום חייו, להשיג את התואר אלוף העולם באגרוף.\n" +
" אחרי אימונים מפרכים הוא פורץ לזירה עטוף בדגל ישראל, אבל הקרב הופך להיות נקודת מפנה בחייו האישיים והמקצועיים.\n" +
"\n" +
" מרחב חושף את הסיפור האישי שלו מעורר השראה בכל הנושאים הקשורים למוטיבציה, מצוינות, לספורט כדרך לניתוב כעסים.\n" +
"\n" +
" שדרים: אושר מוזס ואורי בן חנן");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
//X10 MIN--NEXT BUTTON---------------------------------------------------
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long currentTime =exoPlayer.getCurrentPosition();
currentTime +=300000;
exoPlayer.seekTo(currentTime);
}
});
//X10 MIN--BACK BUTTON------------------------------------------------------
btnPre = findViewById(R.id.btnPre);
btnPre.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
long currentTime =exoPlayer.getCurrentPosition();
currentTime -=300000;
exoPlayer.seekTo(currentTime);
}
});
}
private void prepareExoPlayerFromURL(Uri parse) {
TrackSelector trackSelector = new DefaultTrackSelector();
LoadControl loadControl = new DefaultLoadControl();
exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "RadioEtzion"), null);
ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
MediaSource audioSource = new ExtractorMediaSource(parse, dataSourceFactory, extractorsFactory, null, null);
exoPlayer.addListener(eventListener);
exoPlayer.prepare(audioSource);
initMediaControls();
}
private void initMediaControls() {
initPlayButton();
initSeekBar();
initTxtTime();
}
private void initTxtTime() {
txtStartTime = findViewById(R.id.startTime);
txtEndTime = findViewById(R.id.endTime);
}
private void initSeekBar() {
seekBar = findViewById(R.id.seekBar);
seekBar.requestFocus();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (!fromUser) {
return;
}
exoPlayer.seekTo(progress * 1000);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar.setMax(0);
seekBar.setMax((int) exoPlayer.getDuration() / 1000);
}
private void initPlayButton() {
btnPlay = findViewById(R.id.btnPlay);
btnPause = findViewById(R.id.btnPause);
btnPlay.requestFocus();
btnPlay.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPlayPause(true);
}
});
btnPause.requestFocus();
btnPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setPlayPause(false);
}
});
}
private String stringForTime(int timeMs) {
StringBuilder mFormatBuilder;
Formatter mFormatter;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private void setPlayPause(boolean play) {
isPlaying = play;
exoPlayer.setPlayWhenReady(play);
if (!isPlaying) {
btnPlay.setVisibility(View.VISIBLE);
btnPause.setVisibility(View.INVISIBLE);
} else {
setProgress();
btnPlay.setVisibility(View.INVISIBLE);
btnPause.setVisibility(View.VISIBLE);
}
}
private void setProgress() {
seekBar.setProgress(0);
seekBar.setMax((int) exoPlayer.getDuration() / 1000);
txtStartTime.setText(stringForTime((int) exoPlayer.getCurrentPosition()));
txtEndTime.setText(stringForTime((int) exoPlayer.getDuration()));
if (handler == null) handler = new Handler();
//Make sure you update Seekbar on UI thread
handler.post(new Runnable() {
@Override
public void run() {
if (exoPlayer != null && isPlaying) {
seekBar.setMax((int) exoPlayer.getDuration() / 1000);
int mCurrentPosition = (int) exoPlayer.getCurrentPosition() / 1000;
seekBar.setProgress(mCurrentPosition);
txtStartTime.setText(stringForTime((int) exoPlayer.getCurrentPosition()));
txtEndTime.setText(stringForTime((int) exoPlayer.getDuration()));
handler.postDelayed(this, 1000);
}
}
});
}
@Override
public void onBackPressed() {
exoPlayer.release();
super.onBackPressed();
}
}
| 37.664706
| 162
| 0.598079
|
cbde27fddadfc9fd2342bd7d9d588e09aeeecbbd
| 9,229
|
package com.stc.ts.adm.subsystem.db;
import com.stc.ts.adm.subsystem.BaseSubSystem;
import com.stc.ts.adm.subsystem.Command;
import com.stc.ts.adm.subsystem.SystemName;
import com.stc.ts.db.DbMigrator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.MissingOptionException;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import java.util.Properties;
import static com.stc.ts.adm.subsystem.db.DBSubSystem.DbSubSystemName;
@Slf4j
@SystemName(name = DbSubSystemName, desc = "Help with database migration and installation")
public class DBSubSystem extends BaseSubSystem {
final static String DbSubSystemName = "db";
public DBSubSystem(Properties properties) {
super(DbSubSystemName, properties);
}
private static final Command versionCmd = new Command("v", "version");
private static final Command installCmd = new Command("i", "install");
private static final Command migrateCmd = new Command("m", "migrate");
private static final Command targetCmd = new Command("t", "target");
private static final Command lastCmd = new Command("l", "last");
private static final Command repairCmd = new Command("r", "repair");
private static final Command validateCmd = new Command("V", "validate");
static final Command serverCmd = new Command("s", "server");
static final Command dbNameCmd = new Command("n", "name");
static final Command userCmd = new Command("u", "user");
static final Command passwdCmd = new Command("p", "passwd");
@Override
protected void fillOptions() {
options.addOption(Option.builder(versionCmd.getShortName())
.longOpt(versionCmd.getLongName())
.desc("Show current database info: applied and available schemes")
.valueSeparator(' ')
.argName("")
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(installCmd.getShortName())
.longOpt(installCmd.getLongName())
.desc("Creates 'trawl.service' database and migrates to last schema version. " +
"Use 'migrate' command (" + migrateCmd.toString() + ") if database already exists.")
.valueSeparator(' ')
.argName("")
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(migrateCmd.getShortName())
.longOpt(migrateCmd.getLongName())
.desc("Migrates db to specified schema version.\n" +
"Use 'db " + migrateCmd.toString() + " " + lastCmd.toString() + "' to migrate to latest version.\n" +
"Use 'db " + targetCmd.toString() + "=<target>' to see available schema versions.")
.valueSeparator(' ')
.argName(targetCmd.getLongName() + ">, <" + lastCmd.getLongName())
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(targetCmd.getShortName())
.longOpt(targetCmd.getLongName())
.desc("Target database version for migrate (" + migrateCmd.toString() + ")")
.valueSeparator(' ')
.argName("schema_version")
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(lastCmd.getShortName())
.longOpt(lastCmd.getLongName())
.desc("Latest database version for migrate (" + migrateCmd.toString() + ")")
.valueSeparator(' ')
.argName("")
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(validateCmd.getShortName())
.longOpt(validateCmd.getLongName())
.desc("Validating database schema")
.valueSeparator(' ')
.argName("")
.hasArgs()
.optionalArg(true)
.build());
options.addOption(Option.builder(repairCmd.getShortName())
.longOpt(repairCmd.getLongName())
.desc("Repair database schema")
.valueSeparator(' ')
.argName("")
.hasArgs()
.optionalArg(true)
.build());
OptionGroup connectGroup = new OptionGroup();
connectGroup.addOption(Option.builder(serverCmd.getShortName())
.longOpt(serverCmd.getLongName())
.desc("Server name and port number")
.argName("")
.hasArg(true)
.build());
connectGroup.addOption(Option.builder(dbNameCmd.getShortName())
.longOpt(dbNameCmd.getLongName())
.desc("Database name")
.argName("")
.hasArg(true)
.build());
connectGroup.addOption(Option.builder(userCmd.getShortName())
.longOpt(userCmd.getShortName())
.desc("Database user name")
.argName("")
.hasArg(true)
.build());
connectGroup.addOption(Option.builder(passwdCmd.getShortName())
.longOpt(passwdCmd.getLongName())
.desc("Database user password")
.argName("")
.hasArg(true)
.build());
for (Option option : connectGroup.getOptions()) {
options.addOption(option);
}
}
@Override
protected void proceedCommand(CommandLine cmd) throws Exception {
DbConnectInfo dbConnectInfo = new DbConnectInfo(properties);
dbConnectInfo.parse(cmd);
if (cmd.hasOption(versionCmd.getShortName())) {
showInfo(dbConnectInfo);
} else if (cmd.hasOption(installCmd.getShortName())) {
install(dbConnectInfo);
} else if (cmd.hasOption(migrateCmd.getShortName())) {
migrate(cmd, dbConnectInfo);
} else if (cmd.hasOption(validateCmd.getShortName())) {
validate(cmd, dbConnectInfo);
} else if (cmd.hasOption(repairCmd.getShortName())) {
repair(cmd, dbConnectInfo);
} else {
throw new MissingOptionException(String.format("Missing one of required options: [%s, %s, %s]",
options.getOption(versionCmd.getShortName()),
options.getOption(installCmd.getShortName()),
options.getOption(migrateCmd.getShortName())
));
}
}
private void repair(CommandLine cmd, DbConnectInfo dbConnectInfo) {
DbMigrator.repair(
dbConnectInfo.getSchema(),
dbConnectInfo.getServer(),
dbConnectInfo.getDbName(),
dbConnectInfo.getUsername(),
dbConnectInfo.getPassword());
}
private void validate(CommandLine cmd, DbConnectInfo dbConnectInfo) {
DbMigrator.validate(
dbConnectInfo.getSchema(),
dbConnectInfo.getServer(),
dbConnectInfo.getDbName(),
dbConnectInfo.getUsername(),
dbConnectInfo.getPassword());
}
private void migrate(CommandLine cmd, DbConnectInfo dbConnectInfo) throws Exception {
String targetVersion = "latest";
if (cmd.hasOption(targetCmd.getShortName())) {
if (cmd.hasOption(lastCmd.getShortName()))
throw new Exception(targetCmd.toString() + " and " +
lastCmd.toString() + " not supported at the same migrate command.\n" +
"Use 'db " + migrateCmd.toString() + " " + lastCmd.toString() + "' to migrate to latest version.\n" +
"Or use 'db " + migrateCmd.toString() + " " + targetCmd.toString() + "' to migrate to concrete version.\n");
targetVersion = cmd.getOptionValue(targetCmd.getShortName());
} else if (!cmd.hasOption(lastCmd.getShortName()))
throw new Exception("Required --" + targetCmd.getShortName() + " or " + lastCmd.getShortName() + " options");
DbMigrator.migrate(
dbConnectInfo.getSchema(),
dbConnectInfo.getServer(),
dbConnectInfo.getDbName(),
dbConnectInfo.getUsername(),
dbConnectInfo.getPassword(),
targetVersion);
}
private void install(DbConnectInfo dbConnectInfo) {
DbMigrator.install(
dbConnectInfo.getSchema(),
dbConnectInfo.getServer(),
dbConnectInfo.getDbName(),
dbConnectInfo.getUsername(),
dbConnectInfo.getPassword());
}
private void showInfo(DbConnectInfo dbConnectInfo) {
DbMigrator.printDbInfo(
dbConnectInfo.getSchema(),
dbConnectInfo.getServer(),
dbConnectInfo.getDbName(),
dbConnectInfo.getUsername(),
dbConnectInfo.getPassword());
}
}
| 40.126087
| 132
| 0.57276
|
61ace43d2d7fa245134b8c315e3e10fa4634fadb
| 1,731
|
// This code was based on
// https://github.com/FreakingChicken/TransparentSkins/blob/master/src/main/java/me/FreakingChicken/TransparentSkins/client/renderer/tileentity/TileEntitySkullRendererOverride.java
package piper74.legacy.vanillafix.bugs.mixins;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.render.block.entity.SkullBlockEntityRenderer;
import net.minecraft.util.math.Direction;
import com.mojang.authlib.GameProfile;
import com.mojang.blaze3d.platform.GlStateManager;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Environment(EnvType.CLIENT)
@Mixin(SkullBlockEntityRenderer.class)
public class SkullBlockEntityRendererMixin {
@Inject(method = "render(FFFLnet/minecraft/util/math/Direction;FILcom/mojang/authlib/GameProfile;I)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;enableAlphaTest()V"))
public void method_10108(float f, float g, float h, Direction direction, float j, int k, GameProfile profile, int i, CallbackInfo ci) {
GlStateManager.enableBlend();
GlStateManager.blendFuncSeparate(770, 771, 1, 0);
}
@Inject(method = "render(FFFLnet/minecraft/util/math/Direction;FILcom/mojang/authlib/GameProfile;I)V", at = @At(value = "INVOKE", target = "Lcom/mojang/blaze3d/platform/GlStateManager;popMatrix()V", ordinal = 0))
public void disableblend(float f, float g, float h, Direction direction, float j, int k, GameProfile profile, int i, CallbackInfo ci) {
GlStateManager.disableBlend();
}
}
| 55.83871
| 216
| 0.778163
|
b4bfab7beac2ccf7800459bc1dd9013ee93b13fa
| 2,935
|
package com.thatcoolcoder.terminalRaycast;
import java.io.IOException;
import java.util.ArrayList;
import com.googlecode.lanterna.TerminalPosition;
import com.googlecode.lanterna.TerminalSize;
import com.googlecode.lanterna.graphics.TextGraphics;
import com.googlecode.lanterna.screen.Screen;
import com.googlecode.lanterna.screen.TerminalScreen;
import com.googlecode.lanterna.terminal.DefaultTerminalFactory;
import com.googlecode.lanterna.terminal.Terminal;
public class Main {
private static float frameRate = 1f / 30f;
public static void main(String[] args) throws IOException {
Terminal terminal = new DefaultTerminalFactory().createTerminal();
Screen screen = new TerminalScreen(terminal);
try {
var _walls = new ArrayList<Wall>();
_walls.add(new Wall() {{
start = new Vector3d(-1, 2.5f, 0);
end = new Vector3d(1, 2.5f, 0);
height = 0.5f;
}});
_walls.add(new Wall() {{
start = new Vector3d(-1, 2.5f, 0);
end = new Vector3d(-1, -2.5f, 0);
height = 0.5f;
}});
_walls.add(new Wall() {{
start = new Vector3d(1, 2.5f, 0);
end = new Vector3d(1, -2.5f, 0);
height = 0.5f;
}});
var player = new Player() {{
position = new Vector3d(0, -4, 0);
fieldOfView = (float) (Math.PI / 2);
angle = 0;
viewDistance = 30;
}};
var world = new World() {{
walls = _walls;
viewpoint = player;
}};
var canvas = new RenderCanvas(screen, world, screen.getTerminalSize());
screen.startScreen();
play(canvas, screen, player);
}
catch (IOException e) {
System.out.println("Your terminal sucks");
}
screen.close();
}
private static void play(RenderCanvas canvas, Screen screen, Player player) throws IOException {
float deltaTime = 0;
while (true) {
long frameStart = System.nanoTime();
var input = screen.pollInput();
if (input != null && input.getCharacter() != null && input.getCharacter() == 'q') break;
player.useInput(input);
player.move(deltaTime);
canvas.render();
long frameEnd = System.nanoTime();
float renderTime = (float) ((frameEnd - frameStart) / 10e9);
float sleepLength = Math.max(frameRate - renderTime, 0);
deltaTime = sleepLength + renderTime;
try
{
Thread.sleep((long) (sleepLength * 1000));
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
| 33.352273
| 100
| 0.537649
|
9d31ddeb41ab2970c502ee70b3ecdabf93f44eec
| 600
|
package com.jinhx.design.create.prototype.two;
import java.util.HashMap;
import java.util.Map;
public class PrototypeManager {
private Map<String, IRealizetype> map = new HashMap<>();
public PrototypeManager() {
map.put("realizetypeA", new RealizetypeA());
map.put("realizetypeB", new RealizetypeB());
}
public void addRealizetype(String key, IRealizetype IRealizetype) {
map.put(key, IRealizetype);
}
public IRealizetype getRealizetype(String key) {
IRealizetype temp = map.get(key);
return (IRealizetype) temp.clone();
}
}
| 24
| 71
| 0.673333
|
918b6e0478884c13082d3d4582a4cefe6a14c39f
| 11,095
|
package com.tourcool.core.util;
import android.text.TextUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.FastDateFormat;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static java.lang.System.currentTimeMillis;
/**
* @author :zhoujian
* @description : 时间工具类
* @company :途酷科技
* @date 2018年03月13日下午 04:22
* @Email: 971613168@qq.com
*/
public class DateUtil {
private static final String TAG = "DateUtil";
private final static String PATTERN_DATE_CHINA_TO_DAY = "yyyy年MM月dd日";
private final static String PATTERN_DATE_CHINA_TO_MINITUS = "yyyy年MM月dd日 HH:mm";
private final static String PATTERN = "yyyy-MM-dd HH:mm:ss";
private final static String PATTERN_NO_SECOND = "yyyy-MM-dd HH:mm";
private final static String PATTERN_NO_SPLIT = "yyyyMMddHHmmss";
private final static String PATTERN_DATE = "yyyy-MM-dd";
private final static int TIME_LENGTH = 14;
private final static String PATTERN_HOUR_MINITUS = "HH:mm";
/**
* 获取当前时间戳格式的字符串
*/
public static String getCurrentTime() {
long timeStamp = currentTimeMillis();
return String.valueOf(timeStamp);
}
/**
* 将时间戳转换为时间格式的字符串
*/
public static String getTimeString(String timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN);
if (StringUtils.isNotEmpty(timeMillis)) {
long time = Long.parseLong(timeMillis);
return df.format(new Date(time));
} else {
return "";
}
}
/**
* 将时间戳转换为时间格式的字符串
*/
public static String getTimeStringNoSplit(String timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_NO_SPLIT);
if (StringUtils.isNotEmpty(timeMillis)) {
long time = Long.parseLong(timeMillis);
return df.format(new Date(time));
} else {
return "";
}
}
public static String parseDate(long timeMillis) {
timeMillis = timeMillis * 1000;
final FastDateFormat df = FastDateFormat.getInstance(PATTERN);
try {
return df.format(new Date(timeMillis));
} catch (Exception e) {
return "";
}
}
public static String parseDateDay(long timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_DATE);
try {
return df.format(new Date(timeMillis));
} catch (Exception e) {
return "";
}
}
public static String parseDateNoSecond(long timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_NO_SECOND);
try {
return df.format(new Date(timeMillis));
} catch (Exception e) {
return "";
}
}
public static String parseDateNoSecond(String timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_NO_SECOND);
try {
long time = Long.parseLong(timeMillis);
return df.format(new Date(time));
} catch (Exception e) {
return "";
}
}
public static String parseDateHourAndMinitue(long timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_HOUR_MINITUS);
try {
return df.format(new Date(timeMillis));
} catch (Exception e) {
return "";
}
}
public static String getDateString(String timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_DATE);
if (StringUtils.isNotEmpty(timeMillis)) {
long time = Long.parseLong(timeMillis);
return df.format(new Date(time));
} else {
return "";
}
}
public static long parseDateLong(String timeMillis) {
if (StringUtils.isNotEmpty(timeMillis)) {
try {
BigDecimal bd = new BigDecimal(timeMillis);
String callBackScore = bd.toPlainString();
return Long.parseLong(callBackScore);
} catch (NumberFormatException e) {
return 0;
}
} else {
return 0;
}
}
public static String getDateString(Date date) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_DATE);
try {
return df.format(date);
} catch (NumberFormatException e) {
return "";
}
}
public static String getTimeChineseCharacter(String timeValue) {
if (TextUtils.isEmpty(timeValue)) {
return "";
}
if (timeValue.length() == TIME_LENGTH) {
StringBuilder sb = new StringBuilder("");
sb.append(timeValue.substring(0, 4));
sb.append("年");
sb.append(timeValue.substring(4, 6));
sb.append("月");
sb.append(timeValue.substring(6, 8));
sb.append("日");
sb.append(timeValue.substring(8, 10));
sb.append("时");
sb.append(timeValue.substring(10, 12));
sb.append("分");
sb.append(timeValue.substring(12, 14));
sb.append("秒");
return sb.toString();
}
return "";
}
/**
* 精确到日
*
* @param timeMillis
* @return
*/
public static String getTimeStringChinaToDay(String timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_DATE_CHINA_TO_DAY);
if (StringUtils.isNotEmpty(timeMillis)) {
try {
long time = Long.parseLong(timeMillis);
return df.format(new Date(time));
} catch (NumberFormatException e) {
return "";
}
} else {
return "";
}
}
public static String getTimeStringChinaToMinitus(long timeMillis) {
final FastDateFormat df = FastDateFormat.getInstance(PATTERN_DATE_CHINA_TO_MINITUS);
try {
return df.format(new Date(timeMillis));
} catch (Exception e) {
return "";
}
}
public static String formatDateToShort(String str) {
SimpleDateFormat sf1 = new SimpleDateFormat(PATTERN_DATE, Locale.getDefault());
SimpleDateFormat sf2 = new SimpleDateFormat("MM-dd", Locale.getDefault());
String formatStr;
try {
formatStr = sf2.format(sf1.parse(str));
} catch (ParseException e) {
e.printStackTrace();
return "";
}
return formatStr;
}
public static String formatDateToMonthAndDaySlash(String str) {
SimpleDateFormat sf1 = new SimpleDateFormat(PATTERN_DATE, Locale.getDefault());
SimpleDateFormat sf2 = new SimpleDateFormat("MM/dd", Locale.getDefault());
String formatStr;
try {
formatStr = sf2.format(sf1.parse(str));
} catch (ParseException e) {
e.printStackTrace();
return "";
}
return formatStr;
}
public static String friendlyTime(Date time) {
//获取time距离当前的秒数
int ct = (int) ((System.currentTimeMillis() - time.getTime()) / 1000);
if (ct == 0) {
return "刚刚";
}
if (ct > 0 && ct < 60) {
return ct + "秒前";
}
if (ct >= 60 && ct < 3600) {
return Math.max(ct / 60, 1) + "分钟前";
}
if (ct >= 3600 && ct < 86400)
return ct / 3600 + "小时前";
if (ct >= 86400 && ct < 2592000) { //86400 * 30
int day = ct / 86400;
return day + "天前";
}
if (ct >= 2592000 && ct < 31104000) { //86400 * 30
return ct / 2592000 + "月前";
}
return ct / 31104000 + "年前";
}
/**
* 转换为时间(天,时:分:秒.毫秒)
*
* @param timeMillis
* @return
*/
public static String formatDateTimeChinese(long timeMillis) {
long day = timeMillis / (24 * 60 * 60 * 1000);
long hour = (timeMillis / (60 * 60 * 1000) - day * 24);
long min = ((timeMillis / (60 * 1000)) - day * 24 * 60 - hour * 60);
long s = (timeMillis / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
// long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day > 0 ? day + "," : "") + hour + "小时" + min + "分钟" + s + "秒";
}
public static String formatDateTime(Date date) {
SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
try {
return sf1.format(date);
} catch (Exception e) {
return "";
}
}
public static String formatDateTimeChina(Date date) {
final FastDateFormat df = FastDateFormat.getInstance("yyyy/MM/dd");
try {
return df.format(date);
} catch (Exception e) {
return "";
}
}
/**
* 获取日期字符串。
*
* <pre>
* 日期字符串格式: yyyyMMdd
* 其中:
* yyyy 表示4位年。
* MM 表示2位月。
* dd 表示2位日。
* </pre>
*
* @param date 需要转化的日期。
* @return String "yyyyMMdd"格式的日期字符串。
*/
/**
* 将指定的日期字符串转化为日期对象
*
* @param dateStr 日期字符串
* @return java.util.Date
* @roseuid 3F39FE450385
*/
public static Date getDate(String dateStr) {
if (dateStr.length() == 8) {
// 日期型
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd", Locale.getDefault());
try {
java.util.Date date = df.parse(dateStr);
return date;
} catch (Exception ex) {
// Logger.write("日期格式不符合或者日期为空!请检查!");
return null;
} // end try - catch
} else if (dateStr.length() == 23) {
// 日期时间型
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
try {
java.util.Date date = df.parse(dateStr);
return date;
} catch (Exception ex) {
return null;
} // end try - catch
} else if (dateStr.length() == 6) {
// 时间型
try {
SimpleDateFormat df = new SimpleDateFormat("HHmmss", Locale.getDefault());
return df.parse(dateStr);
} catch (Exception e) {
return null;
}
}
// end if
return null;
}
public static String formatDate1(Date date) {
SimpleDateFormat sf1 = new SimpleDateFormat("yyyy.MM.dd", Locale.getDefault());
try {
return sf1.format(date);
} catch (Exception e) {
return "";
}
}
public static String formatTime(Date date) {
SimpleDateFormat sf1 = new SimpleDateFormat("HH:mm", Locale.getDefault());
try {
return sf1.format(date);
} catch (Exception e) {
return "";
}
}
}
| 29.665775
| 103
| 0.553763
|
420ee3c09ab737d77a5ae767a641fecd8712a76c
| 933
|
/*
* Copyright (c) 2020
* Author: xiaoweixiang
*/
package finished.others.finished.No1047_删除字符串中的所有相邻重复项;
class Solution {
public static void main(String[] args) {
String S = "abbaca";
String res = removeDuplicates(S);
System.out.println("res = " + res);
}
public static String removeDuplicates(String S) {
boolean end = true;
String s = S;
while (end) {
int k = s.length();
s = removeOnce(s);
if (k == s.length()) {
end = false;
}
}
return s;
}
private static String removeOnce(String s) {
StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
builder.delete(i, i + 2);
break;
}
}
return builder.toString();
}
}
| 23.923077
| 55
| 0.489818
|
53b9e1f872995914accebc798438a9ca426f986f
| 1,317
|
/**
* Copyright 2016 LinkedIn Corp. 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.
*/
package com.github.ambry.network;
import io.netty.buffer.ByteBuf;
import java.io.InputStream;
/**
* Simple request
*/
public interface NetworkRequest {
/**
* The request as an input stream is returned to the caller
* @return The inputstream that represents the request
*/
InputStream getInputStream();
/**
* Gets the start time in ms when this request started
* @return The start time in ms when the request started
*/
long getStartTimeInMs();
/**
* Release any resource this request is holding. By default it returns false so this method can be compatible
* with {@link ByteBuf#release()}
* @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated
*/
default boolean release() {
return false;
}
}
| 29.266667
| 114
| 0.712984
|
67f22ab883e6055c271964f1f1a2460f54e59f04
| 2,476
|
package xyz.cofe.win.wmi.cimv2;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.*;
import xyz.cofe.win.activex.GetActiveXComponent;
import xyz.cofe.win.wmi.*;
public class Win32_ShareToDirectoryImpl extends WmiObjImpl implements Win32_ShareToDirectory {
public Win32_ShareToDirectoryImpl(ActiveXComponent activeXComponent) {
super(activeXComponent);
}
public Win32_ShareToDirectoryImpl(ActiveXComponent activeXComponent, Wmi wmi) {
super(activeXComponent, wmi);
}
public Win32_ShareToDirectoryImpl(GetActiveXComponent activeXComponent) {
super(activeXComponent.getActiveXComponent());
}
public Win32_ShareToDirectoryImpl(GetActiveXComponent activeXComponent, Wmi wmi) {
super(activeXComponent.getActiveXComponent(), wmi);
}
public java.util.Optional<Win32_Share> getShare(){
ActiveXComponent ax = getActiveXComponent();
if( ax==null )throw new IllegalStateException("activeXComponent is null");
Variant v = ax.getProperty("Share");
if( v==null || v.isNull() )return java.util.Optional.empty();
if( v.getvt()==8 && wmi!=null ){
String path = v.getString();
WmiObj obj = wmi.getObject(path);
Win32_Share impl = new Win32_ShareImpl(obj.getActiveXComponent(),wmi);
return java.util.Optional.of(impl);
}
Dispatch d = v!=null && !v.isNull() ? v.toDispatch() : null;
ActiveXComponent a = d!=null && d.m_pDispatch!=0 ? new ActiveXComponent(d) : null;
java.util.Optional<Win32_Share> r = a!=null ? java.util.Optional.of( new Win32_ShareImpl(a) ) : java.util.Optional.empty();
return r;
}
public java.util.Optional<CIM_Directory> getSharedElement(){
ActiveXComponent ax = getActiveXComponent();
if( ax==null )throw new IllegalStateException("activeXComponent is null");
Variant v = ax.getProperty("SharedElement");
if( v==null || v.isNull() )return java.util.Optional.empty();
if( v.getvt()==8 && wmi!=null ){
String path = v.getString();
WmiObj obj = wmi.getObject(path);
CIM_Directory impl = new CIM_DirectoryImpl(obj.getActiveXComponent(),wmi);
return java.util.Optional.of(impl);
}
Dispatch d = v!=null && !v.isNull() ? v.toDispatch() : null;
ActiveXComponent a = d!=null && d.m_pDispatch!=0 ? new ActiveXComponent(d) : null;
java.util.Optional<CIM_Directory> r = a!=null ? java.util.Optional.of( new CIM_DirectoryImpl(a) ) : java.util.Optional.empty();
return r;
}
}
| 41.266667
| 131
| 0.703554
|
820f2eb644079f652fdcf460dccf252cfe4f32ca
| 375
|
package org.zcorp.java1;
public class MainUtil {
public static void main(String[] args) {
System.out.println(Integer.valueOf(-1) == Integer.valueOf(-1));
System.out.println(Integer.valueOf(-1) == new Integer(-1));
int result = getInt();
System.out.println(result);
}
private static Integer getInt() {
return null;
}
}
| 26.785714
| 71
| 0.613333
|
0d15c3c23797d7351ab4d4ddf1e3e0b91cf2a416
| 3,801
|
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.*;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
class Shader {
private int vertID;
private int fragID;
private int programID;
public Shader(String vertexFile, String fragmentFile) {
vertID = GL20.glCreateShader(GL20.GL_VERTEX_SHADER);
fragID = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER);
GL20.glShaderSource(vertID, getProgramCode(vertexFile));
compileAndCheck(vertID);
GL20.glShaderSource(fragID, getProgramCode(fragmentFile));
compileAndCheck(fragID);
programID = GL20.glCreateProgram();
GL20.glAttachShader(programID, vertID);
GL20.glAttachShader(programID, fragID);
GL20.glLinkProgram(programID);
GL20.glValidateProgram(programID);
if(GL20.glGetShader(programID, GL20.GL_LINK_STATUS) == GL11.GL_FALSE
|| GL20.glGetShader(programID, GL20.GL_VALIDATE_STATUS) == GL11.GL_FALSE) {
System.out.println(GL20.glGetProgramInfoLog(programID, 2048).trim());
} else {
System.out.println("Compiled and linked " + vertexFile + ", " + fragmentFile + " successfully!");
}
}
private void compileAndCheck(int id) {
GL20.glCompileShader(id);
if(GL20.glGetShader(id, GL20.GL_COMPILE_STATUS) == GL11.GL_FALSE) {
System.out.println(GL20.glGetShaderInfoLog(id, 2048).trim());
}
}
public void start() {
GL20.glUseProgram(programID);
}
public void end() {
GL20.glUseProgram(0);
}
private ByteBuffer getProgramCode(String fileName) {
byte[] code = null;
try {
code = Files.readAllBytes(Paths.get(fileName));
} catch (IOException e) {
System.out.println(e.toString());
e.printStackTrace();
}
// ByteBuffer buffer = ByteBuffer.allocateDirect(code.length);
// buffer.put(code);
// showBuffer(buffer);
ByteBuffer buffer = BufferUtils.createByteBuffer(code.length);
buffer.put(code);
buffer.flip();
// showBuffer(shaderPro);
return buffer;
}
private void showBuffer(ByteBuffer b) {
for (int i = 0; i < b.capacity(); ++i)
System.out.print((char) b.get(i));
System.out.println("");
}
/*private ByteBuffer getProgramCode(String filename) {
InputStream fileInputStream = null;
byte[] shaderCode = null;
try
{
if (fileInputStream == null)
fileInputStream = new FileInputStream(filename);
DataInputStream dataStream = new DataInputStream(fileInputStream);
dataStream.readFully(shaderCode = new byte[ fileInputStream.available() ]);
fileInputStream.close();
dataStream.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
ByteBuffer shaderPro = BufferUtils.createByteBuffer(shaderCode.length);
shaderPro.put(shaderCode);
shaderPro.flip();
// showBuffer(shaderPro);
return shaderPro;
}*/
public void setUniform(String location, int value) {
GL20.glUniform1i(GL20.glGetUniformLocation(programID, location), value);
}
public void setUniform(String location, float value) {
GL20.glUniform1f(GL20.glGetUniformLocation(programID, location), value);
}
public void setUniform(String location, float v0, float v1, float v2, float v3) {
GL20.glUniform4f(GL20.glGetUniformLocation(programID, location), v0, v1, v2, v3);
}
}
| 31.941176
| 109
| 0.63457
|
6dbf1f17c70ca0064236a1f44bc0759175b3206f
| 2,906
|
package org.sunflow.core.shader;
import org.sunflow.SunflowAPI;
import org.sunflow.core.ParameterList;
import org.sunflow.core.Shader;
import org.sunflow.core.ShadingState;
import org.sunflow.image.Color;
import org.sunflow.math.Matrix4;
import org.sunflow.math.Point3;
public class WireframeShader implements Shader {
private Color lineColor;
private Color fillColor;
private float width;
private float cosWidth;
public WireframeShader() {
lineColor = Color.BLACK;
fillColor = Color.WHITE;
// pick a very small angle - should be roughly the half the angular
// width of a
// pixel
width = (float) (Math.PI * 0.5 / 4096);
cosWidth = (float) Math.cos(width);
}
public boolean update(ParameterList pl, SunflowAPI api) {
lineColor = pl.getColor("line", lineColor);
fillColor = pl.getColor("fill", fillColor);
width = pl.getFloat("width", width);
cosWidth = (float) Math.cos(width);
return true;
}
public Color getFillColor(ShadingState state) {
return fillColor;
}
public Color getLineColor(ShadingState state) {
return lineColor;
}
public Color getRadiance(ShadingState state) {
Point3[] p = new Point3[3];
if (!state.getTrianglePoints(p))
return getFillColor(state);
// transform points into camera space
Point3 center = state.getPoint();
Matrix4 w2c = state.getWorldToCamera();
center = w2c.transformP(center);
for (int i = 0; i < 3; i++)
p[i] = w2c.transformP(state.transformObjectToWorld(p[i]));
float cn = 1.0f / (float) Math.sqrt(center.x * center.x + center.y * center.y + center.z * center.z);
for (int i = 0, i2 = 2; i < 3; i2 = i, i++) {
// compute orthogonal projection of the shading point onto each
// triangle edge as in:
// http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
float t = (center.x - p[i].x) * (p[i2].x - p[i].x);
t += (center.y - p[i].y) * (p[i2].y - p[i].y);
t += (center.z - p[i].z) * (p[i2].z - p[i].z);
t /= p[i].distanceToSquared(p[i2]);
float projx = (1 - t) * p[i].x + t * p[i2].x;
float projy = (1 - t) * p[i].y + t * p[i2].y;
float projz = (1 - t) * p[i].z + t * p[i2].z;
float n = 1.0f / (float) Math.sqrt(projx * projx + projy * projy + projz * projz);
// check angular width
float dot = projx * center.x + projy * center.y + projz * center.z;
if (dot * n * cn >= cosWidth)
return getLineColor(state);
}
return getFillColor(state);
}
public void scatterPhoton(ShadingState state, Color power) {
}
}
| 38.236842
| 110
| 0.563661
|
2f7b0b1017454cf829ce9be0588ad8e9d567309b
| 1,363
|
/*
* Copyright 2020 The Netty Project
*
* The Netty 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.incubator.codec.quic;
import io.netty.util.internal.ObjectUtil;
/**
* Used when the remote peer supports the
* <a href="https://tools.ietf.org/html/draft-ietf-quic-datagram-01">QUIC DATAGRAM extension.</a>
*/
public final class QuicDatagramExtensionEvent implements QuicExtensionEvent {
private final int maxLength;
QuicDatagramExtensionEvent(int maxLength) {
this.maxLength = ObjectUtil.checkPositiveOrZero(maxLength, "maxLength");
}
/**
* The maximum datagram payload length the peer will accept. If you try to write bigger datagrams the write will
* fail.
*
* @return the max length.
*/
public int maxLength() {
return maxLength;
}
}
| 32.452381
| 116
| 0.719002
|
63b77228bace19fd05c126e7744cf53870f8a193
| 2,137
|
/*
* Copyright (C) 2015, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The PSYCO: A Predicate-based Symbolic Compositional Reasoning environment
* platform is 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 features.nested;
public class Input {
public int foo(int i) {
System.err.println("\n-------- In foo! Parameter = " + i);
if (i > 64) {
System.err.printf("%s\n", "i > 64");
if ( 5 * i <= 325) {
System.err.printf("%s\n", "5 * i <= 325");
if (i != 65) {
System.err.printf("%s\n", "i != 65");
} else {
System.err.printf("%s\n", "i == 65");
}
return i;
} else if ( i != 66 ) {
System.err.printf("%s\n", "5 * i > 325 && i != 66");
return i + 1;
} else {
System.err.printf("%s\n", "5 * i > 325 && i == 66");
assert(false);
}
}
System.err.printf("%s\n", "i <= 64");
return i + 2;
}
public void bar(double d) {
System.err.println("\n-------- In bar! Parameter = " + d);
if (d >= 3.141) {
System.err.printf("%s\n", "d >= 3.141");
} else {
int i = (int)d + 65;
int j = foo(i);
if (j == i) {
System.err.println("In bar j == i");
}
}
}
public static void main(String[] args) {
double test = -0.5;
int i = (int)test;
System.out.println("-------- In main! : " + i);
Input inst = new Input();
inst.bar(1.732);
}
}
| 30.971014
| 83
| 0.542349
|
323de56454c29932f5648c23b7ce293404fab761
| 3,990
|
/**
* Copyright 2010 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.comcast.video.dawg.house;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import com.comcast.drivethru.exception.HttpException;
import com.comcast.video.dawg.DawgClient;
import com.comcast.video.dawg.common.Config;
import com.comcast.video.dawg.common.DeviceProvider;
import com.comcast.video.dawg.common.MetaStb;
import com.comcast.video.dawg.exception.HttpRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DawgPoundClient extends DawgClient implements IDawgPoundClient, DeviceProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(DawgHouseClient.class);
public static final String DEFAULT_BASE_URL = Config.get("dawg", "dawg-pound-reservations", "http://localhost:8080/dawg-pound/reservations");
public DawgPoundClient() {
this(DEFAULT_BASE_URL);
}
public DawgPoundClient(String baseURL) {
super(fixBaseUrl(baseURL));
}
private static final String fixBaseUrl(String baseURL) {
String url = baseURL + (baseURL.endsWith("/") ? "" : "/");
return url + (url.endsWith("reservations/") ? "" : "reservations/");
}
/* (non-Javadoc)
* @see com.comcast.video.dawg.house.IDawgPoundClient#getReservedDevices(java.lang.String)
*/
@Override
public Collection<MetaStb> getReservedDevices(String token) {
List<MetaStb> devices = new ArrayList<>();
try {
@SuppressWarnings("unchecked")
Map<String, Object>[] maps = client.get("/reserved/token/"+token, Map[].class);
for (Map<String,Object> map : maps) {
devices.add(new MetaStb(map));
}
} catch (HttpException e) {
e.printStackTrace();
throw new HttpRuntimeException(e);
}
return devices;
}
@Override
public void reserve(Reservation reservation) {
String token = reservation.getToken();
String id = reservation.getDeviceId();
long expiration = reservation.getExpiration();
String override = reservation.isForce() ? "/override" : "";
String path = "/reserve" + override + "/" + token + "/" + id + "/" + expiration;
try {
boolean success = client.post(path, Boolean.class);
if (!success) {
String res = reservation.isForce() ? "" : " and is not reserved";
String err = "Could not reserve '" + id + "' for '" + token + "', check that device exists" + res;
throw new HttpRuntimeException(err);
}
} catch (HttpException e) {
e.printStackTrace();
throw new HttpRuntimeException(e);
}
}
@SuppressWarnings("unchecked")
@Override
public Reservation getReservation(String deviceId) {
String path = "/reserved/id/" + deviceId;
Map<String, String> map;
try {
map = client.get(path, Map.class);
} catch (HttpException e) {
e.printStackTrace();
throw new HttpRuntimeException(e);
}
return new Reservation(deviceId, map.get("reserver"), Long.parseLong(map.get("expiration")), false);
}
@Override
public Collection<MetaStb> getDevices(String token) {
return getReservedDevices(token);
}
}
| 36.272727
| 145
| 0.651128
|
101e2d7e0fd42668e24e49dd459d8cc82d0053da
| 663
|
package lib.games.ui.companies;
import com.vaadin.flow.component.grid.Grid;
import lib.games.data.Company;
import lib.games.data.Shop;
public class CompaniesList extends Grid<Company> {
public CompaniesList() {
setSizeFull();
addColumn(Company::getName).setHeader("Name").setSortable(true).setKey("name");
addColumn(Company::getCountry).setHeader("Country").setSortable(true).setKey("country");
addColumn(Company::getFoundationYear).setHeader("Foundation Year").setSortable(true).setKey("year");
setHeightByRows(true);
}
public Company getSelected() {
return asSingleSelect().getValue();
}
}
| 27.625
| 108
| 0.699849
|
386423ca7d391148a4d68f0871d9c041fdcd3434
| 5,156
|
/**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.volatility.local;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.financial.analytics.model.volatility.local.PDEPropertyNamesAndValues.PROPERTY_DISCOUNTING_CURVE_NAME;
import java.util.Collections;
import java.util.Set;
import javax.time.calendar.ZonedDateTime;
import com.opengamma.analytics.financial.model.interestrate.curve.ForwardCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.local.LocalVolatilitySurfaceMoneyness;
import com.opengamma.analytics.financial.model.volatility.local.PDELocalVolatilityCalculator;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.security.FinancialSecurity;
import com.opengamma.id.UniqueId;
import com.opengamma.util.ArgumentChecker;
/**
*
*/
public abstract class LocalVolatilityPDEFunction extends AbstractFunction.NonCompiledInvoker {
/** The name of this local volatility calculation method */
public static final String CALCULATION_METHOD = "LocalVolatilityPDE";
private final String _blackSmileInterpolatorName;
public LocalVolatilityPDEFunction(final String blackSmileInterpolatorName) {
ArgumentChecker.notNull(blackSmileInterpolatorName, "Black smile interpolator name");
_blackSmileInterpolatorName = blackSmileInterpolatorName;
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.SECURITY;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties properties = getResultProperties();
return Collections.singleton(new ValueSpecification(getRequirementName(), target.toSpecification(), properties));
}
protected abstract String getRequirementName();
protected abstract UniqueId getTargetUid(final ComputationTarget target);
protected abstract UniqueId getDiscountingCurveUid(final ComputationTarget target);
protected abstract String getInstrumentType();
protected abstract EuropeanVanillaOption getOption(final FinancialSecurity security, final ZonedDateTime date);
protected abstract ValueProperties getResultProperties();
protected abstract ValueProperties getResultProperties(final ValueRequirement desiredValue);
protected ValueRequirement getVolatilitySurfaceRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties properties = LocalVolatilitySurfaceUtils.addDupireLocalVolatilitySurfaceProperties(ValueProperties.builder().get(), getInstrumentType(), _blackSmileInterpolatorName,
LocalVolatilitySurfacePropertyNamesAndValues.MONEYNESS).get();
return new ValueRequirement(ValueRequirementNames.LOCAL_VOLATILITY_SURFACE, getTargetUid(target), properties);
}
protected ValueRequirement getForwardCurveRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
final String calculationMethod = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_METHOD);
final String forwardCurveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
final ValueProperties properties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, calculationMethod)
.with(CURVE, forwardCurveName).get();
return new ValueRequirement(ValueRequirementNames.FORWARD_CURVE, ComputationTargetType.PRIMITIVE, getTargetUid(target), properties);
}
protected ValueRequirement getDiscountingCurveRequirement(final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties properties = ValueProperties.builder()
.with(ValuePropertyNames.CURVE, desiredValue.getConstraint(PROPERTY_DISCOUNTING_CURVE_NAME)).get();
return new ValueRequirement(ValueRequirementNames.YIELD_CURVE, ComputationTargetType.PRIMITIVE, getDiscountingCurveUid(target), properties);
}
protected Object getResult(final PDELocalVolatilityCalculator<?> calculator, final LocalVolatilitySurfaceMoneyness localVolatility, final ForwardCurve forwardCurve,
final EuropeanVanillaOption option, final YieldAndDiscountCurve discountingCurve) {
return calculator.getResult(localVolatility, forwardCurve, option, discountingCurve);
}
protected String getBlackSmileInterpolatorName() {
return _blackSmileInterpolatorName;
}
}
| 50.54902
| 191
| 0.837083
|
80d1c45ff550daf6e130e482b2c0b460b87ef947
| 6,884
|
package com.ruoyi.web.controller.business;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.ISysFlowService;
import com.ruoyi.service.ISysFlowinfoMovingService;
import com.ruoyi.system.domain.SysFlow;
import com.ruoyi.system.domain.SysFlowinfoMoving;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 流程流转信息Controller
*
* @author ruoyi
* @date 2020-06-09
*/
@Controller
@RequestMapping("/system/flow")
public class SysFlowController extends BaseController {
private String prefix = "system/flow";
@Autowired
private ISysFlowService sysFlowService;
@Autowired
private ISysUserService userService;
@Autowired
private ISysFlowinfoMovingService flowinfoMovingService;
@RequiresPermissions("system:flow:view")
@GetMapping()
public String flow() {
return prefix + "/flow";
}
/**
* 查询流程流转信息列表
*/
@RequiresPermissions("system:flow:list")
@PostMapping("/list")
@ResponseBody
public TableDataInfo list(SysFlow sysFlow) {
startPage();
List<SysFlow> list = sysFlowService.selectSysFlowList(sysFlow);
return getDataTable(list);
}
/**
* 导出流程流转信息列表
*/
@RequiresPermissions("system:flow:export")
@Log(title = "流程流转信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
@ResponseBody
public AjaxResult export(SysFlow sysFlow) {
List<SysFlow> list = sysFlowService.selectSysFlowList(sysFlow);
ExcelUtil<SysFlow> util = new ExcelUtil<SysFlow>(SysFlow.class);
return util.exportExcel(list, "flow");
}
/**
* 新增流程流转信息
*/
@GetMapping("/add")
public String add() {
return prefix + "/add";
}
/**
* 新增保存流程流转信息
*/
@RequiresPermissions("system:flow:add")
@Log(title = "流程流转信息", businessType = BusinessType.INSERT)
@PostMapping("/add")
@ResponseBody
public AjaxResult addSave(SysFlow sysFlow, String dealLink) {
//新增流程中间表数据
sysFlow.setCreateBy(ShiroUtils.getLoginName());
sysFlow.setApplyuser(ShiroUtils.getUserId());
if (sysFlow.getOptionStatus() == 0) {
sysFlow.setHandleruser(ShiroUtils.getUserId());
sysFlow.setStatus(0);
}else{
sysFlow.setStatus(1);
}
sysFlowService.insertSysFlow(sysFlow);
SysUser user = userService.selectUserById(sysFlow.getApplyuser());
//新增流程明细
SysFlowinfoMoving moving = new SysFlowinfoMoving();
moving.setFlowId(sysFlow.getId());
moving.setDealUser(sysFlow.getHandleruser());
moving.setCreateBy(ShiroUtils.getLoginName());
moving.setDealtime(DateUtils.getNowDate());
moving.setOpinion("新建");
moving.setRemark("新建审批单");
if (sysFlow.getOptionStatus() == 0) {
moving.setStatus(1);
moving.setTitle(user.getUserName()+ "新建审批单!");
} else if (sysFlow.getOptionStatus() == 1) {
moving.setStatus(0);
moving.setTitle(user.getUserName()+ "提交审批单!");
}
flowinfoMovingService.insertSysFlowinfoMoving(moving);
if (sysFlow.getOptionStatus() == 1) {
moving = new SysFlowinfoMoving();
moving.setFlowId(sysFlow.getId());
moving.setDealUser(sysFlow.getHandleruser());
moving.setCreateBy(ShiroUtils.getLoginName());
moving.setStatus(1);
moving.setTitle("请审批"+user.getUserName() + "提交的审批单!");
moving.setDealLink(dealLink);
flowinfoMovingService.insertSysFlowinfoMoving(moving);
}
return success();
}
/**
* 新增保存流程流转信息
*/
@RequiresPermissions("system:flow:edit")
@Log(title = "流程流转信息", businessType = BusinessType.INSERT)
@PostMapping("/edit")
@ResponseBody
public AjaxResult editSave(SysFlow sysFlow, String dealLink) {
if (sysFlow.getOptionStatus() == 1) {
SysFlow flow = sysFlowService.selectSysFlowByTypeId(sysFlow.getTypeId());
flow.setUpdateBy(ShiroUtils.getLoginName());
flow.setStatus(1);
flow.setHandleruser(sysFlow.getHandleruser());
sysFlowService.updateSysFlow(flow);
SysUser user = userService.selectUserById(flow.getApplyuser());
//更新上一条明细信息
SysFlowinfoMoving moving = new SysFlowinfoMoving();
moving.setFlowId(flow.getId());
moving = flowinfoMovingService.selectSysLastNumber(moving);
if(moving.getStatus()==0){
moving.setDealtime(DateUtils.getNowDate());
moving.setStatus(0);
flowinfoMovingService.updateSysFlowinfoMoving(moving);
//新增下一条审批流信息
moving = new SysFlowinfoMoving();
moving.setFlowId(flow.getId());
moving.setDealUser(flow.getHandleruser());
moving.setStatus(1);
moving.setTitle("请审批"+user.getUserName() + "提交的审批单!");
moving.setDealLink(dealLink);
flowinfoMovingService.insertSysFlowinfoMoving(moving);
}
}
return success();
}
/**
* 修改流程流转信息
*/
@GetMapping("/edit/{id}")
public String edit(@PathVariable("id") Long id, ModelMap mmap) {
SysFlow sysFlow = sysFlowService.selectSysFlowById(id);
mmap.put("sysFlow", sysFlow);
return prefix + "/edit";
}
// /**
// * 修改保存流程流转信息
// */
// @RequiresPermissions("system:flow:edit")
// @Log(title = "流程流转信息", businessType = BusinessType.UPDATE)
// @PostMapping("/edit")
// @ResponseBody
// public AjaxResult editSave(SysFlow sysFlow) {
// return toAjax(sysFlowService.updateSysFlow(sysFlow));
// }
/**
* 删除流程流转信息
*/
@RequiresPermissions("system:flow:remove")
@Log(title = "流程流转信息", businessType = BusinessType.DELETE)
@PostMapping("/remove")
@ResponseBody
public AjaxResult remove(String ids) {
return toAjax(sysFlowService.deleteSysFlowByIds(ids));
}
}
| 33.096154
| 86
| 0.632626
|
5dacba911f63a5bc51aea4bf831d9875aec4f71b
| 328
|
package com.realm.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.TYPE)
public @interface SyncDescriptions {
SyncDescription[] value();
}
| 20.5
| 44
| 0.807927
|
5a87abd553be506b83d248f16634b9d2a31539bd
| 491
|
package se.maokei.kanban.repositories;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import se.maokei.kanban.domain.Project;
@Repository
public interface ProjectRepository extends CrudRepository<Project, Long> {
Project findByName(String name);
Project findByProjectIdentifier(String projectIdentifier);
@Override
Iterable<Project> findAll();
Iterable<Project> findAllByProjectLeader(String username);
}
| 28.882353
| 74
| 0.808554
|
0eea7045da14cb6e6ba51f70f756d7e361a2fd33
| 741
|
package in.anil.config;
import org.springframework.security.oauth2.client.token.grant.redirect.AbstractRedirectResourceDetails;
/**
* class CustomRefreshTokenDetails
* Created by Anil on 9/6/2018.
*/
public class CustomRefreshTokenDetails extends AbstractRedirectResourceDetails {
private String code;
private String refreshToken;
public CustomRefreshTokenDetails() {
setGrantType("refresh_token");
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
}
| 22.454545
| 103
| 0.700405
|
c85c58cb5530c0928c608637d1b277d89fc6f4d1
| 470
|
package com.djs.learn.javalang.thread2;
public class TestMain2
{
public static void main(String[] args){
SampleThread sampleThread1 = new SampleThread();
SampleThread sampleThread2 = new SampleThread();
sampleThread1.start();
sampleThread2.start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
sampleThread1.interrupt();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
sampleThread2.interrupt();
}
}
| 16.785714
| 50
| 0.7
|
a491670aab6caa4aa94a4e97e853b691599ab500
| 450
|
package ua.com.fielden.platform.dao.exceptions;
/**
* Runtime exception that should be thrown within entity companion implementation in cases where an unexpected number of instances is returned.
*
* @author TG Team
*
*/
public class UnexpectedNumberOfReturnedEntities extends RuntimeException {
private static final long serialVersionUID = 1L;
public UnexpectedNumberOfReturnedEntities(final String msg) {
super(msg);
}
}
| 28.125
| 143
| 0.76
|
0391af26e4c03975d7318b0ed941dc8a022d4d50
| 5,100
|
package com.spme.domain;
/**
* Required Fields:
*
* SCDS - SOURCE CONTROL DATA SET
*
* VOL - THIS FIELD CAN CONTAIN EITHER A VOLUME SERIAL
* NUMBER OR THE FIRST COMMON CHARACTERS IN A RANGE
* OF VOLUME SERIAL NUMBERS. IF PART OF RANGE,
* ENTER THE REMAINING DISTINCTIVE CHARACTERS OF
* THE VOLUME SERIAL NUMBERS IN THE 'FROM' AND 'TO'
* FIELDS, AND IF YOU WANT, THE 'SUF' FIELD.
*
* SG - STORAGE GROUP
*
* Optional Fields:
*
* Set the criteria in the following fields to specify range of
* volumes (you can specify as many as 100 volumes at a time):
*
* FROM - Use this field to specify the characters unique
* to the first volume serial number in a range.
* Use the VOL and SUF fields to select leading
* and trailing characters. Valid entries are
* decimal or hexadecimal numbers or alphabet.
*
* TO - Use this field to specify the characters unique
* to the last volume serial number in a range.
* Use the VOL and SUF fields to select leading
* and trailing characters. Valid entries are
* decimal or hexadecimal numbers or alphabet.
*
* SUF - When you specify values in the FROM and TO
* fields, you can specify in this field the
* common trailing characters in a range of volume
* serial numbers. Enter up to five characters.
*
* TYPE - When you specify hexadecimal numbers in the FROM
* and TO fields, you must enter 'X' in this field.
* When you specify alphabets in the FROM and TO
* fields, you must enter 'A' in this field.
* The default is decimal.
*
* STATUS - STATUS (ENABLE/NOTCON/DISALL/DISNEW/QUIALL/
* QUINEW)
* Up to 32 statuses can be specified separated by
* commas to match the 32 systems. If a status is
* skipped, the system status that falls in between 2
* commas will have default value of ENABLE.
*
* STATUSALL - STATUSALL (ENABLE/NOTCON/DISALL/DISNEW/QUIALL/
* QUINEW)
* If Volume status in all the Systems needs to be
* set to a single value (for example ENABLE),
* STATUSALL is an easier option compared to the
* parameter STATUS.
*
* Note: STATUSALL and STATUS are mutually exclusive.
* And so, while specifying value for one of these
* parameters, either the other parameter should
* not be specified or if specified, it should not
* have any value specified.
*
* UPDHLVLSCDS - When modifying an SCDS, that was formatted
* with a higher level of SMS, using a lower
* level of SMS will make this application fail
* unless you specify the UPDHLVLSCDS parameter
* as 'Y'. Default is 'N'.
*
* If specified, this should be the first
* parameter on either VOLDEL or ADDVOL DD
* names.
*
* Possible values : Y/N/BLANK
*
*/
@SuppressWarnings("unused")
public class StorageGroupVolume {
private String scds;
private String vol;
private String sg;
private String from;
private String to;
private String suf;
private String type;
private String status;
private String statusall;
private String updhlvlscds;
public String getScds() {
return scds;
}
public void setScds(String scds) {
this.scds = scds;
}
public String getVol() {
return vol;
}
public void setVol(String vol) {
this.vol = vol;
}
public String getSg() {
return sg;
}
public void setSg(String sg) {
this.sg = sg;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSuf() {
return suf;
}
public void setSuf(String suf) {
this.suf = suf;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getStatusall() {
return statusall;
}
public void setStatusall(String statusall) {
this.statusall = statusall;
}
public String getUpdhlvlscds() {
return updhlvlscds;
}
public void setUpdhlvlscds(String updhlvlscds) {
this.updhlvlscds = updhlvlscds;
}
}
| 29.651163
| 67
| 0.56
|
388b643fc51913b70ec063a0c10cb3f59ebb47dc
| 18,793
|
/**
* Copyright (c) 2020 Team 3555
*
* 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 org.aluminati3555.frc2020;
import org.aluminati3555.lib.auto.AluminatiAutoSelector;
import org.aluminati3555.lib.auto.AluminatiAutoTask;
import org.aluminati3555.lib.auto.AluminatiAutoSelector.Entry;
import org.aluminati3555.lib.data.AluminatiData;
import org.aluminati3555.lib.drivers.AluminatiMotorGroup;
import org.aluminati3555.lib.drivers.AluminatiDisplay;
import org.aluminati3555.lib.drivers.AluminatiPigeon;
import org.aluminati3555.lib.loops.Loop;
import org.aluminati3555.lib.loops.Looper;
import org.aluminati3555.lib.drivers.AluminatiTalonSRX;
import org.aluminati3555.lib.drivers.AluminatiVictorSPX;
import org.aluminati3555.lib.drivers.AluminatiXboxController;
import org.aluminati3555.lib.pneumatics.AluminatiCompressor;
import org.aluminati3555.lib.pneumatics.AluminatiSolenoid;
import org.aluminati3555.lib.robot.AluminatiRobot;
import org.aluminati3555.lib.system.AluminatiSystem.SystemMode;
import org.aluminati3555.lib.trajectoryfollowingmotion.AluminatiRobotStateEstimator;
import org.aluminati3555.lib.trajectoryfollowingmotion.RobotState;
import org.aluminati3555.lib.util.AluminatiUtil;
import org.aluminati3555.lib.vision.AluminatiCameraHelper;
import org.aluminati3555.lib.vision.AluminatiLimelight;
import org.aluminati3555.lib.vision.AluminatiLimelight.LEDMode;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.Filesystem;
import edu.wpi.first.wpilibj.PowerDistributionPanel;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.GenericHID.Hand;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import com.team254.lib.geometry.Pose2d;
import com.team254.lib.geometry.Rotation2d;
import com.team254.lib.geometry.Translation2d;
import org.aluminati3555.frc2020.auto.actions.ActionAlignWithVision;
import org.aluminati3555.frc2020.auto.actions.ActionTurnToHeading;
import org.aluminati3555.frc2020.auto.modes.Mode10PowerCell;
import org.aluminati3555.frc2020.auto.modes.Mode3PowerCell;
import org.aluminati3555.frc2020.auto.modes.Mode3PowerCellGoForward;
import org.aluminati3555.frc2020.auto.modes.Mode3PowerCellPositionTrenchRun;
import org.aluminati3555.frc2020.auto.modes.Mode5PowerCell2OtherAllianceTrenchRun;
import org.aluminati3555.frc2020.auto.modes.Mode5PowerCell2ShieldGenerator;
import org.aluminati3555.frc2020.auto.modes.Mode5PowerCell3ShieldGenerator;
import org.aluminati3555.frc2020.auto.modes.Mode8PowerCell5TrenchRun;
import org.aluminati3555.frc2020.auto.modes.ModeCharacterizeDrive;
import org.aluminati3555.frc2020.auto.modes.ModeDoNothing;
import org.aluminati3555.frc2020.auto.modes.ModeExamplePath;
import org.aluminati3555.frc2020.auto.modes.ModeExampleTurn;
import org.aluminati3555.frc2020.auto.modes.ModeGoForward;
import org.aluminati3555.frc2020.auto.modes.ModeTuneLongShot;
import org.aluminati3555.frc2020.systems.DriveSystem;
import org.aluminati3555.frc2020.systems.MagazineSystem;
import org.aluminati3555.frc2020.systems.IntakeSystem;
import org.aluminati3555.frc2020.systems.ShooterSystem;
import org.aluminati3555.frc2020.systems.SpinnerSystem;
import org.aluminati3555.frc2020.util.ShooterUtil;
/**
* This is the main class of the robot
*
* @author Caleb Heydon
*/
public class Robot extends AluminatiRobot {
// Robot state
private RobotMode robotMode;
private RobotState robotState;
private AluminatiAutoTask autoTask;
private boolean matchStarted;
private ControlPanelColor controlPanelColor;
// Looper
private Looper looper;
// Robot state estimator
private AluminatiRobotStateEstimator robotStateEstimator;
// Power distribution
private PowerDistributionPanel pdp;
// Digit display
private AluminatiDisplay display;
// Joysticks
private AluminatiXboxController driverController;
private AluminatiXboxController operatorController;
// Limelight
private AluminatiLimelight limelight;
// System faults
RobotFaults robotFaults;
// Systems
private DriveSystem driveSystem;
private SpinnerSystem spinnerSystem;
private ShooterSystem shooterSystem;
private IntakeSystem intakeSystem;
private MagazineSystem magazineSystem;
// Pneumatics
private AluminatiCompressor compressor;
// Auto selector
private AluminatiAutoSelector autoSelector;
// Video display
private VideoDisplay videoDisplay;
@Override
public void robotInit() {
// Configure pid
AluminatiData.velocityKF = 0.277254831449;
AluminatiData.velocityKP = 0.2;
AluminatiData.velocityKI = 0.0001;
AluminatiData.velocityKD = 0.25;
// Configure pure pursuit
AluminatiData.pathFollowingProfileKP = 5;
AluminatiData.pathFollowingProfileKI = 0.0001;
AluminatiData.pathFollowingProfileKV = 0.007;
AluminatiData.pathFollowingProfileKS = 0.076;
AluminatiData.pathFollowingMaxVel = 150;
AluminatiData.pathFollowingMaxAccel = 100;
AluminatiUtil.generatePathFollowingFeedforwardValues();
// Configure stop steering distance to be small since our paths require turning
// at the end
AluminatiData.pathStopSteeringDistance = 6;
// Set encoder data
AluminatiData.encoderUnitsPerRotation = 4096;
// Set robot physical constants
AluminatiData.wheelDiamater = 6;
AluminatiData.driveWidth = 25.125;
// Set thread priority
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread.currentThread().setName("Robot-Thread");
// Set default robot state and mode
robotState = new RobotState();
robotMode = RobotMode.OPERATOR_CONTROLLED;
// Make it clear that matchStarted is false
matchStarted = false;
// Set control panel color to unkown
controlPanelColor = ControlPanelColor.UNKOWN;
// Setup looper
looper = new Looper();
// Disable LiveWindow telemetry
LiveWindow.disableAllTelemetry();
// Setup pdp
pdp = new PowerDistributionPanel();
pdp.clearStickyFaults();
// Setup digit display
display = new AluminatiDisplay();
// Setup joysticks
driverController = new AluminatiXboxController(0);
operatorController = new AluminatiXboxController(1);
// Setup limelight
limelight = new AluminatiLimelight();
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
limelight.setPipeline(0);
robotFaults = new RobotFaults();
// Configure systems
configureSystems();
// Setup pid tuning on actions
ActionTurnToHeading.initialize();
ActionAlignWithVision.initialize();
// Load neural network
if (!Robot.isSimulation()) {
ShooterUtil.load(Filesystem.getDeployDirectory() + "/shooter.ml");
}
// Setup compressor
compressor = new AluminatiCompressor();
compressor.start();
// Setup robot state estimator
robotStateEstimator = new AluminatiRobotStateEstimator(robotState, driveSystem);
looper.register(robotStateEstimator);
// Setup data reporter
looper.register(new DataReporter());
// Start looper
looper.start();
// Setup auto selector
autoSelector = new AluminatiAutoSelector(5810, new Entry("DoNothing", new ModeDoNothing()),
new Entry("CharacterizeDrive", new ModeCharacterizeDrive(driveSystem)),
new Entry("ExamplePath", new ModeExamplePath(robotState, driveSystem)),
new Entry("8PowerCell5TrenchRun",
new Mode8PowerCell5TrenchRun(robotState, limelight, driveSystem, intakeSystem, shooterSystem,
magazineSystem)),
new Entry("5PowerCell2ShieldGenerator",
new Mode5PowerCell2ShieldGenerator(robotState, limelight, driveSystem, intakeSystem, shooterSystem,
magazineSystem)),
new Entry("5PowerCell3ShieldGenerator",
new Mode5PowerCell3ShieldGenerator(robotState, limelight, driveSystem, intakeSystem, shooterSystem,
magazineSystem)),
new Entry("5PowerCell2OtherAllianceTrenchRun",
new Mode5PowerCell2OtherAllianceTrenchRun(
robotState, limelight, driveSystem, intakeSystem, shooterSystem, magazineSystem)),
new Entry("GoForward", new ModeGoForward(robotState, driveSystem)),
new Entry("3PowerCellGoForward",
new Mode3PowerCellGoForward(robotState, limelight, driveSystem, intakeSystem, shooterSystem,
magazineSystem)),
new Entry("10PowerCell",
new Mode10PowerCell(robotState, limelight, driveSystem, intakeSystem, shooterSystem, magazineSystem)),
new Entry("ExampleTurn", new ModeExampleTurn(robotState, driveSystem)),
new Entry("TuneLongShot",
new ModeTuneLongShot(robotState, limelight, driveSystem, intakeSystem, shooterSystem, magazineSystem)),
new Entry("3PowerCell",
new Mode3PowerCell(limelight, driveSystem, intakeSystem, shooterSystem, magazineSystem)),
new Entry("3PowerCellPositionTrenchRun", new Mode3PowerCellPositionTrenchRun(robotState, limelight, driveSystem,
intakeSystem, shooterSystem, magazineSystem)));
// Setup video display
videoDisplay = new VideoDisplay("VideoDisplay", 3);
// Start camera
AluminatiCameraHelper.start(0);
}
@Override
public void robotPeriodic() {
updateDisplay();
Pose2d position = robotState.getLatestFieldToVehicle().getValue();
Translation2d translation = position.getTranslation();
Rotation2d rotation = position.getRotation();
AluminatiAutoTask auto = autoSelector.getSelected();
String autoString = (auto == null) ? "DoNothing" : auto.toString();
videoDisplay.update(controlPanelColor, this.getAverageDT(), translation.x(), translation.y(), rotation.getDegrees(),
autoString, robotFaults, limelight, shooterSystem.get(), shooterSystem.getVelocity(),
magazineSystem.getFeederVelocity(), robotMode, shooterSystem.getHoodPosition());
}
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
// Use brake mode if connected to the driverstation/fms
if (DriverStation.getInstance().isDSAttached() || DriverStation.getInstance().isFMSAttached()) {
driveSystem.brake();
// Turn limelight to current pipeline
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
} else {
// Use coast for vision calibration
driveSystem.coast();
// Have limelight on for vision calibration
limelight.setLEDMode(LEDMode.ON);
}
// Zero gyro if waiting for match to start
if (!matchStarted) {
driveSystem.getGyro().setHeading(Rotation2d.fromDegrees(0));
}
// Update systems
double timestamp = Timer.getFPGATimestamp();
driveSystem.update(timestamp, SystemMode.DISABLED);
spinnerSystem.update(timestamp, SystemMode.DISABLED);
shooterSystem.update(timestamp, SystemMode.DISABLED);
intakeSystem.update(timestamp, SystemMode.DISABLED);
magazineSystem.update(timestamp, SystemMode.DISABLED);
}
@Override
public void autonomousInit() {
matchStarted = true;
// Set brake mode
driveSystem.brake();
// Set limelight mode
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
// Stop auto task if one is running
if (autoTask != null) {
autoTask.stop();
}
double timestamp = Timer.getFPGATimestamp();
// Reset robot state
robotState.reset(timestamp, new Pose2d(0, 0, Rotation2d.fromDegrees(0)), driveSystem);
loadAutoMode();
if (autoTask != null) {
robotMode = RobotMode.AUTONOMOUS;
autoTask.start(timestamp);
}
}
@Override
public void autonomousPeriodic() {
// Set brake mode
driveSystem.brake();
// Set limelight mode
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
double timestamp = Timer.getFPGATimestamp();
autoControl(timestamp);
// Update systems
driveSystem.update(timestamp, SystemMode.AUTONOMOUS);
spinnerSystem.update(timestamp, SystemMode.AUTONOMOUS);
shooterSystem.update(timestamp, SystemMode.AUTONOMOUS);
intakeSystem.update(timestamp, SystemMode.AUTONOMOUS);
magazineSystem.update(timestamp, SystemMode.AUTONOMOUS);
}
@Override
public void teleopInit() {
matchStarted = true;
// Set brake mode
driveSystem.brake();
// Set limelight mode
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
}
@Override
public void teleopPeriodic() {
SystemMode mode = (robotMode == RobotMode.OPERATOR_CONTROLLED) ? SystemMode.OPERATOR_CONTROLLED
: SystemMode.AUTONOMOUS;
// Set brake mode
driveSystem.brake();
// Set limelight mode
limelight.setLEDMode(LEDMode.CURRENT_PIPELINE);
// Fetch control panel color if we do not already have it
if (controlPanelColor == ControlPanelColor.UNKOWN) {
fetchControlPanelColor();
}
double timestamp = Timer.getFPGATimestamp();
autoControl(timestamp);
// Update systems
driveSystem.update(timestamp, mode);
spinnerSystem.update(timestamp, mode);
shooterSystem.update(timestamp, mode);
intakeSystem.update(timestamp, mode);
magazineSystem.update(timestamp, mode);
}
@Override
public void testInit() {
// Mark match as started for testing
matchStarted = true;
// Set coast mode
driveSystem.coast();
}
@Override
public void testPeriodic() {
// Set coast mode
driveSystem.coast();
}
/**
* Configures the robot systems
*/
private void configureSystems() {
// Setup drivetrain
AluminatiMotorGroup left = new AluminatiMotorGroup(new AluminatiTalonSRX(35), new AluminatiVictorSPX(14),
new AluminatiVictorSPX(15));
AluminatiMotorGroup right = new AluminatiMotorGroup(true, new AluminatiTalonSRX(50), new AluminatiVictorSPX(51),
new AluminatiVictorSPX(1));
left.getMasterTalon().setSensorPhase(true);
right.getMasterTalon().setSensorPhase(true);
AluminatiPigeon gyro = new AluminatiPigeon(new AluminatiTalonSRX(42));
AluminatiTalonSRX feederMotor = new AluminatiTalonSRX(46);
driveSystem = new DriveSystem(looper, robotState, left, right, gyro, driverController, robotFaults);
spinnerSystem = new SpinnerSystem(new AluminatiTalonSRX(60), new AluminatiSolenoid(0), operatorController,
robotFaults);
magazineSystem = new MagazineSystem(new AluminatiVictorSPX(7), feederMotor, robotFaults);
shooterSystem = new ShooterSystem(new AluminatiMotorGroup(new AluminatiTalonSRX(23), new AluminatiTalonSRX(45)),
new AluminatiTalonSRX(43), driverController, operatorController, limelight, driveSystem, magazineSystem,
robotFaults);
intakeSystem = new IntakeSystem(new AluminatiTalonSRX(44), new AluminatiSolenoid(2), operatorController,
magazineSystem, robotFaults);
}
/**
* Loads the selected auto into autoTask
*/
private void loadAutoMode() {
autoTask = autoSelector.getSelected();
if (autoTask == null) {
autoTask = new ModeDoNothing();
}
}
/**
* Returns true if the auto kill switch is activated on the driver joystick
*/
private boolean getAutoKillSwitch() {
return (driverController.getRawButton(9) && driverController.getRawButton(10)
&& driverController.getX(Hand.kLeft) >= 0.5 && driverController.getX(Hand.kRight) <= 0.5);
}
/**
* Controls the robot during auto
*/
private void autoControl(double timestamp) {
if (!DriverStation.getInstance().isAutonomous()) {
if (getAutoKillSwitch()) {
// Stop task if there is one
if (autoTask != null) {
autoTask.stop();
}
robotMode = RobotMode.OPERATOR_CONTROLLED;
}
}
if (robotMode == RobotMode.AUTONOMOUS && autoTask != null) {
if (autoTask.isComplete()) {
// Stop task and cleanup
autoTask.stop();
robotMode = RobotMode.OPERATOR_CONTROLLED;
} else {
autoTask.update(timestamp);
}
}
}
/**
* Fetches the control panel target color
*/
private void fetchControlPanelColor() {
String dataString = DriverStation.getInstance().getGameSpecificMessage();
// Stop if the string is empty or null
if (dataString == null || dataString.length() < 1) {
return;
}
char color = dataString.charAt(0);
switch (color) {
case 'B':
controlPanelColor = ControlPanelColor.BLUE;
break;
case 'G':
controlPanelColor = ControlPanelColor.GREEN;
break;
case 'R':
controlPanelColor = ControlPanelColor.RED;
break;
case 'Y':
controlPanelColor = ControlPanelColor.YELLOW;
break;
default:
controlPanelColor = ControlPanelColor.UNKOWN;
break;
}
}
/**
* Updates the digit display
*/
private void updateDisplay() {
display.display(pdp.getVoltage());
}
public enum RobotMode {
AUTONOMOUS, OPERATOR_CONTROLLED
}
public enum ControlPanelColor {
UNKOWN, BLUE, GREEN, RED, YELLOW
}
private class DataReporter implements Loop {
public void onStart(double timestamp) {
}
public void onLoop(double timestamp) {
// Do not report data if connected to the fms
if (!DriverStation.getInstance().isFMSAttached()) {
SmartDashboard.putNumber("leftPower", driveSystem.getLeftGroup().getMasterTalon().getMotorOutputPercent());
SmartDashboard.putNumber("rightPower", driveSystem.getRightGroup().getMasterTalon().getMotorOutputPercent());
SmartDashboard.putNumber("shooterPower", shooterSystem.getOutputPercent());
SmartDashboard.putNumber("feederPower", magazineSystem.getFeederOutputPercent());
}
}
public void onStop(double timestamp) {
}
public String getName() {
return "[DataReporter]";
}
}
}
| 33.439502
| 120
| 0.734316
|
aaa76dc56ce98f82c220ea94529897b6ca2ef4b2
| 77
|
/**
* Contains DTO classes for each property.
*/
package biweekly.property;
| 19.25
| 42
| 0.727273
|
fe975acfcdf1a1a321fbebf5e922969ee0af0a9c
| 1,281
|
package com.sz.projectManagement.modular.business.entity;
import cn.stylefeng.roses.kernel.db.api.pojo.entity.BaseEntity;
import cn.stylefeng.roses.kernel.scanner.api.annotation.field.ChineseDescription;
import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.util.Date;
import java.math.BigDecimal;
/**
* 实例类
*
* @author lipan
* @date 2022/01/11 15:17
*/
@TableName("sz_project_cost")
@Data
@EqualsAndHashCode(callSuper = true)
public class ProjectCost extends BaseEntity {
/**
* 主键
*/
@TableId(value = "id", type = IdType.ASSIGN_ID)
private Long id;
/**
* 父id
*/
@TableField("pid")
private Long pid;
/**
* 类型
*/
@TableField("type_code")
private String typeCode;
/**
* 标题
*/
@TableField("title")
private String title;
/**
* 金额
*/
@TableField("amount")
private BigDecimal amount;
/**
* 备注
*/
@TableField("remark")
private String remark;
/**
* 发生人
*/
@TableField("name")
private String name;
/**
* 时间
*/
@TableField("time")
private Date time;
/**
* 是否删除
*/
@ChineseDescription("是否删除")
private Integer deleted;
}
| 16.636364
| 81
| 0.601874
|
3c2464a6baba9ff5f42dc78ffbee8ed8ac1f3e13
| 3,415
|
/*
* @copyright defined in LICENSE.txt
*/
package hera.it;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import hera.api.model.BlockchainStatus;
import hera.api.model.ChainInfo;
import hera.api.model.ChainStats;
import hera.api.model.NodeStatus;
import hera.api.model.Peer;
import hera.api.model.PeerMetric;
import hera.api.model.ServerInfo;
import hera.api.transaction.NonceProvider;
import hera.api.transaction.SimpleNonceProvider;
import hera.client.AergoClient;
import hera.key.AergoKey;
import java.util.ArrayList;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class BlockchainOperationIT extends AbstractIT {
protected static AergoClient aergoClient;
protected final TestClientFactory clientFactory = new TestClientFactory();
protected final NonceProvider nonceProvider = new SimpleNonceProvider();
protected final AergoKey rich = AergoKey
.of("47hQNJjyUAMmjwdpXSwTYueRd3N8Cc3dwidU8ubtrb781ByAff7HPwPyGUqgA9RxZoeS2JhKs", "1234");
@BeforeClass
public static void before() {
final TestClientFactory clientFactory = new TestClientFactory();
aergoClient = clientFactory.get();
}
@AfterClass
public static void after() throws Exception {
aergoClient.close();
}
@Test
public void shouldFetchBlockchainStatus() {
// when
final BlockchainStatus status = aergoClient.getBlockchainOperation().getBlockchainStatus();
// then
logger.info("Chain status: {}", status);
assertTrue(0 < status.getBestHeight());
assertNotNull(status.getBestBlockHash());
assertNotNull(status.getConsensus());
assertNotNull(status.getChainIdHash());
}
@Test
public void shouldFetchChainInfo() {
// when
final ChainInfo chainInfo = aergoClient.getBlockchainOperation().getChainInfo();
// then
logger.info("Chain info: {}", chainInfo);
assertNotNull(chainInfo);
}
@Test
public void shouldFetchChainStats() {
// when
final ChainStats chainStats = aergoClient.getBlockchainOperation().getChainStats();
// then
final String report = chainStats.getReport();
logger.info("Report: {}", report);
assertNotNull(report);
}
@Test
public void shouldFetchServerInfo() {
// when
final ServerInfo serverInfo =
aergoClient.getBlockchainOperation().getServerInfo(new ArrayList<String>());
// then
logger.info("Server info: {}", serverInfo);
assertNotNull(serverInfo);
}
@Test
public void shouldListPeersFilteringItself() {
// when
final List<Peer> peers = aergoClient.getBlockchainOperation().listPeers();
// then
assertNotNull(peers);
}
@Test
public void shouldListPeersNotFilteringItself() {
// when
final List<Peer> peers = aergoClient.getBlockchainOperation().listPeers(true, true);
// then
assertNotNull(0 < peers.size());
}
@Test
public void shouldListPeerMetrics() {
// when
final List<PeerMetric> peerMetrics = aergoClient.getBlockchainOperation().listPeerMetrics();
// then
logger.info("Peer metrics: {}");
assertNotNull(peerMetrics);
}
@Test
public void shouldFetchNodeStatus() {
// then
final NodeStatus nodeStatus = aergoClient.getBlockchainOperation().getNodeStatus();
// then
logger.info("Node status: {}", nodeStatus);
assertNotNull(nodeStatus);
}
}
| 26.269231
| 96
| 0.725622
|
613b63918b610a28a9652a5e34761474ebadd2c9
| 628
|
package com.bymarcin.openglasses.lua.luafunction;
import ben_mkiv.rendertoolkit.common.widgets.Widget;
import li.cil.oc.api.machine.Arguments;
import li.cil.oc.api.machine.Context;
import com.bymarcin.openglasses.lua.LuaFunction;
public class IsVisible extends LuaFunction{
@Override
public Object[] call(Context context, Arguments arguments) {
super.call(context, arguments);
Widget widget = getSelf().getWidget();
if(widget != null){
return new Object[]{ widget.isVisible() };
}
throw new RuntimeException("Component does not exists!");
}
@Override
public String getName() {
return "isVisible";
}
}
| 23.259259
| 61
| 0.748408
|
7bedb850fbd138b8fa4183e6cc96748f7a29ef19
| 1,035
|
package io.stargate.it.http;
import io.stargate.it.BaseIntegrationTest;
/** Base class for all REST API tests. */
public class BaseRestApiTest extends BaseIntegrationTest {
/**
* Used to define common parameters for configuring REST API service instances. If you need to
* add/override parameters in a subclass, provide a different parametersCustomizer, but make sure
* that it invokes this method as well.
*
* @see ApiServiceSpec#parametersCustomizer()
*/
public static void buildApiServiceParameters(ApiServiceParameters.Builder builder) {
builder.serviceName("rest-api");
builder.servicePort(8082);
builder.servicePortPropertyName("dw.server.connector.port");
builder.metricsPort(8082);
builder.serviceStartedMessage("Started RestServiceServer");
builder.serviceLibDirProperty("stargate.rest.libdir");
builder.serviceJarBase("sgv2-rest-service");
builder.bridgeHostPropertyName("dw.stargate.bridge.host");
builder.bridgePortPropertyName("dw.stargate.bridge.port");
}
}
| 38.333333
| 99
| 0.761353
|
8d3b2bf240ff6ceede5dba325e0bdc57cf7bcfc8
| 1,817
|
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.logging.blocks;
import com.yahoo.bard.webservice.logging.LogInfo;
import com.yahoo.bard.webservice.web.ApiFilter;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
/**
* Inner log block recording information related to the API filters of a query.
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Filter implements LogInfo, Comparable<Filter> {
protected final String dimension;
protected final String field;
protected final String operator;
protected final int numberOfValues;
/**
* Constructor.
*
* @param filter The filter being recorded
*/
public Filter(ApiFilter filter) {
this.dimension = filter.getDimension().getApiName();
this.field = filter.getDimensionField().getName();
this.operator = filter.getOperation().getName();
this.numberOfValues = filter.getValues().size();
}
@SuppressWarnings("checkstyle:separatorwrap")
@Override
public int compareTo(Filter other) {
// Implements a chaining of comparisons. Each comparison is saved and if inequality is detected at this
// point the result of the comparison is returned.
// Checkstyle complains for wrapping the assignment operation
int returnValue;
return (returnValue = this.dimension.compareTo(other.dimension)) != 0
? returnValue : (returnValue = this.field.compareTo(other.field)) != 0
? returnValue : (returnValue = this.operator.compareTo(other.operator)) != 0
? returnValue : Integer.compare(this.numberOfValues, other.numberOfValues);
}
}
| 40.377778
| 115
| 0.705559
|
8bb8a4b0e846499dbcdc8eadbc2cf686ba1607da
| 1,590
|
package com.yonyou.bpm.webservice;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class AddSOAPHeader extends AbstractSoapInterceptor {
private QName qname;
private Map<String, String> values;
public AddSOAPHeader(QName qname, Map<String, String> values) {
super(Phase.WRITE);
this.qname = qname;
this.values = values;
}
public AddSOAPHeader() {
super(Phase.WRITE);
}
@Override
public void handleMessage(SoapMessage message) throws Fault {
if (values == null || values.size() == 0)
return;
if (qname == null)
return;
Document doc = DOMUtils.createDocument();
Element root = doc.createElementNS(qname.getNamespaceURI(),
qname.getPrefix() + ":" + qname.getLocalPart());
for (Map.Entry<String, String> valueEntryTemp : values.entrySet()) {
String key = valueEntryTemp.getKey();
String value = valueEntryTemp.getValue();
Element elementTemp = doc.createElementNS(qname.getNamespaceURI(),
qname.getPrefix() + ":" + key);
elementTemp.setTextContent(value);
root.appendChild(elementTemp);
}
SoapHeader head = new SoapHeader(qname, root);
List<Header> headers = message.getHeaders();
headers.add(head);
}
}
| 28.392857
| 71
| 0.740881
|
050acb90d328f05fa88d141385d679a9bd881d0d
| 4,613
|
/*
* Copyright 2014-2021 Danilo Reinert
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.reinert.requestor.core;
import java.util.Collection;
import io.reinert.requestor.core.header.Header;
import io.reinert.requestor.core.payload.type.CollectionPayloadType;
import io.reinert.requestor.core.payload.type.SinglePayloadType;
import io.reinert.requestor.core.uri.Uri;
/**
* Abstract class for {@link RequestInvoker} interface.
* It has reusable dispatch methods.
*
* @author Danilo Reinert
*/
abstract class AbstractRequestInvoker extends RequestBuilderImpl implements PollingRequestInvoker {
protected final RequestDispatcher dispatcher;
public AbstractRequestInvoker(Uri uri, LeafStore store, RequestDispatcher dispatcher) {
super(uri, store);
this.dispatcher = dispatcher;
}
//===================================================================
// RequestBuilder methods
//===================================================================
@Override
public AbstractRequestInvoker accept(String mediaType) {
super.accept(mediaType);
return this;
}
@Override
public AbstractRequestInvoker contentType(String mediaType) {
super.contentType(mediaType);
return this;
}
@Override
public AbstractRequestInvoker header(String header, String value) {
super.header(header, value);
return this;
}
@Override
public AbstractRequestInvoker header(Header header) {
super.header(header);
return this;
}
@Override
public AbstractRequestInvoker auth(Auth auth) {
super.auth(auth);
return this;
}
@Override
public AbstractRequestInvoker auth(Auth.Provider authProvider) {
super.auth(authProvider);
return this;
}
@Override
public AbstractRequestInvoker payload(Object payload, String... fields) {
super.payload(payload, fields);
return this;
}
@Override
public AbstractRequestInvoker timeout(int timeoutMillis) {
super.timeout(timeoutMillis);
return this;
}
@Override
public AbstractRequestInvoker delay(int delayMillis) {
super.delay(delayMillis);
return this;
}
@Override
public AbstractRequestInvoker retry(int[] delaysMillis, Event... events) {
super.retry(delaysMillis, events);
return this;
}
@Override
public AbstractRequestInvoker save(String key, Object value, Level level) {
super.save(key, value, level);
return this;
}
@Override
public AbstractRequestInvoker save(String key, Object value) {
super.save(key, value);
return this;
}
@Override
public AbstractRequestInvoker poll(PollingStrategy strategy) {
super.poll(strategy);
return this;
}
@Override
public AbstractRequestInvoker poll(PollingStrategy strategy, int intervalMillis) {
super.poll(strategy, intervalMillis);
return this;
}
@Override
public AbstractRequestInvoker poll(PollingStrategy strategy, int intervalMillis, int limit) {
super.poll(strategy, intervalMillis, limit);
return this;
}
//===================================================================
// Internal methods
//===================================================================
protected <T> PollingRequest<T> send(HttpMethod method, Class<T> entityType) {
setMethod(method);
return dispatcher.dispatch(build(), new SinglePayloadType<T>(entityType));
}
protected <T, C extends Collection<T>> PollingRequest<Collection<T>> send(HttpMethod method,
Class<T> entityType,
Class<C> collectionType) {
setMethod(method);
return dispatcher.dispatch(build(), new CollectionPayloadType<T>(collectionType,
new SinglePayloadType<T>(entityType)));
}
}
| 30.348684
| 104
| 0.621938
|
50dfed8251786ab2b49ac301c0369b210c8f656a
| 843
|
package com.burst.sdk.callBack;
import com.burst.sdk.struct.imos.TagParseVideoData;
import com.burst.sdk.struct.imos.TagUserLoginIDInfo;
import com.sun.jna.win32.StdCallLibrary.StdCallCallback;
/**
* @描述:
* @作者: REN
* @时间: 2019/3/19 16:59
*/
public interface XpPlayerTranscodeCallbackPF extends StdCallCallback {
/**
*
* 功能描述: 解码后视频流数据回调函数的指针类型。
* @auther: 任琳珺
* @参数
[IN] pcChannelCode 播放通道编码
[IN] pucBuffer 转码后打包的数据指针
[IN] ulBufSize 缓冲区大小
[IN] lUserParam 用户设置参数,即用户在调用::IMOS_XP_SetTranscodeCB函数时指定的用户参数
[IN] lReserved 预留参数
* @返回
* 无。注解用户应及时处理输出的媒体流数据,确保函数尽快返回,否则会影响播放器内的媒体流处理。
*/
void callBack(TagUserLoginIDInfo.ByReference userLoginIDInfo, byte[] pcChannelCode, TagParseVideoData.ByReference pucBuffer, long lUserParam, long lReserved);
}
| 28.1
| 162
| 0.698695
|
5e1e750cb97246e29a9dbe252a346b4c5d0eba22
| 2,320
|
package dustin.utilities.classloader;
/**
* Utility class for running operations on an explicitly specified class loader.
*/
public class ClassLoaderSwitcher
{
/**
* Execute the specified action on the provided class loader.
*
* @param classLoaderToSwitchTo Class loader from which the
* provided action should be executed.
* @param actionToPerformOnProvidedClassLoader Action to be
* performed on the provided class loader.
* @param <T> Type of Object returned by specified action method.
* @return Object returned by the specified action method.
*/
public static <T> T executeActionOnSpecifiedClassLoader(
final ClassLoader classLoaderToSwitchTo,
final ExecutableAction<T> actionToPerformOnProvidedClassLoader)
{
final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(classLoaderToSwitchTo);
return actionToPerformOnProvidedClassLoader.run();
}
finally
{
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
/**
* Execute the specified action on the provided class loader.
*
* @param classLoaderToSwitchTo Class loader from which the
* provided action should be executed.
* @param actionToPerformOnProvidedClassLoader Action to be
* performed on the provided class loader.
* @param <T> Type of Object returned by specified action method.
* @return Object returned by the specified action method.
* @throws Exception Exception that might be thrown by the
* specified action.
*/
public static <T> T executeActionOnSpecifiedClassLoader(
final ClassLoader classLoaderToSwitchTo,
final ExecutableExceptionableAction<T> actionToPerformOnProvidedClassLoader) throws Exception
{
final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try
{
Thread.currentThread().setContextClassLoader(classLoaderToSwitchTo);
return actionToPerformOnProvidedClassLoader.run();
}
finally
{
Thread.currentThread().setContextClassLoader(originalClassLoader);
}
}
}
| 37.419355
| 100
| 0.698276
|
d7e34359aa572b520e9ab90d18434ddf5b81e042
| 225
|
package example.service;
import example.repo.Customer1452Repository;
import org.springframework.stereotype.Service;
@Service
public class Customer1452Service {
public Customer1452Service(Customer1452Repository repo) {}
}
| 20.454545
| 59
| 0.84
|
a132c3847459e18f37f9a3a86354ead32926b497
| 2,506
|
/**
* Copyright 2006-2020 the original author or authors.
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.mybatis.generator.plugins.dsql;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.kotlin.KotlinFile;
import org.mybatis.generator.api.dom.kotlin.KotlinFunction;
import java.util.List;
/**
* Disables all delete methods in the MyBatisDynamicSQLV2 runtime.
*
* @author Jeff Butler
*/
public class DisableDeletePlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean clientBasicDeleteMethodGenerated(
Method method, Interface interfaze, IntrospectedTable introspectedTable) {
return false;
}
@Override
public boolean clientBasicDeleteMethodGenerated(
KotlinFunction kotlinFunction,
KotlinFile kotlinFile,
IntrospectedTable introspectedTable) {
return false;
}
@Override
public boolean clientDeleteByPrimaryKeyMethodGenerated(
Method method, Interface interfaze, IntrospectedTable introspectedTable) {
return false;
}
@Override
public boolean clientDeleteByPrimaryKeyMethodGenerated(
KotlinFunction kotlinFunction,
KotlinFile kotlinFile,
IntrospectedTable introspectedTable) {
return false;
}
@Override
public boolean clientGeneralDeleteMethodGenerated(
Method method, Interface interfaze, IntrospectedTable introspectedTable) {
return false;
}
@Override
public boolean clientGeneralDeleteMethodGenerated(
KotlinFunction kotlinFunction,
KotlinFile kotlinFile,
IntrospectedTable introspectedTable) {
return false;
}
}
| 31.721519
| 99
| 0.719872
|
0e2baccb3b2e8a6d0dbb40bd1e69b88f4b449fe3
| 1,793
|
package cn.plusman.design.memento;
import java.util.Scanner;
import java.util.Stack;
/**
* cn.plusman.design.memento
*
* @author plusman
* @since 2020/11/8
*/
public class CommandV1 {
public static void main(String[] args) {
InputText inputText = new InputText();
SnapshotHolder snapshotHolder = new SnapshotHolder();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String input = scanner.next();
switch (input) {
case ":list":
System.out.println(inputText.getText());
break;
case ":undo":
Snapshot snapshot = snapshotHolder.popSnapshot();
inputText.restoreSnapshot(snapshot);
break;
default:
snapshotHolder.pushSnapshot(inputText);
inputText.append(input);
break;
}
}
}
}
class InputText {
private StringBuilder text = new StringBuilder();
public String getText() {
return text.toString();
}
public void append(String input) {
this.text.append(input);
}
public void restoreSnapshot(Snapshot snapshot) {
this.text.replace(0, this.text.length(), snapshot.getText());
}
}
class Snapshot {
private String text;
public Snapshot(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
class SnapshotHolder {
private Stack<Snapshot> snapshots = new Stack<>();
public Snapshot popSnapshot() {
return snapshots.pop();
}
public void pushSnapshot(InputText inputText) {
snapshots.push(new Snapshot(inputText.getText()));
}
}
| 23.592105
| 69
| 0.568879
|
dbc03dd322a3155dfc57fc3d8a153d9ae94d982e
| 5,940
|
// PedDecision.java
/*
* Copyright (c) 2008, Gennady & Michael Kushnir
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* o 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.
* o Neither the name of the RUJEL 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 net.rujel.complete;
import net.rujel.base.SettingsBase;
import net.rujel.interfaces.EOInitialiser;
import net.rujel.interfaces.EduGroup;
import net.rujel.interfaces.Student;
import net.rujel.reusables.Various;
import com.webobjects.eoaccess.EOObjectNotAvailableException;
import com.webobjects.eoaccess.EOUtilities;
import com.webobjects.eocontrol.*;
import com.webobjects.foundation.NSArray;
import com.webobjects.foundation.NSDictionary;
import com.webobjects.foundation.NSMutableDictionary;
public class PedDecision extends _PedDecision {
public static void init() {
EOInitialiser.initialiseRelationship(ENTITY_NAME,"student",false,"studentID","Student")
.anyInverseRelationship().setPropagatesPrimaryKey(true);
}
public static final int MANUAL_FLAG = 8;
public Student student() {
return (Student)storedValueForKey("student");
}
public void setStudent(EOEnterpriseObject aValue) {
takeStoredValueForKey(aValue, "student");
}
public static String titleSetting = "pedsovetTitle";
public static String decisionSetting = "pedsovetDecision";
public void awakeFromInsertion(EOEditingContext ec) {
super.awakeFromInsertion(ec);
setFlags(new Integer(0));
}
public void turnIntoFault(EOFaultHandler handler) {
super.turnIntoFault(handler);
}
public static PedDecision setForStudent(Student student, boolean on) {
EOEditingContext ec = student.editingContext();
try {
PedDecision dec = (PedDecision)EOUtilities.objectMatchingKeyAndValue(
ec, ENTITY_NAME, "student", student);
if(on)
return dec;
else if (dec.specDecision() == null && dec.flags().intValue() == 0)
ec.deleteObject(dec);
} catch (EOObjectNotAvailableException e) {
if(on) {
PedDecision dec = (PedDecision)EOUtilities.createAndInsertInstance(ec, ENTITY_NAME);
dec.setStudent(student);
}
}
return null;
}
public static NSArray getForStudents(NSArray list, EOEditingContext ec) {
EOQualifier qual = Various.getEOInQualifier("student", list);
EOFetchSpecification fs = new EOFetchSpecification(ENTITY_NAME,qual,null);
NSArray found = ec.objectsWithFetchSpecification(fs);
return found;
}
public static NSMutableDictionary dictForGroup(EduGroup gr) {
if(gr == null)
return null;
EOEditingContext ec = gr.editingContext();
NSMutableDictionary dict = new NSMutableDictionary();
NSDictionary crs = SettingsBase.courseDict(gr);
dict.takeValueForKey(
SettingsBase.stringSettingForCourse("pedsovetTitle",crs, ec), "title");
EOQualifier qual = Various.getEOInQualifier("student", gr.list());
EOFetchSpecification fs = new EOFetchSpecification(ENTITY_NAME,qual,null);
NSArray found = ec.objectsWithFetchSpecification(fs);
String dflt = defaultDecision(gr);
for (int i = 0; i < found.count(); i++) {
PedDecision dec = (PedDecision)found.objectAtIndex(i);
String decision = dec.specDecision();
if(decision == null)
decision = formatDefault(dflt, dec.student());
else if(decision.length() == 0)
continue;
dict.setObjectForKey(decision, dec.student());
}
return dict;
}
public static String defaultDecision(EduGroup gr) {
NSDictionary crs = SettingsBase.courseDict(gr);
String dflt = SettingsBase.stringSettingForCourse(
"pedsovetDecision",crs, gr.editingContext());
if(dflt == null || gr.grade() == null)
return dflt;
int next = gr.grade().intValue();
next++;
return String.format(dflt, new Integer(next));
}
public static String formatDefault(String result, Student stu) {
int idx1 = result.indexOf('[');
if(idx1 < 0)
return result;
int idx2 = result.indexOf(']', idx1);
if(idx2 < 0)
return result;
StringBuilder buf = new StringBuilder(result.length());
buf.append(result.substring(0, idx1));
while (idx1 >= 0) {
int idx3 = result.indexOf('|', idx1);
if(idx3 > idx1 && idx3 < idx2) {
if(stu.person().sex()) {
if(idx3 > idx1 +1)
buf.append(result.substring(idx1 +1, idx3));
} else {
if(idx2 > idx3 +1)
buf.append(result.substring(idx3 +1, idx2));
}
}
idx1 = result.indexOf('[',idx2);
idx3 = result.indexOf(']',idx3);
if(idx1 > idx2 && idx3 > 1) {
buf.append(result.substring(idx2 +1, idx1));
idx2 = idx3;
}
} // while (idx1 >= 0)
buf.append(result.substring(idx2 +1));
return buf.toString();
}
}
| 36
| 90
| 0.729798
|
6200c4ec1834eca7f2692b081635bfe9381faaec
| 537
|
package net.jodah.failsafe.util.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Schedules executions.
*
* @author Jonathan Halterman
* @see Schedulers
* @see net.jodah.failsafe.util.concurrent.DefaultScheduledFuture
*/
public interface Scheduler {
/**
* Schedules the {@code callable} to be called after the {@code delay} for the {@code unit}.
*/
ScheduledFuture<?> schedule(Callable<?> callable, long delay, TimeUnit unit);
}
| 26.85
| 94
| 0.743017
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.