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
|
|---|---|---|---|---|---|
dc91895bdb220a20e82e630b4cb1c28539ca169a
| 133
|
package com.coffee.baby.pattern.dynamicproxy;
public interface TagetObject {
void doSomethig();
void doSomethingElse();
}
| 14.777778
| 45
| 0.736842
|
b58041ae3b26a183a1afad0528a0b926f493511c
| 2,270
|
/*
* Copyright (c) 2021 Tim Langhammer
*
* 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 earth.eu.jtzipi.modules.fx;
import javafx.beans.property.*;
import javafx.scene.control.Control;
import javafx.scene.control.Skin;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import javafx.scene.shape.StrokeType;
public class BendButton extends Control {
private final StringProperty fxTextProp = new SimpleStringProperty( this, "FX_TEXT_PROP" );
private final ObjectProperty<Image> fxImageProp = new SimpleObjectProperty<>();
private final ObjectProperty<StrokeType> fxFrameStrokeTypeProp = new SimpleObjectProperty<>();
private final ObjectProperty<Color> fxFrameStrokeColorProp = new SimpleObjectProperty<>();
private final DoubleProperty fxFrameStrokeWidthProp = new SimpleDoubleProperty();
public BendButton( final String text, final Image image, final double prefWidth, final double prefHeight ) {
this.fxTextProp.setValue( text );
this.fxImageProp.setValue( image );
setWidth( prefWidth );
setHeight( prefHeight );
// setOnMouseEntered( me -> setBorder( new Bo ) );
}
public final StringProperty getTextPropFX() {
return this.fxTextProp;
}
public final ObjectProperty<Color> getFrameStrokeColorPropFX(){
return this.fxFrameStrokeColorProp;
}
public final ObjectProperty<StrokeType> getFrameStrokeTypePropFX() {
return this.fxFrameStrokeTypeProp;
}
public final DoubleProperty getFrameStrokeWidthPropFX() {
return this.fxFrameStrokeWidthProp;
}
@Override
protected Skin<?> createDefaultSkin() {
return new BendButtonSkin( this );
}
}
| 31.527778
| 112
| 0.720705
|
b48ec95eb95d2abe4524ae22b739f77a5305c52f
| 1,353
|
package ru.didim99.tstu.core.graphics.curve.builder;
import android.graphics.PointF;
import ru.didim99.tstu.core.graphics.math.Mat4;
import ru.didim99.tstu.core.graphics.math.Vec4;
/**
* Created by didim99 on 02.03.20.
*/
class CubicInterpolator {
private Mat4 basisMatrix;
private float[] pointsPuffer;
private int step;
private double dt;
CubicInterpolator(float[] pointsPuffer, Mat4 basisMatrix) {
this.pointsPuffer = pointsPuffer;
this.basisMatrix = basisMatrix;
}
void setLastPointIndex(int index) {
this.step = BaseBuilder.STEP_POINTS / index;
this.dt = BaseBuilder.T_MAX / step;
}
void interpolate(int i, Vec4 gx, Vec4 gy) {
double t = BaseBuilder.T_MIN;
Vec4 vt = new Vec4();
PointF prev = null;
float x, y;
int offset = i * step * 4;
for (int index = 0; index < step * 4; index += 4) {
vt.set(t * t * t, t * t, t, 1);
vt = vt.multiply(basisMatrix);
x = (float) gx.multiply(vt);
y = (float) gy.multiply(vt);
if (prev != null) {
pointsPuffer[offset + index] = prev.x;
pointsPuffer[offset + index + 1] = prev.y;
pointsPuffer[offset + index + 2] = x;
pointsPuffer[offset + index + 3] = y;
} else {
prev = new PointF();
index -= 4;
}
prev.set(x, y);
t += dt;
}
}
}
| 25.055556
| 61
| 0.603843
|
bdef3455065fe3b4c897785897c318e1c29d6efa
| 2,104
|
/**
* @author AlgoBuilder
* @see <a href="https://github.com/AlgoBuilder">Source Code</a>
*/
public class SampleImplementation {
public static void main(String[] args) {
// Gene domains
Integer[] domain_1 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_2 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_3 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_4 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_5 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_6 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
Integer[] domain_7 = {0, 1, 2, 3, 4, 5, 7, 8, 9};
// initialize gene
Gene[] genes = new Gene[7];
genes[0] = new Gene().setDomain(domain_1);
genes[1] = new Gene().setDomain(domain_2);
genes[2] = new Gene().setDomain(domain_3);
genes[3] = new Gene().setDomain(domain_4);
genes[4] = new Gene().setDomain(domain_5);
genes[5] = new Gene().setDomain(domain_6);
genes[6] = new Gene().setDomain(domain_7);
int num = 10; // number of individuals in a generation
int generations = 20; // number of generations
GeneticAlgorithm geneticAlgorithm = new GeneticAlgorithm()
.setFitnessFunction(new SampleFitnessFunction()).setGeneDomain(genes).setGenSize(num)
.initializePopulation();
// output "Average fitness" and "Best fitness" per generation
System.out.println("Avg\tBest");
for (int i=0; i<generations; i++) {
System.out.println("Gen. " + i + ":\t" + + geneticAlgorithm.getCurrentPopulation().getPopFitness() / num
+ "\t" + geneticAlgorithm.getCurrentPopulation().getFittest().getFitness());
if (i != generations - 1)
geneticAlgorithm.getNextGeneration(0.2);
}
// info on fittest @generations
System.out.print("---------------------\nFittest chromosome:\t");
geneticAlgorithm.getCurrentPopulation().getFittest().getChromosome().printChromosome();
}
}
| 42.08
| 117
| 0.553232
|
608911d16f89c32e25ef89a2553554644d8d618e
| 6,442
|
/*
*
* Copyright 2012-2014 Eurocommercial Properties NV
*
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.estatio.integtests.lease;
import java.math.BigDecimal;
import javax.inject.Inject;
import org.assertj.core.api.Assertions;
import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.estatio.dom.lease.Lease;
import org.estatio.dom.lease.LeaseItemType;
import org.estatio.dom.lease.LeaseRepository;
import org.estatio.dom.lease.LeaseTermForIndexable;
import org.estatio.dom.lease.LeaseTermForPercentage;
import org.estatio.dom.lease.LeaseTermForTurnoverRent;
import org.estatio.fixture.EstatioBaseLineFixture;
import org.estatio.fixture.lease.LeaseForOxfTopModel001Gb;
import org.estatio.fixture.lease.LeaseItemAndTermsForOxfTopModel001;
import org.estatio.integtests.EstatioIntegrationTest;
public class LeaseTermsForPercentage_IntegTest extends EstatioIntegrationTest {
@Inject
LeaseRepository leaseRepository;
public static class LeaseTermForPercentageOver2011Test extends LeaseTermsForPercentage_IntegTest {
LeaseTermForIndexable indexTerm1;
LeaseTermForIndexable indexTerm2;
LeaseTermForTurnoverRent torTerm;
LeaseTermForPercentage percentageTerm;
Lease topmodelLease;
@Before
public void setUp() throws Exception {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(ExecutionContext executionContext) {
executionContext.executeChild(this, new EstatioBaseLineFixture());
executionContext.executeChild(this, new LeaseForOxfTopModel001Gb());
executionContext.executeChild(this, new LeaseItemAndTermsForOxfTopModel001());
}
});
}
@Test
public void test() throws Exception {
// given
topmodelLease = leaseRepository.findLeaseByReference(LeaseForOxfTopModel001Gb.REF);
topmodelLease.verifyUntil(new LocalDate(2012, 01, 01));
indexTerm1 = (LeaseTermForIndexable) topmodelLease.findFirstItemOfType(LeaseItemType.RENT).getTerms().first();
indexTerm2 = (LeaseTermForIndexable) indexTerm1.getNext();
torTerm = (LeaseTermForTurnoverRent) topmodelLease.findFirstItemOfType(LeaseItemType.TURNOVER_RENT).getTerms().first();
torTerm.setAuditedTurnover(BigDecimal.valueOf(1111111.00));
topmodelLease.verifyUntil(new LocalDate(2012, 01, 01));
// when
Assertions.assertThat(indexTerm1.valueForDate(new LocalDate(2011, 07, 14))).isEqualTo(new BigDecimal("20200.00"));
Assertions.assertThat(indexTerm1.getStartDate()).isEqualTo(new LocalDate(2010, 07, 15));
Assertions.assertThat(indexTerm2.valueForDate(new LocalDate(2012, 07, 14))).isEqualTo(new BigDecimal("20846.40"));
Assertions.assertThat(indexTerm2.getStartDate()).isEqualTo(new LocalDate(2011, 07, 15));
Assertions.assertThat(torTerm.valueForDate(new LocalDate(2012, 01, 01))).isEqualTo(new BigDecimal("57279.16"));
percentageTerm = (LeaseTermForPercentage) topmodelLease.findFirstItemOfType(LeaseItemType.RENTAL_FEE).getTerms().first();
// then
Assertions.assertThat(percentageTerm.valueForDate(new LocalDate(2012, 01, 01))).isEqualTo(new BigDecimal("1166.67"));
}
}
public static class LeaseTermForPercentageNoTurnOverRent extends LeaseTermsForPercentage_IntegTest {
LeaseTermForIndexable indexTermLast;
LeaseTermForIndexable indexTermPrevious;
LeaseTermForPercentage percentageTermLast;
Lease topmodelLease;
@Before
public void setUp() throws Exception {
runFixtureScript(new FixtureScript() {
@Override
protected void execute(ExecutionContext executionContext) {
executionContext.executeChild(this, new EstatioBaseLineFixture());
executionContext.executeChild(this, new LeaseForOxfTopModel001Gb());
executionContext.executeChild(this, new LeaseItemAndTermsForOxfTopModel001());
}
});
}
@Test
public void test() throws Exception {
// given
topmodelLease = leaseRepository.findLeaseByReference(LeaseForOxfTopModel001Gb.REF);
topmodelLease.verifyUntil(new LocalDate(2016, 01, 01));
indexTermLast = (LeaseTermForIndexable) topmodelLease.findFirstItemOfType(LeaseItemType.RENT).getTerms().last();
indexTermPrevious = (LeaseTermForIndexable) indexTermLast.getPrevious();
// when
Assertions.assertThat(indexTermLast.valueForDate(new LocalDate(2015, 07, 15))).isEqualTo(new BigDecimal("21305.02"));
Assertions.assertThat(indexTermLast.getStartDate()).isEqualTo(new LocalDate(2015, 07, 15));
Assertions.assertThat(indexTermPrevious.valueForDate(new LocalDate(2014, 07, 14))).isEqualTo(new BigDecimal("21305.02"));
Assertions.assertThat(indexTermPrevious.getStartDate()).isEqualTo(new LocalDate(2014, 07, 15));
percentageTermLast = (LeaseTermForPercentage) topmodelLease.findFirstItemOfType(LeaseItemType.RENTAL_FEE).getTerms().last();
// then
Assertions.assertThat(percentageTermLast.valueForDate(new LocalDate(2016, 01, 01))).isEqualTo(new BigDecimal("319.58"));
Assertions.assertThat(percentageTermLast.getStartDate()).isEqualTo(new LocalDate(2015, 01, 01));
Assertions.assertThat(percentageTermLast.getEndDate()).isEqualTo(new LocalDate(2015, 12, 31));
Assertions.assertThat(percentageTermLast.getOriginalValue()).isEqualTo(new BigDecimal("21305.04"));
}
}
}
| 45.687943
| 136
| 0.707234
|
594e32e92583efb283eeca37ac838500e2546657
| 169
|
package com.dragome.utils;
public class NamingUtils {
public static String javaToDragomeNotation(Class<?> aClazz) {
return aClazz.getName().replace(".", "_");
}
}
| 18.777778
| 62
| 0.715976
|
849dd1ef9deebb04a2238591eb03a5560147a3c1
| 302
|
package com.bitdubai.fermat_dap_api.layer.dap_transaction;
import com.bitdubai.fermat_api.Plugin;
/**
* Created by Manuel Perez (darkpriestrelative@gmail.com) on 09/09/15.
*/
public interface DAPTransactionSubsystem {
void start () throws CantStartSubsystemException;
Plugin getPlugin();
}
| 25.166667
| 70
| 0.774834
|
d8084284bf3fd1dc1f1fb4b76cff761a9d1784ab
| 277
|
package com.penglecode.xmodule.common.consts;
/**
* 常量池
* @param <T>
* @author pengpeng
* @date 2019年6月6日 下午12:56:51
*/
public interface ConstantPool<T> {
/**
* 从常量池中获取常量值
* @param constant
* @return
*/
public T get(Constant<T> constant);
}
| 15.388889
| 46
| 0.602888
|
d5f566da32bdb05911a2c12ebed4834a170dc9dd
| 606
|
package imooc.naga.entity.plugin;
import imooc.naga.core.util.JsonUtil;
import lombok.SneakyThrows;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.List;
@Converter
public class OutParamJpaConverterJson implements AttributeConverter<List, String> {
@SneakyThrows
@Override
public String convertToDatabaseColumn(List stringObjectMap) {
return JsonUtil.toJson(stringObjectMap);
}
@SneakyThrows
@Override
public List<PackageOutParam> convertToEntityAttribute(String s) {
return JsonUtil.fromJsonList(PackageOutParam.class,s);
}
}
| 24.24
| 83
| 0.80198
|
982580037531a78b0347774876216f70655e0d13
| 3,449
|
/**
* Copyright 2015 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 dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import wherehows.models.table.Dataset;
public class DatasetWithUserRowMapper implements RowMapper<Dataset> {
@Override
public Dataset mapRow(ResultSet rs, int rowNum) throws SQLException {
Dataset dataset = new Dataset();
dataset.id = rs.getInt(DatasetRowMapper.DATASET_ID_COLUMN);
dataset.name = rs.getString(DatasetRowMapper.DATASET_NAME_COLUMN);
dataset.urn = rs.getString(DatasetRowMapper.DATASET_URN_COLUMN);
dataset.schema = rs.getString(DatasetRowMapper.DATASET_SCHEMA_COLUMN);
dataset.source = rs.getString(DatasetRowMapper.DATASET_SOURCE_COLUMN);
if (StringUtils.isNotBlank(dataset.urn) && dataset.urn.substring(0, 4)
.equalsIgnoreCase(DatasetRowMapper.HDFS_PREFIX)) {
dataset.hdfsBrowserLink =
DatasetRowMapper.HDFS_BROWSER_URL + dataset.urn.substring(DatasetRowMapper.HDFS_URN_PREFIX_LEN);
}
String strOwner = rs.getString(DatasetRowMapper.DATASET_OWNER_ID_COLUMN);
String strOwnerName = rs.getString(DatasetRowMapper.DATASET_OWNER_NAME_COLUMN);
String strOwnerEmail = rs.getString(DatasetRowMapper.DATASET_OWNER_EMAIL_COLUMN);
String[] owners = StringUtils.isNotBlank(strOwner) ? strOwner.split(",") : null;
String[] ownerNames = StringUtils.isNotBlank(strOwnerName) ? strOwnerName.split(",") : null;
String[] ownerEmail = StringUtils.isNotBlank(strOwnerEmail) ? strOwnerEmail.split(",") : null;
dataset.owners = utils.Dataset.fillDatasetOwnerList(owners, ownerNames, ownerEmail);
Time created = rs.getTime(DatasetRowMapper.DATASET_CREATED_TIME_COLUMN);
Time modified = rs.getTime(DatasetRowMapper.DATASET_MODIFIED_TIME_COLUMN);
Long sourceModifiedTime = rs.getLong(DatasetRowMapper.DATASET_SOURCE_MODIFIED_TIME_COLUMN);
Integer schemaHistoryId = rs.getInt(DatasetRowMapper.SCHEMA_HISTORY_ID_COLUMN);
if (modified != null && sourceModifiedTime != null && sourceModifiedTime > 0) {
dataset.modified = new java.util.Date(modified.getTime());
dataset.formatedModified = dataset.modified.toString();
}
if (created != null) {
dataset.created = new java.util.Date(created.getTime());
} else if (modified != null) {
dataset.created = new java.util.Date(modified.getTime());
}
dataset.hasSchemaHistory = schemaHistoryId != null && schemaHistoryId > 0;
Long watchId = rs.getLong(DatasetRowMapper.DATASET_WATCH_ID_COLUMN);
Integer favoriteId = rs.getInt(DatasetRowMapper.FAVORITE_DATASET_ID_COLUMN);
dataset.isFavorite = favoriteId != null && favoriteId > 0;
if (watchId != null && watchId > 0) {
dataset.watchId = watchId;
dataset.isWatched = true;
} else {
dataset.watchId = 0L;
dataset.isWatched = false;
}
return dataset;
}
}
| 41.059524
| 106
| 0.742824
|
29efea1edfebe54cd9cf2181a0a7f29f3642596e
| 29,596
|
/*
* Copyright 2016 ForgeRock AS.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.forgerock.cuppa;
import static org.forgerock.cuppa.Cuppa.*;
import static org.forgerock.cuppa.TestCuppaSupport.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.forgerock.cuppa.functions.HookFunction;
import org.forgerock.cuppa.functions.TestFunction;
import org.forgerock.cuppa.model.Hook;
import org.forgerock.cuppa.model.TestBlock;
import org.forgerock.cuppa.reporters.Reporter;
import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class ExecutionTests {
private Reporter reporter;
private HookFunction outerBeforeFn1;
private HookFunction outerBeforeFn2;
private HookFunction outerAfterFn1;
private HookFunction outerAfterFn2;
private HookFunction outerBeforeEachFn1;
private HookFunction outerBeforeEachFn2;
private HookFunction outerAfterEachFn1;
private HookFunction outerAfterEachFn2;
private TestFunction outerTest1Fn;
private TestFunction outerTest2Fn;
private HookFunction nested1BeforeFn;
private HookFunction nested1AfterFn;
private HookFunction nested1BeforeEachFn;
private HookFunction nested1AfterEachFn;
private TestFunction nested1Test1Fn;
private TestFunction nested1Test2Fn;
private HookFunction nested2BeforeFn;
private HookFunction nested2AfterFn;
private HookFunction nested2BeforeEachFn;
private HookFunction nested2AfterEachFn;
private TestFunction nested2Test1Fn;
private TestFunction nested2Test2Fn;
private TestBlock root;
private TestBlock outer;
private TestBlock nested1;
private TestBlock nested2;
private org.forgerock.cuppa.model.Test outerTest1;
private org.forgerock.cuppa.model.Test outerTest2;
private org.forgerock.cuppa.model.Test nested1Test1;
private org.forgerock.cuppa.model.Test nested1Test2;
private org.forgerock.cuppa.model.Test nested2Test1;
private org.forgerock.cuppa.model.Test nested2Test2;
private List<TestBlock> parentsOfOuter;
private List<TestBlock> parentsOfOuterChildren;
private List<TestBlock> parentsOfNested1Children;
private List<TestBlock> parentsOfNested2Children;
private Hook outerBefore1;
private Hook outerAfter1;
private Hook outerBefore2;
private Hook outerAfter2;
private Hook outerBeforeEach1;
private Hook outerAfterEach1;
private Hook outerBeforeEach2;
private Hook outerAfterEach2;
private Hook nested1Before;
private Hook nested1After;
private Hook nested1BeforeEach;
private Hook nested1AfterEach;
private Hook nested2Before;
private Hook nested2After;
private Hook nested2BeforeEach;
private Hook nested2AfterEach;
private InOrder order;
private Exception exception;
@BeforeMethod
public void setupMocks() throws Exception {
reporter = mock(Reporter.class, "reporter");
outerBeforeFn1 = mock(HookFunction.class, "outerBeforeFn1");
outerBeforeFn2 = mock(HookFunction.class, "outerBeforeFn2");
outerAfterFn1 = mock(HookFunction.class, "outerAfterFn1");
outerAfterFn2 = mock(HookFunction.class, "outerAfterFn2");
outerBeforeEachFn1 = mock(HookFunction.class, "outerBeforeEachFn1");
outerBeforeEachFn2 = mock(HookFunction.class, "outerBeforeEachFn2");
outerAfterEachFn1 = mock(HookFunction.class, "outerAfterEachFn1");
outerAfterEachFn2 = mock(HookFunction.class, "outerAfterEachFn2");
outerTest1Fn = mock(TestFunction.class, "outerTest1Fn");
outerTest2Fn = mock(TestFunction.class, "outerTest2Fn");
nested1BeforeFn = mock(HookFunction.class, "nested1BeforeFn");
nested1AfterFn = mock(HookFunction.class, "nested1AfterFn");
nested1BeforeEachFn = mock(HookFunction.class, "nested1BeforeEachFn");
nested1AfterEachFn = mock(HookFunction.class, "nested1AfterEachFn");
nested1Test1Fn = mock(TestFunction.class, "nested1Test1Fn");
nested1Test2Fn = mock(TestFunction.class, "nested1Test2Fn");
nested2BeforeFn = mock(HookFunction.class, "nested2BeforeFn");
nested2AfterFn = mock(HookFunction.class, "nested2AfterFn");
nested2BeforeEachFn = mock(HookFunction.class, "nested2BeforeEachFn");
nested2AfterEachFn = mock(HookFunction.class, "nested2AfterEachFn");
nested2Test1Fn = mock(TestFunction.class, "nested2Test1Fn");
nested2Test2Fn = mock(TestFunction.class, "nested2Test2Fn");
exception = new Exception();
root = defineTests(() -> {
describe("outer", () -> {
before("outerBefore1", outerBeforeFn1);
before("outerBefore2", outerBeforeFn2);
after("outerAfter1", outerAfterFn1);
after("outerAfter2", outerAfterFn2);
beforeEach("outerBeforeEach1", outerBeforeEachFn1);
beforeEach("outerBeforeEach2", outerBeforeEachFn2);
afterEach("outerAfterEach1", outerAfterEachFn1);
afterEach("outerAfterEach2", outerAfterEachFn2);
it("outerTest1", outerTest1Fn);
it("outerTest2", outerTest2Fn);
describe("nested1", () -> {
before("nested1Before", nested1BeforeFn);
after("nested1After", nested1AfterFn);
beforeEach("nested1BeforeEach", nested1BeforeEachFn);
afterEach("nested1AfterEach", nested1AfterEachFn);
it("nested1Test1", nested1Test1Fn);
it("nested1Test2", nested1Test2Fn);
});
describe("nested2", () -> {
before("nested2Before", nested2BeforeFn);
after("nested2After", nested2AfterFn);
beforeEach("nested2BeforeEach", nested2BeforeEachFn);
afterEach("nested2AfterEach", nested2AfterEachFn);
it("nested2Test1", nested2Test1Fn);
it("nested2Test2", nested2Test2Fn);
});
});
});
parentsOfOuter = Collections.singletonList(root);
outer = findTestBlock(root, "outer");
parentsOfOuterChildren = Arrays.asList(root, outer);
nested1 = findTestBlock(root, "nested1");
parentsOfNested1Children = Arrays.asList(root, outer, nested1);
nested2 = findTestBlock(root, "nested2");
parentsOfNested2Children = Arrays.asList(root, outer, nested2);
outerTest1 = findTest(root, "outerTest1");
outerTest2 = findTest(root, "outerTest2");
nested1Test1 = findTest(root, "nested1Test1");
nested1Test2 = findTest(root, "nested1Test2");
nested2Test1 = findTest(root, "nested2Test1");
nested2Test2 = findTest(root, "nested2Test2");
outerBefore1 = findHook(root, "outerBefore1");
outerAfter1 = findHook(root, "outerAfter1");
outerBefore2 = findHook(root, "outerBefore2");
outerAfter2 = findHook(root, "outerAfter2");
outerBeforeEach1 = findHook(root, "outerBeforeEach1");
outerAfterEach1 = findHook(root, "outerAfterEach1");
outerBeforeEach2 = findHook(root, "outerBeforeEach2");
outerAfterEach2 = findHook(root, "outerAfterEach2");
nested1Before = findHook(root, "nested1Before");
nested1After = findHook(root, "nested1After");
nested1BeforeEach = findHook(root, "nested1BeforeEach");
nested1AfterEach = findHook(root, "nested1AfterEach");
nested2Before = findHook(root, "nested2Before");
nested2After = findHook(root, "nested2After");
nested2BeforeEach = findHook(root, "nested2BeforeEach");
nested2AfterEach = findHook(root, "nested2AfterEach");
order = inOrder(reporter, outerBeforeFn1, outerBeforeFn2, outerAfterFn1, outerAfterFn2,
outerBeforeEachFn1, outerBeforeEachFn2, outerAfterEachFn1, outerAfterEachFn2, outerTest1Fn,
outerTest2Fn, nested1BeforeFn, nested1AfterFn, nested1BeforeEachFn, nested1AfterEachFn,
nested1Test1Fn, nested1Test2Fn, nested2BeforeFn, nested2AfterFn, nested2BeforeEachFn,
nested2AfterEachFn, nested2Test1Fn, nested2Test2Fn);
}
@AfterMethod
public void verifyNoMoreInteractionsWithMocks() {
verifyNoMoreInteractions(reporter, outerBeforeFn1, outerBeforeFn2, outerAfterFn1, outerAfterFn2,
outerBeforeEachFn1, outerBeforeEachFn2, outerAfterEachFn1, outerAfterEachFn2, outerTest1Fn,
outerTest2Fn, nested1BeforeFn, nested1AfterFn, nested1BeforeEachFn, nested1AfterEachFn,
nested1Test1Fn, nested1Test2Fn, nested2BeforeFn, nested2AfterFn, nested2BeforeEachFn,
nested2AfterEachFn, nested2Test1Fn, nested2Test2Fn);
}
@Test
public void verifyExecutionWithNoFailures() throws Exception {
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
verifyNormalNested1Execution();
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterTestFailure() throws Exception {
doThrow(exception).when(outerTest1Fn).apply();
runTests(root, reporter);
verifyStart();
verifyBlockHookPass(outerBefore1, parentsOfOuterChildren);
verifyBlockHookPass(outerBefore2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestFail(outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestPass(outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyNormalNested1Execution();
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterBeforeHookFailure() throws Exception {
setupHookFailure(outerBeforeFn1);
runTests(root, reporter);
verifyStart();
verifyBlockHookFail(outerBefore1, parentsOfOuterChildren);
verifyTestSkip(outerTest1, parentsOfOuterChildren);
verifyTestSkip(outerTest2, parentsOfOuterChildren);
verifySkipNested1Execution();
verifySkipNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterAfterHookFailure() throws Exception {
setupHookFailure(outerAfterFn1);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
verifyNormalNested1Execution();
verifyNormalNested2Execution();
verifyBlockHookFail(outerAfter1, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterBeforeEachHookFailure() throws Exception {
setupHookFailure(outerBeforeEachFn1);
runTests(root, reporter);
verifyStart();
verifyBlockHookPass(outerBefore1, parentsOfOuterChildren);
verifyBlockHookPass(outerBefore2, parentsOfOuterChildren);
verifyTestHookFail(outerBeforeEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestSkip(outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestSkip(outerTest2, parentsOfOuterChildren);
verifySkipNested1Execution();
verifySkipNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterBeforeEachHookFailureOnSecondCall() throws Exception {
setupHookFailure(outerBeforeEachFn1, 1);
runTests(root, reporter);
verifyStart();
verifyBlockHookPass(outerBefore1, parentsOfOuterChildren);
verifyBlockHookPass(outerBefore2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestPass(outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookFail(outerBeforeEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestSkip(outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifySkipNested1Execution();
verifySkipNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterBeforeEachHookFailureOnThirdCall() throws Exception {
setupHookFailure(outerBeforeEachFn1, 2);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookPass(nested1Before, parentsOfNested1Children);
verifyTestHookFail(outerBeforeEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test2, parentsOfNested1Children);
verifyBlockHookPass(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
verifySkipNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithOuterAfterEachHookFailure() throws Exception {
setupHookFailure(outerAfterEachFn1);
runTests(root, reporter);
verifyStart();
verifyBlockHookPass(outerBefore1, parentsOfOuterChildren);
verifyBlockHookPass(outerBefore2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestPass(outerTest1, parentsOfOuterChildren);
verifyTestHookFail(outerAfterEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestSkip(outerTest2, parentsOfOuterChildren);
verifySkipNested1Execution();
verifySkipNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithNested1BeforeHookFailure() throws Exception {
setupHookFailure(nested1BeforeFn);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookFail(nested1Before, parentsOfNested1Children);
verifyTestSkip(nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test2, parentsOfNested1Children);
verifyBlockHookPass(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithNested1AfterHookFailure() throws Exception {
setupHookFailure(nested1AfterFn);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookPass(nested1Before, parentsOfNested1Children);
verifyNested1TestPass(nested1Test1);
verifyNested1TestPass(nested1Test2);
verifyBlockHookFail(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithNested1BeforeEachHookFailure() throws Exception {
setupHookFailure(nested1BeforeEachFn);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookPass(nested1Before, parentsOfNested1Children);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookFail(nested1BeforeEach, parentsOfNested1Children, nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test1, parentsOfNested1Children);
verifyTestHookPass(nested1AfterEach, parentsOfNested1Children, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test2, parentsOfNested1Children);
verifyBlockHookPass(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
@Test
public void verifyExecutionWithNested1AfterEachHookFailure() throws Exception {
setupHookFailure(nested1AfterEachFn);
runTests(root, reporter);
verifyStart();
verifyNormalOuterExecution();
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookPass(nested1Before, parentsOfNested1Children);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(nested1BeforeEach, parentsOfNested1Children, nested1Test1, parentsOfNested1Children);
verifyTestPass(nested1Test1, parentsOfNested1Children);
verifyTestHookFail(nested1AfterEach, parentsOfNested1Children, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test2, parentsOfNested1Children);
verifyBlockHookPass(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
verifyNormalNested2Execution();
verifyBlockHookPass(outerAfter1, parentsOfOuterChildren);
verifyBlockHookPass(outerAfter2, parentsOfOuterChildren);
verifyEnd();
}
private void setupHookFailure(HookFunction f) throws Exception {
setupHookFailure(f, 0);
}
private void setupHookFailure(HookFunction f, int goodCalls) throws Exception {
doAnswer(new Answer() {
private int calls;
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
if (calls >= goodCalls) {
throw exception;
}
calls++;
return null;
}
}).when(f).apply();
}
private void verifyTestPass(org.forgerock.cuppa.model.Test test, List<TestBlock> parents)
throws Exception {
order.verify(reporter).testStart(test, parents);
order.verify(test.function.get()).apply();
order.verify(reporter).testPass(test, parents);
order.verify(reporter).testEnd(test, parents);
}
private void verifyTestFail(org.forgerock.cuppa.model.Test test, List<TestBlock> parents) throws Exception {
order.verify(reporter).testStart(test, parents);
order.verify(test.function.get()).apply();
order.verify(reporter).testFail(test, parents, exception);
order.verify(reporter).testEnd(test, parents);
}
private void verifyNormalOuterExecution() throws Exception {
verifyBlockHookPass(outerBefore1, parentsOfOuterChildren);
verifyBlockHookPass(outerBefore2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestPass(outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest1, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestPass(outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, outerTest2, parentsOfOuterChildren);
}
private void verifyNormalNested1Execution() throws Exception {
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyBlockHookPass(nested1Before, parentsOfNested1Children);
verifyNested1TestPass(nested1Test1);
verifyNested1TestPass(nested1Test2);
verifyBlockHookPass(nested1After, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
}
private void verifyNested1TestPass(org.forgerock.cuppa.model.Test test) throws Exception {
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, test, parentsOfNested1Children);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, test, parentsOfNested1Children);
verifyTestHookPass(nested1BeforeEach, parentsOfNested1Children, test, parentsOfNested1Children);
verifyTestPass(test, parentsOfNested1Children);
verifyTestHookPass(nested1AfterEach, parentsOfNested1Children, test, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, test, parentsOfNested1Children);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, test, parentsOfNested1Children);
}
private void verifyNormalNested2Execution() throws Exception {
order.verify(reporter).testBlockStart(nested2, parentsOfOuterChildren);
verifyBlockHookPass(nested2Before, parentsOfNested2Children);
verifyNested2TestPass(nested2Test1);
verifyNested2TestPass(nested2Test2);
verifyBlockHookPass(nested2After, parentsOfNested2Children);
order.verify(reporter).testBlockEnd(nested2, parentsOfOuterChildren);
}
private void verifyNested2TestPass(org.forgerock.cuppa.model.Test test) throws Exception {
verifyTestHookPass(outerBeforeEach1, parentsOfOuterChildren, test, parentsOfNested2Children);
verifyTestHookPass(outerBeforeEach2, parentsOfOuterChildren, test, parentsOfNested2Children);
verifyTestHookPass(nested2BeforeEach, parentsOfNested2Children, test, parentsOfNested2Children);
verifyTestPass(test, parentsOfNested2Children);
verifyTestHookPass(nested2AfterEach, parentsOfNested2Children, test, parentsOfNested2Children);
verifyTestHookPass(outerAfterEach1, parentsOfOuterChildren, test, parentsOfNested2Children);
verifyTestHookPass(outerAfterEach2, parentsOfOuterChildren, test, parentsOfNested2Children);
}
private void verifyStart() {
order.verify(reporter).start(root);
order.verify(reporter).testBlockStart(root, Collections.emptyList());
order.verify(reporter).testBlockStart(outer, parentsOfOuter);
}
private void verifyEnd() {
order.verify(reporter).testBlockEnd(outer, parentsOfOuter);
order.verify(reporter).testBlockEnd(root, Collections.emptyList());
order.verify(reporter).end();
}
private void verifySkipNested1Execution() throws Exception {
order.verify(reporter).testBlockStart(nested1, parentsOfOuterChildren);
verifyTestSkip(nested1Test1, parentsOfNested1Children);
verifyTestSkip(nested1Test2, parentsOfNested1Children);
order.verify(reporter).testBlockEnd(nested1, parentsOfOuterChildren);
}
private void verifySkipNested2Execution() throws Exception {
order.verify(reporter).testBlockStart(nested2, parentsOfOuterChildren);
verifyTestSkip(nested2Test1, parentsOfNested2Children);
verifyTestSkip(nested2Test2, parentsOfNested2Children);
order.verify(reporter).testBlockEnd(nested2, parentsOfOuterChildren);
}
private void verifyBlockHookPass(Hook hook, List<TestBlock> parents) throws Exception {
order.verify(reporter).blockHookStart(hook, parents);
order.verify(hook.function).apply();
order.verify(reporter).blockHookPass(hook, parents);
}
private void verifyTestHookPass(Hook hook, List<TestBlock> parents, org.forgerock.cuppa.model.Test test,
List<TestBlock> testParents) throws Exception {
order.verify(reporter).testHookStart(hook, parents, test, testParents);
order.verify(hook.function).apply();
order.verify(reporter).testHookPass(hook, parents, test, testParents);
}
private void verifyTestHookFail(Hook hook, List<TestBlock> parents, org.forgerock.cuppa.model.Test test,
List<TestBlock> testParents) throws Exception {
order.verify(reporter).testHookStart(hook, parents, test, testParents);
order.verify(hook.function).apply();
order.verify(reporter).testHookFail(hook, parents, test, testParents, exception);
order.verify(reporter).hookFail(hook, parents, exception);
}
private void verifyBlockHookFail(Hook hook, List<TestBlock> parents) throws Exception {
order.verify(reporter).blockHookStart(hook, parents);
order.verify(hook.function).apply();
order.verify(reporter).blockHookFail(hook, parents, exception);
order.verify(reporter).hookFail(hook, parents, exception);
}
private void verifyTestSkip(org.forgerock.cuppa.model.Test test, List<TestBlock> parents) {
order.verify(reporter).testSkip(test, parents);
}
}
| 48.919008
| 112
| 0.737566
|
60bc8b7583e5065dd25e3d9d70072f9bd63207f8
| 5,880
|
package sqlite.feature.optional.case4;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import com.abubusoft.kripton.android.KriptonLibrary;
/**
* <p>This is the content provider generated for {@link AppDataSource}</p>
*
* <h2>Content provider authority:</h2>
* <pre>com.abubusoft.kripton.example</pre>
*
* <h2>Supported query operations</h2>
* <table>
* <tr><th>URI</th><th>DAO.METHOD</th></tr>
* <tr><td><pre>content://com.abubusoft.kripton.example/artists/title/:id</pre></td><td>{@link DaoArtistImpl#selectTitleById0ForContentProvider}</td></tr>
* <tr><td><pre>content://com.abubusoft.kripton.example/artists/title2/:id</pre></td><td>{@link DaoArtistImpl#selectTitle2ById1ForContentProvider}</td></tr>
* </table>
*
*
*
*/
public class BindAppContentProvider extends ContentProvider {
/**
* <p>content provider's URI.</p>
* <pre>content://com.abubusoft.kripton.example</pre>
*/
public static final String URI = "content://com.abubusoft.kripton.example";
/**
* <p>datasource singleton</p>
*/
private static BindAppDataSource dataSource;
/**
* <p>Content provider authority</p>
*/
public static final String AUTHORITY = "com.abubusoft.kripton.example";
/**
* <p>URI matcher</p>
*/
private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* <p>Uri</p>
* <pre>content://com.abubusoft.kripton.example/artists/title/#</pre>
*/
private static final Uri URI_PATH_ARTIST_1 = Uri.parse(URI+"/artists/title/#");
/**
* <p>Uri</p>
* <pre>content://com.abubusoft.kripton.example/artists/title2/#</pre>
*/
private static final Uri URI_PATH_ARTIST_2 = Uri.parse(URI+"/artists/title2/#");
static final String PATH_ARTIST_1 = "artists/title/#";
static final String PATH_ARTIST_2 = "artists/title2/#";
static final int PATH_ARTIST_1_INDEX = 1;
static final int PATH_ARTIST_2_INDEX = 2;
/**
* <h2>URI standard</h2>
* <pre>content://com.abubusoft.kripton.example/artists/title/#</pre></p>
* <h2>URI with parameters</h2>
* <pre>content://com.abubusoft.kripton.example/artists/title/:id</pre>
*
* <p>Method associated to this URI is {@link DaoArtistImpl#selectTitleById0ForContentProvider}</p>
*/
public static final Uri URI_ARTIST_SELECT_TITLE_BY_ID = URI_PATH_ARTIST_1;
/**
* <h2>URI standard</h2>
* <pre>content://com.abubusoft.kripton.example/artists/title2/#</pre></p>
* <h2>URI with parameters</h2>
* <pre>content://com.abubusoft.kripton.example/artists/title2/:id</pre>
*
* <p>Method associated to this URI is {@link DaoArtistImpl#selectTitle2ById1ForContentProvider}</p>
*/
public static final Uri URI_ARTIST_SELECT_TITLE2_BY_ID = URI_PATH_ARTIST_2;
static {
sURIMatcher.addURI(AUTHORITY, PATH_ARTIST_1, PATH_ARTIST_1_INDEX);
sURIMatcher.addURI(AUTHORITY, PATH_ARTIST_2, PATH_ARTIST_2_INDEX);
}
/**
* <p>Create datasource and open database in read mode.</p>
*
* @see android.content.ContentProvider#onCreate()
*/
@Override
public boolean onCreate() {
if (KriptonLibrary.getContext()==null) {
KriptonLibrary.init(getContext());
}
dataSource = BindAppDataSource.getInstance();
dataSource.openWritableDatabase();
return true;
}
/**
* <p>Close database.</p>
*
* @see android.content.ContentProvider#shutdown()
*/
@Override
public void shutdown() {
super.shutdown();
dataSource.close();
}
/**
*
* <h2>Supported query operations</h2>
* <table>
* <tr><th>URI</th><th>DAO.METHOD</th></tr>
* <tr><td><pre>content://com.abubusoft.kripton.example/artists/title/:id</pre></td><td>{@link DaoArtistImpl#selectTitleById0ForContentProvider}</td></tr>
* <tr><td><pre>content://com.abubusoft.kripton.example/artists/title2/:id</pre></td><td>{@link DaoArtistImpl#selectTitle2ById1ForContentProvider}</td></tr>
* </table>
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
Cursor returnCursor=null;
switch (sURIMatcher.match(uri)) {
case PATH_ARTIST_1_INDEX: {
// URI: content://com.abubusoft.kripton.example/artists/title/:id
returnCursor=dataSource.getDaoArtist().selectTitleById0ForContentProvider(uri, projection, selection, selectionArgs, sortOrder);
break;
}
case PATH_ARTIST_2_INDEX: {
// URI: content://com.abubusoft.kripton.example/artists/title2/:id
returnCursor=dataSource.getDaoArtist().selectTitle2ById1ForContentProvider(uri, projection, selection, selectionArgs, sortOrder);
break;
}
default: {
throw new IllegalArgumentException("Unknown URI for SELECT operation: " + uri);
}
}
return returnCursor;
}
@Override
public Uri insert(Uri uri, ContentValues contentValues) {
throw new IllegalArgumentException("Unknown URI for DELETE operation: " + uri);
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection,
String[] selectionArgs) {
throw new IllegalArgumentException("Unknown URI for UPDATE operation: " + uri);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new IllegalArgumentException("Unknown URI for DELETE operation: " + uri);
}
@Override
public String getType(Uri uri) {
switch (sURIMatcher.match(uri)) {
case PATH_ARTIST_1_INDEX: {
return "vnd.android.cursor.dir/vnd.com.abubusoft.kripton.example.artist";
}
case PATH_ARTIST_2_INDEX: {
return "vnd.android.cursor.dir/vnd.com.abubusoft.kripton.example.artist";
}
}
throw new IllegalArgumentException("Unknown URI for getType operation: " + uri);
}
}
| 32.666667
| 158
| 0.692857
|
0ae6a2e04da277edd36fecafcb8c27e6a2ae5dbd
| 984
|
/*
* Copyright 2020 Google 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.google.tsunami.common.version;
import com.google.auto.value.AutoValue;
import com.google.errorprone.annotations.Immutable;
@Immutable(containerOf = "T")
@AutoValue
abstract class LessThanTestCase<T> {
abstract T smaller();
abstract T larger();
static <T> LessThanTestCase<T> create(T smaller, T larger) {
return new AutoValue_LessThanTestCase<>(smaller, larger);
}
}
| 31.741935
| 75
| 0.747967
|
5445d02aa9462292273473d7b9e342a86239e444
| 1,989
|
/**
* @license
* Copyright 2018, Instituto Federal do Rio Grande do Sul (IFRS)
*
* 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 edu.ifrs.cooperativeeditor.mail;
import javax.ejb.Stateless;
import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.JMSProducer;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* @author Rodrigo Prestes Machado
*/
@Stateless
public class EmailClient {
private static ConnectionFactory connectionFactory;
private static Queue queue;
public void sendEmail(String tile, String emails, String message, String startTime, String url) {
try {
InitialContext ic = new InitialContext();
connectionFactory = (ConnectionFactory) ic.lookup("java:jboss/DefaultJMSConnectionFactory");
queue = (Queue) ic.lookup("java:/jms/queue/CooperativeEditorEmailQueue");
JMSContext jmsContext = connectionFactory.createContext();
JMSProducer producer = jmsContext.createProducer();
MapMessage map = jmsContext.createMapMessage();
map.setString("tile", tile);
map.setString("emails", emails);
map.setString("message", message);
map.setString("startTime", startTime);
map.setString("url", url);
producer.send(queue, map);
} catch (NamingException | JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 31.078125
| 98
| 0.736551
|
09122b5c8ad0e9ec642bd85d63175b0c5ce507b9
| 2,643
|
package org.maxkey.util;
import java.util.Date;
import org.maxkey.util.DateUtils;
public class DateUtilsTest {
/**
* Main method for test.
*
* @param args
* @throws EncryptException
*/
public static void main(String[] args) throws Exception {
String stringValue = "20110610090519";
System.out.println(stringValue);
// System.out.println("Parse \"" + stringValue
// + "\" using format pattern \"" + DateUtils.FORMAT_DATE_DEFAULT
// + "\" with method \"DateUtils.parse()\", result: "
// + DateUtils.parse(stringValue));
// stringValue = "20080506";
// System.out.println("Parse \"" + stringValue
// + "\" using method \"DateUtils.tryParse()\", result: "
// + DateUtils.tryParse(stringValue));
// String s = DateUtils.getExchangeFormat(stringValue,FORMAT_DATE_YYYYMMDDHHMMSS,DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS);
// System.out.print("--->>>"+s);
// String str = "2011-08-09";
// System.out.println(UserPasswordUtil.decrypt("PVuyeIHtXnXv5oSPwPUug66w=="));
// System.out.println(DateUtils.getFormtPattern1ToPattern2(str, DateUtils.FORMAT_DATE_YYYY_MM_DD, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
// str = "aaa\r\nbbb";
// List<String> list = StringUtil.strToList(str, "\r\n");
// System.out.println(list.size());
// System.out.println(StringUtil.listToStr(null, ","));
// String value = "a,b,,c,,";
// System.out.println(value.split("\\,").length);
// System.out.println(StringUtil.removeSplit(value, ","));
// Class clazz = TmEmployeeUserInfo.class;
// Field field = clazz.getDeclaredField("spellName");
// System.out.println(field.getName());
// System.out.println(UserPasswordUtil.encrypt("oscwebadmin@163.com"));
//System.out.println(JCEnDecrypt.randomDecrypt("2AF5022B2E78478A9761FD3381BB"));
// System.out.println(JCEnDecrypt.randomEncrypt("aaa")); 41l2Iw4V
// String regEx="[1]{1}[3,5,8,6]{1}[0-9]{9}"; //��ʾa��f
// System.out.println(Pattern.compile(regEx).matcher("18258842633").find());
// Date lockoutDate = DateUtils.addDate(new Date(), 0, 30, 0); //解锁时间
// System.out.println(DateUtils.format(lockoutDate, DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
Date date = new Date();
System.out.println(DateUtils.format(DateUtils.addDate(date, 0, 0, 1, 0, 0, 0),DateUtils.FORMAT_DATE_YYYY_MM_DD_HH_MM_SS));
System.out.println(DateUtils.format(DateUtils.addMinutes(new Date(), Integer.parseInt("2")*1000),DateUtils.FORMAT_DATE_ISO_TIMESTAMP));
System.out.println(DateUtils.toUtc(date));
System.out.println(DateUtils.toUtcLocal("2015-11-04T16:00:22.875Z"));
System.out.println(DateUtils.toUtcLocal("2015-11-04T23:58:14.286+08:00"));
}
}
| 41.952381
| 143
| 0.707529
|
dcf564cd613031999fa9f9df392b64e46698d6dc
| 171
|
package de.vinado.wicket.participate.model;
/**
* @author Vincent Nadoll (vincent.nadoll@gmail.com)
*/
public enum Voice {
SOPRANO,
ALTO,
TENOR,
BASS
}
| 14.25
| 52
| 0.654971
|
0096ab41b3cf9178d41926d1e1a0a73010700f91
| 1,390
|
package ru.otus.domain;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Author {
private Long id;
@NotNull
@NotEmpty
@Size(max = 255)
private String name;
@NotNull
@NotEmpty
@Size(max = 255)
private String surname;
public Author() {
}
public Author(final Builder builder) {
this.id = builder.id;
this.name = builder.name;
this.surname = builder.surname;
}
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(final String surname) {
this.surname = surname;
}
@Override
public String toString() {
return "Author{" +
"id=" + id +
", name='" + name + '\'' +
", surname='" + surname + '\'' +
'}';
}
public static class Builder{
private Long id;
private String name;
private String surname;
public Builder id(final Long id){
this.id = id;
return this;
}
public Builder name(final String name){
this.name = name;
return this;
}
public Builder surname(final String surname){
this.surname = surname;
return this;
}
public Author build() {
return new Author(this);
}
}
}
| 16.352941
| 47
| 0.657554
|
22fba4c49005ad46917c6817a7b82ff3b40ca999
| 1,657
|
package nl.m4jit.framework.wsaccess.wswrapper;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* @author joris
*/
public abstract class XMLWSWrapper {
public static Document getDocument(String baseurl, String... paramaters) throws XMLWSWrapperException {
String paramatersstring = "";
for (String paramater : paramaters) {
String[] array = paramater.split("=");
String name = array[0];
String value = array[1];
//String value = URLEncoder.encode(array[1], "ISO-8859-1"); ??
paramatersstring += paramatersstring.startsWith("?") ? "&" : "?";
paramatersstring += name + "=" + value;
}
String urlstring = baseurl + paramatersstring;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
URL url = new URL(urlstring);
InputStream is = url.openStream();
Document doc = db.parse(is);
doc.getDocumentElement().normalize();
return doc;
} catch (ParserConfigurationException ex) {
throw new XMLWSWrapperException(ex);
} catch (IOException ex) {
throw new XMLWSWrapperException(ex);
} catch (SAXException ex) {
throw new XMLWSWrapperException(ex);
}
}
}
| 29.070175
| 107
| 0.623416
|
e09740565974e775be8ec9d8b38f7f14cf8826d3
| 5,661
|
/*
* Copyright 2009 Kantega AS
*
* 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 no.kantega.publishing.admin.multimedia.action;
import no.kantega.commons.exception.NotAuthorizedException;
import no.kantega.publishing.common.data.Multimedia;
import no.kantega.publishing.common.data.enums.MultimediaType;
import no.kantega.publishing.common.exception.ObjectInUseException;
import no.kantega.publishing.common.service.MultimediaService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
/**
* Controller for handling deletion of multimedia objects, i.e. files or folders.
*/
@Controller
@RequestMapping("/admin/multimedia/DeleteMultimedia.action")
public class DeleteMultimediaAction {
private static final String ERROR_VIEW = "/WEB-INF/jsp/admin/generic/popup-error.jsp";
private static final String BEFORE_DELETE_VIEW = "/WEB-INF/jsp/admin/multimedia/delete/confirmdelete.jsp";
private static final String CONFIRM_DELETE_VIEW = "/WEB-INF/jsp/admin/multimedia/reloadparent.jsp";
/**
* Ask if user wants to delete
* @param model MVC model
* @param itemIdToDelete id of the multimedia item (folder or file) to delete
* @param currentNavigateItem the item currently active in the navigator. May potentially be different from the item to
* delete if the user uses the context menu to select item to delete.
* @param request current http request.
* @return view asking the user to confirm or abort the delete action.
*/
@RequestMapping(method = RequestMethod.GET)
public String showConfirmDialog(Model model,
@RequestParam("id") Integer itemIdToDelete,
@RequestParam(required = false, defaultValue = "-1") Integer currentNavigateItem,
HttpServletRequest request) {
MultimediaService mediaService = new MultimediaService(request);
Multimedia mm = mediaService.getMultimedia(itemIdToDelete);
if (mm.getType() == MultimediaType.FOLDER) {
model.addAttribute("message", "aksess.confirmdeletefolder.text");
} else {
model.addAttribute("message", "aksess.confirmdelete.text");
}
model.addAttribute("multimedia", mm);
model.addAttribute("currentNavigateItem", currentNavigateItem);
return BEFORE_DELETE_VIEW;
}
/**
* Perform the actual delete operation.
* @param model MVC model
* @param itemIdToDelete id of the multimedia item (folder or file) to delete
* @param currentNavigateItem the item currently active in the navigator. May potentially be different from the item to
* delete if the user uses the context menu to select item to delete.
* @param request current http request.
* @return confirm view or error view if something happens, typically if an item is in use somewhere.
*/
@RequestMapping(method = RequestMethod.POST)
public String performDelete(Model model,
@RequestParam("id") Integer itemIdToDelete,
@RequestParam(required = false, defaultValue = "-1") Integer currentNavigateItem,
HttpServletRequest request) {
MultimediaService mediaService = new MultimediaService(request);
Multimedia mm = mediaService.getMultimedia(itemIdToDelete);
if (mm != null) {
// Go to the parent folder after deletion if attempting to delete the currently viewed folder,
// otherwise stay at the current folder.
int navigateTo = (currentNavigateItem == itemIdToDelete.intValue()) ? mm.getParentId() : currentNavigateItem;
model.addAttribute("navigateTo", navigateTo);
if (mm.getType() == MultimediaType.FOLDER && (mm.getNoFiles() + mm.getNoSubFolders()) > 0) {
try {
mediaService.deleteMultimediaFolder(itemIdToDelete);
} catch (NotAuthorizedException e) {
model.addAttribute("message", "aksess.confirmdelete.notauthorized");
return ERROR_VIEW;
}
} else {
try {
mediaService.deleteMultimedia(itemIdToDelete);
} catch (ObjectInUseException e) {
model.addAttribute("error", "feil.no.kantega.publishing.common.exception.ObjectInUseException");
return ERROR_VIEW;
} catch (NotAuthorizedException e) {
model.addAttribute("message", "aksess.confirmdelete.notauthorized");
return ERROR_VIEW;
}
}
}
model.addAttribute("message", "aksess.confirmdelete.multimedia.finished");
return CONFIRM_DELETE_VIEW;
}
}
| 46.785124
| 123
| 0.66914
|
9e57c289984a735a65362dbe4c1d327c9fbe1043
| 6,629
|
/*
* Copyright 2018 The Feast 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 feast.ingestion.service;
import com.google.protobuf.Empty;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import feast.core.CoreServiceGrpc;
import feast.core.CoreServiceProto.CoreServiceTypes.GetEntitiesRequest;
import feast.core.CoreServiceProto.CoreServiceTypes.GetEntitiesResponse;
import feast.core.CoreServiceProto.CoreServiceTypes.GetFeaturesRequest;
import feast.core.CoreServiceProto.CoreServiceTypes.GetFeaturesResponse;
import feast.core.CoreServiceProto.CoreServiceTypes.GetStorageRequest;
import feast.core.CoreServiceProto.CoreServiceTypes.GetStorageResponse;
import feast.core.CoreServiceProto.CoreServiceTypes.ListEntitiesResponse;
import feast.core.CoreServiceProto.CoreServiceTypes.ListFeaturesResponse;
import feast.core.CoreServiceProto.CoreServiceTypes.ListStorageResponse;
import feast.specs.EntitySpecProto.EntitySpec;
import feast.specs.FeatureSpecProto.FeatureSpec;
import feast.specs.StorageSpecProto.StorageSpec;
/** Class responsible for retrieving Feature, Entity, and Storage Spec from Core API. */
@Slf4j
public class CoreSpecService implements SpecService {
private final ManagedChannel channel;
private final CoreServiceGrpc.CoreServiceBlockingStub blockingStub;
public CoreSpecService(String uri) {
this(ManagedChannelBuilder.forTarget(uri));
}
public CoreSpecService(ManagedChannelBuilder<?> channelBuilder) {
channel = channelBuilder.usePlaintext(true).build();
blockingStub = CoreServiceGrpc.newBlockingStub(channel);
}
/**
* Get map of entity ID and {@link EntitySpec} from Core API, given a collection of entityId.
*/
public Map<String, EntitySpec> getEntitySpecs(Iterable<String> entityIds) {
GetEntitiesRequest request = GetEntitiesRequest.newBuilder().addAllIds(entityIds).build();
try {
GetEntitiesResponse response = blockingStub.getEntities(request);
return response
.getEntitiesList()
.stream()
.collect(Collectors.toMap(EntitySpec::getName, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getEntitySpecs: {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve entity spec", e);
}
}
/**
* Get all {@link EntitySpec} from Core API.
*/
public Map<String, EntitySpec> getAllEntitySpecs() {
try {
ListEntitiesResponse response = blockingStub.listEntities(Empty.getDefaultInstance());
return response
.getEntitiesList()
.stream()
.collect(Collectors.toMap(EntitySpec::getName, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getAllEntitySpecs: {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve entity spec", e);
}
}
/**
* Get map of {@link FeatureSpec} from Core API, given a collection of featureId.
*/
public Map<String, FeatureSpec> getFeatureSpecs(Iterable<String> featureIds) {
try {
GetFeaturesRequest request = GetFeaturesRequest.newBuilder().addAllIds(featureIds).build();
GetFeaturesResponse response = blockingStub.getFeatures(request);
return response
.getFeaturesList()
.stream()
.collect(Collectors.toMap(FeatureSpec::getId, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getFeatureSpecs: {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve feature specs", e);
}
}
/**
* Get all {@link FeatureSpec} available in Core API.
*/
public Map<String, FeatureSpec> getAllFeatureSpecs() {
try {
ListFeaturesResponse response = blockingStub.listFeatures(Empty.getDefaultInstance());
return response
.getFeaturesList()
.stream()
.collect(Collectors.toMap(FeatureSpec::getId, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getAllFeatureSpecs, {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve feature specs", e);
}
}
/**
* Get map of {@link StorageSpec} from Core API, given a collection of storageId.
*/
public Map<String, StorageSpec> getStorageSpecs(Iterable<String> storageIds) {
try {
GetStorageRequest request = GetStorageRequest.newBuilder().addAllIds(storageIds).build();
GetStorageResponse response = blockingStub.getStorage(request);
return response
.getStorageSpecsList()
.stream()
.collect(Collectors.toMap(StorageSpec::getId, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getStorageSpecs: {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve storage specs", e);
}
}
/**
* Get all {@link StorageSpec} from Core API.
*/
public Map<String, StorageSpec> getAllStorageSpecs() {
try {
ListStorageResponse response = blockingStub.listStorage(Empty.getDefaultInstance());
return response
.getStorageSpecsList()
.stream()
.collect(Collectors.toMap(StorageSpec::getId, Function.identity()));
} catch (StatusRuntimeException e) {
log.error("GRPC error in getAllStorageSpecs, {}", e.getStatus());
throw new SpecRetrievalException("Unable to retrieve storage specs", e);
}
}
/**
* Shutdown GRPC channel.
*/
public void shutdown() throws InterruptedException {
log.info("Shutting down CoreSpecService");
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
@AllArgsConstructor
public static class Builder implements SpecService.Builder {
private String uri;
@Override
public SpecService build() {
return new CoreSpecService(uri);
}
}
}
| 37.241573
| 97
| 0.72575
|
a94ade28f9039db9f588e4efd7eee2f2dde50342
| 431
|
package com.ncme.springboot.mapper;
import com.ncme.springboot.model.SystemExperts;
public interface SystemExpertsMapper {
int deleteByPrimaryKey(Integer id);
int insert(SystemExperts record);
int insertSelective(SystemExperts record);
SystemExperts selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(SystemExperts record);
int updateByPrimaryKey(SystemExperts record);
}
| 25.352941
| 59
| 0.763341
|
14bca575ef748b66928c360865de9c86af98143c
| 2,851
|
package net.haesleinhuepf.clijx.plugins;
import ij.measure.ResultsTable;
import net.haesleinhuepf.clij.clearcl.ClearCLBuffer;
import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum;
import net.haesleinhuepf.clij.macro.CLIJMacroPlugin;
import net.haesleinhuepf.clij.macro.CLIJOpenCLProcessor;
import net.haesleinhuepf.clij.macro.documentation.OffersDocumentation;
import net.haesleinhuepf.clij2.AbstractCLIJ2Plugin;
import net.haesleinhuepf.clij2.CLIJ2;
import net.haesleinhuepf.clij2.plugins.StatisticsOfLabelledPixels;
import net.haesleinhuepf.clij2.utilities.HasClassifiedInputOutput;
import net.haesleinhuepf.clij2.utilities.IsCategorized;
import org.scijava.plugin.Plugin;
@Plugin(type = CLIJMacroPlugin.class, name = "CLIJx_labelMaxiumIntensityMap")
public class LabelMaximumIntensityMap extends AbstractCLIJ2Plugin implements CLIJMacroPlugin, CLIJOpenCLProcessor, OffersDocumentation, IsCategorized, HasClassifiedInputOutput {
@Override
public String getInputType() {
return "Image, Label Image";
}
@Override
public String getOutputType() {
return "Image";
}
@Override
public String getParameterHelpText() {
return "Image input, Image label_map, ByRef Image destination";
}
@Override
public boolean executeCL() {
return labelMaximumIntensityMap(getCLIJ2(), (ClearCLBuffer) args[0], (ClearCLBuffer) args[1], (ClearCLBuffer) args[2]);
}
public static boolean labelMaximumIntensityMap(CLIJ2 clij2, ClearCLBuffer input, ClearCLBuffer label_map, ClearCLBuffer result) {
int number_of_labels = (int)clij2.maximumOfAllPixels(label_map);
ClearCLBuffer size_array = clij2.create(number_of_labels + 1,1, 1);
ResultsTable table = new ResultsTable();
clij2.statisticsOfBackgroundAndLabelledPixels(input, label_map, table);
clij2.pushResultsTableColumn(size_array, table, StatisticsOfLabelledPixels.STATISTICS_ENTRY.MAXIMUM_INTENSITY.toString());
// ignore background measurement
clij2.setColumn(size_array, 0, 0);
clij2.replaceIntensities(label_map, size_array, result);
size_array.close();
return true;
}
@Override
public ClearCLBuffer createOutputBufferFromSource(ClearCLBuffer input)
{
return getCLIJ2().create(input.getDimensions(), NativeTypeEnum.Float);
}
@Override
public String getDescription() {
return "Takes an image and a corresponding label map, determines the mean intensity per label and replaces every label with the that number.\n\nThis results in a parametric image expressing mean object intensity.";
}
@Override
public String getAvailableForDimensions() {
return "2D, 3D";
}
@Override
public String getCategories() {
return "Visualisation, Label, Measurement";
}
}
| 36.551282
| 222
| 0.750263
|
ed91112e521158c4f0e55d62eb165347a9a090a8
| 1,331
|
package com.lambdaschool.foundation.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "sections")
public class Section extends Auditable
{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long sectionid;
@Column(nullable = false,
unique = true)
private String sectionname;
@OneToMany(mappedBy = "section",
cascade = CascadeType.ALL)
@JsonIgnoreProperties(value = "section", allowSetters = true)
private List<Book> books = new ArrayList<>();
public Section()
{
}
public Section(String sectionname)
{
this.sectionname = sectionname;
}
public long getSectionid()
{
return sectionid;
}
public void setSectionid(long sectionid)
{
this.sectionid = sectionid;
}
public String getSectionname()
{
return sectionname;
}
public void setSectionname(String sectionname)
{
this.sectionname = sectionname;
}
public List<Book> getBooks()
{
return books;
}
public void setBooks(List<Book> books)
{
this.books = books;
}
@Override
public String toString()
{
return "Section{" + "sectionid=" + sectionid + ", sectionname='" + sectionname + '\'' + ", books=" + books + '}';
}
}
| 18.746479
| 117
| 0.672427
|
ce871e28104bf5609e56e6c3fb284cebd2607645
| 2,646
|
package me.majiajie.swipebacktest.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import me.majiajie.pagerbottomtabstrip.Controller;
import me.majiajie.pagerbottomtabstrip.PagerBottomTabLayout;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectListener;
import me.majiajie.swipebacktest.R;
import me.majiajie.swipebacktest.adapter.FragmentViewPagerAdapter;
import me.majiajie.swipebacktest.fragment.AFragment;
public class MainActivity extends BaseActivity
{
private Controller mController;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar(R.id.toolbar);
initBottomTab();
initViewPager();
initEvent();
setSwipeBackEnable(false);//设置不能边缘滑动返回
}
private void initBottomTab()
{
PagerBottomTabLayout bottomTabLayout = (PagerBottomTabLayout) findViewById(R.id.tab);
mController = bottomTabLayout.builder()
.addTabItem(android.R.drawable.ic_menu_camera, "相机")
.addTabItem(android.R.drawable.ic_menu_compass, "位置")
.addTabItem(android.R.drawable.ic_menu_search, "搜索")
.addTabItem(android.R.drawable.ic_menu_help, "帮助")
.build();
}
private void initViewPager()
{
List<Fragment> fragmentList = new ArrayList<>();
fragmentList.add(AFragment.newInstance("1"));
fragmentList.add(AFragment.newInstance("2"));
fragmentList.add(AFragment.newInstance("3"));
fragmentList.add(AFragment.newInstance("4"));
mViewPager = (ViewPager) findViewById(R.id.viewPager);
if(mViewPager != null)
{
mViewPager.setAdapter(new FragmentViewPagerAdapter(getSupportFragmentManager(), fragmentList));
}
}
private void initEvent()
{
mController.addTabItemClickListener(new OnTabItemSelectListener()
{
@Override
public void onSelected(int index, Object tag)
{
mViewPager.setCurrentItem(index,false);
}
@Override
public void onRepeatClick(int index, Object tag)
{
//重复选中
}
});
}
public void next(View v)
{
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
}
| 28.451613
| 107
| 0.663643
|
3491c41c1a7dab2e8935d74334264e274649017a
| 803
|
package com.zb.leetcode.leetcode;
import com.zb.leetcode.utils.P;
public class LC035 {
public static void main(String[] args) {
P.p("123");
// searchInsert(new int[]{1,3,4,7}, 2);
boolean flag = true;
}
public static int searchInsert(int[] nums, int target) {
if(null == nums || 0 == nums.length) {
return 0;
}
int left = 0;
int right = nums.length-1;
while(left < right && (right - left) > 1) {
int middle = (int)((left + right) / 2 + 0.5f);
if(target > nums[middle]) {
left = middle;
} else if(target < nums[middle]) {
right = middle;
} else {
return middle;
}
}
return right;
}
}
| 24.333333
| 60
| 0.469489
|
9e5f8961f4f97956901ea324bc06e00fd85aeb47
| 2,381
|
/*******************************************************************************
* Copyright 2016 ContainX and OpenStack4j
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.huawei.openstack4j.model.common.functions;
import com.google.common.base.Function;
import com.huawei.openstack4j.model.common.header.HeaderNameValue;
import com.huawei.openstack4j.model.common.header.Range;
/**
* Transforms a Header Range array into a single HeaderNameValue object
*
* @author Jeremy Unruh
*/
public class RangesToHeaderNameValue implements Function<Range[], HeaderNameValue> {
public static final RangesToHeaderNameValue INSTANCE = new RangesToHeaderNameValue();
@Override
public HeaderNameValue apply(Range[] input) {
if (input == null || input.length == 0)
return null;
if (input.length == 1)
return input[0].toHeader();
String name = input[0].toHeader().getName();
StringBuilder value = new StringBuilder(String.valueOf(input[0].toHeader().getValue()));
for (int i = 1; i < input.length; i++) {
value.append(",");
value.append(input[i].value());
}
return new HeaderNameValue(name, value.toString());
}
}
| 45.788462
| 96
| 0.48929
|
2f543ec4fa4f69773d98fc006a349053585172ce
| 2,415
|
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.projectWizard.importSources;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* @author nik
*/
public class JavaSourceRootDetectionUtilTest {
@Test
public void simple() {
assertPackageDetected("package p; \n" +
"class A {}", "p");
assertPackageDetected("package p; \n" +
"import java.util.Set;" +
"class A {}", "p");
assertPackageDetected("class A {}", "");
assertPackageDetected("import java.util.*;\n" +
"class A {}", "");
assertPackageDetected("invalid", null);
}
@Test
public void comments() {
assertPackageDetected("/* aa */ package p;", "p");
assertPackageDetected("// aa\n" +
"package p;", "p");
assertPackageDetected("/* a */ /* b */ package p;", "p");
assertPackageDetected("package /* a */ p;", "p");
assertPackageDetected("package p /* a */;", "p");
}
@Test
public void qualified() {
assertPackageDetected("package p.q;", "p.q");
assertPackageDetected("package p . q;", "p.q");
assertPackageDetected("package /* xxx */ p . q;", "p.q");
assertPackageDetected("package p . /* xxx */ q;", "p.q");
}
@Test
public void validPackageAnnotation() {
assertPackageDetected("@Deprecated package p.q;", "p.q");
assertPackageDetected("@java.lang.Deprecated package p.q;", "p.q");
assertPackageDetected("@Generated(\"text\") package p.q;", "p.q");
assertPackageDetected("@Generated( (\"text\") ) package p.q;", "p.q");
assertPackageDetected("@Generated((\"text\"), (\"text\")) package p.q;", "p.q");
assertPackageDetected("@Generated(\"text\")\n" +
"@Deprecated\n" +
"package p.q;", "p.q");
assertPackageDetected("@Deprecated/*aa*/ package p.q;", "p.q");
}
@Test
public void invalidPackageAnnotation() {
assertPackageDetected("@Deprecatedpackage p.q;", null);
assertPackageDetected("@javax.annotation.Generated(\"text\" package p.q;", null);
}
private static void assertPackageDetected(String text, String packageName) {
assertEquals(packageName, JavaSourceRootDetectionUtil.getPackageName(text));
}
}
| 36.590909
| 140
| 0.604969
|
b87b5c54b9036904b2c9098c4fd33be89d095de6
| 338
|
package com.advent.data;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
public class DataSet {
@JsonProperty
private List<String> data;
public List<String> getData() {
return data;
}
public void setData(List<String> data) {
this.data = data;
}
}
| 16.9
| 61
| 0.627219
|
55e86dae313afa99e953ba47c43e0c516b104d6f
| 9,132
|
// Copyright 2018 The Feed Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.feed.piet;
import static com.google.android.libraries.feed.common.Validators.checkNotNull;
import static com.google.android.libraries.feed.common.Validators.checkState;
import android.view.View;
import com.google.search.now.ui.piet.ElementsProto.BindingContext;
import com.google.search.now.ui.piet.PietProto.PietSharedState;
import com.google.search.now.ui.piet.PietProto.Stylesheet;
import com.google.search.now.ui.piet.PietProto.Template;
import java.util.List;
/**
* Methods to enable creation and binding of Templates.
*
* <p>This class creates and binds adapters for templates allowing for reuse of full template
* layouts as a unit. Release and recycling is handled by the ElementAdapterFactory.
*/
class TemplateBinder {
private final KeyedRecyclerPool<ElementAdapter<? extends View, ?>> templateRecyclerPool;
private final ElementAdapterFactory adapterFactory;
TemplateBinder(
KeyedRecyclerPool<ElementAdapter<? extends View, ?>> templateRecyclerPool,
ElementAdapterFactory adapterFactory) {
this.templateRecyclerPool = templateRecyclerPool;
this.adapterFactory = adapterFactory;
}
/** Higher-performance method that creates and binds an adapter for a template all at once. */
ElementAdapter<? extends View, ?> createAndBindTemplateAdapter(
TemplateAdapterModel model, FrameContext frameContext) {
// Create the template context for use in both create and bind
// This is a modestly expensive operation, and calling createTemplateAdapter followed by
// bindTemplateAdapter would do it twice.
FrameContext templateContext =
frameContext.createTemplateContext(model.getTemplate(), model.getBindingContext());
TemplateKey templateKey = makeTemplateKey(model, frameContext);
ElementAdapter<? extends View, ?> adapter = templateRecyclerPool.get(templateKey);
if (adapter == null) {
// Create new adapter
adapter =
adapterFactory.createAdapterForElement(model.getTemplate().getElement(), templateContext);
adapter.setKey(templateKey);
}
adapter.bindModel(model.getTemplate().getElement(), templateContext);
return adapter;
}
ElementAdapter<? extends View, ?> createTemplateAdapter(
TemplateAdapterModel model, FrameContext frameContext) {
TemplateKey templateKey = makeTemplateKey(model, frameContext);
ElementAdapter<? extends View, ?> adapter = templateRecyclerPool.get(templateKey);
if (adapter == null) {
// Make new FrameContext here
FrameContext templateContext =
frameContext.createTemplateContext(model.getTemplate(), model.getBindingContext());
// Create new adapter
adapter =
adapterFactory.createAdapterForElement(model.getTemplate().getElement(), templateContext);
adapter.setKey(templateKey);
}
return adapter;
}
void bindTemplateAdapter(
ElementAdapter<? extends View, ?> adapter,
TemplateAdapterModel model,
FrameContext frameContext) {
TemplateKey templateKey = makeTemplateKey(model, frameContext);
checkNotNull(adapter.getKey(), "Adapter key was null; not initialized correctly?");
checkState(
adapter.getKey() instanceof TemplateKey,
"bindTemplateAdapter only applicable for template adapters");
checkState(templateKey.equals(adapter.getKey()), "Template keys did not match");
FrameContext templateContext =
frameContext.createTemplateContext(model.getTemplate(), model.getBindingContext());
adapter.bindModel(model.getTemplate().getElement(), templateContext);
}
private static TemplateKey makeTemplateKey(
TemplateAdapterModel model, FrameContext frameContext) {
return new TemplateKey(
model.getTemplate(),
frameContext.getPietSharedStates(),
frameContext.getMediaQueryStylesheet(model.getTemplate()));
}
/**
* Determines whether two templates are compatible for recycling. We're going to call the hash
* code good enough for performance reasons (.equals() is expensive), and hope we don't get a lot
* of collisions.
*/
@SuppressWarnings({"ReferenceEquality", "EqualsUsingHashCode"})
static boolean templateEquals(/*@Nullable*/ Template template1, /*@Nullable*/ Template template2) {
if (template1 == template2) {
return true;
} else if (template1 == null || template2 == null) {
return false;
}
return template1.hashCode() == template2.hashCode();
}
/** Wrap the Template proto object as the recycler key. */
static class TemplateKey extends RecyclerKey {
private final Template template;
/*@Nullable*/ private final List<PietSharedState> pietSharedStates;
// If the Template references a Stylesheet that has MediaQueryConditions on it, it needs to be
// part of the key.
/*@Nullable*/ private final Stylesheet mediaQueryBasedStylesheet;
TemplateKey(
Template template,
/*@Nullable*/ List<PietSharedState> pietSharedStates,
/*@Nullable*/ Stylesheet mediaQueryBasedStylesheet) {
this.template = template;
this.pietSharedStates = pietSharedStates;
this.mediaQueryBasedStylesheet = mediaQueryBasedStylesheet;
}
/** Equals checks the hashCode of the component fields to avoid expensive proto equals. */
@SuppressWarnings({"ReferenceEquality", "EqualsUsingHashCode"})
@Override
public boolean equals(/*@Nullable*/ Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TemplateKey)) {
return false;
}
TemplateKey that = (TemplateKey) o;
// Check that Templates are equal
if (!templateEquals(template, that.template)) {
return false;
}
// Check that PietSharedStates are equal or both null
if (that.pietSharedStates == null ^ this.pietSharedStates == null) {
return false;
}
if (this.pietSharedStates != null
&& that.pietSharedStates != null
&& (this.pietSharedStates.size() != that.pietSharedStates.size()
|| this.pietSharedStates.hashCode() != that.pietSharedStates.hashCode())) {
return false;
}
// Check that stylesheets are equal or both null
if (that.mediaQueryBasedStylesheet == null ^ this.mediaQueryBasedStylesheet == null) {
return false;
}
if (this.mediaQueryBasedStylesheet != null
&& that.mediaQueryBasedStylesheet != null
&& this.mediaQueryBasedStylesheet.hashCode()
!= that.mediaQueryBasedStylesheet.hashCode()) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = template.hashCode();
result = 31 * result + (pietSharedStates != null ? pietSharedStates.hashCode() : 0);
result =
31 * result
+ (mediaQueryBasedStylesheet != null ? mediaQueryBasedStylesheet.hashCode() : 0);
return result;
}
}
static class TemplateAdapterModel {
private final Template template;
private final BindingContext bindingContext;
TemplateAdapterModel(Template template, BindingContext bindingContext) {
this.template = template;
this.bindingContext = bindingContext;
}
TemplateAdapterModel(
String templateId, FrameContext frameContext, BindingContext bindingContext) {
this.template =
checkNotNull(
frameContext.getTemplate(templateId), "Template was not found: %s", templateId);
this.bindingContext = bindingContext;
}
public Template getTemplate() {
return template;
}
BindingContext getBindingContext() {
return bindingContext;
}
@SuppressWarnings({"ReferenceEquality", "EqualsUsingHashCode"})
@Override
public boolean equals(/*@Nullable*/ Object o) {
if (this == o) {
return true;
}
if (!(o instanceof TemplateAdapterModel)) {
return false;
}
TemplateAdapterModel that = (TemplateAdapterModel) o;
return templateEquals(template, that.template)
&& (bindingContext == that.bindingContext
|| (bindingContext.getBindingValuesCount()
== that.bindingContext.getBindingValuesCount()
&& bindingContext.hashCode() == that.bindingContext.hashCode()));
}
@Override
public int hashCode() {
int result = template.hashCode();
result = 31 * result + bindingContext.hashCode();
return result;
}
}
}
| 36.094862
| 101
| 0.697
|
dbb5cef1c3d0088d09124117bf75de12dcde7d16
| 1,498
|
/*
* Copyright (C) 2015 Adam Huang <poisondog@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package poisondog.select;
import java.util.List;
import java.util.Random;
/**
* 輪盤選擇法
* @author Adam Huang
*/
public class Roulette implements Selector {
private Random mRandom;
/**
* Constructor
*/
public Roulette() {
mRandom = new Random();
}
/**
* Constructor
*/
public Roulette(long seed) {
mRandom = new Random(seed);
}
@Override
public Ball execute(List<Ball> participants) {
double sum = 0;
for (int i = 0; i < participants.size(); i++) {
sum += ((Ball) participants.get(i)).getKey();
}
double index = mRandom.nextDouble() * sum;
double current = 0;
for (int i = 0; i < participants.size(); i++) {
current += (participants.get(i)).getKey();
if (current > index) {
return participants.get(i);
}
}
return participants.get(participants.size() - 1);
}
}
| 25.389831
| 76
| 0.648198
|
df5838bb82cd562d7e6784d2fc6c260275c9649c
| 1,895
|
/*
* 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 persistencia.entidades;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
*
* @author User
*/
@Entity
@Table(name="produto_fornecedor")
public class Produto_fornecedor {
@Id
@GeneratedValue
private int codigo;
private String codigoFornecedor;
@ManyToOne
@JoinColumn(name = "produto")
private Produto produto;
@ManyToOne
@JoinColumn(name = "fornecedor")
private Fornecedor fornecedor;
public int getID() {
return codigo;
}
public void setID(int ID) {
this.codigo = ID;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getCodigoFornecedor() {
return codigoFornecedor;
}
public void setCodigoFornecedor(String codigoFornecedor) {
this.codigoFornecedor = codigoFornecedor;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
public Fornecedor getFornecedor() {
return fornecedor;
}
public void setFornecedor(Fornecedor fornecedor) {
this.fornecedor = fornecedor;
}
@Override
public String toString(){
return fornecedor.getNome();
}
}//Fim da classe
| 20.824176
| 79
| 0.673351
|
7452bb914751da68ffde13894a0d41c9f782f7c3
| 11,940
|
package org.firstinspires.ftc.teamcode.subsystems;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.HardwareMap;
import com.qualcomm.robotcore.util.ElapsedTime;
import com.qualcomm.robotcore.util.Range;
import org.firstinspires.ftc.robotcontroller.external.samples.HardwarePushbot;
import java.util.Timer;
import java.util.TimerTask;
/***
*
*/
public class MecanumDrive {
public DcMotorEx leftFrontDrive = null;
public DcMotorEx leftRearDrive = null;
public DcMotorEx rightFrontDrive = null;
public DcMotorEx rightRearDrive = null;
public HardwareMap hardwareMap = null;
private double turnAngleThres = 20;
private double goAngleThres = 5;
private double leftFrontPower=0.0;
private double leftRearPower=0.0;
private double rightFrontPower=0.0;
private double rightRearPower=0.0;
Timer timer = new Timer();
/* Declare OpMode members. */
private ElapsedTime runtime = new ElapsedTime();
static final double COUNTS_PER_MOTOR_REV = 560 ; // eg: TETRIX Motor Encoder
static final double DRIVE_GEAR_REDUCTION = 1.0 ; // This is < 1.0 if geared UP
static final double WHEEL_DIAMETER_INCHES = 100 / 25.4 ; // For figuring circumference
static final double COUNTS_PER_INCH = (COUNTS_PER_MOTOR_REV * DRIVE_GEAR_REDUCTION) /
(WHEEL_DIAMETER_INCHES * 3.1415);
static final double DRIVE_SPEED = 0.6;
static final double TURN_SPEED = 0.5;
public MecanumDrive() {
}
public void init(HardwareMap hardwareMap){
this.hardwareMap = hardwareMap;
leftFrontDrive= hardwareMap.get(DcMotorEx.class,"lf");
leftRearDrive= hardwareMap.get(DcMotorEx.class,"lr");
rightFrontDrive= hardwareMap.get(DcMotorEx.class,"rf");
rightRearDrive= hardwareMap.get(DcMotorEx.class,"rr");
leftFrontDrive.setDirection(DcMotorEx.Direction.REVERSE);
leftRearDrive.setDirection(DcMotorEx.Direction.REVERSE);
rightFrontDrive.setDirection(DcMotorEx.Direction.FORWARD);
rightRearDrive.setDirection(DcMotorEx.Direction.FORWARD);
}
public void initEncoder(){
leftFrontDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftRearDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightFrontDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
rightRearDrive.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
leftFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
leftRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
public void encoderDrive(double speed,
double leftTiles, double rightTiles,
double timeoutS) {
int lfTarget;
int lrTarget;
int rfTarget;
int rrTarget;
// Determine new target position, and pass to motor controller
lfTarget = leftFrontDrive.getCurrentPosition() + (int)(leftTiles * 24 * COUNTS_PER_INCH);
lrTarget = leftRearDrive.getCurrentPosition() + (int)(rightTiles * 24 * COUNTS_PER_INCH);
rfTarget = rightFrontDrive.getCurrentPosition() + (int)(rightTiles * 24 * COUNTS_PER_INCH);
rrTarget = rightRearDrive.getCurrentPosition() + (int)(rightTiles * 24 * COUNTS_PER_INCH);
leftFrontDrive.setTargetPosition(lfTarget);
leftRearDrive.setTargetPosition(lrTarget);
rightFrontDrive.setTargetPosition(rfTarget);
rightRearDrive.setTargetPosition(rrTarget);
// Turn On RUN_TO_POSITION
leftFrontDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
leftRearDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
rightFrontDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
rightRearDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
// reset the timeout time and start motion.
runtime.reset();
leftFrontDrive.setPower(Math.abs(speed));
leftRearDrive.setPower(Math.abs(speed));
rightFrontDrive.setPower(Math.abs(speed));
rightRearDrive.setPower(Math.abs(speed));
// keep looping while we are still active, and there is time left, and both motors are running.
// Note: We use (isBusy() && isBusy()) in the loop test, which means that when EITHER motor hits
// its target position, the motion will stop. This is "safer" in the event that the robot will
// always end the motion as soon as possible.
// However, if you require that BOTH motors have finished their moves before the robot continues
// onto the next step, use (isBusy() || isBusy()) in the loop test.
while ((runtime.seconds() < timeoutS) &&
(leftFrontDrive.isBusy() && leftRearDrive.isBusy() && rightFrontDrive.isBusy() && rightRearDrive.isBusy())) {
}
// Stop all motion;
leftFrontDrive.setPower(0);
leftRearDrive.setPower(0);
rightFrontDrive.setPower(0);
rightRearDrive.setPower(0);
// Turn off RUN_TO_POSITION
leftFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
leftRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
// sleep(250); // optional pause after each move
}
public void drive(double y, double x, double rotation, double timeInSecs) {
drive(y,x,rotation);
timer.schedule(new TaskStop(), (long) (timeInSecs*1000));
}
// public void initMotor("")
class TaskStop extends TimerTask {
@Override
public void run() {
stop();
}
}
/***
*
* @param y 前进后退;大于0向前,小于0向后;
* @param x 左右平移;大于0向右,小于0向左;
* @param rotation 左右旋转;大于0右转,小于0左转;
*/
public void drive(double y, double x, double rotation) {
// 计算四个轮子的速度值
leftFrontPower = y + x + rotation;
leftRearPower = y - x + rotation;
rightFrontPower = y - x - rotation;
rightRearPower = y + x - rotation;
// 速度数值归一化。 将他们按比例收缩到-1到1之间。
double maxMagnitude = Math.abs(leftFrontPower);
maxMagnitude = (Math.max(maxMagnitude, Math.abs(leftRearPower)));
maxMagnitude = (Math.max(maxMagnitude, Math.abs(rightFrontPower)));
maxMagnitude = (Math.max(maxMagnitude, Math.abs(rightRearPower)));
if (maxMagnitude > 1.0) {
leftFrontPower = leftFrontPower/maxMagnitude;
leftRearPower = leftRearPower/maxMagnitude;
rightFrontPower = rightFrontPower/maxMagnitude;
rightRearPower = rightRearPower/maxMagnitude;
}
rightFrontDrive.setPower(rightFrontPower);
leftFrontDrive.setPower(leftFrontPower);
rightRearDrive.setPower(rightRearPower);
leftRearDrive.setPower(leftRearPower);
}
/***
* 直行。
* @param speed 速度;
*/
public void go(double speed) {
drive(speed, 0, 0);
}
/**
* 按指定角度直行。
*
* @param speed 速度;
* @param targetAngle 目标角度;
* @param currentAngle 当前角度;
*/
public boolean go(double speed, double targetAngle, double currentAngle) {
if (Math.abs(speed) < 0.001) {
drive(0, 0, 0);
return true;
}
speed = Range.clip(speed, -1, 1);
if (Math.abs(speed) > 0.9)
speed *= 0.9;
double angle = currentAngle - targetAngle;
angle = Range.clip(angle, -goAngleThres, goAngleThres);
double angleDelta = (angle / goAngleThres) * 0.10;
drive(speed, 0, angleDelta);
return false;
}
/**
* 转弯
*
* @param speed 速度;
*/
public void turn(double speed) {
drive(0, 0, speed);
}
/**
* 转弯到指定角度
*
* @param speed 速度;
* @param targetAngle 目标角度;
* @param currentAngle 当前角度;
*/
public boolean turn(double speed, double targetAngle, double currentAngle) {
if (Math.abs(speed) < 0.001) {
drive(0, 0, 0);
return true;
}
double angleError = Range.clip((currentAngle-targetAngle), -turnAngleThres, turnAngleThres) / turnAngleThres;
drive(0, 0, Math.abs(speed) * angleError);
return Math.abs(targetAngle - currentAngle) < 1;
}
/**
* 平移
*
* @param speed 速度;
*/
public void drift(double speed) {
drive(0, speed, 0);
}
/**
* 平移;
*
* @param speed 速度;
* @param targetAngle 目标角度;
* @param currentAngle 当前角度;
*/
public boolean drift(double speed, double targetAngle, double currentAngle) {
if (Math.abs(speed) < 0.001) {
drive(0, 0, 0);
return true;
}
speed = Range.clip(speed, -1, 1);
if (Math.abs(speed) > 0.8)
speed *= 0.8;
double angleErr = currentAngle-targetAngle;
angleErr = Range.clip(angleErr, -goAngleThres, goAngleThres);
double angleDelta = (angleErr / goAngleThres) * 0.1;
drive(0, speed, angleDelta);
return false;
}
public void stop() {
drive(0, 0, 0);
}
/*
* Method to perfmorm a relative move, based on encoder counts.
* Encoders are not reset as the move is based on the current position.
* Move will stop if any of three conditions occur:
* 1) Move gets to the desired position
* 2) Move runs out of time
* 3) Driver stops the opmode running.
*/
public void goEncoder(double speed,
int leftFrontDistance, int leftRearDistance,
int rightFrontDistance, int rightRearDistance ) {
leftFrontDrive.setTargetPosition(leftFrontDrive.getCurrentPosition()+leftFrontDistance);
leftRearDrive.setTargetPosition(leftRearDrive.getCurrentPosition()+leftFrontDistance);
rightFrontDrive.setTargetPosition(rightFrontDrive.getCurrentPosition()+leftFrontDistance);
rightRearDrive.setTargetPosition(rightRearDrive.getCurrentPosition()+leftFrontDistance);
// Turn On RUN_TO_POSITION
leftFrontDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
leftRearDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
rightFrontDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
rightRearDrive.setMode(DcMotor.RunMode.RUN_TO_POSITION);
}
public void initDriveMode(){
leftFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
leftRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightFrontDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
rightRearDrive.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
}
public void loop(){
rightFrontDrive.setPower(rightFrontPower);
leftFrontDrive.setPower(leftFrontPower);
rightRearDrive.setPower(leftRearPower);
leftRearDrive.setPower(rightRearPower);
}
@Override
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("driver_power_rf="+rightFrontPower);
builder.append("driver_power_lf="+leftFrontPower);
builder.append("driver_power_lr="+leftRearPower);
builder.append("driver_power_rr="+rightRearPower);
return builder.toString();
}
}
| 35.963855
| 126
| 0.632161
|
a4c1809f006a73bbe9e787f6ce0545243dad3885
| 4,632
|
/*
* 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 co.edu.uniandes.csw.escarabajos.dtos;
import co.edu.uniandes.csw.escarabajos.entities.ModeloEntity;
/**
* ModeloDTO Objeto de transferencia de datos del modelo de la bicicleta. Los
* DTO contienen las representaciones de los JSON que se transfieren entre el
* cliente y el servidor.
*
* Al serializarse como JSON esta clase implementa el siguiente modelo: <br>
* <pre>
* {
* "id": number,
* "marca": String,
* "referencia": String,
* "calificacionMedia": double,
* "tipoModelo":String
*
* }
* </pre> Por ejemplo un modelo se representa asi:<br>
*
* <pre>
*
* {
* "id": 1,
* "marca": "BMXTREME",
* "referencia": "BMEXTREME-MTN-2017",
* "calificacionMedia": 4.50,
* "tipoModelo": "Accesorio"
* }
*
* </pre>
*
* @author Andres
*/
public class ModeloDTO {
/**
* Atributo que modela el id unico del modelo.
*/
private Long id;
/**
* Atributo que modela la marca del modelo.
*/
private String marca;
/**
* Atributo que modela la referencia del modelo.
*/
private String referencia;
/**
* Atributo que modela la calificacionMedia del modelo.
*/
private Double calificacionMedia;
/**
* Atributo que modela la el tipo de modelo.
*/
private String tipoModelo;
/**
* Constructor por defecto.
*/
public ModeloDTO() {
//empty
}
/**
* Conviertir Entity a DTO (Crea un nuevo DTO con los valores que recibe en
* la entidad que viene de argumento.
*
* @param modelo: Es la entidad que se va a convertir a DTO
*/
public ModeloDTO(ModeloEntity modelo) {
if (modelo != null) {
this.id = modelo.getId();
this.marca = modelo.getMarca();
this.referencia = modelo.getReferencia();
this.calificacionMedia = modelo.getCalificacionMedia();
this.tipoModelo = modelo.getTipoModelo();
}
}
//-----------------------------------------------------------
// Métodos
//-----------------------------------------------------------
/**
* Convertir DTO a Entity
*
* @return Un Entity con los valores del DTO
*/
public ModeloEntity toEntity() {
ModeloEntity entity = new ModeloEntity();
entity.setId(this.getId());
entity.setCalificacionMedia(this.getCalificacionMedia());
entity.setMarca(this.getMarca());
entity.setReferencia(this.getReferencia());
entity.setTipoModelo(this.getTipoModelo());
return entity;
}
/**
* Devuelve el id
*
* @return id
*/
public Long getId() {
return id;
}
/**
* Modifica el id
*
* @param id nuevo id
*/
public void setId(Long id) {
this.id = id;
}
/**
* Devuelve la marca
*
* @return marca
*/
public String getMarca() {
return marca;
}
/**
* Modifica la marca
*
* @param marca nueva marca
*/
public void setMarca(String marca) {
this.marca = marca;
}
/**
* Devuelve la referencia
*
* @return referencia
*/
public String getReferencia() {
return referencia;
}
/**
* Modifica la referencia
*
* @param referencia nueva referencia
*/
public void setReferencia(String referencia) {
this.referencia = referencia;
}
/**
* Devuelve calificacion media
*
* @return the calificacionMedia
*/
public Double getCalificacionMedia() {
return calificacionMedia;
}
/**
* Modifica calificacion media
*
* @param calificacionMedia nueva calificacionMedia
*/
public void setCalificacionMedia(Double calificacionMedia) {
this.calificacionMedia = calificacionMedia;
}
/**
* Devuelve el tipo de modelo
*
* @return tipoModelo
*/
public String getTipoModelo() {
return tipoModelo;
}
/**
* Modifica el tipo de modelo
*
* @param tipoModelo nuevo tipo de Modelo
*/
public void setTipoModelo(String tipoModelo) {
this.tipoModelo = tipoModelo;
}
}
| 23.632653
| 80
| 0.541235
|
2b0e71ead6648967fa582c20e2713120fa89df8f
| 2,544
|
/*
* Copyright © 2017-2018 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors.
* 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.
*
* Funding Source: Food and Drug Administration ("Funding Agency") effective 18 September 2014 as Contract no.
* HHSF22320140030I/HHSF22301006T (the "Prime Contract").
*
* 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 NON-INFRINGEMENT. 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 com.hphc.mystudies.bean;
/**
* @author BTC
*
*/
public class StudySessionBean {
private String isLive;
private String permission;
private Integer sessionStudyCount;
private String studyId;
/**
* @return the isLive
*/
public String getIsLive() {
return isLive;
}
/**
* @return the permission
*/
public String getPermission() {
return permission;
}
/**
* @return the sessionStudyCount
*/
public Integer getSessionStudyCount() {
return sessionStudyCount;
}
/**
* @return the studyId
*/
public String getStudyId() {
return studyId;
}
/**
* @param isLive
* the isLive to set
*/
public void setIsLive(String isLive) {
this.isLive = isLive;
}
/**
* @param permission
* the permission to set
*/
public void setPermission(String permission) {
this.permission = permission;
}
/**
* @param sessionStudyCount
* the sessionStudyCount to set
*/
public void setSessionStudyCount(Integer sessionStudyCount) {
this.sessionStudyCount = sessionStudyCount;
}
/**
* @param studyId
* the studyId to set
*/
public void setStudyId(String studyId) {
this.studyId = studyId;
}
}
| 26.5
| 113
| 0.712657
|
f3c118a0acfab3ccd723e4ca1c3a027b22d52e57
| 332
|
package reports.ex2.screen.entity.bookpublication;
import io.jmix.ui.screen.*;
import reports.ex2.entity.BookPublication;
@UiController("jmxrpr_BookPublication.edit")
@UiDescriptor("book-publication-edit.xml")
@EditedEntityContainer("bookPublicationDc")
public class BookPublicationEdit extends StandardEditor<BookPublication> {
}
| 33.2
| 74
| 0.834337
|
6505f8482320d59364902c9167c9f0adc8fbf586
| 4,909
|
/*
* Copyright 2009 Kantega AS
*
* 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 no.kantega.publishing.api.taglibs.security;
import no.kantega.commons.exception.SystemException;
import no.kantega.publishing.common.Aksess;
import no.kantega.publishing.common.service.TopicMapService;
import no.kantega.publishing.security.SecuritySession;
import no.kantega.publishing.security.data.Role;
import no.kantega.publishing.security.data.User;
import no.kantega.publishing.security.realm.SecurityRealm;
import no.kantega.publishing.topicmaps.data.Topic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.List;
import java.util.Map;
import static org.apache.commons.lang3.StringUtils.isBlank;
public class GetUserTag extends TagSupport {
private static final Logger log = LoggerFactory.getLogger(GetUserTag.class);
private static WebApplicationContext webApplicationContext;
private String name = "currentuser";
private String userid = null;
private boolean getRoles = false;
private boolean getRoleTopics = false;
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();
try {
if (webApplicationContext == null) {
webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletContext());
}
SecuritySession session = SecuritySession.getInstance(request);
User user = null;
if(!isBlank(userid)) {
try {
SecurityRealm realm = null;
Map<String,SecurityRealm> beansOfType = webApplicationContext.getBeansOfType(SecurityRealm.class);
for (SecurityRealm r : beansOfType.values()) {
user = r.lookupUser(userid);
if(user != null){
realm = r;
break;
}
}
if (user != null) {
if (getRoles || getRoleTopics) {
List<Role> roles = realm.lookupRolesForUser(user.getId());
for (Role role : roles) {
user.addRole(role);
}
if (getRoleTopics && Aksess.isTopicMapsEnabled()) {
// Hent topics for bruker
TopicMapService topicService = new TopicMapService(request);
if (user.getRoles() != null) {
for (Role role : roles) {
List<Topic> tmp = topicService.getTopicsBySID(role);
for (Topic aTmp : tmp) {
user.addTopic(aTmp);
}
}
}
}
}
}
} catch (SystemException e) {
user = null;
}
} else {
user = session.getUser();
}
if (user != null) {
request.setAttribute(name, user);
}
} catch (Exception e) {
log.error("Error setting user", e);
throw new JspTagException(e);
}
return SKIP_BODY;
}
public int doEndTag() throws JspException {
userid = null;
name = "currentuser";
return EVAL_PAGE;
}
public void setUserid(String userid) {
this.userid = userid;
}
public void setName(String name) {
this.name = name;
}
public void setGetroles(String getRoles) {
if ("true".equalsIgnoreCase(getRoles)) {
this.getRoles = true;
}
}
public void setGetroletopics(boolean getTopics) {
this.getRoleTopics = getTopics;
}
}
| 35.832117
| 125
| 0.572825
|
bbc4b073042669a5ae5c03d51d1caa18656aa882
| 12,969
|
package Main;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import dao.Dao;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Date;
import java.util.Enumeration;
import java.sql.ResultSet;
import java.util.regex.Pattern;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.plaf.FontUIResource;
public class StartPoint {
//定义一系列的JPanel 和需要的变量
private String p ;
private static Dao dao = new Dao() ;
private JFrame frame;
private JTextField name_text;
private JPasswordField passwordField;
private JLabel login_info ;
private JLabel lblNewLabel_1 ;
private JLabel lblNewLabel ;
private JButton login_button ;
private JButton reset_button ;
private JPanel login ;
private JFrame mainFrame ;
private left_menu left ;
private sale sale ;
private Time time ;
private Kc_manager kc_manager ;
private Stats stats ;
private person person ;
private String name ;
private Modify modify ;
private JDialog exit ;
private final JPanel contentPanel = new JPanel();
private JButton exit_button ;
private JButton cancel ;
private JLabel sure_exit ;
private JDialog modify_success ;
private final success_modify success = new success_modify() ;
private JDialog sale_tip ;
private final sale_success sale_success = new sale_success() ;
//判断一个字符串能否被转化为数字,用来对一些必须是数字的框进行检验
public static boolean isNumber(String str)
{
return str.matches("[0-9]+") ;
}
/**
* Launch the application.
*/
//设置字体
private static void initGlobalFont(){
FontUIResource fontUIResource = new FontUIResource(new Font("宋体",Font.PLAIN, 15));
for (Enumeration keys = UIManager.getDefaults().keys(); keys.hasMoreElements();) {
Object key = keys.nextElement();
Object value= UIManager.get(key);
if (value instanceof FontUIResource) {
UIManager.put(key, fontUIResource);
}
}
}
//主函数入口
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try
{
BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
UIManager.put("RootPane.setupButtonVisible", false);
}
catch(Exception e)
{
//TODO exception
}
try {
StartPoint window = new StartPoint();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public StartPoint() {
initGlobalFont() ;
initialize();
}
/**
* judge the username and password
* @param username
* @param password
* @return
*/
private static boolean judge(String username,String password){
ResultSet rs = dao.executeQuery("select username,password from Login_info") ;
try{
while(rs.next()){
if(rs.getString("username").trim().equals(username)&&rs.getString("password").trim().equals(password)){
return true ;
}
}
}catch(Exception e){
e.printStackTrace();
}
return false ;
}
/**
*
*/
public void exit(){
exit.setLayout(null);
exit.getContentPane().add(contentPanel);
contentPanel.setLayout(null);
contentPanel.setBounds(0, 0, 450, 300);
exit_button = new JButton("确 定") ;
exit_button.setBounds(80, 150, 80, 50);
contentPanel.add(exit_button) ;
cancel = new JButton("取 消") ;
cancel.setBounds(290, 150, 80, 50);
contentPanel.add(cancel) ;
sure_exit = new JLabel("真 的 要 退 出 吗 ?") ;
sure_exit.setBounds(145, 50, 200, 60);
contentPanel.add(sure_exit) ;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
sale_tip = new JDialog(mainFrame,true) ;
sale_tip.setLayout(null);
sale_tip.setBounds(750, 350, 450, 300);
sale_tip.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
sale_tip.setVisible(false);
sale_tip.getContentPane().add(sale_success);
modify_success = new JDialog(mainFrame,true) ;
modify_success.setLayout(null);
modify_success.setBounds(750, 350, 450, 300);
modify_success.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
modify_success.setVisible(false);
modify_success.getContentPane().add(success);
exit = new JDialog(mainFrame,true) ;
exit.setBounds(750, 350, 450, 300);
exit.setTitle("退出系统");
exit.setVisible(false);
exit.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
exit() ;
stats = new Stats(dao) ;
kc_manager = new Kc_manager(dao) ;
time = new Time() ;
sale = new sale(dao) ;
left = new left_menu() ;
mainFrame = new JFrame() ;
mainFrame.setLayout(null);
mainFrame.setBounds(400, 150, 1100, 700);
mainFrame.setTitle("库存管理系统V1.0");
frame = new JFrame();
frame.setTitle("登 录");
frame.setBounds(550, 200, 800, 600);
//frame.getContentPane().add(new left_menu()) ;
JPanel temp = new JPanel() ;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
name_text = new JTextField();
name_text.setBounds(300, 200, 198, 44);
name_text.setColumns(10);
login = new JPanel() ;
login.setLayout(null);
login.setBounds(0, 0, 800, 600);
temp.setLayout(null);
temp.setBounds(0, 0, 800, 600);
temp.add(name_text) ;
frame.getContentPane().add(login);
reset_button = new JButton("重 置");
reset_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
name_text.setText("");
passwordField.setText("");
login_info.setText("");
}
});
reset_button.setBounds(300, 318, 77, 36);
login_button = new JButton("登 陆");
login_button.setBounds(421, 318, 77, 36);
lblNewLabel = new JLabel("用户名");
lblNewLabel.setBounds(250, 200, 68, 44);
lblNewLabel_1 = new JLabel("密 码");
lblNewLabel_1.setBounds(250, 264, 68, 44);
passwordField = new JPasswordField();
passwordField.setBounds(300, 264, 198, 44);
login_info = new JLabel("");
login_info.setBounds(238, 360, 317, 44);
login.add(lblNewLabel) ;
login.add(lblNewLabel_1);
login.add(login_button) ;
login.add(login_info) ;
login.add(reset_button) ;
login.add(passwordField) ;
login.add(name_text) ;
this.action() ;
mainFrame.getContentPane().add(left) ;
mainFrame.getContentPane().add(sale) ;
mainFrame.getContentPane().add(time) ;
}
public void action(){
left.getSale_show().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
mainFrame.remove(stats);
mainFrame.remove(kc_manager);
mainFrame.remove(modify);
sale.setTemp(sale.getList().getSelectedItem().toString().trim());
sale.update();
mainFrame.getContentPane().add(sale) ;
mainFrame.repaint();
}
});
sale.getList().addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if(e.getStateChange()==ItemEvent.SELECTED){
String temp = sale.getList().getSelectedItem().toString() ;
sale.setTemp(temp);
sale.update();
sale.repaint();
}
}
});
left.getInout_show().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
mainFrame.remove(stats) ;
mainFrame.remove(sale);
mainFrame.remove(modify);
kc_manager.reupdate();
mainFrame.getContentPane().add(kc_manager) ;
mainFrame.repaint();
}
});
left.getSale_stats().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
stats.getList().addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if(e.getStateChange()==ItemEvent.SELECTED){
p = stats.getList().getSelectedItem().toString() ;
stats.update(p);
}
}
});
stats.list_update();
stats.update(stats.getList().getSelectedItem().toString().trim());
mainFrame.remove(kc_manager);
mainFrame.remove(sale);
mainFrame.remove(modify) ;
mainFrame.getContentPane().add(stats);
mainFrame.repaint();
}
});
left.getModify_password().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
mainFrame.remove(sale) ;
mainFrame.remove(kc_manager);
mainFrame.remove(stats);
mainFrame.getContentPane().add(modify) ;
mainFrame.repaint();
}
});
left.getExit_system().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
exit.setVisible(true);
}
});
exit_button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
cancel.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
exit.setVisible(false);
}
});
login_button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(judge(name_text.getText().trim(), String.valueOf(passwordField.getPassword()).trim())){
name = name_text.getText().trim() ;
person = new person(name) ;
if(modify==null){
modify = new Modify(name) ;
}
frame.setVisible(false);
mainFrame.getContentPane().add(person);
mainFrame.setVisible(true);
modify.getSure().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String old_pass = String.valueOf(modify.getOld().getPassword()).trim() ;
String new_pass = String.valueOf(modify.getNew().getPassword()).trim() ;
String re_new = String.valueOf(modify.getSure_password().getPassword()).trim() ;
if(!new_pass.equals("")){
if(judge(modify.getName().trim(),old_pass)){
if(new_pass.equals(re_new)){
dao.executeQuery("update Login_info set password = "+"'"+re_new+"'"+"where username="+"'"+modify.getName().trim()+"'") ;
modify_success.setVisible(true);
}
else{
modify.getTip().setText("提示:两次密码输入不一致,请检查后重试!");
modify.repaint();
}
}else{
modify.getTip().setText("提示:旧密码输入错误,请重新输入!");
modify.repaint();
}
}
else{
modify.getTip().setText("提示:新密码不能为空!");
modify.repaint();
}
}
});
}else{
login_info.setText("用户名或密码输入错误,请检查后重试");
}
}
});
sale.getSure().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String num = sale.getSale_num().getText().trim() ;
if(isNumber(num)){
int nums = Integer.valueOf(num) ;
int x = Integer.valueOf(sale.getNum().getText().trim()) ;
if(nums>x){
sale.getTip().setText("购买失败!超出库存");
sale.repaint();
}else{
int temp = x-nums ;
Date date = new Date() ;
String sql1 = "update Tb_kc set tb_nums="+String.valueOf(temp)+" where tb_title='"+
sale.getList().getSelectedItem().toString().trim()+"'" ;
dao.execute(sql1);
java.text.SimpleDateFormat fmt1 = new java.text.SimpleDateFormat("yyyy-MM-dd");
String sql = String.format("insert into Tb_Sale(id,tb_title,tb_nums,tb_value,tb_date) values(NULL,'"+
sale.getList().getSelectedItem().toString().trim()+"',"+String.valueOf(nums)+","+
String.valueOf(Float.valueOf(sale.getSingle_value().getText().trim())*(1.0)*nums)+",'"+
fmt1.format(date)+"')") ;
dao.execute(sql);
sale.getTip().setText("");
sale.repaint();
sale_tip.setVisible(true);
sale.setTemp(sale.getList().getSelectedItem().toString().trim());
sale.update();
sale.repaint();
}
}else{
sale.getTip().setText("购买失败!请检查非法字符");
sale.repaint();
}
}
});
sale_success.getBtnNewButton().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
sale_tip.setVisible(false);
}
});
}
}
| 26.685185
| 130
| 0.664739
|
7a3873331c15a2a291b814e05288a4fbcd97d4b2
| 776
|
package com.gostrange;
import java.util.ArrayList;
import java.util.List;
public class Actions {
private Position playerPossiblePosition;
private List<Position> removePossiblePositions;
public Actions() {
this.setPlayerPossiblePosition(null);
this.setRemovePossiblePositions(new ArrayList<Position>());
}
public List<Position> getRemovePossiblePositions() {
return removePossiblePositions;
}
public void setRemovePossiblePositions(List<Position> removePossiblePositions) {
this.removePossiblePositions = removePossiblePositions;
}
public Position getPlayerPossiblePosition() {
return playerPossiblePosition;
}
public void setPlayerPossiblePosition(Position playerPossiblePosition) {
this.playerPossiblePosition = playerPossiblePosition;
}
}
| 23.515152
| 81
| 0.80799
|
06a4a0b5642d4c80060e9ce307a167cfd23e141a
| 849
|
package com.github.switcherapi.client.model.criteria;
import java.util.Arrays;
/**
* @author Roger Floriano (petruki)
* @since 2019-12-24
*/
public class Domain extends SwitcherElement {
private String name;
private long version;
private Group[] group;
public Group[] getGroup() {
return group;
}
public void setGroup(Group[] group) {
this.group = group;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
@Override
public String toString() {
return String.format("Domain [name = %s, description = %s, activated = %s, version = %s, group = %s]",
name, description, activated, version, Arrays.toString(group));
}
}
| 15.436364
| 105
| 0.660777
|
c79b01e87a3f5166537125ff3e195cb947c5c0ad
| 1,610
|
/*
* 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.spark.network.shuffle.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.Assert.*;
public class FetchShuffleBlockChunksSuite {
@Test
public void testFetchShuffleBlockChunksEncodeDecode() {
FetchShuffleBlockChunks shuffleBlockChunks =
new FetchShuffleBlockChunks("app0", "exec1", 0, 0, new int[] {0}, new int[][] {{0, 1}});
Assert.assertEquals(2, shuffleBlockChunks.getNumBlocks());
int len = shuffleBlockChunks.encodedLength();
Assert.assertEquals(49, len);
ByteBuf buf = Unpooled.buffer(len);
shuffleBlockChunks.encode(buf);
FetchShuffleBlockChunks decoded = FetchShuffleBlockChunks.decode(buf);
assertEquals(shuffleBlockChunks, decoded);
}
}
| 37.44186
| 94
| 0.754037
|
32566fc42fff508e9d519a165230ac5c2054636b
| 1,196
|
package com.softlayer.api.example;
import com.softlayer.api.ApiClient;
import com.softlayer.api.RestApiClient;
/** Base class for all examples that parses the command-line arguments */
public abstract class Example {
public void start(String[] args) throws Exception {
// Args are username, api key, and (optional) base URL
if (args.length < 2 || args.length > 3) {
throw new RuntimeException("Username and api key required. Base URL can optionally be provided");
}
String baseUrl = args.length == 3 ? args[2] : RestApiClient.BASE_URL;
// Add trailing slash if not present
if (!baseUrl.endsWith("/")) {
baseUrl += '/';
}
RestApiClient client;
// mvn -e -q compile exec:java -Dexec.args="QuickTest Bearer eyJraWQ.....
if (args[0].trim().equals("Bearer")) {
client = new RestApiClient(baseUrl).withBearerToken(args[1]);
} else {
client = new RestApiClient(baseUrl).withCredentials(args[0], args[1]);
}
run(client);
}
/** Run the example with the given client */
public abstract void run(ApiClient client) throws Exception;
}
| 36.242424
| 109
| 0.62709
|
a557e0a739beedb5e5d75bbcc1384c8f4fdecc1c
| 262
|
package com.mysticcoders.mysticpaste.web.pages.history;
/**
* Created with IntelliJ IDEA.
* User: kinabalu
* Date: 3/10/14
* Time: 7:01 PM
* To change this template use File | Settings | File Templates.
*/
public class PopularPage extends HistoryPage {
}
| 21.833333
| 64
| 0.721374
|
a30b631c8565dc1fc59e5223eb5cbb477b20ebc4
| 4,703
|
package com.bfsi.mfi.vo;
import java.util.Date;
import com.bfsi.mfi.entity.DepositRedemptionTxnTracker;
public class DepositRedemptionTxnTrackerVO extends MaintenanceVO<DepositRedemptionTxnTracker>{
public DepositRedemptionTxnTrackerVO()
{
entity=new DepositRedemptionTxnTracker();
}
public DepositRedemptionTxnTrackerVO(DepositRedemptionTxnTracker entity) {
super(entity);
}
public String getMbsTxnId() {
return entity.getId();
}
public void setMbsTxnId(String mbsTxnId) {
entity.setId(mbsTxnId);
}
public String getAgendaId() {
return entity.getAgendaId();
}
public void setAgendaId(String agendaId) {
entity.setAgendaId(agendaId);
}
public String getTxnCode()
{
return entity.getTxnCode();
}
public void setTxnCode(String txnCode)
{
entity.setTxnCode(txnCode);
}
public long getSeqNo() {
return entity.getSeqNo();
}
public void setSeqNo(long seqNo) {
entity.setSeqNo(seqNo);
}
public String getCbsAcRefNo() {
return entity.getCbsAcRefNo();
}
public void setCbsAcRefNo(String cbsAcRefNo) {
entity.setCbsAcRefNo(cbsAcRefNo);
}
public String getBranchCode() {
return entity.getBranchCode();
}
public void setBranchCode(String branchCode) {
entity.setBranchCode(branchCode);
}
public String getCustomerId() {
return entity.getCustomerId();
}
public void setCustomerId(String customerId) {
entity.setCustomerId(customerId);
}
public String getCustomerFullName() {
return entity.getCustomerFullName();
}
public void setCustomerFullName(String customerFullName) {
entity.setCustomerFullName(customerFullName);
}
public String getAgentId() {
return entity.getAgentId();
}
public void setAgentId(String agentId) {
entity.setAgentId(agentId);
}
public String getAgentName() {
return entity.getAgentName();
}
public void setAgentName(String agentName) {
entity.setAgentName(agentName);
}
public String getLocationCode() {
return entity.getLocationCode();
}
public void setLocationCode(String locationCode) {
entity.setLocationCode(locationCode);
}
public String getLocationDesc() {
return entity.getLocationDesc();
}
public void setLocationDesc(String locationDesc) {
entity.setLocationDesc(locationDesc);
}
public Double getAmountPaidOut() {
return entity.getAmountPaidOut();
}
public void setAmountPaidOut(Double amountPaidOut) {
entity.setAmountPaidOut(amountPaidOut);
}
public String getTxnNarrative() {
return entity.getTxnNarrative();
}
public void setTxnNarrative(String txnNarrative) {
entity.setTxnNarrative(txnNarrative);
}
public Date getTxnInitTime() {
return entity.getTxnInitTime();
}
public void setTxnInitTime(Date txnInitTime) {
entity.setTxnInitTime(txnInitTime);
}
public Date getTxnSyncTime() {
return entity.getTxnSyncTime();
}
public void setTxnSyncTime(Date txnSyncTime) {
entity.setTxnSyncTime(txnSyncTime);
}
public String getTxnStatusDesc() {
return entity.getTxnStatusDesc();
}
public void setTxnStatusDesc(String txnStatusDesc) {
entity.setTxnStatusDesc(txnStatusDesc);
}
public Double getRedemptionAmount() {
return entity.getRedemptionAmount();
}
public void setRedemptionAmount(Double redemptionAmount) {
entity.setRedemptionAmount(redemptionAmount);
}
public String getTxnErrCode() {
return entity.getTxnErrCode();
}
public void setTxnErrCode(String txnErrCode) {
entity.setTxnErrCode(txnErrCode);
}
public String getTxnErrMessage() {
return entity.getTxnErrMessage();
}
public void setTxnErrMessage(String txnErrMessage) {
entity.setTxnErrMessage(txnErrMessage);
}
/*For Tag No : EGA-MN15-000021 Starts*/
public String getGeneratedSms() {
return entity.getGeneratedSms();
}
public void setGeneratedSms(String generatedSms) {
entity.setGeneratedSms(generatedSms);
}
public String getSmsMobileNo() {
return entity.getSmsMobileNo();
}
public void setSmsMobileNo(String smsMobileNo) {
entity.setSmsMobileNo(smsMobileNo);
}
public String getSmsContent() {
return entity.getGeneratedSms();
}
public void setSmsContent(String smsContent) {
entity.setSmsContent(smsContent);
}
public String getGeneratedRevr() {
return entity.getGeneratedRevr();
}
public void setGeneratedRevr(String generatedRevr) {
entity.setGeneratedRevr(generatedRevr);
}
public String getFullPartInd() {
return entity.getFullPartInd();
}
public void setFullPartInd(String fullPartInd) {
entity.setFullPartInd(fullPartInd);
}
public String getSyncType() {
return entity.getSyncType();
}
public void setSyncType(String syncType) {
entity.setSyncType(syncType);
}
/*For Tag No : EGA-MN15-000021 End*/
}
| 19.595833
| 95
| 0.750159
|
6d5e3a2bffc15ae415dbc9525adbc3516d686fc4
| 690
|
/**
* Atom interface
*/
package dimerconstr.containers.atom;
import dimerconstr.aux.math.Vector3d;
import dimerconstr.containers.molecule.IMolecule;
public interface IAtom {
//Get owner molecule
public IMolecule getMolecule();
//Set owner molecule
public void setMolecule(IMolecule molecule);
//Get intramolecular name
public String getName();
//Get atomic index
public Integer getIndex();
//Get van der Waals radius
public Double getVanDerWaalsRadius();
//Get atomic coordinates
public Vector3d getPosition();
//Set atomic coordinates
public void setPosition(Vector3d position);
//Get donor-acceptor marker (DAM)
public EDonorAcceptorMarker getDonorAcceptorMarker();
}
| 25.555556
| 54
| 0.781159
|
d4650484219776e261786ec3ec88f368a00708fd
| 2,540
|
package io.geekidea.springboot.assembly.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Builder;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* <p>
* Api响应对象
* </p>
*
* @author liujixiang
* @since 2018/12/28
*/
@Data
@Builder
public class ApiResult implements Serializable {
private static final String SUCCESS = "成功";
private static final String FAILED = "失败";
private static final String OPERATION_SUCCESS = "操作成功";
private static final String OPERATION_FAILED = "操作失败";
/**
* 响应码
*/
private Integer code;
/**
* 响应消息
*/
private String msg;
/**
* 响应数据
*/
private Object data;
/**
* 响应时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss:S")
private Date time;
/**
* 根据条件判断,返回操作结果
* @param flag
* @param msgPrefix
* @return
*/
public static ApiResult result(Boolean flag,String msgPrefix){
if (flag){
return ok(msgPrefix + SUCCESS);
}
return failed(msgPrefix + FAILED);
}
/**
* 操作成功
* @return
*/
public static ApiResult ok(){
return ok(null);
}
/**
* 操作成功
* @param msg
* @return
*/
public static ApiResult ok(String msg){
return ok(msg,null);
}
/**
* 操作成功
* @param data
* @return
*/
public static ApiResult ok(Object data){
return ok(null,data);
}
/**
* 操作成功
* @param msg
* @param data
* @return
*/
public static ApiResult ok(String msg,Object data){
if (msg == null){
msg = OPERATION_SUCCESS;
}
return ApiResult.builder().code(200).msg(msg).data(data).time(new Date()).build();
}
/**
* 操作失败
* @return
*/
public static ApiResult failed(){
return failed(null);
}
/**
* 操作失败
* @param msg
* @return
*/
public static ApiResult failed(String msg){
return failed(msg,null);
}
/**
* 操作失败
* @param data
* @return
*/
public static ApiResult failed(Object data){
return failed(null,data);
}
/**
* 操作失败
* @param msg
* @param data
* @return
*/
public static ApiResult failed(String msg,Object data){
if (msg == null){
msg = OPERATION_FAILED;
}
return ApiResult.builder().code(500).msg(msg).data(data).time(new Date()).build();
}
}
| 18.014184
| 90
| 0.537402
|
d4369c9f98169507d27d8f6385365a0387db82ac
| 419
|
package com.wenox.users.repository;
import com.wenox.users.domain.VerifyMailToken;
import java.util.UUID;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface VerifyMailTokenRepository extends CrudRepository<VerifyMailToken, UUID> {
VerifyMailToken findByToken(String token);
VerifyMailToken findByUserEmail(String email);
}
| 26.1875
| 90
| 0.840095
|
bdc858b64077084eb5095af88e3623f8fc4b7bae
| 3,726
|
package net.snapecraft.customserverutil_v3;
import net.snapecraft.customserverutil_v3.commands.*;
import net.snapecraft.customserverutil_v3.listener.JoinListener;
import net.snapecraft.customserverutil_v3.listener.QuitListener;
import net.snapecraft.customserverutil_v3.warp.WarpProtection;
import org.bukkit.plugin.java.JavaPlugin;
public class CustomServerUtilv3 extends JavaPlugin {
public static String getPrefix() {
return prefix;
}
public static final String prefix = "§7[§3Server§7]§5 > §r";
public static String getNoPerm() {
return noPerm;
}
public static final String noPerm = prefix + "§cDu hast nicht die nötige Berechtigung, um diesen Command auszuführen!";
public static CustomServerUtilv3 ins = null;
@Override
public void onEnable() {
ins = this;
System.out.println("\n\n\n _ _ _ _ _____ \n" +
" | | | | | | | | |____ |\n" +
" ___ _ _ ___| |_ ___ _ __ ___ | | ___ | |__ | |__ _ ___ __ / /\n" +
" / __| | | / __| __/ _ \\| '_ ` _ \\| |/ _ \\| '_ \\| '_ \\| | | \\ \\ / / \\ \\\n" +
"| (__| |_| \\__ \\ || (_) | | | | | | | (_) | |_) | |_) | |_| |\\ V /.___/ /\n" +
" \\___|\\__,_|___/\\__\\___/|_| |_| |_|_|\\___/|_.__/|_.__/ \\__, | \\_/ \\____/ \n" +
" __/ | \n" +
" |___/ \n\n\n");
registerConfig();
registerCommands();
registerListeners();
super.onEnable();
}
private void registerConfig() {
saveConfig();
reloadConfig();
getConfig().addDefault("joinmsg", true);
getConfig().addDefault("jointxt", "&7[&a+&7]&2 PLAYERNAME");
getConfig().addDefault("leavemsg", true);
getConfig().addDefault("leavetxt", "&7[&c-&7]&2 PLAYERNAME");
getConfig().options().copyDefaults(true);
saveConfig();
reloadConfig();
}
private void registerCommands() {
getCommand("tpa").setExecutor(new SendTpaCMD());
getCommand("tpaccept").setExecutor(new AcceptTpaCMD());
getCommand("tpdecline").setExecutor(new DeclineTpaCMD());
getCommand("home").setExecutor(new HomeCMD());
getCommand("sethome").setExecutor(new HomeCMD());
getCommand("s").setExecutor(new GameModeCMD());
getCommand("c").setExecutor(new GameModeCMD());
getCommand("sp").setExecutor(new GameModeCMD());
getCommand("sun").setExecutor(new SunCMD());
getCommand("day").setExecutor(new DayCMD());
getCommand("night").setExecutor(new NightCMD());
getCommand("heal").setExecutor(new HealCMD());
getCommand("fly").setExecutor(new FlyCMD());
getCommand("build").setExecutor(new BuildModeCMD());
getCommand("warp").setExecutor(new WarpCMD());
getCommand("setwarp").setExecutor(new SetWarpCMD());
getCommand("removewarp").setExecutor(new RemoveWarpCMD());
getCommand("spawn").setExecutor(new SpawnCMD());
}
private void registerListeners() {
getServer().getPluginManager().registerEvents(new JoinListener(), this);
getServer().getPluginManager().registerEvents(new QuitListener(), this);
getServer().getPluginManager().registerEvents(new WarpProtection(), this);
if(getServer().getPluginManager().getPlugin("Reset") != null){
}
}
public static CustomServerUtilv3 getInstance() {
return ins;
}
}
| 36.891089
| 123
| 0.555019
|
6820eca449c11f91ab7e447251369735f590f94d
| 1,649
|
/*
* 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.empire.spring;
import org.apache.empire.db.DBRecordData;
/**
* Interface used by {@link EmpireTemplate} for mapping
* {@link org.apache.empire.db.DBRecordData} to an Object.
*
* Typically it can be used to extract data from a DBReader, but without
* iterating over it, it is handled by EmpireTemplate.
*
* This class is the Empire equivalent of Spring's
* {@link org.springframework.jdbc.core.RowMapper}.
*
*/
public interface DBRecordMapper<K> {
/**
* Implementations must implement this method to map data in a DBRecordData.
*
* @param record
* the DBRecordData to map
* @param rowNum
* the number of the current row
* @return the result object
*/
public abstract K mapRecord(DBRecordData record, int rowNum);
}
| 32.98
| 78
| 0.704669
|
327be4e4fa99843cbbf59cf89c4a813fa4cb48f7
| 343
|
package com.websystique.springsecurity.service;
import java.util.Optional;
import org.springframework.security.core.userdetails.UserDetailsService;
import com.websystique.springsecurity.model.User;
public interface UserService extends UserDetailsService {
User findById(int id);
Optional<User> findBySso(String sso);
}
| 22.866667
| 73
| 0.787172
|
cfff1243f5531be463ca2aafce02a10bbe490ed5
| 4,309
|
package com.packleader.rapid.example.store.resources.v1;
import com.packleader.rapid.example.store.domain.Customer;
import com.packleader.rapid.example.store.domain.Order;
import com.packleader.rapid.example.store.services.CustomerService;
import com.packleader.rapid.example.store.services.OrderService;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;
@RequestMapping("v1/customers")
@Api(value = "v1/customers",
description = "Customers of the RAPID Store",
tags = {"CustomersResource"})
@RestController
public class CustomerResource {
@Autowired
private CustomerService customerService;
@Autowired
private OrderService orderService;
@RequestMapping(method = RequestMethod.GET, value = "{customerId}", produces = "application/json")
@ApiOperation(value = "Fetches a customer by their ID")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Found the customer"),
@ApiResponse(code = 404, message = "Customer was not found")
})
public Customer findCustomer(
@ApiParam(name = "customerId", required = true, value = "customer Id") @PathVariable("customerId") UUID customerId) {
return customerService.find(customerId);
}
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
@ApiOperation(value = "Fetches all customers")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Found the customers")
})
public List<Customer> findAllCustomers() {
return customerService.findAll();
}
@RequestMapping(method = RequestMethod.POST, produces = "application/json")
@ApiOperation(value = "Enrolls a new customer to the store")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Customer was successfully created")
})
public Customer createCustomer(
@ApiParam(name = "Customer", required = true, value = "Customer to enroll in the store") @RequestBody Customer customer,
HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_CREATED);
return customerService.create(customer);
}
@RequestMapping(method = RequestMethod.PUT, produces = "application/json")
@ApiOperation(value = "Updates an existing customer")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Customer was successfully updated"),
@ApiResponse(code = 404, message = "Customer was not found")
})
public Customer updateCustomer(
@ApiParam(name = "Customer", required = true, value = "Customer to update in the store") @RequestBody Customer customer) {
return customerService.update(customer);
}
@RequestMapping(method = RequestMethod.DELETE, value = "{customerId}", produces = "application/json")
@ApiOperation(value = "Deletes a customer from the store")
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Customer was successfully deleted"),
@ApiResponse(code = 404, message = "Customer was not found")
})
public void deleteCustomer(
@ApiParam(name = "customerId", required = true, value = "customer Id") @PathVariable("customerId") UUID customerId,
HttpServletResponse response) {
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
customerService.delete(customerId);
}
@RequestMapping(method = RequestMethod.GET, value = "{customerId}/orders", produces = "application/json")
@ApiOperation(value = "Fetches all orders for a customer")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Found the customer"),
@ApiResponse(code = 404, message = "Customer was not found")
})
public List<Order> findOrdersForCustomer(
@ApiParam(name = "customerId", required = true, value = "customer Id") @PathVariable("customerId") UUID customerId,
@ApiParam(name = "status", required = false, value = "status") @RequestParam(required = false) Order.Status status) {
return orderService.findByCustomerId(customerId, status);
}
}
| 45.357895
| 134
| 0.690647
|
4c3df287f41a57f6587811eb84533fe622f3531b
| 549
|
package io.github.emotionbug.jdbc.sshj;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author boky
*/
public class ConnectionData {
private static final Logger log = LoggerFactory.getLogger(ConnectionData.class);
final String ourUrl;
final String forwardingUrl;
public ConnectionData(String ourUrl, String forwardingUrl) {
this.ourUrl = ourUrl;
this.forwardingUrl = forwardingUrl;
}
public String getOurUrl() {
return ourUrl;
}
public String getForwardingUrl() {
return forwardingUrl;
}
}
| 18.931034
| 82
| 0.730419
|
e29089a2ad6bb367867b6e8b7b94f4d6d46c77ef
| 1,032
|
package com.idealista.android.sample.app.movies.presenter;
import com.idealista.android.elves.navigator.Navigator;
import com.idealista.android.elves.view.mvp.presenter.Presenter;
import com.idealista.android.sample.app.model.MovieModel;
import com.idealista.android.sample.app.movies.presenter.command.GetTitleCommand;
import com.idealista.android.sample.app.movies.presenter.command.MoviesCommands;
import com.idealista.android.sample.app.movies.view.MoviesView;
public class MoviesPresenter extends Presenter<MoviesView> {
private final MoviesCommands commands;
MoviesPresenter(MoviesView view, MoviesCommands commands) {
super(view);
this.commands = commands;
}
@Override
public void start() {
GetTitleCommand getTitleCommand = commands.titleCommand();
getTitleCommand.execute();
}
@Override
public void stop() {
}
public void onMovieClicked(MovieModel movie, Navigator<MovieModel> toMovieNavigator) {
toMovieNavigator.goTo(movie);
}
}
| 30.352941
| 90
| 0.754845
|
e6a24352e93f21da61088495041b8dcffde70434
| 4,214
|
package com.codepath.apps.restclienttemplate;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.codepath.apps.restclienttemplate.models.Tweet;
import com.codepath.asynchttpclient.callback.JsonHttpResponseHandler;
import org.parceler.Parcels;
import okhttp3.Headers;
public class ComposeActivity extends AppCompatActivity {
public static String TAG = "ComposeActivity";
public static int MAX_LENGTH_TWEET = 280;
Button btnTweet;
EditText etCompose;
TextView tvCharCount;
TwitterClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compose);
client = TwitterApplication.getRestClient(this);
btnTweet = findViewById(R.id.btnTweet);
etCompose = findViewById(R.id.etCompose);
tvCharCount = findViewById(R.id.tvCharCount);
tvCharCount.setTextColor(Color.BLUE);
//Add click listener to tweet button
btnTweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String tweetContent = etCompose.getText().toString();
if(tweetContent.isEmpty()){
Toast.makeText(ComposeActivity.this, "Tweet cannot be empty!", Toast.LENGTH_LONG).show();
}
if(tweetContent.length()>MAX_LENGTH_TWEET){
Toast.makeText(ComposeActivity.this, "Tweet cannot exceed 280 characters", Toast.LENGTH_LONG).show();
}
Toast.makeText(ComposeActivity.this, tweetContent, Toast.LENGTH_LONG);
//Make api call to twitter api
client.publishTweet(tweetContent, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Headers headers, JSON json) {
Log.i(TAG, "onSuccess "+TAG);
Tweet tweet = Tweet.fromJson(json.jsonObject);
Log.i(TAG, "published tweet "+ tweet.body);
Intent intent = new Intent();
//pass tweet back
intent.putExtra("tweet", Parcels.wrap(tweet));
setResult(RESULT_OK);
//close activity
finish();
}
@Override
public void onFailure(int statusCode, Headers headers, String response, Throwable throwable) {
Log.e(TAG, "onFailure compose publish tweet "+response, throwable);
}
});
}
});
//Add listener to compose
etCompose.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Fires right as the text is being changed (even supplies the range of text)
// Log.i(TAG, "i: "+i+" i1: "+i1+" i2: "+i2+" charSeq: "+charSequence);
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// Fires right before text is changing
// Log.i(TAG, "Before changing: i: "+i+" i1: "+i1+" i2: "+i2+" charSeq: "+charSequence);
int length = charSequence.length();
tvCharCount.setText(length+"/280");
if(length>280)
tvCharCount.setTextColor(Color.RED);
else
tvCharCount.setTextColor(Color.BLUE);
}
@Override
public void afterTextChanged(Editable editable) {
// Fires right after the text has changed
}
});
}
}
| 40.133333
| 121
| 0.594922
|
1d85b10c864efe7ca4ea24759efb146e0a4a928a
| 1,556
|
package lxy.liying.ipgw.post;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import java.net.UnknownHostException;
import lxy.liying.ipgw.url.IPGWUrl;
/**
* 断开全部连接
*
* @author 李颖
*/
class DisconnectAll {
private static Request<String> mRequest;
/**
* 静态方法,断开网络
*
* @param username 用户名
* @param password 密码
* @return 成功:Post结果,网页源代码。 失败:"提交数据失败"
*/
static String disconnectAll(String username, String password) throws UnknownHostException {
// 创建请求
mRequest = NoHttp.createStringRequest(IPGWUrl.POST_DISCONNECTALL_URL, RequestMethod.POST);
mRequest.setUserAgent("Mozilla/5.0 (Linux; Android 4.4.4; Nexus 5 Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.114 Mobile Safari/537.36");
mRequest.setAcceptLanguage("zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4");
mRequest.add("action", "logout")
.add("username", username)
.add("password", password)
.add("ajax", 1);
// 调用同步请求,直接拿到请求结果。
Response<String> response = NoHttp.startRequestSync(mRequest);
if (response.isSucceed()) {
return response.get();
} else {
return "";
}
}
/**
* 取消请求
*/
static void cancel() {
if (mRequest != null) {
mRequest.cancel();
}
}
}
| 27.298246
| 172
| 0.591902
|
41e5ce1072463ec419913359cec24e2f6dffce23
| 611
|
package pl.sdacademy.tarr2020java6.java.zaawansowana.klasy.standardowa;
import pl.sdacademy.tarr2020java6.java.zaawansowana.oop.zadanie1.animals.Animal;
import pl.sdacademy.tarr2020java6.java.zaawansowana.oop.zadanie1.plants.Plant;
/**
* @author : Jakub Olszewski [http://github.com/jakub-olszewski]
* @project : tarr2019java4-tdd-project
* @since : 17.05.2020
**/
public class Pies extends Animal {
public Pies(String name) {
super(name);
}
public void aport(Plant plant) {
System.out.println(getName()+ " aportuje "+plant.getClass().getSimpleName().toLowerCase());
}
}
| 29.095238
| 99
| 0.721768
|
f6c409d1852df8b0d8c3e1195f0eefaf1e495e6f
| 7,185
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.aws.greengrass.componentmanager.plugins.docker;
import com.aws.greengrass.componentmanager.exceptions.InvalidArtifactUriException;
import com.aws.greengrass.componentmanager.models.ComponentArtifact;
import com.aws.greengrass.logging.api.Logger;
import com.aws.greengrass.logging.impl.LogManager;
import com.aws.greengrass.util.Utils;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides utilities to interpret and validate a docker image artifact URI.
*
*/
public final class DockerImageArtifactParser {
public static final String INVALID_DOCKER_ARTIFACT_URI_MESSAGE = "Invalid Docker image artifact uri. "
+ "URI should follow the format of `docker:registry/image_name[:tag]|[@digest]`, "
+ "where registry, tag or digest are optional";
private static final Logger logger = LogManager.getLogger(DockerImageArtifactParser.class);
// Artifact URI follows docker's official grammar for registry-image spec
// Reference - https://github.com/distribution/distribution/blob/main/reference/reference.go#L6
// Example docker uri - docker:foo.bar:8080/path/to/image:v1.10
// Example domain - www.amazon-us.com:8080
private static final String DOMAIN_COMPONENT_REGEX = "([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])";
private static final String DOMAIN_REGEX =
String.format("(%s(\\.%s)*(:[0-9]+)?)", DOMAIN_COMPONENT_REGEX, DOMAIN_COMPONENT_REGEX);
private static final String PATH_COMPONENT_REGEX = "([a-z0-9]+)(([_.]|__|[-]*)([a-z0-9]+))*";
private static final String PATH_REGEX = String.format("(%s(/%s)*)", PATH_COMPONENT_REGEX, PATH_COMPONENT_REGEX);
private static final String DOCKER_ARTIFACT_REGEX_STRING = String.format(
"^docker:((?<registry>%s)/)?(?<imageName>%s)(?<imageVersion>(:(?<imageTag>[\\w.-]+)|"
+ "@(?<imageDigest>[\\w:.-]+)))?$", DOMAIN_REGEX, PATH_REGEX);
public static final Pattern DOCKER_ARTIFACT_REGEX_PATTERN = Pattern.compile(DOCKER_ARTIFACT_REGEX_STRING);
// More detailed regex for tag and digest
// Example tag - v1.12.1
private static final String IMAGE_TAG_REGEX = "([\\w][\\w.-]{0,127})";
private static final Pattern IMAGE_TAG_REGEX_PATTERN = Pattern.compile("^" + IMAGE_TAG_REGEX + "$");
// <algorithm+hex> ; example digest - @sha256:c4ffb87b09eba99383ee89b309d6d521
private static final String DIGEST_REGEX = "([A-Za-z][A-Za-z0-9]*:[0-9a-fA-F]{32,})";
private static final Pattern DIGEST_REGEX_PATTERN = Pattern.compile("^" + DIGEST_REGEX + "$");
private static List<String> PRIVATE_ECR_REGISTRY_IDENTIFIERS = Arrays.asList("dkr.ecr", "amazonaws");
private static String PUBLIC_ECR_REGISTRY_IDENTIFIER = "public.ecr.aws";
private DockerImageArtifactParser() {
}
/**
* Extract and image instance with image and registry details from an artifact URI, also validates the URI.
*
* @param artifact component artifact
* @return Image instance with image and registry details
* @throws InvalidArtifactUriException If URI validation against docker defined specification fails
*/
public static Image getImage(ComponentArtifact artifact) throws InvalidArtifactUriException {
// Valid docker uri is docker:registry/image_name:tag|@digest
Matcher matcher = DOCKER_ARTIFACT_REGEX_PATTERN.matcher(artifact.getArtifactUri().toString());
if (!matcher.find()) {
throw new InvalidArtifactUriException(INVALID_DOCKER_ARTIFACT_URI_MESSAGE);
}
String registryEndpoint = matcher.group("registry");
if (Utils.isEmpty(registryEndpoint)) {
// No registry specified, the default is docker hub's registry server
// e.g. ubuntu == library/ubuntu == docker.io/library/ubuntu == registry.hub.docker.com/library/ubuntu
registryEndpoint = "registry.hub.docker.com/library";
}
String imageName = matcher.group("imageName");
if (Utils.isEmpty(imageName)) {
throw new InvalidArtifactUriException(INVALID_DOCKER_ARTIFACT_URI_MESSAGE);
}
String imageTag = matcher.group("imageTag");
if (!Utils.isEmpty(imageTag)) {
Matcher tagMatcher = IMAGE_TAG_REGEX_PATTERN.matcher(imageTag);
if (!tagMatcher.find()) {
throw new InvalidArtifactUriException(
String.format("Image tag %s has invalid format, should follow regex " + IMAGE_TAG_REGEX,
imageTag));
}
}
String imageDigest = matcher.group("imageDigest");
if (!Utils.isEmpty(imageDigest)) {
Matcher digestMatcher = DIGEST_REGEX_PATTERN.matcher(imageDigest);
if (!digestMatcher.find()) {
throw new InvalidArtifactUriException(
String.format("Image digest %s has invalid format, should follow regex " + DIGEST_REGEX,
imageDigest));
}
}
String imageVersion = matcher.group("imageVersion");
if (Utils.isEmpty(imageVersion)) {
// No digest/tag specified, docker engine will pull the latest image
logger.atWarn().kv("artifact-uri", artifact.getArtifactUri())
.log("An image version is not present. Specify an image version via an image tag or digest to"
+ " ensure that the component is immutable and that the deployment will consistently "
+ "deliver the same artifacts");
imageTag = "latest";
}
return new Image(getRegistryFromArtifact(registryEndpoint), imageName, imageTag, imageDigest,
artifact.getArtifactUri());
}
private static Registry getRegistryFromArtifact(String endpoint) {
Registry.RegistryType type;
Registry.RegistrySource source;
if (endpoint.contains(PUBLIC_ECR_REGISTRY_IDENTIFIER)) {
source = Registry.RegistrySource.ECR;
type = Registry.RegistryType.PUBLIC;
} else if (containsAll(endpoint, PRIVATE_ECR_REGISTRY_IDENTIFIERS)) {
source = Registry.RegistrySource.ECR;
type = Registry.RegistryType.PRIVATE;
} else {
source = Registry.RegistrySource.OTHER;
// Currently all registries other than ECR are assumed to be public since
// we do not have support for private registries other than ECR.
// When we do support private non-ECR registries, this will need to be
// inferred based on additional component artifact attributes
type = Registry.RegistryType.PUBLIC;
}
return new Registry(endpoint, source, type);
}
private static boolean containsAll(String str, List<String> subStrs) {
for (String subStr : subStrs) {
if (!str.contains(subStr)) {
return false;
}
}
return true;
}
}
| 47.9
| 117
| 0.663605
|
d6474e1d01cbcc9f37dbf50a976826aabb7284f4
| 571
|
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.cli.picocli;
public class Print {
public static void errln(String string) {
// CHECKSTYLE:OFF
System.err.println(string);
// CHECKSTYLE:ON
}
public static void trace(Throwable e) {
// CHECKSTYLE:OFF
e.printStackTrace();
// CHECKSTYLE:ON
}
public static void outln(String string) {
// CHECKSTYLE:OFF
System.out.println(string);
// CHECKSTYLE:ON
}
}
| 21.148148
| 67
| 0.614711
|
1771f7fe0aa90c1c8bd2176f5d9c11a0ab2cb69c
| 517
|
package InversaoDeCor;
import static org.opencv.imgcodecs.Imgcodecs.IMREAD_COLOR;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class Manipular {
public static Mat abrirImagem(String path) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
return Imgcodecs.imread(path, IMREAD_COLOR);
}
public static Mat copiarImagem(Mat imagem) {
return imagem.clone();
}
public void salvarImagem(String path, Mat img) {
Imgcodecs.imwrite(path, img);
}
}
| 20.68
| 58
| 0.765957
|
7f2a6e837e9c78a510e1c9c239059b63d37f86dd
| 5,345
|
package com.zr.workflow.activiti.util;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
/**
* GFJsonUtil:<br/>
* 用 Gson 将bean转换Json确保数据的正确,<br/>
* 使用 FastJson 将Json转换Bean
* @author zhourq
*
*/
public class GFJsonUtil {
private Logger log = LoggerFactory.getLogger(GFJsonUtil.class);
private static volatile GFJsonUtil instance;
private GFJsonUtil() {}
public static GFJsonUtil get() {
if (instance == null) {
synchronized (GFJsonUtil.class) {
if (instance == null) {
instance = new GFJsonUtil();
}
}
}
return instance;
}
/**
* 将Object转换成json:
* @param obj
* @return
*/
public String toJson(Object obj) {
String json = toJson(obj,null);
return json;
}
/**
* 将Object转换成json:
* @param obj
* @param type 转换方式
* @return
*/
public String toJson(Object obj,String type) {
String json = "";
if(StringUtil.isEmpty(type)) {
json = toJsonByFastJson(obj);
}else {
json = toJsonByGson(obj);
}
return json;
}
/**
* 用Gson 将Object转换成json:
* 实体类中需要打印的字段需要加上注解@Expose
* @param obj
* @return
*/
public String toJsonByGson(Object obj) {
GsonBuilder gsonBuilder = new GsonBuilder();
// gsonBuilder.serializeNulls(); //序列化null值
//fixed Gson.toJson happened IllegalArgumentException: class xxx declares multiple JSON fields named key
// gsonBuilder.excludeFieldsWithoutExposeAnnotation(); 只序列化Expose注解字段
Gson gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
// /**
// * 用Gson批量添加json属性
// * @param jsonObj
// * @param resultMap
// * @return
// */
// public JsonObject addProperty(JsonObject jsonObj, Map<String, Object> resultMap) {
// Iterator<String> resultKeyIterator = resultMap.keySet().iterator();
// while (resultKeyIterator.hasNext()) {
// String key = (String) resultKeyIterator.next();
// Object value = resultMap.get(key);
// addProperty(jsonObj,key,value);
// }
// return jsonObj;
// }
//
// /**
// * 用Gson添加json属性
// * @param jsonObj
// * @param key
// * @param value
// */
// public void addProperty(JsonObject jsonObj, String key, Object value) {
// boolean isContains = jsonObj.has(key);
// if(isContains)jsonObj.remove(key);
// jsonObj.addProperty(key, toJson(value));
// }
//
/**
* 验证一个字符串是否是合法的JSON串
*
* @param json 要验证的字符串
* @return true-合法 ,false-非法
*/
public boolean validate(String json) {
if (StringUtils.isBlank(json)) {
return false;
}
try {
new JsonParser().parse(json);
return true;
} catch (JsonParseException e) {
log.error("json格式错误");
return false;
}
}
/**
* 用FastJson 将Object转换成json:
* @param obj
* @return
*/
public String toJsonByFastJson(Object obj) {
String json = JSON.toJSONString(obj,false);//不格式化
return json;
}
/**
* 用fastJson将json转为bean;
* @param json
* @param clazz
* @return
*/
public <T> T parseJson(String json,Class<T> clazz) {
return JSON.parseObject(json, clazz);
}
/**
* 将字符串转换为json数组
* @param jsonStr
* @return
*/
public JSONArray parseArray(String jsonStr) {
return JSON.parseArray(jsonStr);
}
/**
* 用fastJson获取json属性
* @param json
* @param paramKey
* @return
*/
public String getProperty(String json, String paramKey) {
JSONObject obj = JSON.parseObject(json);
return getProperty(obj, paramKey);
}
/**
* 用fastJson获取json属性
* @param obj
* @param paramKey
* @return
*/
public String getProperty(JSONObject obj, String paramKey) {
if(null == obj) return "";
Set<String> set = obj.keySet();
if(set.contains(paramKey)) {
return obj.get(paramKey) == null ? "" : obj.get(paramKey).toString();
}else {
return "";
}
}
/**
* 用fastJson获取json 对象属性
* @param json
* @param paramKey
* @return
*/
public JSONObject getJSONObject(String json, String paramKey) {
JSONObject obj = JSON.parseObject(json);
Set<String> set = obj.keySet();
if(set.contains(paramKey)) {
return obj.get(paramKey) == null ? null : (JSONObject)obj.get(paramKey);
}else {
return null;
}
}
/**
* 用fastJson获取json 数组属性
* @param json
* @param paramKey
* @return
*/
public JSONArray getJSONArray(String json, String paramKey) {
JSONObject obj = JSON.parseObject(json);
Set<String> set = obj.keySet();
if(set.contains(paramKey)) {
return obj.get(paramKey) == null ? null : (JSONArray)obj.get(paramKey);
}else {
return null;
}
}
/**
* 是否包含某元素
* @param json
* @param paramKey
* @return
*/
public boolean containsKey(String json, String paramKey) {
JSONObject obj = JSON.parseObject(json);
Set<String> set = obj.keySet();
if(set.contains(paramKey)) {
return true;
}else {
return false;
}
}
/**
* 用fastJson去除json 某属性
* @param json
* @param key
* @return
*/
public String remove(String json,String key) {
JSONObject obj = JSON.parseObject(json);
Set<String> set = obj.keySet();
if(set.contains(key)) {
set.remove(key);
json = obj.toString();
}
return json;
}
}
| 20.797665
| 106
| 0.656876
|
09ac7679d94627c318dfb45cbf20f09e5b55a0cc
| 1,804
|
package piza.otavio.cambadaforum.user;
public class User {
private String email; // User's email
private String login; // User's login
private String name; // User's name
private String password; // User's password
private int points = 0; // User's point
// Getters and Setters
/**
* Gets the email of the user
*
* @return the email of the user
*/
public String getEmail() {
return email;
}
/**
* Gets the login of the user
*
* @return the login of the user
*/
public String getLogin() {
return login;
}
/**
* Gets the name of the user
*
* @return the name of the user
*/
public String getName() {
return name;
}
/**
* Gets the user password
*
* @return the password of the user
*/
public String getPassword() {
return password;
}
/**
* Gets the points of the user
*
* @return the points of the user
*/
public int getPoints() {
return points;
}
/**
* Sets the email of the user
*
* @param email of the user
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Sets the login of the user
*
* @param login of the user
*/
public void setLogin(String login) {
this.login = login;
}
/**
* Sets the name of the user
*
* @param name of the user
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the password of the user
*
* @param password of the user
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Sets the points of the user
*
* @param points of the user
*/
public void setPoints(int points) {
this.points = points;
}
// Methods
/**
* Adds points to the user
*
* @param points to be added
*/
public void addPoints(int points) {
this.points += points;
}
}
| 16.4
| 44
| 0.613636
|
6b55a04a4dee156b6fb4e3401396c74d80e3a205
| 12,187
|
package org.concord.energy3d.agents;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import org.concord.energy3d.gui.MainFrame;
import org.concord.energy3d.undo.AddPartCommand;
import org.concord.energy3d.undo.AdjustThermostatCommand;
import org.concord.energy3d.undo.ChangeBuildingUValueCommand;
import org.concord.energy3d.undo.ChangeCityCommand;
import org.concord.energy3d.undo.ChangeDateCommand;
import org.concord.energy3d.undo.ChangePartColorCommand;
import org.concord.energy3d.undo.ChangePartUValueCommand;
import org.concord.energy3d.undo.EditPartCommand;
import org.concord.energy3d.undo.MovePartCommand;
import org.concord.energy3d.undo.PastePartCommand;
import org.concord.energy3d.undo.RemovePartCommand;
import org.concord.energy3d.undo.RotateBuildingCommand;
import org.concord.energy3d.util.Util;
/**
* @author Charles Xie
*
*/
public class EventMinerSheet2 implements Agent {
String eventString;
private final String name;
private final Map<String, Feedback> warnings;
private final Map<String, Feedback> reminders;
private final Map<String, Feedback> mustdos;
private final String validationRegex;
private final List<Feedback> progressFeedback;
static List<Class<?>> observers = new ArrayList<Class<?>>();
static {
observers.add(AnalysisEvent.class);
observers.add(DataCollectionEvent.class);
observers.add(ChangePartUValueCommand.class);
observers.add(ChangeBuildingUValueCommand.class);
observers.add(ChangeDateCommand.class);
observers.add(ChangeCityCommand.class);
observers.add(ChangePartColorCommand.class);
observers.add(AddPartCommand.class);
observers.add(EditPartCommand.class);
observers.add(PastePartCommand.class);
observers.add(RemovePartCommand.class);
observers.add(MovePartCommand.class);
observers.add(RotateBuildingCommand.class);
observers.add(AdjustThermostatCommand.class);
}
public EventMinerSheet2(final String name) {
this.name = name;
// cases that we can immediately decide the feedback
mustdos = new LinkedHashMap<String, Feedback>();
mustdos.put("A+?", new Feedback(JOptionPane.INFORMATION_MESSAGE, false, "Try analyzing the energy use of the house using the menu<br>Analysis > Buildings > Dail Energy Analysis for Selected Building..."));
mustdos.put("#{2,}", new Feedback(JOptionPane.QUESTION_MESSAGE, false, "Do you want to collect the U-value of the selected wall and the energy result<br>following the analysis and type it in the table?"));
mustdos.put("W+?", new Feedback(JOptionPane.INFORMATION_MESSAGE, false, "Your task is to investigate how changing the U-value of a wall affects the energy use of the house.<br>Right-click a wall and select \"Insulation...\" from the popup menu to change its U-value. Don't apply<br>the change to all walls."));
// warnings upon the occurrence of the specified events
warnings = new LinkedHashMap<String, Feedback>();
warnings.put("[C]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You changed the location. As each location has a different climate,<br>changing the location may affect the result of energy use."));
warnings.put("[D]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You changed the date. As each date has different weather conditions,<br>changing the date may affect the result of energy use."));
warnings.put("[L]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You changed the color of some part of the house. As the color of a house may affect its absorption of solar energy,<br>changing the color may affect the result of energy use."));
warnings.put("[P]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "Modification of the house (other than the U-value) is not recommended for this investigation<br>as it may interfere with the effect of the U-value on energy use."));
warnings.put("[R]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You changed the U-value of an object that is not a wall.<br>In this investigation, you should select a wall and change only its U-value."));
warnings.put("[T]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "Adjusting the thermostat is not recommended for this investigation<br>as it may interfere with the effect of the U-value on energy use."));
warnings.put("[U]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You changed the U-values of all walls.<br>In this investigation, you should select a wall and change only its U-value."));
warnings.put("[Y]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "You ran an annual energy analysis.<br>In this investigation, you should run only daily energy analyses."));
warnings.put("[Z]+?", new Feedback(JOptionPane.WARNING_MESSAGE, false, "Rotation of the house is not recommended for this investigation<br>as it may interfere with the effect of the U-value on energy use."));
// reminders upon the absence of the specified events
reminders = new LinkedHashMap<String, Feedback>();
reminders.put("#{2,}", new Feedback(JOptionPane.QUESTION_MESSAGE, true, "Do you want to collect the U-value of the selected wall and the energy result<br>of the No. {ANALYSIS_NUMBER} analysis and type it in the table?"));
// compound regex
String violations = "";
for (final String x : warnings.keySet()) {
violations += x.substring(x.indexOf('[') + 1, x.lastIndexOf(']'));
}
validationRegex = "(A([^" + violations + "]*?W+?[^" + violations + "]*?)(?=A))+?";
// instruction for progress
progressFeedback = new ArrayList<Feedback>();
progressFeedback.add(new Feedback(JOptionPane.INFORMATION_MESSAGE, false, "You have only run a valid daily energy analysis.<br>You need to run at least two such analyses."));
progressFeedback.add(new Feedback(JOptionPane.QUESTION_MESSAGE, false, "You have run two valid analyses. Did you compare the results to find the relationship<br>between the difference in energy use and the change of the U-value?"));
progressFeedback.add(new Feedback(JOptionPane.QUESTION_MESSAGE, false, "You have run {COUNT_PATTERN} valid analyses. What relationship between the energy use<br>of the house and the U-value of the wall did you find?"));
}
@Override
public void sense(final MyEvent e) {
eventString = EventUtil.eventsToString(observers, 10000, null);
System.out.println(this + " Sensing:" + e.getName() + ">>> " + eventString);
}
@Override
public void actuate() {
System.out.println(this + " Actuating: " + eventString);
Feedback f = null;
for (final String regex : mustdos.keySet()) { // check the must-do's first
if (Util.countMatch(Pattern.compile(regex).matcher(eventString)) == 0) {
f = mustdos.get(regex);
break;
}
}
if (f == null) {
final String[] segments = eventString.split("A+?"); // if no A is found, the entire event string is the only segment returned
if (segments != null && segments.length > 0) {
f = getFeedbackSingleCharacter(segments, warnings); // prioritize warnings
if (f == null) {
f = getFeedbackMultiCharacter(segments, reminders); // if there is no warning, check reminders
}
if (f == null) { // if no warning or reminder is found, check progress
boolean latestHandled = false;
String latestSegment;
if (segments.length == 1) {
latestSegment = eventString;
} else {
latestSegment = segments[segments.length - 1];
}
if (latestSegment.indexOf('W') != -1) {
latestHandled = true;
f = new Feedback(JOptionPane.QUESTION_MESSAGE, false, "Looks like that you have adjusted the U-value.<br>Do you want to follow up with an analysis?");
}
if (!latestHandled) {
String s = "";
for (int i = 0; i < segments.length - 1; i++) {
s += segments[i] + 'A';
}
final int count = Util.countMatch(Pattern.compile(validationRegex).matcher(s));
// System.out.println(">>>" + s + " = " + count + ", " + validationRegex);
f = progressFeedback.get(Math.min(count, progressFeedback.size() - 1));
f.setCustomMessage(f.getMessage().replaceAll("\\{COUNT_PATTERN\\}", (count + 1) + ""));
}
}
}
}
final String msg = f == null ? "Oops, I am embarrassed, but I have no advice." : f.getCustomMessage();
JOptionPane.showMessageDialog(MainFrame.getInstance(), "<html>" + msg + "</html>", "Advice", f == null ? JOptionPane.PLAIN_MESSAGE : f.getType());
}
// This applies to only single-character indicators
private Feedback getFeedbackSingleCharacter(final String[] segments, final Map<String, Feedback> map) {
// Forgive the starter (meaning don't use i >= 0 in the for loop) because:
// 1) no analysis has been run and 2) modifying the state before analysis is fine as long as the condition is kept the same later.
for (int i = segments.length - 1; i > 0; i--) {
String seg = segments[i];
if ("".equals(seg)) {
continue; // skip AA (A immediately followed by A)
}
if (i == segments.length - 1 && seg.endsWith("?")) { // skip the ask if it is the last event in the whole event string (not the current segment)
seg = seg.substring(0, seg.length() - 1);
}
// reverse the order so that the latest can be processed first
for (int x = seg.length() - 1; x >= 0; x--) {
final String s = Character.toString(seg.charAt(x));
for (final String regex : map.keySet()) {
boolean find = Pattern.compile(regex).matcher(s).find();
final Feedback f = map.get(regex);
if (f.getNegate()) {
find = !find;
}
if (find) {
// from the start of the string to the first A has the index 0, so the analysis index will start from 1
f.setCustomMessage(f.getMessage().replaceAll("\\{ANALYSIS_NUMBER\\}", i + ""));
return f;
}
}
}
if (seg.lastIndexOf('?') != -1) { // go no further than the last ask
break;
}
}
return null;
}
private Feedback getFeedbackMultiCharacter(final String[] segments, final Map<String, Feedback> map) {
// Forgive the starter (meaning don't use i >= 0 in the for loop) because:
// 1) no analysis has been run and 2) modifying the state before analysis is fine as long as the condition is kept the same later.
for (int i = segments.length - 1; i > 0; i--) {
String seg = segments[i];
if ("".equals(seg)) {
continue; // skip AA (A immediately followed by A)
}
if (i == segments.length - 1 && seg.endsWith("?")) { // skip the ask if it is the last event in the whole event string (not the current segment)
seg = seg.substring(0, seg.length() - 1);
}
// reverse the order so that the latest can be processed first (TODO: This somehow applies to only single-character indicators!)
seg = new StringBuilder(seg).reverse().toString();
for (final String regex : map.keySet()) {
boolean find = Pattern.compile(regex).matcher(seg).find();
final Feedback f = map.get(regex);
if (f.getNegate()) {
find = !find;
}
if (find) {
// from the start of the string to the first A has the index 0, so the analysis index will start from 1
f.setCustomMessage(f.getMessage().replaceAll("\\{ANALYSIS_NUMBER\\}", i + ""));
return f;
}
}
if (seg.lastIndexOf('?') != -1) { // go no further than the last ask
break;
}
}
return null;
}
MyEvent idChangeEvent() {
final List<MyEvent> u = EventUtil.getEvents(ChangePartUValueCommand.class);
if (u.size() < 2) {
return null;
}
long oldId = -1;
long newId = -1;
for (final MyEvent x : u) {
if (x instanceof ChangePartUValueCommand) {
final ChangePartUValueCommand command = (ChangePartUValueCommand) x;
newId = command.getPart().getId();
if (oldId == -1) { // first
oldId = newId;
} else {
if (newId != oldId) {
return x;
}
}
}
}
return null;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
}
| 47.980315
| 313
| 0.688767
|
7a8bca5199a4e37f305af3e3bb9229e4ed55628b
| 4,396
|
package com.nepxion.discovery.platform.server.entity.vo;
/**
* <p>Title: Nepxion Discovery</p>
* <p>Description: Nepxion Discovery</p>
* <p>Copyright: Copyright (c) 2017-2050</p>
* <p>Company: Nepxion</p>
*
* @author Ning Zhang
* @version 1.0
*/
import java.util.List;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.baomidou.mybatisplus.annotation.TableField;
import com.nepxion.discovery.platform.server.entity.base.BaseEntity;
public class MenuVo extends BaseEntity {
private static final long serialVersionUID = -4924651888194918771L;
@TableField("`name`")
private String name;
@TableField("`url`")
private String url;
@TableField("`show_flag`")
private Boolean showFlag;
@TableField(value = "`default_flag`")
private Boolean defaultFlag;
@TableField(value = "`blank_flag`")
private Boolean blankFlag;
@TableField("`icon_class`")
private String iconClass;
@TableField("`parent_id`")
private Long parentId;
@TableField("`parent_name`")
private String parentName;
@TableField("`order`")
private Long order;
@TableField("`description`")
private String description;
@TableField("`can_insert`")
private Boolean canInsert;
@TableField("`can_delete`")
private Boolean canDelete;
@TableField("`can_update`")
private Boolean canUpdate;
@TableField("`can_select`")
private Boolean canSelect;
@TableField(exist = false)
private List<MenuVo> children;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Boolean getShowFlag() {
return showFlag;
}
public void setShowFlag(Boolean showFlag) {
this.showFlag = showFlag;
}
public Boolean getDefaultFlag() {
return defaultFlag;
}
public void setDefaultFlag(Boolean defaultFlag) {
this.defaultFlag = defaultFlag;
}
public Boolean getBlankFlag() {
return blankFlag;
}
public void setBlankFlag(Boolean blankFlag) {
this.blankFlag = blankFlag;
}
public String getIconClass() {
return iconClass;
}
public void setIconClass(String iconClass) {
this.iconClass = iconClass;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Long getOrder() {
return order;
}
public void setOrder(Long order) {
this.order = order;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getCanInsert() {
return canInsert;
}
public void setCanInsert(Boolean canInsert) {
this.canInsert = canInsert;
}
public Boolean getCanDelete() {
return canDelete;
}
public void setCanDelete(Boolean canDelete) {
this.canDelete = canDelete;
}
public Boolean getCanUpdate() {
return canUpdate;
}
public void setCanUpdate(Boolean canUpdate) {
this.canUpdate = canUpdate;
}
public Boolean getCanSelect() {
return canSelect;
}
public void setCanSelect(Boolean canSelect) {
this.canSelect = canSelect;
}
public List<MenuVo> getChildren() {
return children;
}
public void setChildren(List<MenuVo> children) {
this.children = children;
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
@Override
public boolean equals(Object object) {
return EqualsBuilder.reflectionEquals(this, object);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
| 21.443902
| 88
| 0.649227
|
e9fa8d4aeae8ead33fb633d646660e6d43909bfa
| 1,965
|
package eapli.base.app.common.console.presentation.PesquisarCatalogo;
import eapli.base.catalogo.application.PesquisarCatalogoController;
import eapli.base.catalogo.domain.Catalogo;
import eapli.base.catalogo.persistencia.CatalogoRepositorio;
import eapli.base.colaborador.persistencia.ColaboradorRepositorio;
import eapli.base.equipa.domain.Equipa;
import eapli.base.equipa.persistencia.EquipaRepositorio;
import eapli.base.infrastructure.persistence.PersistenceContext;
import eapli.base.servico.application.PesquisarServicoController;
import eapli.base.servico.domain.Servico;
import eapli.framework.infrastructure.authz.application.AuthorizationService;
import eapli.framework.infrastructure.authz.application.AuthzRegistry;
import eapli.framework.infrastructure.authz.application.UserSession;
import eapli.framework.infrastructure.authz.domain.model.SystemUser;
import eapli.framework.io.util.Console;
import eapli.framework.presentation.console.AbstractUI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PesquisaCatalogoTituloUI extends AbstractUI {
private final PesquisarCatalogoController pcController = new PesquisarCatalogoController();
public PesquisaCatalogoTituloUI(){}
@Override
protected boolean doShow() {
final String titulo = Console.readLine("Indique o Título que quer pesquisar:");
final Set<Catalogo> listaCatalogo = (Set<Catalogo>) pcController.pesquisaTitulo(titulo);
if(!listaCatalogo.isEmpty()){
for (Catalogo ct : listaCatalogo){
System.out.println("############################ " + ct.toString() + " ############################\n");
}
return true;
}
System.out.println("Não conseguimos encontrar esse Catalogo");
return false;
}
@Override
public String headline() {
return "Pesquisar pelo Título do Catálogo";
}
}
| 37.075472
| 126
| 0.743003
|
f8c1a565f636d6b15179eb380e15d71c29114038
| 539
|
package org.openpanda.microservice.ddd.rule;
/**
* Created by lingen on 2016/12/24.
*/
public class PandaRuntimeException extends RuntimeException {
private String errorCode;
private String description;
public PandaRuntimeException(String errorCode,String description){
super(errorCode);
this.errorCode = errorCode;
this.description = description;
}
public String getErrorCode() {
return errorCode;
}
public String getDescription() {
return description;
}
}
| 19.962963
| 70
| 0.680891
|
26bd0d1d1907257e29aed4c41bb30ca3ac1d9721
| 122
|
//5, 22, 5, 27
package p;
class A {
public void m() {
int temp = 2 + 3;
int a = 1 - (temp);
}
}
| 11.090909
| 27
| 0.401639
|
4e8960203f68b3c0486e48acedd063b39c90af29
| 949
|
package org.kodejava.example.swing;
import javax.swing.*;
import java.awt.*;
public class JLabelHTMLStyle extends JFrame {
public JLabelHTMLStyle() {
setTitle("JLabel with HTML Style");
initComponents();
}
private void initComponents() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(400, 200);
Container container = getContentPane();
container.setLayout(new FlowLayout(FlowLayout.CENTER));
// Create a JLabel object that display a string formatted using HTML.
// 14 font size with red and italic.
String text = "<html>" +
"<font size='16' color='orange'><strong>Hello World</strong></font>" +
"</html>";
JLabel label = new JLabel(text);
container.add(label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JLabelHTMLStyle().setVisible(true));
}
}
| 30.612903
| 82
| 0.635406
|
e70804b5e1ebda967343aee75131a706a0cc9f8f
| 4,621
|
package io.opensphere.csvcommon.common.datetime;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import io.opensphere.core.common.configuration.date.DateFormat;
import io.opensphere.core.common.configuration.date.DateFormatsConfig;
import io.opensphere.core.common.configuration.date.DateFormat.Type;
import io.opensphere.core.preferences.Preferences;
import io.opensphere.core.preferences.PreferencesRegistry;
import io.opensphere.core.util.collections.New;
import io.opensphere.mantle.util.MantleConstants;
/**
* Migrates the old DateFormatsConfiguration.xml to the new
* com.bitsys.common.configuration.date.v1.DateFormatsConfiguration.xml.
*
*/
public class Migrator
{
/**
* The key to the migration property.
*/
private static final String ourMigratedKey = "v1Migrated";
/**
* Migrates the old DateFormatsConfiguration.xml to the new
* com.bitsys.common.configuration.date.v1.DateFormatsConfiguration.xml.
*
* @param provider Used get and save the new formats file.
* @param registry Used to get the old formats file.
*/
public void migrate(ConfigurationProvider provider, PreferencesRegistry registry)
{
Preferences newPreferences = registry.getPreferences(MantleConstants.USER_DATE_FORMAT_CONFIG_FILE_TOPIC);
boolean alreadyMigrated = newPreferences.getBoolean(ourMigratedKey, false);
if (!alreadyMigrated)
{
Preferences preferences = registry.getPreferences("DateFormatConfiguration");
DateFormatsConfig oldConfig = preferences.getJAXBObject(DateFormatsConfig.class,
MantleConstants.USER_DATE_FORMAT_CONFIG_FILE_KEY, null);
DateFormatsConfig newConfig = provider.getDateFormats();
List<DateFormat> formatsToAdd = New.list();
if (oldConfig != null)
{
Map<String, DateFormat> formats = mapFormats(newConfig);
for (DateFormat format : oldConfig.getFormats())
{
if (!formats.containsKey(format.getSdf()))
{
boolean isValid = isFormatValid(format);
if (isValid)
{
formatsToAdd.add(format);
}
}
}
if (!formatsToAdd.isEmpty())
{
provider.saveFormats(formatsToAdd);
}
}
newPreferences.putBoolean(ourMigratedKey, true, this);
}
}
/**
* Checks to see if this format is worthy enough for the new formats
* configuration file.
*
* @param format The format to check.
* @return True if the format is valid, false otherwise.
*/
private boolean isFormatValid(DateFormat format)
{
boolean isValid = false;
if (StringUtils.isNotEmpty(format.getSdf()) && !format.getSdf().contains("f"))
{
String formatString = format.getSdf();
boolean containsTime = formatString.contains("H") || formatString.contains("m") || formatString.contains("s")
|| formatString.contains("S") || formatString.contains("h");
boolean containsDate = formatString.contains("y") || formatString.contains("M") || formatString.contains("d");
if (containsTime && containsDate && format.getType() != Type.TIMESTAMP)
{
format.setType(Type.TIMESTAMP);
}
else if (containsTime && !containsDate && format.getType() != Type.TIME)
{
format.setType(Type.TIME);
}
else if (!containsTime && containsDate && format.getType() != Type.DATE)
{
format.setType(Type.DATE);
}
isValid = true;
}
return isValid;
}
/**
* Maps the formats and uses their simple date format string as a unique
* key.
*
* @param config The configuration containing the formats to use.
* @return The mapped formats.
*/
private Map<String, DateFormat> mapFormats(DateFormatsConfig config)
{
Map<String, DateFormat> mappedFormats = New.map();
for (DateFormat format : config.getFormats())
{
mappedFormats.put(format.getSdf(), format);
}
return mappedFormats;
}
}
| 34.485075
| 123
| 0.592729
|
14667347366f6a1b81195b34dea77d56791d25e9
| 2,346
|
package com.lambda.iith.dashboard.Cabsharing;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import com.lambda.iith.dashboard.MainActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import Model.Filter;
public class BookingFilter extends AsyncTask<Filter, Void, Void> {
@Override
protected Void doInBackground(Filter... filters) {
JSONArray JA = null;
JSONArray JA2 = null;
String response = filters[0].response;
SharedPreferences sharedPreferences = filters[0].sharedPreferences;
final String startTime = sharedPreferences.getString("startTime", " NA NA ");
final String endTime = sharedPreferences.getString("endTime", " NA NA ");
final int CabID = sharedPreferences.getInt("Route", 100);
try {
JA = new JSONArray(response);
JA2 = new JSONArray();
for (int i = 0; i < JA.length(); i++) {
JSONObject JO = (JSONObject) JA.get(i);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd:HH:mm");
java.util.Date T1 = format1.parse(startTime.substring(0, 10) + ":" + startTime.substring(11, 16));
java.util.Date T2 = format1.parse(endTime.substring(0, 10) + ":" + endTime.substring(11, 16));
java.util.Date T3 = format1.parse(JO.getString("StartTime").substring(0, 10) + ":" + JO.getString("StartTime").substring(11, 16));
java.util.Date T4 = format1.parse(JO.getString("EndTime").substring(0, 10) + ":" + JO.getString("EndTime").substring(11, 16));
if ((JO.getInt("RouteID") == CabID) && !((JO.getString("Email")).equals(MainActivity.email)) && ((T3.compareTo(T1) >= 0 && T3.compareTo(T2) <= 0) || (T4.compareTo(T1) >= 0 && T4.compareTo(T2) <= 0))) {
JA2.put(JO);
}
}
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("CabShares", JA2.toString());
edit.commit();
} catch (ParseException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
| 34.5
| 217
| 0.603154
|
444ee46a60bd263b34dee1e4bb4ba3e505c7455d
| 2,020
|
package org.houqian.core.bootstrap;
import org.houqian.core.source.collection.ArrayList;
import java.util.List;
/**
* @author : houqian
* @version : 1.0
* @since : 2019-06-17
*/
public class ArrayListBS {
public static void main(String[] args) {
// ------------------------无参数构造器实例化--------------------------
// 0. ArrayList 是如何实例化的?
// 0.1 无参数构造器
/** 直接开辟一个空数组
*/
List<String> list = new ArrayList<>();
/**
* 如何添加元素的?
*
* 计算 Capcity
* 如果当前数组长度为 0,并且 minCap(即用户指定 ArrayList 初始容量)为 1(这里会对指定容量做+1操作)
* 那么,将当前 capcity 设置为Math.max(DEFAULT_CAPACITY, minCapacity)
*
* if (minCapacity - elementData.length > 0)
* 扩容
* newCap = 1.5 * oldCap
* if newCap < minCap
* newCap = minCap
* 将 old 数组的元素拷贝到新数组
*
* 赋值
* eleArr[size++] = 传进来的元素
*
*/
list.add("1");
/**
* 如何判断元素是否存在?
*
* 实际上调用 indexOf 方法
* 如果传入 null
* 用 eleArr[i] == null 判断,true 就返回
* 如果传入不为 null
* 用 equals 判断
*
* 总结,其实就是为了防止空指针异常。这里用的是遍历数组查找
*
* 时间复杂度 O(N)
*/
list.contains("1");
/**
* 如何实现 fail-fast?
* 记录一个 modCount,每次修改数组modCount+1
* 在需要 fail-fast 的方法体中:
* expectedModCount = modCount;
* xxxxx modCount ++;
* if(expectedModCount != modCount) throw ConcurrentModificationException
*/
/**
* subList 是如何实现的?
* 检测长度
* fromIdx < 0 || toIndex > currentArrayListSize ,抛出IndexOutOfBoundsException
* fromIdx > toIdx , 抛出IllegalArgumentException
*
* 创建视图
* 其实是 new Sublist(当前 ArrayList 实例, fromIdx, toIdx)
* 与 ArrayList 继承了相同的抽象类,实现了相同的方法
* private class SubList extends AbstractList<E> implements RandomAccess
*
* 维护 Offset,lastRef
*
*
*/
List<String> subList = list.subList(0, 1);
// ------------------------指定初始化容量实例化--------------------------
List<String> list2 = new ArrayList<>(1);
list.add("2");
}
}
| 22.444444
| 84
| 0.538614
|
5ef1ad420d4519af4a461274904f1246f58d7ecd
| 6,250
|
/*
* Copyright 2015 recommenders.net.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.recommenders.rival.evaluation.metric.ranking;
import net.recommenders.rival.core.DataModelIF;
import net.recommenders.rival.evaluation.metric.AbstractMetric;
import net.recommenders.rival.evaluation.metric.EvaluationMetric;
import net.recommenders.rival.evaluation.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Abstract class which represents all the basic elements of a ranking based
* metric.
*
* @param <U> - type associated to users' ids
* @param <I> - type associated to items' ids
*
* @author <a href="http://github.com/alansaid">Alan</a>.
* @author <a href="http://github.com/abellogin">Alejandro</a>.
*/
public abstract class AbstractRankingMetric<U, I> extends AbstractMetric<U, I> implements EvaluationMetric<U> {
/**
* Array of cutoff levels.
*/
private int[] ats;
/**
* Relevance threshold.
*/
private double relevanceThreshold;
/**
* Default constructor with predictions and groundtruth information.
*
* @param predictions predicted scores for users and items
* @param test groundtruth information for users and items
*/
public AbstractRankingMetric(final DataModelIF<U, I> predictions, final DataModelIF<U, I> test) {
this(predictions, test, 1.0);
}
/**
* Constructor where the relevance threshold can be initialized.
*
* @param predictions predicted ratings
* @param test groundtruth ratings
* @param relThreshold relevance threshold
*/
public AbstractRankingMetric(final DataModelIF<U, I> predictions, final DataModelIF<U, I> test, final double relThreshold) {
this(predictions, test, relThreshold, new int[]{});
}
/**
* Constructor where the cutoff levels can be initialized.
*
* @param predictions predicted ratings
* @param test groundtruth ratings
* @param cutoffLevels cutoffs
* @param relThreshold relevance threshold
*/
public AbstractRankingMetric(final DataModelIF<U, I> predictions, final DataModelIF<U, I> test, final double relThreshold, final int[] cutoffLevels) {
super(predictions, test);
setValue(Double.NaN);
this.ats = Arrays.copyOf(cutoffLevels, cutoffLevels.length);
this.relevanceThreshold = relThreshold;
}
/**
* Gets the relevance threshold.
*
* @return the relevance threshold
*/
protected double getRelevanceThreshold() {
return relevanceThreshold;
}
/**
* Method that transforms the user data from pairs of (item, score) into
* ranked lists of relevance values, by using ground truth information.
*
* @return a map with the transformed data, one list per user
*/
public Map<U, List<Pair<I, Double>>> processDataAsRankedTestRelevance() {
Map<U, List<Pair<I, Double>>> data = new HashMap<U, List<Pair<I, Double>>>();
for (U testUser : getTest().getUsers()) {
Map<I, Double> userPredictedRatings = new HashMap<>();
for (I i : getPredictions().getUserItems(testUser)) {
userPredictedRatings.put(i, getPredictions().getUserItemPreference(testUser, i));
}
if (!userPredictedRatings.isEmpty()) {
List<Pair<I, Double>> rankedTestRel = new ArrayList<Pair<I, Double>>();
for (I item : rankItems(userPredictedRatings)) {
double rel = getTest().getUserItemPreference(testUser, item);
if (Double.isNaN(rel)) {
rel = 0.0;
}
rankedTestRel.add(new Pair<I, Double>(item, rel));
}
data.put(testUser, rankedTestRel);
}
}
return data;
}
/**
* Method that computes the number of relevant items in the test set for a
* user.
*
* @param user a user
* @return the number of relevant items the user has in the test set
*/
protected double getNumberOfRelevantItems(final U user) {
int n = 0;
if (getTest().getUserItems(user) != null) {
for (I i : getTest().getUserItems(user)) {
if (getTest().getUserItemPreference(user, i) >= relevanceThreshold) {
n++;
}
}
}
return n * 1.0;
}
/**
* Method that computes the binary precision of a specific item, taking into
* account its relevance value.
*
* @param rel the item's relevance
* @return the binary precision of the item
*/
protected double computeBinaryPrecision(final double rel) {
double prec = 0.0;
if (rel >= relevanceThreshold) {
prec = 1.0;
}
return prec;
}
/**
* Returns the array of cutoff levels where this metric has computed values
* at.
*
* @return the array of cutoff levels
*/
public int[] getCutoffs() {
return ats;
}
/**
* Method to return the metric value at a particular cutoff level.
*
* @param at cutoff level
* @return the metric corresponding to the requested cutoff level
*/
public abstract double getValueAt(final int at);
/**
* Method to return the metric value at a particular cutoff level for a
* given user.
*
* @param user the user
* @param at cutoff level
* @return the metric corresponding to the requested user at the cutoff
* level
*/
public abstract double getValueAt(final U user, final int at);
}
| 33.42246
| 154
| 0.63408
|
cc5ee886f0ec98b89409dbf71aee59f460175712
| 4,976
|
/** \file
*
* Mar 28, 2018
*
* Copyright Ian Kaplan 2018
*
* @author Ian Kaplan, www.bearcave.com, iank@bearcave.com
*/
package booksearch.model;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIgnore;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBIndexHashKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable;
/**
* <p>
* BookInfo
* </p>
*
* <p>
* Information about a book. The information in this class comes from the book information form
* filled out by the user.
* </p>
* <p>
* This class is annotated so that it can be persisted to DynamoDB.
* </p>
* <p>
* Apr 6, 2018
* </p>
*
* @author Ian Kaplan, iank@bearcave.com
*/
@DynamoDBTable(tableName="book_table")
public class BookInfo {
@NotBlank(message="A book title is required")
private String title;
@NotBlank(message="An author name is required")
private String author;
@NotBlank(message="Please include a genre for the book")
private String genre;
private String publisher;
@Digits(integer=4, fraction=0, message="Please enter a year")
private String year;
@Pattern(regexp="^\\d{0,8}(\\.\\d{1,4})?$", message="Please enter a price i.e., 16, 16.00, 15.95")
private String price;
@DynamoDBHashKey(attributeName="title")
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = trimString( title );
}
@DynamoDBRangeKey(attributeName="author")
@DynamoDBIndexHashKey(attributeName="author", globalSecondaryIndexName="author_index")
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = trimString( author );
}
@DynamoDBAttribute(attributeName="genre")
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = trimString( genre );
}
@DynamoDBAttribute(attributeName="publisher")
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = trimString( publisher );
}
@DynamoDBAttribute(attributeName="year")
public void setYear(String year) {
this.year = trimString( year );
}
public String getYear() {
return this.year;
}
@DynamoDBAttribute(attributeName="price")
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = trimString( price );
}
@DynamoDBIgnore
private String trimString(String input) {
String rslt = "";
if (input != null && input.length() > 0) {
rslt = input.trim();
}
return rslt;
}
@Override
@DynamoDBIgnore
public String toString() {
return "BookForm [title=" + title + ", author=" + author + ", genre=" + genre + ", publisher=" + publisher + ", year = " + year + ", price=" + price
+ "]";
}
@Override
@DynamoDBIgnore
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof BookInfo)) {
return false;
}
BookInfo other = (BookInfo) obj;
if (author == null) {
if (other.author != null) {
return false;
}
} else if (!author.equals(other.author)) {
return false;
}
if (genre == null) {
if (other.genre != null) {
return false;
}
} else if (!genre.equals(other.genre)) {
return false;
}
if (price == null) {
if (other.price != null) {
return false;
}
} else if (!price.equals(other.price)) {
return false;
}
if (publisher == null) {
if (other.publisher != null) {
return false;
}
} else if (!publisher.equals(other.publisher)) {
return false;
}
if (title == null) {
if (other.title != null) {
return false;
}
} else if (!title.equals(other.title)) {
return false;
}
if (year == null) {
if (other.year != null) {
return false;
}
} else if (!year.equals(other.year)) {
return false;
}
return true;
}
}
| 27.491713
| 156
| 0.574156
|
8188efe4ffe07ea5281f613e6aee897fcc04360c
| 4,481
|
package cc.mrbird.febs.app.controller;
import cc.mrbird.febs.app.entity.MetroToOfficeBuilding;
import cc.mrbird.febs.app.service.IMetroToOfficeBuildingService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
* Controller
*
* @author 冷酷的苹果
* @date 2020-05-06 09:18:18
*/
@Slf4j
@Validated
@Controller
@RequiredArgsConstructor
public class MetroToOfficeBuildingController extends BaseController {
private final IMetroToOfficeBuildingService metroToOfficeBuildingService;
@GetMapping(FebsConstant.VIEW_PREFIX + "metroToOfficeBuilding")
public String metroToOfficeBuildingIndex() {
return FebsUtil.view("metroToOfficeBuilding/metroToOfficeBuilding");
}
@GetMapping("metroToOfficeBuilding")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:list")
public FebsResponse getAllMetroToOfficeBuildings(MetroToOfficeBuilding metroToOfficeBuilding) {
return new FebsResponse().success().data(metroToOfficeBuildingService.findMetroToOfficeBuildings(metroToOfficeBuilding));
}
@GetMapping("metroToOfficeBuilding/list")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:list")
public FebsResponse metroToOfficeBuildingList(QueryRequest request, MetroToOfficeBuilding metroToOfficeBuilding) {
Map<String, Object> dataTable =
getDataTable(this.metroToOfficeBuildingService.findMetroToOfficeBuildings(request,
metroToOfficeBuilding));
return new FebsResponse().success().data(dataTable);
}
@ControllerEndpoint(operation = "新增MetroToOfficeBuilding", exceptionMessage = "新增MetroToOfficeBuilding失败")
@PostMapping("metroToOfficeBuilding")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:add")
public FebsResponse addMetroToOfficeBuilding(@Valid MetroToOfficeBuilding metroToOfficeBuilding) {
this.metroToOfficeBuildingService.createMetroToOfficeBuilding(metroToOfficeBuilding);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "删除MetroToOfficeBuilding", exceptionMessage = "删除MetroToOfficeBuilding失败")
@GetMapping("metroToOfficeBuilding/delete")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:delete")
public FebsResponse deleteMetroToOfficeBuilding(MetroToOfficeBuilding metroToOfficeBuilding) {
this.metroToOfficeBuildingService.deleteMetroToOfficeBuilding(metroToOfficeBuilding);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "修改MetroToOfficeBuilding", exceptionMessage = "修改MetroToOfficeBuilding失败")
@PostMapping("metroToOfficeBuilding/update")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:update")
public FebsResponse updateMetroToOfficeBuilding(MetroToOfficeBuilding metroToOfficeBuilding) {
this.metroToOfficeBuildingService.updateMetroToOfficeBuilding(metroToOfficeBuilding);
return new FebsResponse().success();
}
@ControllerEndpoint(operation = "修改MetroToOfficeBuilding", exceptionMessage = "导出Excel失败")
@PostMapping("metroToOfficeBuilding/excel")
@ResponseBody
@RequiresPermissions("metroToOfficeBuilding:export")
public void export(QueryRequest queryRequest, MetroToOfficeBuilding metroToOfficeBuilding,
HttpServletResponse response) {
List<MetroToOfficeBuilding> metroToOfficeBuildings =
this.metroToOfficeBuildingService.findMetroToOfficeBuildings(queryRequest, metroToOfficeBuilding).getRecords();
ExcelKit.$Export(MetroToOfficeBuilding.class, response).downXlsx(metroToOfficeBuildings, false);
}
}
| 44.366337
| 129
| 0.793796
|
808ed8198c4339e2748a58ca825491faf6d24955
| 1,907
|
package top.tangyh.lamp.authority.service.common;
import top.tangyh.basic.base.service.SuperService;
import top.tangyh.lamp.authority.entity.common.LoginLog;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
/**
* <p>
* 业务接口
* 系统日志
*
* </p>
*
* @author zuihou
* @date 2019-10-20
*/
public interface LoginLogService extends SuperService<LoginLog> {
/**
* 记录登录日志
*
* @param userId 用户id
* @param account 账号
* @param ua 浏览器
* @param ip 客户端IP
* @param location 客户端地址
* @param description 登陆描述消息
* @return 登录日志
*/
LoginLog save(Long userId, String account, String ua, String ip, String location, String description);
/**
* 获取系统总 登录次数
*
* @return Long
*/
Long getTotalLoginPv();
/**
* 获取系统今日 登录次数
*
* @return Long
*/
Long getTodayLoginPv();
/**
* 获取系统总 登录IV
*
* @return Long
*/
Long getTotalLoginIv();
/**
* 获取系统今日 登录IV
*
* @return Long
*/
Long getTodayLoginIv();
/**
* 获取系统近十天来的访问记录
*
* @param account 账号
* @return 系统近十天来的访问记录
*/
List<Map<String, String>> findLastTenDaysVisitCount(String account);
/**
* 按浏览器来统计数量
*
* @return 浏览器访问量
*/
List<Map<String, Object>> findByBrowser();
/**
* 按操作系统来统计数量
*
* @return 操作系统访问量
*/
List<Map<String, Object>> findByOperatingSystem();
/**
* 清理日志
*
* @param clearBeforeTime 多久之前的
* @param clearBeforeNum 多少条
* @return 是否成功
*/
boolean clearLog(LocalDateTime clearBeforeTime, Integer clearBeforeNum);
/**
* 总 PV
*
* @return
*/
Long getTotalPv();
/**
* 今日 PV
*
* @return
*/
Long getTodayPv();
/**
* pv 计数
*/
void pvIncr();
}
| 16.439655
| 106
| 0.541164
|
b080ae7b1b81b49f0146859a7da140e4fdc4cc0d
| 6,467
|
/*
* Copyright 2019-present HiveMQ GmbH
*
* 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.hivemq.codec.encoder.mqtt5;
import com.google.common.primitives.ImmutableIntArray;
import com.hivemq.extension.sdk.api.annotations.NotNull;
import com.hivemq.codec.encoder.MqttEncoder;
import com.hivemq.configuration.service.SecurityConfigurationService;
import com.hivemq.mqtt.message.MessageType;
import com.hivemq.mqtt.message.QoS;
import com.hivemq.mqtt.message.dropping.MessageDroppedService;
import com.hivemq.mqtt.message.mqtt5.Mqtt5UserProperties;
import com.hivemq.mqtt.message.publish.PUBLISH;
import io.netty.buffer.ByteBuf;
import javax.inject.Singleton;
import java.util.List;
import static com.hivemq.codec.encoder.mqtt5.Mqtt5MessageEncoderUtil.*;
import static com.hivemq.configuration.entity.mqtt.MqttConfigurationDefaults.MAX_EXPIRY_INTERVAL_DEFAULT;
import static com.hivemq.mqtt.message.mqtt5.MessageProperties.*;
/**
* @author Silvio Giebl
* @author Florian Limpöck
*/
@Singleton
public class Mqtt5PublishEncoder extends Mqtt5MessageWithUserPropertiesEncoder<PUBLISH> implements MqttEncoder<PUBLISH> {
private static final int FIXED_HEADER = MessageType.PUBLISH.ordinal() << 4;
public Mqtt5PublishEncoder(final @NotNull MessageDroppedService messageDroppedService,
final @NotNull SecurityConfigurationService securityConfigurationService) {
super(messageDroppedService, securityConfigurationService);
}
@Override
void encode(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
encodeFixedHeader(publish, out);
encodeVariableHeader(publish, out);
encodePayload(publish, out);
}
@Override
int calculateRemainingLengthWithoutProperties(@NotNull final PUBLISH publish) {
int remainingLength = 0;
remainingLength += MqttBinaryData.encodedLength(publish.getTopic());
//packetIdentifier
if (publish.getQoS() != QoS.AT_MOST_ONCE) {
remainingLength += 2;
}
final byte[] payload = publish.getPayload();
if (payload != null) {
remainingLength += payload.length;
}
return remainingLength;
}
@Override
int calculatePropertyLength(@NotNull final PUBLISH publish) {
int propertyLength = 0;
propertyLength += fixedPropertyLength(publish);
propertyLength += publish.getUserProperties().encodedLength();
final ImmutableIntArray subscriptionIdentifiers = publish.getSubscriptionIdentifiers();
if (subscriptionIdentifiers != null) {
for (int i = 0; i < subscriptionIdentifiers.length(); i++) {
propertyLength += variableByteIntegerPropertyEncodedLength(subscriptionIdentifiers.get(i));
}
}
return propertyLength;
}
@Override
@NotNull Mqtt5UserProperties getUserProperties(@NotNull final PUBLISH publish) {
return publish.getUserProperties();
}
private int fixedPropertyLength(@NotNull final PUBLISH publish) {
int propertyLength = 0;
propertyLength += intPropertyEncodedLength(publish.getMessageExpiryInterval(), MAX_EXPIRY_INTERVAL_DEFAULT);
propertyLength += nullablePropertyEncodedLength(publish.getPayloadFormatIndicator());
propertyLength += nullablePropertyEncodedLength(publish.getContentType());
propertyLength += nullablePropertyEncodedLength(publish.getResponseTopic());
propertyLength += nullablePropertyEncodedLength(publish.getCorrelationData());
return propertyLength;
}
private void encodeFixedHeader(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
int flags = 0;
if (publish.isDuplicateDelivery()) {
flags |= 0b1000;
}
flags |= publish.getQoS().ordinal() << 1;
if (publish.isRetain()) {
flags |= 0b0001;
}
out.writeByte(FIXED_HEADER | flags);
MqttVariableByteInteger.encode(publish.getRemainingLength(), out);
}
private void encodeVariableHeader(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
MqttBinaryData.encode(publish.getTopic(), out);
if (publish.getQoS() != QoS.AT_MOST_ONCE) {
out.writeShort(publish.getPacketIdentifier());
}
encodeProperties(publish, out);
}
private void encodeProperties(@NotNull final PUBLISH publish,
@NotNull final ByteBuf out) {
MqttVariableByteInteger.encode(publish.getPropertyLength(), out);
encodeFixedProperties(publish, out);
encodeOmissibleProperties(publish, out);
final ImmutableIntArray subscriptionIdentifiers = publish.getSubscriptionIdentifiers();
if (subscriptionIdentifiers != null) {
for (int i = 0; i < subscriptionIdentifiers.length(); i++) {
encodeVariableByteIntegerProperty(SUBSCRIPTION_IDENTIFIER, subscriptionIdentifiers.get(i), out);
}
}
}
private void encodeFixedProperties(@NotNull final PUBLISH publish, @NotNull final ByteBuf out) {
encodeIntProperty(MESSAGE_EXPIRY_INTERVAL, publish.getMessageExpiryInterval(), MAX_EXPIRY_INTERVAL_DEFAULT, out);
encodeNullableProperty(PAYLOAD_FORMAT_INDICATOR, publish.getPayloadFormatIndicator(), out);
encodeNullableProperty(CONTENT_TYPE, publish.getContentType(), out);
encodeNullableProperty(RESPONSE_TOPIC, publish.getResponseTopic(), out);
encodeNullableProperty(CORRELATION_DATA, publish.getCorrelationData(), out);
}
private void encodePayload(@NotNull final PUBLISH publish, @NotNull final ByteBuf out) {
final byte[] payload = publish.getPayload();
if ((payload != null)) {
out.writeBytes(payload);
}
}
}
| 36.744318
| 121
| 0.698315
|
91417d22562153fc2f993864498faeb337bff2af
| 1,120
|
package rero.bridges.menu;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import sleep.runtime.*;
import sleep.engine.*;
import rero.script.*;
public class ScriptedItem extends JMenuItem implements ActionListener
{
protected ScriptInstance owner;
protected Block code;
public ScriptedItem(ScriptInstance _owner, String _label, Block _code)
{
if (_label.indexOf('&') > -1)
{
setText( _label.substring(0, _label.indexOf('&')) + _label.substring(_label.indexOf('&') + 1, _label.length()) );
setMnemonic(_label.charAt(_label.indexOf('&') + 1));
}
else
{
setText(_label);
}
owner = _owner;
code = _code;
addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
HashMap locals = ScriptedPopupMenu.getMenuData();
if (locals == null)
{
locals = new HashMap();
}
locals.put("$command", e.getActionCommand());
ScriptCore.runCode(owner, code, locals);
}
}
| 21.538462
| 123
| 0.609821
|
fa435340db9146d06023927f6ae5621fa13d4e4b
| 950
|
package linklist;
import java.util.ArrayList;
import java.util.List;
//回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
public class LinkedList234 {
public static void main(String[] args) {
Solution234 mSolution = new Solution234();
ListNode n1 = new ListNode(1);
// ListNode n2 = new ListNode(2);
// ListNode n3 = new ListNode(1);
//
// n1.next = n2;
// n2.next = n3;
System.out.println(mSolution.isPalindrome(n1));
}
}
class Solution234 {
public boolean isPalindrome(ListNode head) {
if(head==null)
{
return false;
}
List<Integer> array = new ArrayList<Integer>();
while(head!=null){
array.add(head.val);
head = head.next;
}
for(int i=0;i<array.size()/2;i++) {
int a = array.get(i);
int b = array.get(array.size()-1-i);
if(a!=b) {
return false;
}
}
return true;
}
}
| 16.37931
| 52
| 0.548421
|
0fea9160ec006e53c5fd1be1be1f1c880c28adf9
| 1,134
|
package wraith.colormeoutlines;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexFormat;
import net.minecraft.client.render.VertexFormats;
import wraith.colormeoutlines.mixin.RenderLayerInvoker;
@Environment(EnvType.CLIENT)
public class CustomRenderLayer extends RenderLayer {
public static final RenderLayer OUTLINE = RenderLayerInvoker.of("colormeoutlines", VertexFormats.LINES, VertexFormat.DrawMode.LINES, 256, true, true,
RenderLayer.MultiPhaseParameters.builder()
.shader(LINES_SHADER)
.layering(VIEW_OFFSET_Z_LAYERING)
.lineWidth(new CustomLineWidth())
.transparency(TRANSLUCENT_TRANSPARENCY)
.target(ITEM_TARGET)
.writeMaskState(ALL_MASK)
.cull(DISABLE_CULLING)
.build(true));
private CustomRenderLayer() {
super("colormeoutlines", VertexFormats.POSITION, VertexFormat.DrawMode.LINES, 0, false, false, null, null);
}
}
| 39.103448
| 153
| 0.688713
|
aa0bbb20fbf665429f4cd036e813bbdd7d034d2d
| 507
|
package com.stylingandroid.prism;
import android.support.annotation.ColorInt;
public class SetterAdapter implements Setter {
private final ColorSetter colorSetter;
public SetterAdapter(ColorSetter colorSetter) {
this.colorSetter = colorSetter;
}
@Override
public void setColour(@ColorInt int colour) {
colorSetter.setColor(colour);
}
@Override
public void setTransientColour(@ColorInt int colour) {
colorSetter.setTransientColor(colour);
}
}
| 23.045455
| 58
| 0.717949
|
c247cb01ef2708d8a0fd047c8d312b4982140f1e
| 2,471
|
package org.usfirst.frc.team3042.robot.commands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.smartdashboard.SendableRegistry;
import org.usfirst.frc.team3042.lib.Log;
import org.usfirst.frc.team3042.robot.Robot;
import org.usfirst.frc.team3042.robot.RobotMap;
import org.usfirst.frc.team3042.robot.subsystems.Spinner;
/** Spinner_SetSpeed **********************************************************/
public class Spinner_SetSpeed extends Command {
/** Configuration Constants ***********************************************/
private static final Log.Level LOG_LEVEL = RobotMap.LOG_SPINNER_CLOSED_LOOP;
private static final double DEFAULT_SPEED = RobotMap.SPINNER_DEFAULT_SPEED;
/** Instance Variables ****************************************************/
Spinner spinner = Robot.spinner;
Log log = new Log(LOG_LEVEL, SendableRegistry.getName(spinner));
String speedLabel = "Spinner Speed";
/** Spinner_SetSpeed ******************************************************
* Required subsystems will cancel commands when this command is run.
*/
public Spinner_SetSpeed() {
log.add("Constructor", Log.Level.TRACE);
requires(spinner);
}
/** initialize ************************************************************
* Called just before this Command runs the first time
*/
protected void initialize() {
log.add("Initialize", Log.Level.TRACE);
spinner.closedLoop.setSpeed(-1 * DEFAULT_SPEED);
}
/** execute ***************************************************************
* Called repeatedly when this Command is scheduled to run
*/
protected void execute() {
}
/** isFinished ************************************************************
* Make this return true when this Command no longer needs to run execute()
*/
protected boolean isFinished() {
return false;
}
/** end *******************************************************************
* Called once after isFinished returns true
*/
protected void end() {
log.add("End", Log.Level.TRACE);
terminate();
}
/** interrupted ***********************************************************
* Called when another command which requires one or more of the same
* subsystems is scheduled to run
*/
protected void interrupted() {
log.add("Interrupted", Log.Level.TRACE);
terminate();
}
/** Graceful End **********************************************************/
private void terminate() {
spinner.stop();
}
}
| 30.8875
| 80
| 0.554431
|
1aaf7b6024d0cae75078bd5f28cf6aa9ce5758fd
| 325
|
package org.devgateway.toolkit.persistence.repository.category;
import org.devgateway.toolkit.persistence.dao.categories.Ward;
import org.springframework.transaction.annotation.Transactional;
/**
* @author idobre
* @since 2019-06-26
*/
@Transactional
public interface WardRepository extends CategoryRepository<Ward> {
}
| 25
| 66
| 0.812308
|
814b798ebce83a1ae94055a6321eff3e0e02245f
| 310
|
package com.itxiaoming.jiamingweather.gson;
/**
* 作者:xjm.
* 邮箱:xiaojiaming@infosec.com.cn
* 公司:Infosec Technology
* 创建时间:Created on 2017/1/13 16:10.
* 该类的作用:
* 版本号:
*/
public class AQI {
public AQICity city;
public class AQICity{
public String aqi;
public String pm25;
}
}
| 16.315789
| 43
| 0.641935
|
499081d35e439c08c69057d5259720154c947754
| 534
|
package org.d11.boot.application.util;
import org.d11.boot.application.model.D11Entity;
import org.modelmapper.AbstractConverter;
import java.util.List;
import java.util.stream.Collectors;
/**
* Converts a list of D11 entities to a list of ids.
*/
public class D11EntityListMapperConverter extends AbstractConverter<List<D11Entity>, List<Long>> {
@Override
protected List<Long> convert(final List<D11Entity> d11Entities) {
return d11Entities.stream().map(D11Entity::getId).collect(Collectors.toList());
}
}
| 26.7
| 98
| 0.756554
|
444b2740f59b96efb6719943da5aae7bf0ab2ddf
| 2,166
|
/*
* Copyright (c) 2005-2011 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.application.meeting.util.helpers;
import org.mifos.application.meeting.business.MeetingTypeEntity;
/**
* When ever we require a frequency(recurrence pattern) to be stored, we create
* a "meeting" (this is not necessarily a meeting in the sense we present to the
* users).
*
* See also {@link MeetingTypeEntity}.
*/
public enum MeetingType {
/* Schedule of loan installment payments for an account */
LOAN_INSTALLMENT((short) 1),
/*
* This is not to generate a schedule, but to calculate the interest after
* the specified time period.
*/
SAVINGS_INTEREST_CALCULATION_TIME_PERIOD((short) 2),
/* Schedule for posting interest to an account */
SAVINGS_INTEREST_POSTING((short) 3),
/* This is what we call a "meeting" in the user interface. */
CUSTOMER_MEETING((short) 4),
/* Recurrence of a fee. Can be for either a loan or a customer. */
PERIODIC_FEE((short) 5);
Short value;
MeetingType(Short value) {
this.value = value;
}
public Short getValue() {
return value;
}
public static MeetingType fromInt(int value) {
for (MeetingType meetingType : MeetingType.values()) {
if (meetingType.getValue() == value) {
return meetingType;
}
}
throw new RuntimeException("meeting type " + value + " unrecognized");
}
}
| 30.507042
| 80
| 0.680979
|
c679c279cabc5137a2b51b0325f2cb53dc069e33
| 2,880
|
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7019834
* @summary test default implementation of Principal.implies
*/
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosPrincipal;
import javax.security.auth.x500.X500Principal;
public class Implies {
public static void main(String[] args) throws Exception {
X500Principal duke = new X500Principal("CN=Duke");
// should not throw NullPointerException
testImplies(duke, (Subject)null, false);
Set<Principal> principals = new HashSet<>();
principals.add(duke);
testImplies(duke, principals, true);
X500Principal tux = new X500Principal("CN=Tux");
principals.add(tux);
testImplies(duke, principals, true);
principals.add(new KerberosPrincipal("duke@java.com"));
testImplies(duke, principals, true);
principals.clear();
principals.add(tux);
testImplies(duke, principals, false);
System.out.println("test passed");
}
private static void testImplies(Principal principal,
Set<? extends Principal> principals,
boolean result)
throws SecurityException
{
Subject subject = new Subject(true, principals, Collections.emptySet(),
Collections.emptySet());
testImplies(principal, subject, result);
}
private static void testImplies(Principal principal,
Subject subject, boolean result)
throws SecurityException
{
if (principal.implies(subject) != result) {
throw new SecurityException("test failed");
}
}
}
| 35.555556
| 79
| 0.670833
|
9f76a32e0c2e3ae4801b674e307a609dc28a86d9
| 9,429
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.ingest.processor;
import org.elasticsearch.ingest.TestProcessor;
import org.elasticsearch.ingest.TestTemplateService;
import org.elasticsearch.ingest.core.CompoundProcessor;
import org.elasticsearch.ingest.core.IngestDocument;
import org.elasticsearch.ingest.core.Processor;
import org.elasticsearch.ingest.core.TemplateService;
import org.elasticsearch.ingest.core.ValueSource;
import org.elasticsearch.test.ESTestCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
public class ForEachProcessorTests extends ESTestCase {
public void testExecute() throws Exception {
List<String> values = new ArrayList<>();
values.add("foo");
values.add("bar");
values.add("baz");
IngestDocument ingestDocument = new IngestDocument(
"_index", "_type", "_id", null, null, null, null, Collections.singletonMap("values", values)
);
ForEachProcessor processor = new ForEachProcessor(
"_tag", "values", Collections.singletonList(new UppercaseProcessor("_tag", "_value"))
);
processor.execute(ingestDocument);
List<String> result = ingestDocument.getFieldValue("values", List.class);
assertThat(result.get(0), equalTo("FOO"));
assertThat(result.get(1), equalTo("BAR"));
assertThat(result.get(2), equalTo("BAZ"));
}
public void testExecuteWithFailure() throws Exception {
IngestDocument ingestDocument = new IngestDocument(
"_index", "_type", "_id", null, null, null, null, Collections.singletonMap("values", Arrays.asList("a", "b", "c"))
);
TestProcessor testProcessor = new TestProcessor(id -> {
if ("c".equals(id.getFieldValue("_value", String.class))) {
throw new RuntimeException("failure");
}
});
ForEachProcessor processor = new ForEachProcessor("_tag", "values", Collections.singletonList(testProcessor));
try {
processor.execute(ingestDocument);
fail("exception expected");
} catch (RuntimeException e) {
assertThat(e.getMessage(), equalTo("failure"));
}
assertThat(testProcessor.getInvokedCounter(), equalTo(3));
assertThat(ingestDocument.getFieldValue("values", List.class), equalTo(Arrays.asList("a", "b", "c")));
testProcessor = new TestProcessor(id -> {
String value = id.getFieldValue("_value", String.class);
if ("c".equals(value)) {
throw new RuntimeException("failure");
} else {
id.setFieldValue("_value", value.toUpperCase(Locale.ROOT));
}
});
Processor onFailureProcessor = new TestProcessor(ingestDocument1 -> {});
processor = new ForEachProcessor(
"_tag", "values",
Collections.singletonList(new CompoundProcessor(Arrays.asList(testProcessor), Arrays.asList(onFailureProcessor)))
);
processor.execute(ingestDocument);
assertThat(testProcessor.getInvokedCounter(), equalTo(3));
assertThat(ingestDocument.getFieldValue("values", List.class), equalTo(Arrays.asList("A", "B", "c")));
}
public void testMetaDataAvailable() throws Exception {
List<Map<String, Object>> values = new ArrayList<>();
values.add(new HashMap<>());
values.add(new HashMap<>());
IngestDocument ingestDocument = new IngestDocument(
"_index", "_type", "_id", null, null, null, null, Collections.singletonMap("values", values)
);
TestProcessor innerProcessor = new TestProcessor(id -> {
id.setFieldValue("_value.index", id.getSourceAndMetadata().get("_index"));
id.setFieldValue("_value.type", id.getSourceAndMetadata().get("_type"));
id.setFieldValue("_value.id", id.getSourceAndMetadata().get("_id"));
});
ForEachProcessor processor = new ForEachProcessor("_tag", "values", Collections.singletonList(innerProcessor));
processor.execute(ingestDocument);
assertThat(innerProcessor.getInvokedCounter(), equalTo(2));
assertThat(ingestDocument.getFieldValue("values.0.index", String.class), equalTo("_index"));
assertThat(ingestDocument.getFieldValue("values.0.type", String.class), equalTo("_type"));
assertThat(ingestDocument.getFieldValue("values.0.id", String.class), equalTo("_id"));
assertThat(ingestDocument.getFieldValue("values.1.index", String.class), equalTo("_index"));
assertThat(ingestDocument.getFieldValue("values.1.type", String.class), equalTo("_type"));
assertThat(ingestDocument.getFieldValue("values.1.id", String.class), equalTo("_id"));
}
public void testRestOfTheDocumentIsAvailable() throws Exception {
List<Map<String, Object>> values = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Map<String, Object> object = new HashMap<>();
object.put("field", "value");
values.add(object);
}
Map<String, Object> document = new HashMap<>();
document.put("values", values);
document.put("flat_values", new ArrayList<>());
document.put("other", "value");
IngestDocument ingestDocument = new IngestDocument("_index", "_type", "_id", null, null, null, null, document);
TemplateService ts = TestTemplateService.instance();
ForEachProcessor processor = new ForEachProcessor(
"_tag", "values", Arrays.asList(
new AppendProcessor("_tag", ts.compile("flat_values"), ValueSource.wrap("value", ts)),
new SetProcessor("_tag", ts.compile("_value.new_field"), (model) -> model.get("other")))
);
processor.execute(ingestDocument);
assertThat(ingestDocument.getFieldValue("values.0.new_field", String.class), equalTo("value"));
assertThat(ingestDocument.getFieldValue("values.1.new_field", String.class), equalTo("value"));
assertThat(ingestDocument.getFieldValue("values.2.new_field", String.class), equalTo("value"));
assertThat(ingestDocument.getFieldValue("values.3.new_field", String.class), equalTo("value"));
assertThat(ingestDocument.getFieldValue("values.4.new_field", String.class), equalTo("value"));
List<String> flatValues = ingestDocument.getFieldValue("flat_values", List.class);
assertThat(flatValues.size(), equalTo(5));
assertThat(flatValues.get(0), equalTo("value"));
assertThat(flatValues.get(1), equalTo("value"));
assertThat(flatValues.get(2), equalTo("value"));
assertThat(flatValues.get(3), equalTo("value"));
assertThat(flatValues.get(4), equalTo("value"));
}
public void testRandom() throws Exception {
int numProcessors = randomInt(8);
List<Processor> processors = new ArrayList<>(numProcessors);
for (int i = 0; i < numProcessors; i++) {
processors.add(new Processor() {
@Override
public void execute(IngestDocument ingestDocument) throws Exception {
String existingValue = ingestDocument.getFieldValue("_value", String.class);
ingestDocument.setFieldValue("_value", existingValue + ".");
}
@Override
public String getType() {
return null;
}
@Override
public String getTag() {
return null;
}
});
}
int numValues = randomIntBetween(1, 32);
List<String> values = new ArrayList<>(numValues);
for (int i = 0; i < numValues; i++) {
values.add("");
}
IngestDocument ingestDocument = new IngestDocument(
"_index", "_type", "_id", null, null, null, null, Collections.singletonMap("values", values)
);
ForEachProcessor processor = new ForEachProcessor("_tag", "values", processors);
processor.execute(ingestDocument);
List<String> result = ingestDocument.getFieldValue("values", List.class);
assertThat(result.size(), equalTo(numValues));
String expectedString = "";
for (int i = 0; i < numProcessors; i++) {
expectedString = expectedString + ".";
}
for (String r : result) {
assertThat(r, equalTo(expectedString));
}
}
}
| 45.114833
| 126
| 0.644395
|
cef04f6ddd93284245851eb19a08d6b1c2035bb8
| 16,635
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.editor.retools.probe;
import java.awt.Component;
import java.awt.Container;
import java.awt.KeyboardFocusManager;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.FocusManager;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import org.netbeans.api.editor.EditorRegistry;
import org.netbeans.lib.editor.util.swing.DocumentUtilities;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataObject;
import org.openide.modules.ModuleInfo;
import org.openide.util.Lookup;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
/**
*
* @author Vita Stejskal <vstejskal at netbeans.org>
*/
public class Probe {
private static final Logger LOG = Logger.getLogger(Probe.class.getName());
private final Map<String, Throwable> originsToMention = new HashMap<String, Throwable>();
public Probe() {
}
public String getStatus() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos, true, "utf-8"); //NOI18N
try {
String msg = "Editor Probe " + getVersion() + " dumping info..."; //NOI18N
Installer.FLOG.info(msg);
ps.println(msg);
if (isJdkPatched()) {
ps.println("The Probe's JDK patches detected, excellent!"); //NOI18N
} else {
ps.println("The Probe can't detect its JDK patches and is running with limited functionality only."); //NOI18N
}
originsToMention.clear();
addEnvironmentInfo(ps);
addAllMopdules(ps);
addGeneralStatus(ps);
List<? extends JTextComponent> editors = EditorRegistry.componentList();
for(int i = 0; i < editors.size(); i++) {
addSingleEditorStatus(editors.get(i), i, ps);
}
addFailedFocusRequests(ps);
addOrigins(ps);
msg = "Editor Probe " + getVersion() + " dump finished!"; //NOI18N
Installer.FLOG.info(msg);
ps.println(msg);
} finally {
ps.flush();
ps.close();
}
return baos.toString("utf-8"); //NOI18N
} catch (UnsupportedEncodingException uee) {
LOG.log(Level.WARNING, null, uee);
return uee.getMessage();
}
}
private void addEnvironmentInfo(PrintStream ps) {
try {
ClassLoader cl = Lookup.getDefault().lookup(ClassLoader.class);
Class<?> topLoggingClass = cl.loadClass("org.netbeans.core.startup.TopLogging"); //NOI18N
Method printSystemInfoMethod = topLoggingClass.getDeclaredMethod("printSystemInfo", PrintStream.class); //NOI18N
printSystemInfoMethod.setAccessible(true);
printSystemInfoMethod.invoke(null, ps);
} catch (Exception e) {
LOG.log(Level.INFO, null, e);
}
}
private void addAllMopdules(PrintStream ps) {
Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class);
for(ModuleInfo mi : modules) {
ps.print(" "); //NOI18N
ps.print(mi.getCodeName());
ps.print(" ["); //NOI18N
ps.print(mi.getSpecificationVersion());
ps.print(" "); //NOI18N
ps.print(mi.getBuildVersion());
ps.println("]"); //NOI18N
}
addSeparator(ps);
}
private void addGeneralStatus(PrintStream ps) {
List<? extends JTextComponent> editors = EditorRegistry.componentList();
ps.println("Registered editors: " + editors.size()); //NOI18N
ps.println("Last focused editor: " + editorId(EditorRegistry.lastFocusedComponent())); //NOI18N
ps.println("Currently focused editor: " + editorId(EditorRegistry.focusedComponent())); //NOI18N
ps.println();
// Dump focus info:
KeyboardFocusManager kfm = FocusManager.getCurrentKeyboardFocusManager();
ps.println("Focus manager: " + s2s(kfm)); //NOI18N
ps.println("Active window: " + s2s(kfm.getActiveWindow())); //NOI18N
ps.println("Focused window: " + s2s(kfm.getFocusedWindow())); //NOI18N
ps.println("Netbeans main window: " + s2s(WindowManager.getDefault().getMainWindow())); //NOI18N
ps.println("Focus cycle root: " + s2s(kfm.getCurrentFocusCycleRoot())); //NOI18N
ps.println("Permanent focus owner: " + s2s(kfm.getPermanentFocusOwner())); //NOI18N
ps.print("Focus owner: "); //NOI18N
dumpAncestors(kfm.getFocusOwner(), ps, ""); //NOI18N
addSeparator(ps);
}
private void addSingleEditorStatus(JTextComponent editor, int index, PrintStream ps) {
ps.println("Editor[" + index + "]: " + editorId(editor)); //NOI18N
// Dump component info
ps.println("JTextComponent: " + s2s(editor)); //NOI18N
ps.println("Enabled: " + editor.isEnabled()); //NOI18N
ps.println("Editable: " + editor.isEditable()); //NOI18N
ps.println("Focusable: " + editor.isFocusable()); //NOI18N
ps.println("Focus owner: " + editor.isFocusOwner()); //NOI18N
ps.println("Valid: " + editor.isValid()); //NOI18N
ps.println("Caret: " + s2s(editor.getCaret())); //NOI18N
ps.println("Caret offset: " + editor.getCaretPosition()); //NOI18N
ps.println("Selection: <" + editor.getSelectionStart() + "," + editor.getSelectionEnd() + ">"); //NOI18N
ps.println("UI: " + s2s(editor.getUI())); //NOI18N
ps.println("Parent: " + s2s(editor.getParent())); //NOI18N
ps.println("Keymap size: " + editor.getKeymap().getBoundKeyStrokes().length); //NOI18N
ps.println();
// Dump document info
Document document = editor.getDocument();
ps.println("Document: " + s2s(document)); //NOI18N
ps.println("Mimetype: '" + document.getProperty("mimeType") + "'"); //NOI18N
ps.println("Length: " + document.getLength()); //NOI18N
ps.println("Read locked: " + DocumentUtilities.isReadLocked(document)); //NOI18N
ps.println("Write locked: " + DocumentUtilities.isWriteLocked(document)); //NOI18N
// dump all fields from the whole class hierarchy
ps.println();
// Dump file info
FileObject file = getFileObjectFor(document);
if (file != null) {
ps.println("File: " + file.getPath()); //NOI18N
ps.println("Mimetype: '" + file.getMIMEType() + "'"); //NOI18N
ps.println("Readonly: " + !file.canWrite()); //NOI18N
} else {
ps.println("Stream: " + document.getProperty(Document.StreamDescriptionProperty)); //NOI18N
}
ps.println();
// Dump TopComponent hierarchy
TopComponent topComponent = (TopComponent) SwingUtilities.getAncestorOfClass(TopComponent.class, editor);
dumpComponentHierarchy(topComponent, ps, "");
addSeparator(ps);
}
private void addOrigins(PrintStream ps) {
if (originsToMention.size() > 0) {
ps.println("Known java.awt.Component origins:"); //NOI18N
List<String> references = new ArrayList<String>(originsToMention.keySet());
Collections.sort(references);
for(String r : references) {
Throwable origin = originsToMention.get(r);
ps.println("<a name=\"" + r + "\"></a>"); //NOI18N
origin.printStackTrace(ps);
}
addSeparator(ps);
}
}
private void addFailedFocusRequests(PrintStream ps) {
ps.println("Failed calls to java.awt.Component.requestFocus() and similar:"); //NOI18N
Throwable [] failedRequests = getFailedFocusRequests();
if (failedRequests.length > 0) {
for(Throwable stacktrace : failedRequests) {
ps.println();
stacktrace.printStackTrace(ps);
}
} else {
ps.println("No failures!"); //NOI18N
}
addSeparator(ps);
}
private void addSeparator(PrintStream ps) {
ps.println("-------------------------------------------------------------------------------"); // NOI18N
}
public static String s2s(Object o) {
return _s2s(o, false);
}
private static String _s2s(Object o, boolean linkToOrigin) {
if (o == null) {
return "null"; //NOI18N
} else {
String classAndHash = o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); //NOI18N
if (linkToOrigin) {
classAndHash = "<a href=\"#" + classAndHash + "\">" + classAndHash + "</a>"; //NOI18N
}
if (o instanceof Container) {
return classAndHash
+ "; name='" + ((Component) o).getName() + "'" //NOI18N
+ "; isFocusable=" + ((Component) o).isFocusable() //NOI18N
+ "; isFocusOwner=" + ((Component) o).isFocusOwner() //NOI18N
+ "; focusTraversalPolicy=" + s2s(((Container) o).getFocusTraversalPolicy()) //NOI18N
;
} else if (o instanceof Component) {
return classAndHash
+ "; name='" + ((Component) o).getName() + "'" //NOI18N
+ "; isFocusable=" + ((Component) o).isFocusable() //NOI18N
+ "; isFocusOwner=" + ((Component) o).isFocusOwner() //NOI18N
;
} else {
return classAndHash;
}
}
}
private String s2sLink(Component o) {
Throwable origin = findOrigin(o);
if (origin != null) {
String classAndHash = o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); //NOI18N
originsToMention.put(classAndHash, origin);
return _s2s(o, true);
} else {
return s2s(o);
}
}
public static boolean isJdkPatched() {
findOrigin(null);
getFailedFocusRequests();
return !noFindOriginMethod && !noGetFailedFocusRequestsMethod;
}
private static boolean noFindOriginMethod = false;
private static Throwable findOrigin(Component c) {
Throwable origin = null;
if (!noFindOriginMethod) {
try {
Method findOriginMethod = Component.class.getDeclaredMethod("findOrigin", Component.class); //NOI18N
findOriginMethod.setAccessible(true);
origin = (Throwable) findOriginMethod.invoke(null, c);
} catch (Exception e) {
noFindOriginMethod = true;
LOG.log(Level.INFO, null, e);
}
}
return origin;
}
private static boolean noGetFailedFocusRequestsMethod = false;
private static Throwable[] getFailedFocusRequests() {
Throwable[] failedRequests = new Throwable[0];
if (!noGetFailedFocusRequestsMethod) {
try {
Method findOriginMethod = Component.class.getDeclaredMethod("getFailedFocusRequests"); //NOI18N
findOriginMethod.setAccessible(true);
failedRequests = (Throwable []) findOriginMethod.invoke(null);
} catch (Exception e) {
noGetFailedFocusRequestsMethod = true;
LOG.log(Level.INFO, null, e);
}
}
return failedRequests;
}
private String editorId(JTextComponent c) {
if (c == null) {
return "null"; //NOI18N
} else {
Document d = c.getDocument();
Object stream = d.getProperty(Document.StreamDescriptionProperty);
FileObject f = getFileObjectFor(d);
return s2sLink(c) + "; stream=" + (f != null ? f.getPath() : s2s(stream)) + "; mimeType='" + d.getProperty("mimeType") + "'"; //NOI18N
}
}
private static FileObject getFileObjectFor(Document d) {
Object stream = d.getProperty(Document.StreamDescriptionProperty);
FileObject f = null;
if (stream instanceof FileObject) {
f = (FileObject) stream;
} else if (stream instanceof DataObject) {
f = ((DataObject) stream).getPrimaryFile();
}
return f;
}
private void dumpComponentHierarchy(Component c, PrintStream ps, String indent) {
if (c != null) {
if (c.isFocusOwner()) {
ps.print("* "); //NOI18N
} else {
ps.print(" "); //NOI18N
}
ps.print(indent);
ps.print(s2sLink(c));
ps.println();
if (c instanceof Container) {
for(Component child : ((Container) c).getComponents()) {
dumpComponentHierarchy(child, ps, indent + " "); //NOI18N
}
}
} else {
ps.print(" "); //NOI18N
ps.print(indent);
ps.println(s2s(c));
}
}
private void dumpAncestors(Component c, PrintStream ps, String indent) {
ps.print(indent);
if (c != null) {
ps.println(s2sLink(c));
if (c.getParent() != null) {
dumpAncestors(c.getParent(), ps, indent + " "); //NOI18N
}
} else {
ps.println(s2s(c));
}
}
public static String getVersion() {
Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class);
for(ModuleInfo m : modules) {
if (m.getCodeNameBase().equals("org.netbeans.modules.editor.probe")) { //NOI18N
return m.getSpecificationVersion().toString();
}
}
return "?"; //NOI18N
}
}
| 40.474453
| 146
| 0.590502
|
90e4025877aaed9cc7d4c18e3e2271e5f73d4883
| 7,742
|
package com.endava.cats.args;
import com.endava.cats.util.CatsUtil;
import com.google.common.collect.Maps;
import io.github.ludovicianul.prettylogger.PrettyLogger;
import io.github.ludovicianul.prettylogger.PrettyLoggerFactory;
import lombok.Getter;
import lombok.Setter;
import picocli.CommandLine;
import javax.inject.Singleton;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Singleton
public class FilesArguments {
private static final String ALL = "all";
private final PrettyLogger log = PrettyLoggerFactory.getLogger(this.getClass());
private final Map<String, Map<String, String>> headers = new HashMap<>();
private final Map<String, Map<String, String>> refData = new HashMap<>();
private final CatsUtil catsUtil;
private Map<String, Map<String, Object>> customFuzzerDetails = new HashMap<>();
private Map<String, Map<String, Object>> securityFuzzerDetails = new HashMap<>();
@CommandLine.Option(names = {"--urlParams"},
description = "A comma separated list of @|bold name:value|@ pairs of parameters to be replaced inside the URLs", split = ",")
@Getter
private List<String> params;
@CommandLine.Option(names = {"--headers"},
description = "Specifies custom headers that will be passed along with request. This can be used to pass oauth or JWT tokens for authentication purposed for example")
@Getter
@Setter
private File headersFile;
@CommandLine.Option(names = {"--refData"},
description = "Specifies the file with fields that must have a fixed value in order for requests to succeed. " +
"If this is supplied when @|bold FunctionalFuzzer|@ is also enabled, the @|bold FunctionalFuzzer|@ will consider it a @|bold refData|@ template and try to replace any variables")
@Getter
@Setter
private File refDataFile;
@CommandLine.Option(names = {"--functionalFuzzerFile"},
description = "Specifies the file used by the @|bold FunctionalFuzzer|@ that will be used to create user-supplied payloads")
@Getter
@Setter
private File customFuzzerFile;
@CommandLine.Option(names = {"--securityFuzzerFile"},
description = "Specifies the file used by the @|bold SecurityFuzzer|@ that will be used to inject special strings in order to exploit possible vulnerabilities")
@Getter
@Setter
private File securityFuzzerFile;
@CommandLine.Option(names = {"--createRefData"},
description = "This is only applicable when enabling the @|bold FunctionalFuzzer |@. It will instruct the @|bold FunctionalFuzzer|@ to create a @|bold,underline --refData|@ file " +
"with all the paths defined in the @|bold,underline customFuzzerFile|@ and the corresponding @|bold output|@ variables")
@Getter
@Setter
private boolean createRefData;
public FilesArguments(CatsUtil cu) {
this.catsUtil = cu;
}
/**
* Loads all supplied files for --securityFuzzerFile, --customFuzzerFile, --refData, --urlParams and --headers.
*
* @throws IOException if something happens during file processing
*/
public void loadConfig() throws IOException {
loadSecurityFuzzerFile();
loadCustomFuzzerFile();
loadRefData();
loadURLParams();
loadHeaders();
}
public void loadSecurityFuzzerFile() throws IOException {
if (securityFuzzerFile == null) {
log.info("No security custom Fuzzer file. SecurityFuzzer will be skipped!");
} else {
securityFuzzerDetails = catsUtil.parseYaml(securityFuzzerFile.getAbsolutePath());
}
}
public void loadCustomFuzzerFile() throws IOException {
if (customFuzzerFile == null) {
log.info("No custom Fuzzer file. FunctionalFuzzer will be skipped!");
} else {
customFuzzerDetails = catsUtil.parseYaml(customFuzzerFile.getAbsolutePath());
}
}
public void loadRefData() throws IOException {
if (refDataFile == null) {
log.info("No reference data file was supplied! Payloads supplied by Fuzzers will remain unchanged!");
} else {
catsUtil.loadFileToMap(refDataFile.getAbsolutePath(), refData);
log.info("Reference data file loaded successfully: {}", refData);
}
}
public void loadURLParams() {
if (params == null) {
log.info("No URL parameters supplied!");
} else {
log.info("URL parameters: {}", params);
}
}
public void loadHeaders() throws IOException {
if (headersFile == null) {
log.info("No headers file was supplied! No additional header will be added!");
} else {
catsUtil.loadFileToMap(headersFile.getAbsolutePath(), headers);
}
}
/**
* Returns a list of the --urlParams supplied. The list will contain strings in the {@code name:value} pairs.
*
* @return a name:value list of url params to be replaced when calling the service
*/
public List<String> getUrlParamsList() {
return Optional.ofNullable(this.params).orElse(Collections.emptyList());
}
/**
* Replaces the current URL parameters with the {@code --urlParams} arguments supplied.
* The URL parameters are expected to be included in curly brackets.
*
* @param startingUrl the base url; http://localhost:8080/{petId}
* @return the initial URL with the parameters replaced with --urlParams supplied values
*/
public String replacePathWithUrlParams(String startingUrl) {
for (String line : this.getUrlParamsList()) {
String[] urlParam = line.split(":");
String pathVar = "{" + urlParam[0] + "}";
if (startingUrl.contains(pathVar)) {
startingUrl = startingUrl.replace(pathVar, urlParam[1]);
}
}
return startingUrl;
}
/**
* Returns the header values supplied in the --headers argument.
* <p>
* The map keys are the contract paths or {@code all} if headers are applied to all paths.
*
* @return a Map representation of the --headers file with paths being the Map keys
*/
public Map<String, Map<String, String>> getHeaders() {
return this.headers;
}
/**
* Returns the reference data from the --refData file supplied as argument.
* <p>
* It return reference data for both the given path and under the {@code all} key.
*
* @param currentPath the current API path
* @return a Map with the supplied --refData
*/
public Map<String, String> getRefData(String currentPath) {
Map<String, String> currentPathRefData = Optional.ofNullable(this.refData.get(currentPath)).orElse(Maps.newHashMap());
Map<String, String> allValues = Optional.ofNullable(this.refData.get(ALL)).orElse(Collections.emptyMap());
currentPathRefData.putAll(allValues);
return currentPathRefData;
}
/**
* Returns a Map representation of the --customFuzzer. Map keys are test cases IDs.
*
* @return a Map representation of the --customFuzzer
*/
public Map<String, Map<String, Object>> getCustomFuzzerDetails() {
return this.customFuzzerDetails;
}
/**
* Returns a Map representation of the --securityFuzzer. Map keys are test cases IDs.
*
* @return a Map representation of the --securityFuzzer
*/
public Map<String, Map<String, Object>> getSecurityFuzzerDetails() {
return this.securityFuzzerDetails;
}
}
| 38.71
| 198
| 0.663782
|
52b232575c8196f8ad4473f24f58e9546e8c447e
| 3,012
|
/*
* 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.rds.transform.v20140815;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.rds.model.v20140815.DescribeTasksResponse;
import com.aliyuncs.rds.model.v20140815.DescribeTasksResponse.TaskProgressInfo;
import java.util.Map;
import com.aliyuncs.transform.UnmarshallerContext;
public class DescribeTasksResponseUnmarshaller {
public static DescribeTasksResponse unmarshall(DescribeTasksResponse describeTasksResponse, UnmarshallerContext context) {
describeTasksResponse.setRequestId(context.stringValue("DescribeTasksResponse.RequestId"));
describeTasksResponse.setTotalRecordCount(context.integerValue("DescribeTasksResponse.TotalRecordCount"));
describeTasksResponse.setPageNumber(context.integerValue("DescribeTasksResponse.PageNumber"));
describeTasksResponse.setPageRecordCount(context.integerValue("DescribeTasksResponse.PageRecordCount"));
List<TaskProgressInfo> items = new ArrayList<TaskProgressInfo>();
for (int i = 0; i < context.lengthValue("DescribeTasksResponse.Items.Length"); i++) {
TaskProgressInfo taskProgressInfo = new TaskProgressInfo();
taskProgressInfo.setDBName(context.stringValue("DescribeTasksResponse.Items["+ i +"].DBName"));
taskProgressInfo.setBeginTime(context.stringValue("DescribeTasksResponse.Items["+ i +"].BeginTime"));
taskProgressInfo.setProgressInfo(context.stringValue("DescribeTasksResponse.Items["+ i +"].ProgressInfo"));
taskProgressInfo.setFinishTime(context.stringValue("DescribeTasksResponse.Items["+ i +"].FinishTime"));
taskProgressInfo.setTaskAction(context.stringValue("DescribeTasksResponse.Items["+ i +"].TaskAction"));
taskProgressInfo.setTaskId(context.stringValue("DescribeTasksResponse.Items["+ i +"].TaskId"));
taskProgressInfo.setProgress(context.stringValue("DescribeTasksResponse.Items["+ i +"].Progress"));
taskProgressInfo.setExpectedFinishTime(context.stringValue("DescribeTasksResponse.Items["+ i +"].ExpectedFinishTime"));
taskProgressInfo.setStatus(context.stringValue("DescribeTasksResponse.Items["+ i +"].Status"));
taskProgressInfo.setTaskErrorCode(context.stringValue("DescribeTasksResponse.Items["+ i +"].TaskErrorCode"));
taskProgressInfo.setTaskErrorMessage(context.stringValue("DescribeTasksResponse.Items["+ i +"].TaskErrorMessage"));
items.add(taskProgressInfo);
}
describeTasksResponse.setItems(items);
return describeTasksResponse;
}
}
| 53.785714
| 123
| 0.788513
|
4543897899ec6d3d235c0a7b9451934bcccf01b7
| 1,057
|
/*
* 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 inheritance;
import java.util.LinkedList;
import java.util.Random;
/**
*
* @author tylerpowell
*/
public class InheritanceCollectionPractice {
private static LinkedList<Vehicle> vList;
public static void main (String[] args){
vList = new LinkedList<>();
generateRandomBalloon(999999999);
} // close main
public static void generateRandomBalloon(int numOf){
Random rand = new Random();
for(int i = 0; i < numOf; i++){
Balloon b = new Balloon();
double hours = rand.nextDouble();
// double hours = rand.nextDouble() * Balloon.;
System.out.println("Generated rand hours of: " + hours);
b.setNumFlyingHours((int) hours);
vList.add(b);
}
System.out.println("Generate list of size: " + vList.size());
}
} // close class
| 27.102564
| 79
| 0.625355
|
51462684d16a71da0a9ebd29af2a66d5976b09f2
| 1,284
|
package org;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.NamingException;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.action.ActionContext;
public class UpdatePersonUid {
private static final String DATASOURCE_X5SYS = "system";
public static JSONObject updatePersonUid(JSONObject params, ActionContext context) throws SQLException, NamingException {
Connection conn = context.getConnection(DATASOURCE_X5SYS);
Statement stmt = null;
JSONObject ret = new JSONObject();
String pid = params.getString("pid");
int uid =Integer.parseInt(params.getString("uid") == null ? "0" : params.getString("uid").toString()); ;
System.out.print(uid);
String sql = "update sa_opperson set sNumb=" + uid + " where sID= '"+pid+"'" ;
stmt = conn.createStatement();
int i = stmt.executeUpdate(sql);
System.out.print(i);
if(i>0){
ret.put("state", true);
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}else{
ret.put("state", false);
if(stmt!=null)
stmt.close();
if(conn!=null)
conn.close();
}
return ret;
}
public static JSONObject personAvatar(JSONObject params, ActionContext context) throws SQLException, NamingException {
return null;
}
}
| 28.533333
| 122
| 0.713396
|
4c79be96b7bc3040609f9a72c33f61b858a12213
| 1,342
|
package edu.eci.ieti.envirify.security.userdetails;
import edu.eci.ieti.envirify.model.User;
import edu.eci.ieti.envirify.persistence.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Service that provides details of a user
* @author Error 418
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
/**
* Get a user by username
* @param username username of the user
* @return the user that has the username
* @throws UsernameNotFoundException in case that the app didn't found the username
*/
@Override
@Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = null;
user = userRepository.findByEmail(username);
if(user==null){
throw new UsernameNotFoundException("User not found");
}
return UserDetailsImpl.build(user);
}
}
| 35.315789
| 93
| 0.760805
|
fb91bc1caf69360a9c32cda1c70e8715b5b9e7de
| 1,132
|
/*
* Copyright (c) 2016 Uber Technologies, Inc. (hoodie-dev-group@uber.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.uber.hoodie.common.model;
/**
* Type of the Hoodie Table.
*
* Currently, 1 type is supported
*
* COPY_ON_WRITE - Performs upserts by versioning entire files, with later versions containing newer
* value of a record.
*
* In the future, following might be added.
*
* MERGE_ON_READ - Speeds up upserts, by delaying merge until enough work piles up.
*
* SIMPLE_LSM - A simple 2 level LSM tree.
*/
public enum HoodieTableType {
COPY_ON_WRITE, MERGE_ON_READ
}
| 31.444444
| 100
| 0.725265
|
de79970bf148f033f1d7d568f59d070617b90c49
| 10,740
|
//package mindustry.desktop.steam;
//
//import arc.*;
//import arc.struct.*;
//import arc.util.*;
//import com.codedisaster.steamworks.*;
//import mindustry.*;
//import mindustry.content.*;
//import mindustry.entities.type.*;
//import mindustry.entities.units.*;
//import mindustry.game.EventType.*;
//import mindustry.game.Stats.*;
//import mindustry.type.*;
//
//import static mindustry.Vars.*;
//import static mindustry.desktop.steam.SAchievement.*;
//
//@SuppressWarnings("unchecked")
//public class SStats implements SteamUserStatsCallback{
// public final SteamUserStats stats = new SteamUserStats(this);
//
// private boolean updated = false;
// private ObjectSet<String> mechs = new ObjectSet<>();
// private int statSavePeriod = 4; //in minutes
//
// public SStats(){
// stats.requestCurrentStats();
//
// Events.on(ClientLoadEvent.class, e -> {
// mechs = Core.settings.getObject("mechs", ObjectSet.class, ObjectSet::new);
//
// Core.app.addListener(new ApplicationListener(){
// Interval i = new Interval();
//
// @Override
// public void update(){
// if(i.get(60f / 4f)){
// checkUpdate();
// }
// }
// });
//
// Timer.schedule(() -> {
// if(updated){
// stats.storeStats();
// }
// }, statSavePeriod * 60, statSavePeriod * 60);
// });
// }
//
// public void onUpdate(){
// this.updated = true;
// }
//
// private void checkUpdate(){
// if(campaign()){
// SStat.maxUnitActive.max(unitGroup.count(t -> t.getTeam() == player.getTeam()));
//
// if(unitGroup.count(u -> u.getType() == UnitTypes.phantom && u.getTeam() == player.getTeam()) >= 10){
// active10Phantoms.complete();
// }
//
// if(unitGroup.count(u -> u.getType() == UnitTypes.crawler && u.getTeam() == player.getTeam()) >= 50){
// active50Crawlers.complete();
// }
//
// for(TileEntity entity : player.getTeam().cores()){
// if(!content.items().contains(i -> i.type == ItemType.material && entity.items.get(i) < entity.block.itemCapacity)){
// fillCoreAllCampaign.complete();
// break;
// }
// }
// }
// }
//
// private void registerEvents(){
// Events.on(UnitDestroyEvent.class, e -> {
// if(ncustom()){
// if(e.unit.getTeam() != Vars.player.getTeam()){
// SStat.unitsDestroyed.add();
//
// if(e.unit instanceof BaseUnit && ((BaseUnit)e.unit).isBoss()){
// SStat.bossesDefeated.add();
// }
// }
// }
// });
//
// Events.on(ZoneConfigureCompleteEvent.class, e -> {
// if(!content.zones().contains(z -> !z.canConfigure())){
// configAllZones.complete();
// }
// });
//
// Events.on(Trigger.newGame, () -> Core.app.post(() -> {
// if(campaign() && player.getClosestCore() != null && player.getClosestCore().items.total() >= 10 * 1000){
// drop10kitems.complete();
// }
// }));
//
// Events.on(CommandIssueEvent.class, e -> {
// if(campaign() && e.command == UnitCommand.attack){
// issueAttackCommand.complete();
// }
// });
//
// Events.on(BlockBuildEndEvent.class, e -> {
// if(campaign() && e.player == player && !e.breaking){
// SStat.blocksBuilt.add();
//
// if(e.tile.block() == Blocks.router && e.tile.entity.proximity().contains(t -> t.block() == Blocks.router)){
// chainRouters.complete();
// }
//
// if(e.tile.block() == Blocks.daggerFactory){
// buildDaggerFactory.complete();
// }
//
// if(e.tile.block() == Blocks.meltdown || e.tile.block() == Blocks.spectre){
// if(e.tile.block() == Blocks.meltdown && !Core.settings.getBool("meltdownp", false)){
// Core.settings.putSave("meltdownp", true);
// }
//
// if(e.tile.block() == Blocks.spectre && !Core.settings.getBool("spectrep", false)){
// Core.settings.putSave("spectrep", true);
// }
//
// if(Core.settings.getBool("meltdownp", false) && Core.settings.getBool("spectrep", false)){
// buildMeltdownSpectre.complete();
// }
// }
// }
// });
//
// Events.on(BlockDestroyEvent.class, e -> {
// if(campaign() && e.tile.getTeam() != player.getTeam()){
// SStat.blocksDestroyed.add();
// }
// });
//
// Events.on(MapMakeEvent.class, e -> SStat.mapsMade.add());
//
// Events.on(MapPublishEvent.class, e -> SStat.mapsPublished.add());
//
// Events.on(UnlockEvent.class, e -> {
// if(e.content == Items.thorium) obtainThorium.complete();
// if(e.content == Items.titanium) obtainTitanium.complete();
//
// if(!content.zones().contains(Zone::locked)){
// unlockAllZones.complete();
// }
// });
//
// Events.on(Trigger.openWiki, openWiki::complete);
//
// Events.on(Trigger.exclusionDeath, dieExclusion::complete);
//
// Events.on(Trigger.drown, drown::complete);
//
// trigger(Trigger.impactPower, powerupImpactReactor);
//
// trigger(Trigger.flameAmmo, useFlameAmmo);
//
// trigger(Trigger.turretCool, coolTurret);
//
// trigger(Trigger.suicideBomb, suicideBomb);
//
// Events.on(Trigger.enablePixelation, enablePixelation::complete);
//
// Events.on(Trigger.thoriumReactorOverheat, () -> {
// if(campaign()){
// SStat.reactorsOverheated.add();
// }
// });
//
// trigger(Trigger.shock, shockWetEnemy);
//
// trigger(Trigger.phaseDeflectHit, killEnemyPhaseWall);
//
// trigger(Trigger.itemLaunch, launchItemPad);
//
// Events.on(UnitCreateEvent.class, e -> {
// if(campaign() && e.unit.getTeam() == player.getTeam()){
// SStat.unitsBuilt.add();
// }
// });
//
// Events.on(LoseEvent.class, e -> {
// if(campaign()){
// if(world.getZone().metCondition() && (state.wave - world.getZone().conditionWave) / world.getZone().launchPeriod >= 1){
// skipLaunching2Death.complete();
// }
// }
// });
//
// Events.on(LaunchEvent.class, e -> {
// if(state.rules.tutorial){
// completeTutorial.complete();
// }
//
// SStat.timesLaunched.add();
// });
//
// Events.on(LaunchItemEvent.class, e -> {
// SStat.itemsLaunched.add(e.stack.amount);
// });
//
// Events.on(WaveEvent.class, e -> {
// if(ncustom()){
// SStat.maxWavesSurvived.max(Vars.state.wave);
//
// if(state.stats.buildingsBuilt == 0 && state.wave >= 10){
// survive10WavesNoBlocks.complete();
// }
// }
// });
//
// Events.on(PlayerJoin.class, e -> {
// if(Vars.net.server()){
// SStat.maxPlayersServer.max(Vars.playerGroup.size());
// }
// });
//
// Events.on(ResearchEvent.class, e -> {
// if(e.content == Blocks.router) researchRouter.complete();
//
// if(!TechTree.all.contains(t -> t.block.locked())){
// researchAll.complete();
// }
// });
//
// Events.on(WinEvent.class, e -> {
// if(campaign()){
// if(Vars.state.wave <= 5 && state.rules.attackMode){
// defeatAttack5Waves.complete();
// }
//
// if(Vars.state.rules.attackMode){
// SStat.attacksWon.add();
// }
//
// RankResult result = state.stats.calculateRank(world.getZone(), state.launched);
// if(result.rank == Rank.S) earnSRank.complete();
// if(result.rank == Rank.SS) earnSSRank.complete();
// }
//
// if(state.rules.pvp){
// SStat.pvpsWon.add();
// }
// });
//
// Events.on(MechChangeEvent.class, e -> {
// if(campaign()){
// if(mechs.add(e.mech.name)){
// SStat.zoneMechsUsed.max(mechs.size);
// Core.settings.putObject("mechs", mechs);
// Core.settings.save();
// }
// }
// });
// }
//
// private void trigger(Trigger trigger, SAchievement ach){
// Events.on(trigger, () -> {
// if(campaign()){
// ach.complete();
// }
// });
// }
//
// private boolean ncustom(){
// return campaign();
// }
//
// private boolean campaign(){
// return Vars.world.isZone();
// }
//
// @Override
// public void onUserStatsReceived(long gameID, SteamID steamID, SteamResult result){
// registerEvents();
//
// if(result != SteamResult.OK){
// Log.err("Failed to recieve steam stats: {0}", result);
// }else{
// Log.info("Recieved steam stats.");
// }
// }
//
// @Override
// public void onUserStatsStored(long gameID, SteamResult result){
// Log.info("Stored stats: {0}", result);
//
// if(result == SteamResult.OK){
// updated = true;
// }
// }
//
// @Override
// public void onUserStatsUnloaded(SteamID steamID){
//
// }
//
// @Override
// public void onUserAchievementStored(long l, boolean b, String s, int i, int i1){
//
// }
//
// @Override
// public void onLeaderboardFindResult(SteamLeaderboardHandle steamLeaderboardHandle, boolean b){
//
// }
//
// @Override
// public void onLeaderboardScoresDownloaded(SteamLeaderboardHandle steamLeaderboardHandle, SteamLeaderboardEntriesHandle steamLeaderboardEntriesHandle, int i){
//
// }
//
// @Override
// public void onLeaderboardScoreUploaded(boolean b, SteamLeaderboardHandle steamLeaderboardHandle, int i, boolean b1, int i1, int i2){
//
// }
//
// @Override
// public void onGlobalStatsReceived(long l, SteamResult steamResult){
//
// }
//}
| 32.644377
| 163
| 0.50121
|
79981580f245442603a15393a1077cc474c6f912
| 698
|
package sim.com.read;
import org.objectweb.asm.ClassReader;
import java.io.IOException;
/**
* @QQ交流群: 648741281
* @Email: 177300883312@163.com
* @微信: londu19930418
* @Author: Simon.Mr
* @Created 2020/5/22
*/
public class TestReader {
public static void main(String[] args) throws IOException {
/**
* 1 读取目标类
* 注意事项: 采用org.objectweb.asm.ClassReader包
*/
ClassReader reader = new ClassReader("sim.com.vo.User");
/**
* 2 创建对象
*/
SimUUClassVisitor simUUClassVisitor = new SimUUClassVisitor();
/**
* 3 执行
*/
reader.accept(simUUClassVisitor,ClassReader.SKIP_DEBUG);
}
}
| 18.368421
| 70
| 0.591691
|
7c4b0cd9582ac1339f7fcc49cd5de4f2e55560a2
| 1,323
|
// Java program to implement optimized matrix chain multiplication problem.
// https://www.geeksforgeeks.org/matrix-chain-multiplication-a-on2-solution/?ref=rp
// https://www.youtube.com/watch?v=9uUVFNOT3_Y&list=PL_z_8CaSLPWekqhdCPmFohncHwz8TY2Go&index=35
import java.util.*;
import java.lang.*;
import java.io.*;
class MCM_dp{
// Matrix Mi has dimension p[i-1] x p[i] for i = 1..n
static int MatrixChainOrder(int p[], int n)
{
/* For simplicity of the program, one extra row and one extra column are
allocated in dp[][]. 0th row and 0th column of dp[][] are not used */
int [][]dp=new int[n][n];
/* dp[i, j] = Minimum number of scalar multiplications needed to compute the matrix M[i]M[i+1]...M[j]
= M[i..j] where dimension of M[i] is p[i-1] x p[i] */
// cost is zero when multiplying one matrix.
for (int i=1; i<n; i++)
dp[i][i] = 0;
// Simply following above recursive formula.
for (int L=1; L<n-1; L++)
for (int i=1; i<n-L; i++)
dp[i][i+L] = Math.min(dp[i+1][i+L] + p[i-1]*p[i]*p[i+L], dp[i][i+L-1] + p[i-1]*p[i+L-1]*p[i+L]);
return dp[1][n-1];
}
// Driver code
public static void main(String args[])
{
int arr[] = {10, 20, 30, 40, 30} ;
int size = arr.length;
System.out.print("Minimum number of multiplications is "+ MatrixChainOrder(arr, size));
}
}
| 30.068182
| 102
| 0.637188
|
076294f198b524b1a45818d3744f152b663c2f8b
| 1,628
|
package com.silabs.thunderboard.demos.ui;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.silabs.thunderboard.R;
import com.silabs.thunderboard.common.ui.ButtonSpinnerDrawable;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SwitchControl extends FrameLayout {
@Bind(R.id.switch_image)
ImageView image;
@Bind(R.id.switch_text)
TextView text;
ButtonSpinnerDrawable spinnerDrawable;
private Context context;
public SwitchControl(Context context) {
this(context, null, 0);
}
public SwitchControl(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwitchControl(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.switch_control, null, false);
addView(view);
ButterKnife.bind(this, view);
spinnerDrawable = new ButtonSpinnerDrawable(context);
image.setImageDrawable(spinnerDrawable);
this.context = context;
}
public void setChecked(boolean checked) {
if (checked) {
spinnerDrawable.start();
} else {
spinnerDrawable.stop();
}
text.setText(context.getString(checked ? R.string.on : R.string.off));
}
}
| 26.688525
| 81
| 0.707617
|
1e7b6f2e4f3f65b7e846a5184c5c290afbc25a8b
| 1,657
|
/*
* Copyright 2018 Alfresco, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.activiti.runtime.api.cmd.impl;
import java.util.List;
import org.activiti.runtime.api.cmd.ProcessCommands;
import org.activiti.runtime.api.cmd.RemoveProcessVariables;
public class RemoveProcessVariablesImpl extends CommandImpl<ProcessCommands> implements RemoveProcessVariables {
private String processInstanceId;
private List<String> variableNames;
private ProcessCommands commandType = ProcessCommands.REMOVE_PROCESS_VARIABLES;
public RemoveProcessVariablesImpl() {
}
public RemoveProcessVariablesImpl(String processInstanceId,
List<String> variableNames) {
this.processInstanceId = processInstanceId;
this.variableNames = variableNames;
}
@Override
public List<String> getVariableNames() {
return variableNames;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public ProcessCommands getCommandType() {
return commandType;
}
}
| 30.685185
| 112
| 0.725407
|
7877f27066b32521909358ee51480449bf5e3316
| 519
|
package dev.patika.homework04.repository;
import dev.patika.homework04.entity.SystemLog;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface LogRepository extends CrudRepository<SystemLog,Long> {
@Query("SELECT l FROM SystemLog l WHERE l.type LIKE %?1%" +
"OR l.description LIKE %?1%")
List<SystemLog> search(String word);
}
| 32.4375
| 71
| 0.764933
|
6c7603f09b7cd454b7652a264e4b4d84aac4c9ba
| 2,864
|
package manggo.com.query;
import org.apache.commons.collections.CollectionUtils;
import java.util.Collections;
import java.util.List;
public class Page<T> implements IPage<T> {
private static final long serialVersionUID = 8545996863226528798L;
private List<T> records;
private long total;
private long size;
private long current;
private String[] ascs;
private String[] descs;
private boolean optimizeCountSql;
public Page() {
this.records = Collections.emptyList();
this.total = 0L;
this.size = 10L;
this.current = 1L;
this.optimizeCountSql = true;
}
public Page(long current, long size) {
this(current, size, 0L);
}
public Page(long current, long size, long total) {
this.records = Collections.emptyList();
this.total = 0L;
this.size = 10L;
this.current = 1L;
this.optimizeCountSql = true;
if (current > 1L) {
this.current = current;
}
this.size = size;
this.total = total;
}
public boolean hasPrevious() {
return this.current > 1L;
}
public boolean hasNext() {
return this.current < this.getPages();
}
public List<T> getRecords() {
return this.records;
}
public Page<T> setRecords(List<T> records) {
this.records = records;
return this;
}
public long getTotal() {
return this.total;
}
public Page<T> setTotal(long total) {
this.total = total;
return this;
}
public long getSize() {
return this.size;
}
public Page<T> setSize(long size) {
this.size = size;
return this;
}
public long getCurrent() {
return this.current;
}
public Page<T> setCurrent(long current) {
this.current = current;
return this;
}
public String[] ascs() {
return this.ascs;
}
public Page<T> setAscs(List<String> ascs) {
if (CollectionUtils.isNotEmpty(ascs)) {
this.ascs = (String[]) ascs.toArray(new String[0]);
}
return this;
}
public Page<T> setAsc(String... ascs) {
this.ascs = ascs;
return this;
}
public String[] descs() {
return this.descs;
}
public Page<T> setDescs(List<String> descs) {
if (CollectionUtils.isNotEmpty(descs)) {
this.descs = (String[]) descs.toArray(new String[0]);
}
return this;
}
public Page<T> setDesc(String... descs) {
this.descs = descs;
return this;
}
public boolean optimizeCountSql() {
return this.optimizeCountSql;
}
public Page<T> setOptimizeCountSql(boolean optimizeCountSql) {
this.optimizeCountSql = optimizeCountSql;
return this;
}
}
| 21.862595
| 70
| 0.577863
|
3d0dc37c4ea0f463b174ea55c88b9404ce03156e
| 2,536
|
package npc.model;
import java.util.ArrayList;
import java.util.List;
import l2f.commons.util.Rnd;
import l2f.gameserver.data.xml.holder.NpcHolder;
import l2f.gameserver.model.Creature;
import l2f.gameserver.model.Player;
import l2f.gameserver.model.SimpleSpawner;
import l2f.gameserver.model.Zone;
import l2f.gameserver.model.Zone.ZoneType;
import l2f.gameserver.model.instances.BossInstance;
import l2f.gameserver.model.instances.MinionInstance;
import l2f.gameserver.model.instances.NpcInstance;
import l2f.gameserver.network.serverpackets.PlaySound;
import l2f.gameserver.scripts.Functions;
import l2f.gameserver.templates.npc.NpcTemplate;
import l2f.gameserver.utils.Location;
public class QueenAntInstance extends BossInstance
{
private static final int Queen_Ant_Larva = 29002;
private List<SimpleSpawner> _spawns = new ArrayList<SimpleSpawner>();
private NpcInstance Larva = null;
public QueenAntInstance(int objectId, NpcTemplate template)
{
super(objectId, template);
}
public NpcInstance getLarva()
{
if (Larva == null)
{
Larva = SpawnNPC(Queen_Ant_Larva, new Location(-21600, 179482, -5846, Rnd.get(0, 0xFFFF)));
}
return Larva;
}
@Override
protected int getKilledInterval(MinionInstance minion)
{
return minion.getNpcId() == 29003 ? 10000 : 280000 + Rnd.get(40000);
}
@Override
protected void onDeath(Creature killer)
{
broadcastPacketToOthers(new PlaySound(PlaySound.Type.MUSIC, "BS02_D", 1, 0, getLoc()));
Functions.deSpawnNPCs(_spawns);
Larva = null;
super.onDeath(killer);
}
@Override
protected void onSpawn()
{
super.onSpawn();
getLarva();
broadcastPacketToOthers(new PlaySound(PlaySound.Type.MUSIC, "BS01_A", 1, 0, getLoc()));
// Synerge - On Queen Ant spawn teleport every player that is inside the zone to the closest town
final Zone zone = getZone(ZoneType.epic);
if (zone != null)
{
for (Player player : zone.getInsidePlayers())
{
if (player == null)
continue;
player.teleToClosestTown();
}
}
}
private NpcInstance SpawnNPC(int npcId, Location loc)
{
NpcTemplate template = NpcHolder.getInstance().getTemplate(npcId);
if (template == null)
{
System.out.println("WARNING! template is null for npc: " + npcId);
Thread.dumpStack();
return null;
}
try
{
SimpleSpawner sp = new SimpleSpawner(template);
sp.setLoc(loc);
sp.setAmount(1);
sp.setRespawnDelay(0);
_spawns.add(sp);
return sp.spawnOne();
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
| 24.621359
| 99
| 0.729495
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.